instruction
stringlengths
34
53.1k
completion
stringlengths
5
524k
__original_row_idx
int64
0
50k
conversations
listlengths
2
2
Background Though this is a bit late for Pi Day, I saw an article about Pilish and thought it would make a great challenge. Pilish is created by using a sequence of words where each word's length corresponds to a digit of pi. Example from Wikipedia: The following Pilish poem (written by Joseph Shipley) matches the fir...
Here’s a Python solution that evaluates whether a given input of words forms Basic Pilish, Standard Pilish, or is Incorrect based on the provided criteria: ```python def pi_gen(n=100): from mpmath import mp mp.dps = n return str(mp.pi)[2:] def pilish(words, pi_digits=None): if pi_digits is None: ...
10,331
[ { "from": "human", "value": "Background\nThough this is a bit late for Pi Day, I saw an article about Pilish and thought it would make a great challenge. Pilish is created by using a sequence of words where each word's length corresponds to a digit of pi.\nExample from Wikipedia:\n\nThe following Pilish poe...
The Challenge A bubble sort takes a list of non-repeating integers and sorts them in ascending order, with only the use of one operation: switching two numbers which are next to eachother. However for this puzzle, you must take in two strings, which are both anagrams, and bubble sort the letters of the first string int...
Here's a solution for bubble sorting two anagrams using the specified conditions in Python. The code is designed to be concise for the purpose of code golf: ```python def bubble_sort(s1,s2): s1=list(s1) for i in range(len(s1)): for j in range(len(s1)-1): if s1[j]>s1[j+1]:s1[j],s1[j+1]=s1[j+...
16,081
[ { "from": "human", "value": "The Challenge\nA bubble sort takes a list of non-repeating integers and sorts them in ascending order, with only the use of one operation: switching two numbers which are next to eachother.\nHowever for this puzzle, you must take in two strings, which are both anagrams, and bubb...
Note: although this is tagged as Python, other languages are permitted Challenge What you have to do is write the shortest functions to perform the same actions as the following Python 2 built in functions: Range >>> range(1, 10, 1) [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(1, 10, 2) [1, 3, 5, 7, 9] >>> range(10, 5, -1) [1...
Here are the implementations of the specified functions in Python, adhering to the rules and avoiding the use of the specified built-in functions. The implementations are kept as concise as possible to minimize byte count. ```python def r(s, e, t): if not all(isinstance(i, int) for i in [s, e, t]) or t == 0: ...
14,571
[ { "from": "human", "value": "Note: although this is tagged as Python, other languages are permitted\nChallenge\nWhat you have to do is write the shortest functions to perform the same actions as the following Python 2 built in functions:\nRange\n>>> range(1, 10, 1)\n[1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>> range(1,...
You're sitting in the school cafeteria, microwaving your food like you always do around lunch. Suddenly the programming devil rises from the ashes of your burnt food and proposes a challenge: Sup guys, I have a challenge. How did this happen? What did you ever do wrong? Was it that one bad macro in C? The programming...
Here's a concise Python solution that calculates the mean value of throwing a die `n` times, where the die has more faces than the number of throws. The solution adheres to the challenge requirements: ```python import random n,f=map(int,input().split()) print(round(sum(random.randint(1,f) for _ in range(n))/n))if f>n ...
15,524
[ { "from": "human", "value": "You're sitting in the school cafeteria, microwaving your food like you always do around lunch. Suddenly the programming devil rises from the ashes of your burnt food and proposes a challenge:\n\nSup guys, I have a challenge.\n\nHow did this happen? What did you ever do wrong? Wa...
The year is 930, and the Gregorian Church is having a problem. They have thousands of pages of chant music, but the problem is that all the sheet music was simply thrown onto a pile instead of having any real organisation system: Image by user gamerprinter at Cartographers' Guild. The Church needs to organise all the ...
Here is a concise Python program that solves the problem you described. This implementation reads a list of comma-separated notes, determines the Dorian scale they belong to, and outputs the appropriate scale: ```python n=['C','C#','D','D#','E','F','F#','G','G#','A','A#','B'] m=sorted(set(input().split(','))) for i in...
14,345
[ { "from": "human", "value": "The year is 930, and the Gregorian Church is having a problem. They have thousands of pages of chant music, but the problem is that all the sheet music was simply thrown onto a pile instead of having any real organisation system:\n\nImage by user gamerprinter at Cartographers' G...
(spoilers on decade-old TV show below) In the HBO show "The Wire", the dealers use a system of encoding phone numbers where they "jump the 5" on the number pad. +-----------+ | 1 | 2 | 3 | +-----------+ | 4 | 5 | 6 | +-----------+ | 7 | 8 | 9 | +-----------+ | # | 0 | * | +-----------+ A "1" becomes a "9", "4" becom...
Here's a concise Python solution for the problem that avoids direct swaps or array lookups, while also keeping dashes intact. The approach uses a simple mathematical transformation to achieve the encoding. ```python def encode(n):return''.join(str((int(c)%10)^6)for c in n if c.isdigit()or c=='-') ``` ### Explanation:...
14,608
[ { "from": "human", "value": "(spoilers on decade-old TV show below)\nIn the HBO show \"The Wire\", the dealers use a system of encoding phone numbers where they \"jump the 5\" on the number pad. \n+-----------+\n| 1 | 2 | 3 |\n+-----------+\n| 4 | 5 | 6 |\n+-----------+\n| 7 | 8 | 9 |\n+-----------+\n| # |...
Background You are working for some board-game manufacturer and need to produce wooden tiles with the numbers from 0 to n engraved on them for some game. However, without further ado, some tiles would become indistinguishable, e.g., 6 and 9. To avoid this, you have to equip numbers that can be confused with others (and...
To solve the task of printing numbers from `0` to `n` with the specified formatting for rotation-confused numbers, we can write a short program in Python. The logic consists of determining which numbers should have a dot appended based on their rotation characteristics. Here is a concise Python program that accomplish...
14,807
[ { "from": "human", "value": "Background\nYou are working for some board-game manufacturer and need to produce wooden tiles with the numbers from 0 to n engraved on them for some game. However, without further ado, some tiles would become indistinguishable, e.g., 6 and 9. To avoid this, you have to equip num...
Note: this challenge involves downloading and sifting through HTML webpages. If your language cannot handle this you might not want to participate in this challenge. Introduction There are always discussions over in The Nineteenth Byte Chat about who leads the starboard. So, lets help everyone out and count the total a...
## Python, 137 bytes ```python import requests from collections import Counter N=int(input()) sums=Counter() for i in range((N-1)//50+1): for m in requests.get(f'https://yourstarboardurl.com/page/{i+1}').json():sums[m['user_id']]+=1 print([k for k,v in sums.most_common(5)]) ``` **Explanation:** - This Python code re...
16,158
[ { "from": "human", "value": "Note: this challenge involves downloading and sifting through HTML webpages. If your language cannot handle this you might not want to participate in this challenge.\nIntroduction\nThere are always discussions over in The Nineteenth Byte Chat about who leads the starboard. So, l...
During work on some project I needed to draw pixels on screen. I found some put-pixel function in JS, but code was quite big and clumsy - so I wonder, how small put-pixel function can be... Challenge Create the smallest put-pixel function. We count size of whole program: initialization code (if needed), function and co...
Here's a small and efficient solution for your pixel-drawing challenge using JavaScript and HTML5 Canvas. This example defines a `putPixel` function to set individual pixels based on the provided parameters. The implementation is as minimal as possible while fulfilling the requirements. ```html <canvas id="c" width="2...
13,163
[ { "from": "human", "value": "During work on some project I needed to draw pixels on screen. I found some put-pixel function in JS, but code was quite big and clumsy - so I wonder, how small put-pixel function can be...\nChallenge\nCreate the smallest put-pixel function.\nWe count size of whole program: init...
This is a code golf challenge to see the shortest implementation of an automated guesser in the pen and paper game bulls and cows. The game works as follows: A (usually 4 digit) secret code with only distinct integers 0-9 is picked by one player. A second player guesses codes that each receive a rank. This rank contai...
Here’s a short implementation of an automated guesser for the Bulls and Cows game in Python. This code utilizes a brute-force approach, generating all possible combinations of 4-digit distinct integers and then evaluating them against the provided feedback. ```python def rateGuess(guess): # Simulated method; replace ...
14,901
[ { "from": "human", "value": "This is a code golf challenge to see the shortest implementation of an automated guesser in the pen and paper game bulls and cows. \nThe game works as follows:\nA (usually 4 digit) secret code with only distinct integers 0-9 is picked by one player. A second player guesses codes...
Write a program that takes as its input a string consisting of printable characters (ASCII 20-7E) and an integer n in [2,16] and performs the following modification to the string. Each character in the string is converted to its ASCII code (the examples given are in hexadecimal, though base 10 is also acceptable). The...
Here is a concise Python solution that fulfills the requirements of the given problem in a code-golf style: ```python s,n=input().split();n=int(n) x=''.join(f'{ord(c):x}' for c in s) y=''.join([x[i:i+2] for i in range(0,len(x),2)])[:len(x)//2*2] print(''.join(chr(int(y[i:i+2],n)) for i in range(0,len(y),2) if 32<=int(...
16,199
[ { "from": "human", "value": "Write a program that takes as its input a string consisting of printable characters (ASCII 20-7E) and an integer n in [2,16] and performs the following modification to the string.\n\nEach character in the string is converted to its ASCII code (the examples given are in hexadecim...
The point of this challenge is to find the smallest positive integer that uses up at least all of the digits supplied in the input after it is squared and cubed. So, when provided an input such as 0123456789 (i.e. a number that finds the result): 69² = 4761 69³ = 328509 It means that 69 is the result of such an input....
To solve the challenge of finding the smallest positive integer \( n \) such that the digits of \( n^2 \) and \( n^3 \) together use up at least all the digits in the input (considering the count of each digit), we can follow these steps: 1. **Count the required digits**: First, create a count of each digit (0 through...
11,170
[ { "from": "human", "value": "The point of this challenge is to find the smallest positive integer that uses up at least all of the digits supplied in the input after it is squared and cubed.\nSo, when provided an input such as 0123456789 (i.e. a number that finds the result):\n69² = 4761\n69³ = 328509\n\nIt...
Inspired by @emanresu A's Is it a fibonacci-like sequence? Make sure to upvote that challenge as well! We say a sequence is Fibonacci-like, if, starting from the third term (\$1\$-indexed), each term is the sum of the previous two terms. For example, \$3, 4, 7, 11, 18, 29, 47, 76, 123, 199\cdots\$ is a Fibonacci-like s...
Here's a solution in Python that determines the smallest `n` such that a given non-empty list of positive integers can be part of some `n`-bonacci-like sequence. The code is written to be as concise as possible, adhering to the rules of code-golf: ```python def min_n_bonacci(seq): l = len(seq) for n in range(1...
12,853
[ { "from": "human", "value": "Inspired by @emanresu A's Is it a fibonacci-like sequence? Make sure to upvote that challenge as well!\nWe say a sequence is Fibonacci-like, if, starting from the third term (\\$1\\$-indexed), each term is the sum of the previous two terms. For example, \\$3, 4, 7, 11, 18, 29, 4...
Background A classical logic gate is an idealized electronic device implementing a Boolean function, i.e. one that takes a certain number of Boolean inputs and outputs a Boolean. We only consider two-input logic gates in this challenge. There are \$2^{2 \times 2} = 16\$ distinct two-input logic gates (2×2 input combina...
Here's a Python solution to compute the number of distinct universal n-ary logic gates for any given integer n ≥ 1. This code uses a mathematical formula to arrive at the answer and employs memoization for efficiency. ```python def universal_gates(n): if n == 1: return 1 if n == 2: return 2 ...
12,659
[ { "from": "human", "value": "Background\nA classical logic gate is an idealized electronic device implementing a Boolean function, i.e. one that takes a certain number of Boolean inputs and outputs a Boolean. We only consider two-input logic gates in this challenge.\nThere are \\$2^{2 \\times 2} = 16\\$ dis...
Do you know the optical effect of a tridimensional hand painted whit horizontal lines? Examples This challenge consists of making something like that effect with ascii, and transforming one 2d input into a "3d" output. The algorithm To perform this transformation, you first replace all 1 with a ¯ and all 0 with a _. In...
Here's a Python solution that meets your specifications for the problem. The code takes a 2D array of two specified characters and transforms it into a 3D-like ASCII representation. ```python def transform(input_lines): output = [] for line in input_lines: new_line = [] prev = '0' for c...
12,177
[ { "from": "human", "value": "Do you know the optical effect of a tridimensional hand painted whit horizontal lines?\nExamples\nThis challenge consists of making something like that effect with ascii, and transforming one 2d input into a \"3d\" output.\nThe algorithm\nTo perform this transformation, you firs...
In investing, internal rate of return (IRR), the continuously compounded rate of return economically equivalent to a specified series of cashflows, is often a valuable concept. Your challenge is to demonstrate how to compute IRR in the language of your choice in as few bytes as possible, subject to the following condit...
Here's a Python implementation to compute the Internal Rate of Return (IRR) based on your requirements. This code uses the Newton-Raphson method for root-finding and assumes that the cash flows are given in the specified format as a list of date, cashflow pairs. The implementation is concise and fulfills the conditio...
14,115
[ { "from": "human", "value": "In investing, internal rate of return (IRR), the continuously compounded rate of return economically equivalent to a specified series of cashflows, is often a valuable concept.\nYour challenge is to demonstrate how to compute IRR in the language of your choice in as few bytes as...
Challenge Write a function/program that outputs either the n'th element, or the first n elements, in the well known number sequence: 1, 2, 4, 8, 16 ... Oh, wait... I forgot the first few numbers: 1, 1, 1, 1, 2, 4, 8, 16 ... Heck, I'll add a few more for good measure: 1, 1, 1, 1, 2, 4, 8, 16, 33, 69, 146, 312...
To solve the problem of generating the Generalized Catalan numbers as defined in the prompt, we need to implement a function that can either return the nth element of the sequence or the first n elements, based on the user’s request. ### Formula Breakdown The sequence is defined recursively as follows: - For \( n = 0,...
10,772
[ { "from": "human", "value": "Challenge\nWrite a function/program that outputs either the n'th element, or the first n elements, in the well known number sequence:\n 1, 2, 4, 8, 16 ...\n\nOh, wait... I forgot the first few numbers:\n1, 1, 1, 1, 2, 4, 8, 16 ...\n\nHeck, I'll add a few more for good me...
The game Nim is a mathematical strategy game, where 2 players take turns taking items from distinct heaps. On your turn, you must take at least one item, and you may take as many as you want, provided that you only take from one heap. The player that takes the last item wins! This is a solved game. Before I go into the...
# Python, 115 bytes ```python def nim(a): s = 0 for x in a: s ^= x for i in range(len(a)): if (a[i] ^ s) < a[i]: return [i, a[i] - (a[i] ^ s)] return 0 # Example of running the function print(nim([1, 2, 3, 4, 5])) # Example usage ``` ### Explanation: 1. **XOR Calculation**: The f...
15,506
[ { "from": "human", "value": "The game\nNim is a mathematical strategy game, where 2 players take turns taking items from distinct heaps. On your turn, you must take at least one item, and you may take as many as you want, provided that you only take from one heap. The player that takes the last item wins! T...
The bank has been broken into, and all the local mafia thugs have an unusual alibi: they were at home playing Connect 4! In order to assist with the investigation, you are asked to write a program to validate all the Connect 4 boards that have been seized in order to check that the positions are indeed positions from ...
Here's a short Python solution that validates a Connect 4 board and returns a possible sequence of moves leading to that board position: ```python def validate_board(board): # Flatten the board and count pieces flat_board = [c for row in board for c in row] r_count = flat_board.count('R') y_count = fla...
10,214
[ { "from": "human", "value": "The bank has been broken into, and all the local mafia thugs have an unusual alibi: they were at home playing Connect 4! In order to assist with the investigation, you are asked to write a program to validate all the Connect 4 boards that have been seized in order to check that...
Every 3 seconds, add a room to the house. A house with one room looks like this: |---| |[=]| |---| Two rooms: |---||---| |[=]||[=]| |---||---| Three rooms: |---| |[=]| |---| |---||---| |[=]||[=]| |---||---| Four rooms: |---||---| |[=]||[=]| |---||---| |---||---| |[=]||[=]| |---||---| Five rooms: |---||---| |[=]||[...
Here's a Python code snippet that generates a house with rooms in the specified format. The code will continuously add rooms every 3 seconds and display the output for each number of rooms. ```python import time import math while True: n = int(input()) r = int(math.ceil(n**0.5)) print('\n'.join(['|---' * ...
15,858
[ { "from": "human", "value": "Every 3 seconds, add a room to the house.\nA house with one room looks like this:\n|---|\n|[=]|\n|---|\n\nTwo rooms:\n|---||---|\n|[=]||[=]|\n|---||---|\n\nThree rooms:\n|---|\n|[=]|\n|---|\n\n|---||---|\n|[=]||[=]|\n|---||---|\n\nFour rooms:\n|---||---|\n|[=]||[=]|\n|---||---|\...
Cops thread Robbers Robbers, your job is to find the slices of the corresponding cop's code. Scoring The robber with the most cracks wins. Example Take this code: iimmppoorrtt ssyymmppyy;;pprriinntt((ssyymmppyy..iisspprriimmee((iinnppuutt(()))))) The slice here is [::2], so the robber's post could look like this: Crac...
Sure! It sounds like you're looking for a way to identify and decode a string that has been scrambled by repeating each character. Based on your example, you want to take the original string and use slicing to recover it. Here’s a function to demonstrate how a "robber" could crack a cop's encoded message: ```python ...
12,801
[ { "from": "human", "value": "Cops thread\nRobbers\nRobbers, your job is to find the slices of the corresponding cop's code.\nScoring\nThe robber with the most cracks wins.\nExample\nTake this code:\niimmppoorrtt ssyymmppyy;;pprriinntt((ssyymmppyy..iisspprriimmee((iinnppuutt(())))))\nThe slice here is [::2]...
You decided to organize a rock-paper-scissors championship to find out who is the best. You don't want to let luck to decide the winner so everyone has to give you his or her tactic in writing before the competition. You also like simple things so a move of a competitor (showing rock, paper or scissors) has to be based...
Here is a short implementation of the rock-paper-scissors championship simulator in Python: ```python def rps_championship(strats): def result(a, b): if a == b: return 1, 1 return (2, 0) if (a, b) in [('r', 's'), ('s', 'p'), ('p', 'r')] else (0, 2) scores = [0] * len(strats) fo...
14,911
[ { "from": "human", "value": "You decided to organize a rock-paper-scissors championship to find out who is the best. You don't want to let luck to decide the winner so everyone has to give you his or her tactic in writing before the competition. You also like simple things so a move of a competitor (showing...
You are Desmond Hume. For the last 3 years, you and your partner, Kelvin, have been slave to a computer that requires a very specific sequence to be entered into it every 108 minutes to save the world. 4 8 15 16 23 42 Your partner died 40 days ago (due to an unfortunate accident involving Kelvin's head and a big rock)...
Given the constraints of the challenge, here’s a solution in a suitable language that predates 1978: **FORTRAN**. This program will print the numbers, wait for a time between 104 and 108 minutes, and repeat the process indefinitely. Here’s a minimal implementation in FORTRAN: ```fortran PROGRAM SAVE_WORLD ...
14,836
[ { "from": "human", "value": "You are Desmond Hume. For the last 3 years, you and your partner, Kelvin, have been slave to a computer that requires a very specific sequence to be entered into it every 108 minutes to save the world.\n4 8 15 16 23 42\n\nYour partner died 40 days ago (due to an unfortunate acci...
Given a list of two or more spelled-out serial numbers of equal length greater than two, e.g. [[ "three" , "one" , "four" ], [ "one" , "five" , "nine" ], [ "two" , "six" , "five" ], [ "three" , "five" , "eight" ]] sort the list by the numbers that the words represent: [[ "one" , "five" , "nine" ], [ "t...
To sort the lists based on the spelled-out serial numbers, we need to create a mapping from the spelled numbers to their integer values. Then, we can compare the lists based on the numeric values of the spelled numbers. Here's how we can achieve this: 1. Create a mapping of spelled-out numbers to their corresponding ...
9,368
[ { "from": "human", "value": "Given a list of two or more spelled-out serial numbers of equal length greater than two, e.g.\n[[ \"three\" , \"one\" , \"four\" ],\n [ \"one\" , \"five\" , \"nine\" ],\n [ \"two\" , \"six\" , \"five\" ],\n [ \"three\" , \"five\" , \"eight\" ]]\n\nsort the list by the n...
I'm pretty sure there's not a better way to do this but figured it couldn't hurt to ask. I'm tired of typing out a='abcdefghijklmnopqrstuvwxyz'. Cool languages have Range('a'..'z') or similar What can we come up with with JS that's as short as possible?? for(i=97,a='';i<123;){a+=String.fromCharCode(i++)} is longer tha...
You can simplify the creation of a string containing the lowercase alphabet in JavaScript using a combination of `String.fromCharCode` and `String.fromCharCode` in a more concise way. Here’s a compact solution that is under 50 characters: ```javascript a = String.fromCharCode(...Array(26).fill(0).map((_,i)=>i+97)); ``...
16,879
[ { "from": "human", "value": "I'm pretty sure there's not a better way to do this but figured it couldn't hurt to ask.\nI'm tired of typing out a='abcdefghijklmnopqrstuvwxyz'.\nCool languages have Range('a'..'z') or similar\nWhat can we come up with with JS that's as short as possible??\nfor(i=97,a='';i<123;...
The recent volume of MAA's Mathematics Magazine had an article "Connecting the Dots: Maximal Polygons on a Square Grid" by Sam Chow, Ayla Gafni, and Paul Gafni about making (very convex) \$n^2\$-gons where each vertex is a different point of the \$n \times n\$ grid. One is not allowed to have two consecutive segments ...
To solve the problem of counting "essentially different" \(n^2\)-gons on an \(n \times n\) grid, we need to consider the geometry of the grid and the restrictions on constructing convex polygons with non-collinear segments. Here's a structured approach to implement the solution: ### Steps to Solve the Problem: 1. **U...
12,066
[ { "from": "human", "value": "The recent volume of MAA's Mathematics Magazine had an article \"Connecting the Dots: Maximal Polygons on a Square Grid\" by Sam Chow, Ayla Gafni, and Paul Gafni about making (very convex) \\$n^2\\$-gons where each vertex is a different point of the \\$n \\times n\\$ grid.\n\nOn...
Task Write a program to determine the note sounded, along with how many cents out of tune, of a string tuned to a given frequency and pressed down at a given point. For the sake of simplicity, assume that the frequency of the sound produced and the length of the string to the right of where it is pressed are inversely...
Here's a concise Python solution to determine the note sounded by a string based on the given input. This program takes a frequency and a string marking the pressed point, calculates the frequency of the note produced, identifies the closest note, and computes the cents difference from that note. ```python def note_fr...
14,327
[ { "from": "human", "value": "Task\nWrite a program to determine the note sounded, along with how many cents out of tune, of a string tuned to a given frequency and pressed down at a given point. \nFor the sake of simplicity, assume that the frequency of the sound produced and the length of the string to the...
Let's define a function \$f\$ which, given a positive integer \$x\$, returns the sum of: \$x\$ the smallest digit in the decimal representation of \$x\$ the highest digit in the decimal representation of \$x\$ (which may be the same as the smallest one) For instance: \$f(1)=1+1+1=3\$ \$f(135)=135+1+5=141\$ \$f(209)=...
To solve the problem of finding the smallest \( n \) such that applying the function \( f \) \( n \) times to a given integer \( x \) results in a number that belongs to the sequence \( a_k \), we can write a Python function that implements this logic. The function will repeatedly apply \( f \) to \( x \) until it reac...
12,427
[ { "from": "human", "value": "Let's define a function \\$f\\$ which, given a positive integer \\$x\\$, returns the sum of:\n\n\\$x\\$\nthe smallest digit in the decimal representation of \\$x\\$\nthe highest digit in the decimal representation of \\$x\\$ (which may be the same as the smallest one)\n\nFor ins...
Given a base type T, this can be augmented with * or [], each meaning pointer and array. For example, []*T means "array of pointer to T" and *[]T means "pointer to array of T". Let's call * and [] type modifiers. C has a way of ordering these modifiers tied to the evaluation order. []*T in C-style becomes T *[], and *[...
To transform the given input string of type modifiers (`*` and `[]`) according to the rules you provided, we can follow a systematic approach. We'll evaluate the modifiers and rearrange them based on the rules for ordering. Here's a step-by-step breakdown of how to process the input: 1. **Separate Modifiers**: First,...
12,944
[ { "from": "human", "value": "Given a base type T, this can be augmented with * or [], each meaning pointer and array. For example, []*T means \"array of pointer to T\" and *[]T means \"pointer to array of T\".\nLet's call * and [] type modifiers. C has a way of ordering these modifiers tied to the evaluatio...
Let's build a sequence of positive integers. The rule will be that the next number will be the smallest number which: It hasn't already appeared in the sequence Its absolute difference from the number preceding it wouldn't be equal to any previous absolute difference between consecutive elements. Task Your task is t...
Here is a Python solution to generate the sequence of positive integers based on the given rules. This implementation focuses on being concise for the code-golf challenge. ```python def seq(n): s, d = [1], {1} for _ in range(n-1): x = s[-1] + 1 while True: dx = abs(s[-1] - x) ...
12,689
[ { "from": "human", "value": "Let's build a sequence of positive integers. The rule will be that the next number will be the smallest number which:\n\nIt hasn't already appeared in the sequence\nIts absolute difference from the number preceding it wouldn't be equal to any previous absolute difference betwee...
The task In this challenge, your input is a non-empty list of positive integers, given in the native format of your language. Your output is that same list, in the same format, with some elements removed. You shall remove every occurrence of 1, every second occurrence of 2, every third occurrence 3, and so on. In gener...
## Python, 130 bytes ```python def remove_nth_occurrences(lst): count = {} return [x for x in lst if (count.setdefault(x, 0) := count[x] + 1) % x != 0] ``` ### Explanation: - The function `remove_nth_occurrences` takes a list `lst` as input. - A dictionary `count` is used to track occurrences of each number. ...
16,758
[ { "from": "human", "value": "The task\nIn this challenge, your input is a non-empty list of positive integers, given in the native format of your language.\nYour output is that same list, in the same format, with some elements removed.\nYou shall remove every occurrence of 1, every second occurrence of 2, e...
Your challenge is to golf a program that mimics a data transmission stream. Your program should read input from stdin and output it directly to stdout. To make the problem more interesting, the output stream is 'faulty', and must meet several requirements: There should be a 10% chance that each character is shifted +1...
Here's a compact Python solution that meets all the requirements you've outlined for the faulty data transmission stream. This program reads from standard input and writes to standard output while introducing random character shifts as specified: ```python import sys,random random.seed() c=0 for i in sys.stdin.read():...
13,542
[ { "from": "human", "value": "Your challenge is to golf a program that mimics a data transmission stream. Your program should read input from stdin and output it directly to stdout. To make the problem more interesting, the output stream is 'faulty', and must meet several requirements:\n\nThere should be a 1...
Today, you're going to be writing Polish. No, not Polish notation—Polish, the actual language spoken in Poland. Given a number and a noun, output a Polish sentence telling me that there are that many of that thing, using the appropriate template below. The input consists of an integer in the range from 0 to 200, and a ...
Here’s a Python solution that implements the logic described for generating the correct Polish sentence based on the input number and noun: ```python n, w = int(input()), input() if n == 0: print("Nie ma żadnych " + w + "ów.") elif n == 1: print(f"Jest 1 {w}.") elif n % 10 in {2, 3, 4} and n % 100 not in {12, ...
13,056
[ { "from": "human", "value": "Today, you're going to be writing Polish. No, not Polish notation—Polish, the actual language spoken in Poland.\nGiven a number and a noun, output a Polish sentence telling me that there are that many of that thing, using the appropriate template below.\nThe input consists of an...
This challenge is simple, given a decimal number, convert to binary, and calculate the sum of the sub-strings of the binary number, whose length is shorter than the original number. Here is an example: Input: 11 Binary: 11 -> 1011 Substrings: 101 = 5 011 = 3 10 = 2 01 = 1 11 = 3 1 = 1 0 = 0 1...
Here's a concise Python solution to the challenge: ```python def sum_bin_substrings(n): b = bin(n)[2:] return sum(int(b[i:j], 2) for i in range(len(b)) for j in range(i + 1, len(b) + 1) if j - i < len(b)) print(sum_bin_substrings(int(input()))) ``` You can run this function with the desired input, and it wil...
16,986
[ { "from": "human", "value": "This challenge is simple, given a decimal number, convert to binary, and calculate the sum of the sub-strings of the binary number, whose length is shorter than the original number. Here is an example:\nInput:\n 11\nBinary:\n 11 -> 1011\nSubstrings:\n 101 = 5\n 011 = 3\n 10...
Background This is a standard textbook example to demonstrate for loops. This is one of the first programs I learnt when I started learning programming ~10 years ago. Task You are to print this exact text: ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** Spe...
Here is a solution in Python: ```python for _ in range(10):print('*'*10) ``` This code uses a for loop to print the string `**********` ten times.
17,839
[ { "from": "human", "value": "Background\nThis is a standard textbook example to demonstrate for loops.\nThis is one of the first programs I learnt when I started learning programming ~10 years ago.\nTask\nYou are to print this exact text:\n**********\n**********\n**********\n**********\n**********\n********...
Well, you know it's Snow White, and the evil Queen is at it again. Will Snow White be saved? Will she fall asleep once again? Will the Prince find her? Challenge: Given an arbitrary number (>= 2) of possibly duplicated hexadecimal color values (ranging from #000000 to #FFFFFF) and paired strings, calculate the followin...
Here's a solution in Python that processes the input according to the challenge specifications, calculating the "fairest" answer based on the defined rules. This implementation is relatively short and aims to encapsulate the required logic efficiently. ```python def hamming_distance(a, b): return bin(int(a, 16) ^ ...
10,847
[ { "from": "human", "value": "Well, you know it's Snow White, and the evil Queen is at it again. Will Snow White be saved? Will she fall asleep once again? Will the Prince find her?\nChallenge:\nGiven an arbitrary number (>= 2) of possibly duplicated hexadecimal color values (ranging from #000000 to #FFFFFF)...
You goal is to implement the operation of XOR (carryless) multiplication, defined below, in as few bytes as possible. If we think of bitwise XOR (^) as binary addition without carrying 101 5 ^ 1001 9 ---- 1100 12 5^9=12 we can perform XOR multiplication @ by doing binary long-multiplication but doin...
Here is a concise implementation of XOR multiplication in Python: ```python def xor_mult(a, b): r = 0 while b: if b & 1: r ^= a a <<= 1 b >>= 1 return r ``` ### Explanation: - `r` is initialized to 0; it will hold the result. - The loop continues as long as `b` is not z...
15,296
[ { "from": "human", "value": "You goal is to implement the operation of XOR (carryless) multiplication, defined below, in as few bytes as possible.\nIf we think of bitwise XOR (^) as binary addition without carrying\n 101 5\n^ 1001 9\n ---- \n 1100 12\n \n 5^9=12\n\nwe can perform XOR multiplicat...
Inspired by this question on SO, your task is to produce a program that is valid in (at least) two major versions of your chosen language that produce different output. Rules Any language that has more than one major version can be used. For the purposes of this challenge, I would suggest a "major version" is where ...
For this challenge, I will use Python to illustrate the differences between Python 2 and Python 3. The following code will demonstrate how the same program can produce different outputs in these two major versions of Python. ### Python Code ```python # Python 2.x print "Hello, World!" # Use of print as a statement ``...
13,877
[ { "from": "human", "value": "Inspired by this question on SO, your task is to produce a program that is valid in (at least) two major versions of your chosen language that produce different output.\nRules\n\nAny language that has more than one major version can be used.\n\n\nFor the purposes of this challen...
Backstory, skip if you like Generating high quality pseudo random numbers is a tricky business but the fine engineers at < enter company you love to hate > have mastered it. Their progress bars effortlessly rise above the primitive notion of linearly passing time and add an exhilarating sense of unpredictability to the...
Here's a concise implementation of the progress bar simulator as per the given task. The solution is designed to fit within the constraints of code-golf, prioritizing brevity while still being functional. The implementation uses Python for its simplicity and expressive capabilities. ```python def f(L,S): c=0;T=len(S)...
12,811
[ { "from": "human", "value": "Backstory, skip if you like\nGenerating high quality pseudo random numbers is a tricky business but the fine engineers at < enter company you love to hate > have mastered it. Their progress bars effortlessly rise above the primitive notion of linearly passing time and add an exh...
If we have a binary matrix then we will say that a \$1\$ is stable if it is in the bottom row or it is directly adjacent to a \$1\$ which is stable. In other words there must be a path to the bottom row consisting only of \$1\$s. So in the following matrix the \$1\$s highlighted in red are not stable. $$ 0110\color{red...
Here’s a Python solution to the problem of determining whether a binary matrix can be rearranged into a stable matrix. The approach checks whether each `1` in the matrix can connect to the bottom row, using a simple depth-first search (DFS). Here's the code: ```python def stable_matrix(mat): rows = len(mat) c...
12,768
[ { "from": "human", "value": "If we have a binary matrix then we will say that a \\$1\\$ is stable if it is in the bottom row or it is directly adjacent to a \\$1\\$ which is stable.\nIn other words there must be a path to the bottom row consisting only of \\$1\\$s.\nSo in the following matrix the \\$1\\$s h...
Task Create a program that calculates the factorial of a number using no built-in factorial functions. Easy? The catch is that you must write your entire program (including testing it) in haiku form. You can use as many haikus as you need, but when pronounced, they must follow the 5-7-5 syllable format. Scoring This i...
```python def factorial(n): if n == 0: # Base case defined here, return 1 # Zero factorial's one. result = 1 # Start with result one, for i in range(1, n + 1): # Loop through all numbers, result *= i # Multiply for the fact. return result # ...
13,598
[ { "from": "human", "value": "Task\nCreate a program that calculates the factorial of a number using no built-in factorial functions. Easy? The catch is that you must write your entire program (including testing it) in haiku form.\n\nYou can use as many haikus as you need, but when pronounced, they must foll...
Remove all repeating words from an inputted sentence. Input will be something like cat dog cat dog bird dog Snake snake Snake and the output should be cat dog bird Snake snake. There will always be a single space separating words. Output order must be the same as input. (Refer to the example) You don't need to handle p...
You can achieve this by using a set to keep track of seen words while iterating through the input sentence. Here’s a simple Python function that implements this logic: ```python def remove_repeating_words(sentence): seen = set() result = [] for word in sentence.split(): # Check if the word is in s...
16,153
[ { "from": "human", "value": "Remove all repeating words from an inputted sentence.\nInput will be something like cat dog cat dog bird dog Snake snake Snake and the output should be cat dog bird Snake snake. There will always be a single space separating words.\nOutput order must be the same as input. (Refer...
Before reading this I suggest reading this little puzzle: https://puzzling.stackexchange.com/questions/11408/longest-word-with-adjacent-letters-on-a-keyboard I want you to make a program that takes one argument, a word (only lowercase letters), and outputs "Yes" if the word can be typed with adjacent keys on the keyboa...
Here's a compact Python solution that checks if a word can be typed using adjacent keys on the specified keyboard layout: ```python def can_type_adjacent(word): k = {'q':'', 'w':'qe', 'e':'wr', 'r':'et', 't':'ry', 'y':'tu', 'u':'iy', 'i':'ou', 'o':'p', 'p':'', 'a':'', 's':'qazd', 'd':'wsxrf', 'f':'edcvgb'...
15,129
[ { "from": "human", "value": "Before reading this I suggest reading this little puzzle: https://puzzling.stackexchange.com/questions/11408/longest-word-with-adjacent-letters-on-a-keyboard\nI want you to make a program that takes one argument, a word (only lowercase letters), and outputs \"Yes\" if the word c...
Problem: In your choice of language, write the shortest function that returns the floor of the square root of an unsigned 64-bit integer. Test cases: Your function must work correctly for all inputs, but here are a few which help illustrate the idea: INPUT ⟶ OUTPUT 0 ⟶ 0 ...
Here is a short function to compute the floor of the square root of an unsigned 64-bit integer using Python. This solution utilizes binary search, which provides a time complexity of O(log n). ```python def isqrt(n): if n == 0: return 0 x = 1 << (n.bit_length() // 2) # Start with an initial guess ...
14,241
[ { "from": "human", "value": "Problem:\nIn your choice of language, write the shortest function that returns the floor of the square root of an unsigned 64-bit integer.\nTest cases:\nYour function must work correctly for all inputs, but here are a few which help illustrate the idea:\n INPUT ⟶ O...
I can have a large if/else condition for each 30 minutes but I'm looking for more math and Unicode based solution. Here are clock emojis: . If you lack proper rendering support, you can see them below (they're not in the same order and they may look different to what you see) or at the Unicode chart, page 4. They corre...
Here's a concise Python solution to output the closest clock face emoji based on the current system time. This code calculates which half-hour segment the current time falls into and then maps it to the corresponding clock emoji. ```python import datetime t = datetime.datetime.now().time() # You can replace this lin...
14,758
[ { "from": "human", "value": "I can have a large if/else condition for each 30 minutes but I'm looking for more math and Unicode based solution.\nHere are clock emojis:\n. If you lack proper rendering support, you can see them below (they're not in the same order and they may look different to what you see) ...
I've looked and could not find a post for this, if there is one, I'll remove it quick! Related and also related The goal is (hopefully) clear: create the shortest code (in bytes) that implements the AES256 ECB cipher mode. Either convert the result to Base64 or output a array of bytes. The input contains two parts. The...
Here's a short Python implementation for AES-256 encryption in ECB mode that takes the specified input format, encrypts the message using the provided key, and then outputs the result in Base64 encoding. You'll need the `pycryptodome` library for this implementation, so make sure to install it first: ```bash pip inst...
13,493
[ { "from": "human", "value": "I've looked and could not find a post for this, if there is one, I'll remove it quick! Related and also related\nThe goal is (hopefully) clear: create the shortest code (in bytes) that implements the AES256 ECB cipher mode. Either convert the result to Base64 or output a array o...
The van der Corput sequence is one of the simplest example of low-discrepancy sequence. Its n-th term is just 0.(n written in base 10 and mirrored), so its first terms are : 0.1, 0.2,0.3,0.4, 0.5,0.6,0.7, 0.8,0.9, 0.01, 0.11,0.21,0.31, 0.41,0.51,0.61, 0.71,0.81,0.91, 0.02, 0.12,0.22,0.32, 0.42,0.52,0.62, 0.72,0.82,0.92...
Here's a concise implementation of the van der Corput sequence in Python. It generates the first `n` terms as specified: ```python def van_der_corput(n): return [str(i)[::-1] for i in range(1, n+1)] n = int(input()) print("\n".join(van_der_corput(n))) ``` ### Explanation: 1. **Function Definition**: `van_der_co...
16,874
[ { "from": "human", "value": "The van der Corput sequence is one of the simplest example of low-discrepancy sequence. Its n-th term is just 0.(n written in base 10 and mirrored), so its first terms are :\n0.1, 0.2,0.3,0.4, 0.5,0.6,0.7, 0.8,0.9,\n0.01, 0.11,0.21,0.31, 0.41,0.51,0.61, 0.71,0.81,0.91,\n0.02, 0....
There's a simple digital number lock. After each button press the lock checks if the previous four presses constitute the correct code. I.e. typing 44445 tests two codes: 4444 and 4445. You must brute force it with a code golfed program. Rules Your program must test numbers by printing ASCII digits 0-9 to standard out...
Here's a simple and efficient Python solution that brute forces all possible 4-digit combinations for a digital lock. The solution prints all combinations from `0000` to `9999`, ensuring that each combination is tested correctly. ```python for i in range(10000):print(f"{i:04}") ``` ### Explanation: - The code iterate...
14,459
[ { "from": "human", "value": "There's a simple digital number lock. After each button press the lock checks if the previous four presses constitute the correct code. I.e. typing 44445 tests two codes: 4444 and 4445. You must brute force it with a code golfed program.\nRules\n\nYour program must test numbers ...
Introduction In this challenge you will be solving diagonal Burrows-Wheeler transforms. Here is a general overview of what a diagonal Burrows-Wheeler transform is. To encode a message, you first must guarantee that it is odd in length (i.e. 5, 7, 9, etc.). Then you make a grid, n by n, where n is the length of the mess...
Below, I provide two Python functions to encode and decode a message using the diagonal Burrows-Wheeler transform. These solutions are designed to be concise, focusing on brevity. ### Encoding Function ```python def encode(s): n = len(s) grid = [s[i:] + s[:i] for i in range(n)] return ''.join(grid[i][i] f...
14,998
[ { "from": "human", "value": "Introduction\nIn this challenge you will be solving diagonal Burrows-Wheeler transforms. Here is a general overview of what a diagonal Burrows-Wheeler transform is. To encode a message, you first must guarantee that it is odd in length (i.e. 5, 7, 9, etc.). Then you make a grid,...
There are 95 printable ASCII characters: !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ In the Consolas font (the Stack Exchange code block default), some of the characters have mirrors around a vertical axis of symmetry: These pairs of characters are mirrors of each o...
Here's a solution in Python that meets the requirements of being a mirror of itself while maintaining symmetry and the ability to prepend and append parts to create the desired output behavior. ```python print((lambda n: n + 1)(0)) ``` ### Explanation: - The function defined within the `print` statement takes `n` as ...
15,370
[ { "from": "human", "value": "There are 95 printable ASCII characters:\n !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\n\nIn the Consolas font (the Stack Exchange code block default), some of the characters have mirrors around a vertical axis of symmetry:\n\...
Groups are a widely used structure in Mathematics, and have applications in Computer Science. This code challenge is about the fewest # of characters to create a group table for the additive group Zn. How the table is constructed: For Zn, the elements are {0, 1, 2, ..., n-1}. The table will have n rows and n columns. F...
To generate the group table for the additive group \( \mathbb{Z}_n \), we can create a nested loop that populates the table according to the rules specified. Below is a Python solution that constructs the required table and prints it out in the specified format. The solution is designed to minimize the number of charac...
14,228
[ { "from": "human", "value": "Groups are a widely used structure in Mathematics, and have applications in Computer Science. This code challenge is about the fewest # of characters to create a group table for the additive group Zn.\nHow the table is constructed: For Zn, the elements are {0, 1, 2, ..., n-1}. T...
The Bernoulli numbers (specifically, the second Bernoulli numbers) are defined by the following recursive definition: Where denotes a combination. Given a nonnegative integer m as input, output the decimal representation OR a reduced fraction for the mth second Bernoulli number. If you output a decimal representation...
## Python, 125 bytes ```python def B(m):return(1if m<1else 1-sum(B(k)*comb(m,k)/(m-k+1)for k in range(m)))#cdef comb(a,b):return fact(a)//(fact(b)*fact(a-b))#cdef fact(n):return 1if n<1else n*fact(n-1) ``` ### Explanation: This implementation computes the second Bernoulli numbers using the recursive definition provid...
16,367
[ { "from": "human", "value": "The Bernoulli numbers (specifically, the second Bernoulli numbers) are defined by the following recursive definition:\n\nWhere denotes a combination.\nGiven a nonnegative integer m as input, output the decimal representation OR a reduced fraction for the mth second Bernoulli nu...
A bracelet consists of a number, \$\mathit{N}\$, of beads connected in a loop. Each bead may be any of \$\mathit{C}\$ colours. Bracelets are invariant under rotation (shifting beads around the loop) and reflection (turning the bracelet over). Here are all \$11\$ bracelets with exactly two beads of each of three differe...
Here's a solution in Python that is compact and achieves the desired output: ```python def B(N,C,S): from math import gcd from functools import reduce def phi(n): return len([k for k in range(1,n+1) if gcd(k,n)==1]) def f(n,s,c): if s>n: return 0 return c**(s-1) * sum((-1)*...
13,298
[ { "from": "human", "value": "A bracelet consists of a number, \\$\\mathit{N}\\$, of beads connected in a loop. Each bead may be any of \\$\\mathit{C}\\$ colours. Bracelets are invariant under rotation (shifting beads around the loop) and reflection (turning the bracelet over).\nHere are all \\$11\\$ bracele...
99 is a programming language I invented earlier this week for my challenge Write an interpreter for 99. (Invented but never needed to implement thanks to half a dozen of you. ;) ) The full language spec is in that challenge so I'm not bothering to repost it all here. In 99 you can print individual ASCII characters to s...
To create a solution for the challenge of generating 99 programs that output each ASCII character from 0 to 127, we can leverage the fact that any even-sized variable can produce an ASCII character when it's processed through the given formula (value divided by 9 and taken mod 128). Given this, we can systematically ...
15,054
[ { "from": "human", "value": "99 is a programming language I invented earlier this week for my challenge Write an interpreter for 99. (Invented but never needed to implement thanks to half a dozen of you. ;) ) The full language spec is in that challenge so I'm not bothering to repost it all here.\nIn 99 you ...
This is different from Floating Point XOR, and more in the spirit of a comment by R.. GitHub STOP HELPING ICE on that challenge, but I thought of this idea independently. Generalized XOR The bitwise exclusive or (XOR) operation is usually considered in terms of integers, but it can be naturally generalized (extended, i...
Here is a concise Python solution to the challenge of performing a Generalized XOR on two positive double-precision floating-point numbers: ```python def float_xor(a, b): return float.fromhex(hex(a).replace('.', 'p')) ^ float.fromhex(hex(b).replace('.', 'p')) # Test examples print(float_xor(1.0, 2.0)) ...
12,994
[ { "from": "human", "value": "This is different from Floating Point XOR, and more in the spirit of a comment by R.. GitHub STOP HELPING ICE on that challenge, but I thought of this idea independently.\nGeneralized XOR\nThe bitwise exclusive or (XOR) operation is usually considered in terms of integers, but i...
Given two strings, a parent string and a query string respectively, your task is to determine how many times the query string, or an anagram of the query string; appears in the parent string, in a case-sensitive search. Examples of Behaviour Input 1 AdnBndAndBdaBn dAn Output 1 4 Explanation The substrings are highlig...
Here's a solution in Python that counts how many times a query string or an anagram of the query string appears in the parent string, with case sensitivity. Below are both the golfed and non-golfed versions of the code. ### Golfed Version ```python def f(p,q): n,m=len(p),len(q) from collections import Counter c=Co...
15,297
[ { "from": "human", "value": "Given two strings, a parent string and a query string respectively, your task is to determine how many times the query string, or an anagram of the query string; appears in the parent string, in a case-sensitive search.\nExamples of Behaviour\nInput 1\nAdnBndAndBdaBn\ndAn\n\nOut...
Once upon a time I wanted to order custom tokens for a board game. They say they can do it, and then they present me their price list. I was confused because they charge per inch of head movement, and I have no idea how much will my tokens cost. INPUT: a 2d grid: |,-,\,/ are straight cuts. Each has a length of 1. ┌,┐,...
To solve the problem of calculating the distance the cutting head will move when cutting out custom tokens on a 2D grid, we need to interpret the grid's symbols according to their specified lengths and rules. The algorithm must take into account the unique costs associated with different types of cuts, how the head mov...
10,981
[ { "from": "human", "value": "Once upon a time I wanted to order custom tokens for a board game. They say they can do it, and then they present me their price list. I was confused because they charge per inch of head movement, and I have no idea how much will my tokens cost.\nINPUT: a 2d grid:\n\n|,-,\\,/ ar...
I was trying to write a short MIPS32 code for computing the median of three registers. The rules: Assume that some values are pre-loaded into $t0, $t1, $t2. The median of the three values should be placed in $t0. No branches are allowed, but otherwise any instruction is okay. You may arbitrarily modify the values of a...
To compute the median of three values in registers $t0, $t1, and $t2 without branching, we can utilize a clever combination of bitwise operations and arithmetic. The goal is to find the median using a sequence of operations while respecting the restrictions you provided. Here’s a concise MIPS32 code that computes the ...
12,523
[ { "from": "human", "value": "I was trying to write a short MIPS32 code for computing the median of three registers.\nThe rules:\n\nAssume that some values are pre-loaded into $t0, $t1, $t2.\nThe median of the three values should be placed in $t0.\nNo branches are allowed, but otherwise any instruction is ok...
Inspired by both the challenge "Unique is Cheap" by @Laikoni, where the score is based on the challenge itself, as well as the JavaScript (ES6) answer of @ETHproductions for the "Palindrome Compression" challenge, where he uses a pretty cool compression method for the palindrome-flag, upper/lower case indication, and l...
Here is a JavaScript implementation of a compress and decompress program that adheres to the given challenge requirements. The implementation uses a simple character mapping to compress characters into binary strings, making it efficient given the limited character pool used in the programs. ### JavaScript Implementat...
9,229
[ { "from": "human", "value": "Inspired by both the challenge \"Unique is Cheap\" by @Laikoni, where the score is based on the challenge itself, as well as the JavaScript (ES6) answer of @ETHproductions for the \"Palindrome Compression\" challenge, where he uses a pretty cool compression method for the palind...
The Language: Oppification A funny language to speak is created by applying the following process to each word: Place op after each consonant. So Code becomes Copodope. Yes, that's it. For the purpose of this challenge, y is always a consonant. The Challenge: De-oppification Given an oppified word, return the origina...
To de-oppificate a word, we need to reverse the process that was applied to create the oppified version. The steps are as follows: 1. Traverse through the oppified word character by character. 2. Whenever you encounter a consonant, you should: - Keep the consonant. - Skip the next two characters (which will alwa...
7,750
[ { "from": "human", "value": "The Language: Oppification\nA funny language to speak is created by applying the following process to each word:\n\nPlace op after each consonant. So Code becomes Copodope.\n\nYes, that's it. For the purpose of this challenge, y is always a consonant.\nThe Challenge: De-oppifica...
I don't like typing, so I draw my mazes in a very simple format: # ##### # # # ### # # # # # # # # ##### # Isn't it a-maze-ing? Of course, I think all mazes should look 3d, similar but not he same as this challenge, for maximum a-maze-ingness, so I (grudgingly) manually updated the maze to look like this: +-----...
To solve the problem of converting the 3D maze representation back to its simpler 2D format, we need to carefully interpret the maze's structure using the provided characters. The solution requires parsing the input and reconstructing the maze layout by determining the positions of walls and paths. Here’s a Python fun...
10,730
[ { "from": "human", "value": "I don't like typing, so I draw my mazes in a very simple format:\n# #####\n# #\n# ### #\n# # # #\n# # #\n##### #\n\nIsn't it a-maze-ing? Of course, I think all mazes should look 3d, similar but not he same as this challenge, for maximum a-maze-ingness, so I (grudgingly) ma...
Let's play Russian Roulette! Normally, this would be a race to write the shortest MOD 6 program, but that's not very realistic, as the chance of winning decreases with each click. Here are the rules: Emulate a real six-shooter: A single bullet is placed into one of the six chambers, and the barrel is spun once, onl...
Here's a simple implementation of a Russian Roulette game in Python. The code simulates a six-shooter and follows the rules outlined: ```python import random import sys def russian_roulette(): chambers = [0, 0, 0, 0, 0, 1] # 1 represents the bullet random.shuffle(chambers) # Spin the barrel for i in ran...
16,470
[ { "from": "human", "value": "Let's play Russian Roulette!\nNormally, this would be a race to write the shortest MOD 6 program, but that's not very realistic, as the chance of winning decreases with each click. Here are the rules:\n\nEmulate a real six-shooter: \n\n\nA single bullet is placed into one of the...
A metaquine is a program which is not a quine, but whose output, when run as a program in the same language, is a quine. The goal of this challenge is to write a metaquine. This is code-golf, so shortest code wins, with earliest answer used as a tiebreaker. Note that only full programs are acceptable, due to the defini...
Here’s a Python solution for the metaquine challenge. The program is not a quine itself, but when its output is executed as a Python script, it becomes a quine. ```python s='print("s=%r;exec(s)"%s)';exec(s) ``` ### Explanation: - The string `s` contains the code that will be printed when the program is executed. - Th...
16,908
[ { "from": "human", "value": "A metaquine is a program which is not a quine, but whose output, when run as a program in the same language, is a quine.\nThe goal of this challenge is to write a metaquine. This is code-golf, so shortest code wins, with earliest answer used as a tiebreaker. Note that only full ...
Draw the Biohazard symbol in an arbitrary colour on a distinctly coloured background. The specific proportions were published in the June 27th 1974 issue of the Federal Register of the US Government. Details As output, writing to a file (raster and vector formats are permitted) or displaying on the screen are both all...
I can't directly draw or create images. However, I can provide you with instructions and code that you can use to create the Biohazard symbol in Python using the `matplotlib` library, which supports both raster and vector formats. Here’s how you can do it: 1. **Install Matplotlib** (if you haven't already): ```ba...
10,731
[ { "from": "human", "value": "Draw the Biohazard symbol in an arbitrary colour on a distinctly coloured background. The specific proportions were published in the June 27th 1974 issue of the Federal Register of the US Government.\nDetails\n\nAs output, writing to a file (raster and vector formats are permitt...
Years ago I read the "Best of Ruby Quiz" book by James Edward Gray II (also available online by now). For problem 2 in the book (which is problem 14 on his original RubyQuiz site), he mentions a golfed solution in under 300 bytes, even though he is not a big fan of golfing. So I did wonder if I could beat that and mayb...
Here's a Ruby solution to the LCD challenge that meets the specifications you've outlined. The code aims to generate an LCD-style output for a given integer based on a scaling factor. Here's a golfed solution under 200 bytes: ```ruby s=ARGV[1]?ARGV[1].to_i:2 d=" -- | | | | -- | | | | -- | | | | -- | ...
14,969
[ { "from": "human", "value": "Years ago I read the \"Best of Ruby Quiz\" book by James Edward Gray II (also available online by now). For problem 2 in the book (which is problem 14 on his original RubyQuiz site), he mentions a golfed solution in under 300 bytes, even though he is not a big fan of golfing.\nS...
There have been a lot of prime-/prime factorization-related challenges recently, so I thought it might be interesting to go the other way. Given: a positive integer n, and a non-empty list of positive integers f write a full program or a function to find the smallest integer i such that i >= n and i is a product of n...
Here is a Python solution for your challenge. This function finds the smallest integer that is a product of the elements in the list `f`, where each element can be raised to any nonnegative integer power. The approach uses breadth-first search (BFS) to explore all possible products starting from 1. ```python from coll...
8,646
[ { "from": "human", "value": "There have been a lot of prime-/prime factorization-related challenges recently, so I thought it might be interesting to go the other way.\nGiven:\n\na positive integer n, and\na non-empty list of positive integers f\n\nwrite a full program or a function to find the smallest int...
Inspired by one of many bugs I ran into while implementing selection sort in trilangle. Given a non-empty list of non-negative integers, "sort" the list using the following procedure: Find and output the smallest value in the list. If the list only has one element, stop. Recurse on a sublist: If the last element in t...
Here’s a Python solution that implements the described "selection sort" algorithm in a recursive manner, while following the rules of the challenge. This implementation uses a generator to yield the sorted elements one at a time. ```python def sort(arr): if len(arr) == 1: yield arr[0] return mi...
13,511
[ { "from": "human", "value": "Inspired by one of many bugs I ran into while implementing selection sort in trilangle.\nGiven a non-empty list of non-negative integers, \"sort\" the list using the following procedure:\n\nFind and output the smallest value in the list.\nIf the list only has one element, stop.\...
All bots at the battle arena suddenly got brainfucked and no one can explain why. But who cares as long as they are still able to fight - although Brainfuck is the only language they understand anymore. It's been a while since the last submission so I'll finally annouce the winner of BrainFuckedBotsForBattling: Congra...
### Brainfuck Bot Submission **Bot Name:** StrategicStriker **Bot Code:** ```brainfuck (>++++++[<++++++>-]<[-]) # Set up a large defense in front of my flag (>[-<+>]+) # Transfer the setup defense to the next cell (>++++++++++[<++++++++++>-]<[-]) # Set up another layer of defense ...
14,356
[ { "from": "human", "value": "All bots at the battle arena suddenly got brainfucked and no one can explain why. But who cares as long as they are still able to fight - although Brainfuck is the only language they understand anymore.\n\nIt's been a while since the last submission so I'll finally annouce the w...
Background For the purpose of this challenge, all numbers and their string representations are assumed to be in decimal (base 10). I tried to find proper terminology for this challenge, but I do not think there is any, so I made it up. A self-replicating number is a number that appears as a substring in any of its mult...
Here's a Python solution that implements the behavior specified in the challenge. The program takes two integers `m` and `n` and returns the `m`-th `n`-order self-replicating number or the first `m` such numbers, depending on the input. ```python def self_replicating_numbers(m, n): def count_replicates(x): ...
11,984
[ { "from": "human", "value": "Background\nFor the purpose of this challenge, all numbers and their string representations are assumed to be in decimal (base 10). I tried to find proper terminology for this challenge, but I do not think there is any, so I made it up.\nA self-replicating number is a number tha...
A polyiamond of size \$n\$ is a contiguous shape formed by joining \$n\$ equilateral triangles side by side. Your output should consist of two distinct characters, plus whitespace as necessary (▲ and ▼ work great!). Trailing whitespace is acceptable. You may use any other characters - but you may count ▲▼ as 1 byte e...
Here’s a simple Python solution that takes an input \( n \) and outputs all distinct polyiamonds of size \( n \) using the characters `▲` and `▼`. ```python def polyiamonds(n): from itertools import permutations # We will use a set to keep track of unique polyiamonds unique_polyiamonds = set() # Gen...
12,949
[ { "from": "human", "value": "A polyiamond of size \\$n\\$ is a contiguous shape formed by joining \\$n\\$ equilateral triangles side by side.\nYour output should consist of two distinct characters, plus whitespace as necessary (▲ and ▼ work great!). Trailing whitespace is acceptable. You may use any other...
Introduction The task is simple. When given a number, output the most logical rectangle. To explain what a logical rectangle is, I provided some examples: Input: 24. All possible rectangles have the form A x B, (A and B are both positive integers). So, all possible rectangles for 24 are: 1 x 24 2 x 12 4 x 6 From this...
Here's a compact Python solution that adheres to your requirements and outputs the most logical rectangle for a given number. The code finds all factor pairs of the input number and selects the one with the minimal sum of the factors. ```python def logical_rectangle(n): return min(((i, n // i) for i in range(1, in...
16,451
[ { "from": "human", "value": "Introduction\nThe task is simple. When given a number, output the most logical rectangle. To explain what a logical rectangle is, I provided some examples:\nInput: 24.\nAll possible rectangles have the form A x B, (A and B are both positive integers). So, all possible rectangles...
Alice is an intern in a company that uses Brainfuck as a primary language for both client-side and server-side development. Alice just has written her first code and she's a bit nervous as she's getting ready for her first code review. Alice wants to make her code properly formatted and look nice, but she has no time t...
Here's a concise Python solution that formats a string of Brainfuck code into a square with a centered gap if needed. The program takes into consideration the requirements outlined in your prompt: ```python def format_brainfuck(s): code = ''.join(c for c in s if c > ' ') # Remove whitespaces n = len(code) # ...
10,580
[ { "from": "human", "value": "Alice is an intern in a company that uses Brainfuck as a primary language for both client-side and server-side development. Alice just has written her first code and she's a bit nervous as she's getting ready for her first code review.\nAlice wants to make her code properly form...
There are n people on a 2D plane. Using distances between them we're going to find their positions. To get a unique answer you must make four assumptions: There are at least 3 people. The first person is at position (0, 0). The second person is at position (x, 0) for some x > 0. The third person is at position (x, y) ...
To solve the problem of determining the positions of `n` people given their pairwise distances in a 2D plane, we'll follow the assumptions and constraints you've outlined. The solution involves using a bit of geometry and matrix manipulation to deduce the coordinates. Here's a Python function that implements the neces...
8,603
[ { "from": "human", "value": "There are n people on a 2D plane. Using distances between them we're going to find their positions. To get a unique answer you must make four assumptions:\n\nThere are at least 3 people.\nThe first person is at position (0, 0).\nThe second person is at position (x, 0) for some x...
The goal of this challenge is to make a program that outputs the nth letter of its source code where n is given as input to the program. Like most quine challenges, you are not allowed to read your source code as a file or use any builtin quine functions. Input An integer 0 <= n < len(program). Output The nth character...
# Python, 95 bytes ```python s='s=%r;n=int(input());print(s[n]if n>=0else s[n+len(s)])';n=int(input());print(s[n]if n>=0else s[n+len(s)]) ``` ### Explanation: - The variable `s` holds the source code as a string using the `%r` formatting to represent it. - The program takes an integer input `n`. - It checks if `n` is...
16,811
[ { "from": "human", "value": "The goal of this challenge is to make a program that outputs the nth letter of its source code where n is given as input to the program. Like most quine challenges, you are not allowed to read your source code as a file or use any builtin quine functions.\nInput\nAn integer 0 <=...
The Hamming(7,4) code goes back to 1950. Back then Richard Hamming worked as a mathematician at Bell Labs. Every Friday Hamming set the calculating machines to perform a series of calculation, and collected the results on the following Monday. Using parity checks, these machines were able to detect errors during the co...
Here's a concise solution for the Hamming(7,4) code error correction challenge in Python: ```python def recover(data): p1, p2, d1, p3, d2, d3, d4 = map(int, data) ep1 = (d1 + d2 + d4) % 2 ep2 = (d1 + d3 + d4) % 2 ep3 = (d2 + d3 + d4) % 2 e = (ep1 != p1) * 1 + (ep2 != p2) * 2 + (ep3 != p3) * 4 i...
14,955
[ { "from": "human", "value": "The Hamming(7,4) code goes back to 1950. Back then Richard Hamming worked as a mathematician at Bell Labs. Every Friday Hamming set the calculating machines to perform a series of calculation, and collected the results on the following Monday. Using parity checks, these machines...
You may have seen this one in Die Hard: With a Vengeance... This question is based on the famous 3 and 5 Litre Jug Puzzle, but with a slightly different slant. Golf up some code that when given an integer between 1 and 100 will provide you with the quickest instructions to measure out into a tank, the corresponding num...
Certainly! Below is a Python solution that implements the logic for the 3 and 5 litre jug problem as you've described. It takes an integer input between 1 and 100 and outputs the steps to measure out that specific volume of water into the tank. ```python def measure_water(target): steps = [] five_litre = 0 ...
13,582
[ { "from": "human", "value": "You may have seen this one in Die Hard: With a Vengeance... This question is based on the famous 3 and 5 Litre Jug Puzzle, but with a slightly different slant.\nGolf up some code that when given an integer between 1 and 100 will provide you with the quickest instructions to meas...
Given an input string and a wrapping string, find the location of the first input string char in the wrapping string and replace it with the wrapping string char 1 step to the right of that, find the second char in the wrapping string and replace it with the char 2 steps to the right, find the third and replace it with...
Here's a golfed solution in Python that adheres to your requirements: ```python s,w=input(),input();r='';n=1 for c in s:r+=w[(w.index(c)+n)%len(w)];n+=1 print(r) ``` ### Explanation: 1. **Input**: It takes two strings as input—`s` (the input string) and `w` (the wrapping string). 2. **Loop**: It iterates through each...
12,964
[ { "from": "human", "value": "Given an input string and a wrapping string, find the location of the first input string char in the wrapping string and replace it with the wrapping string char 1 step to the right of that, find the second char in the wrapping string and replace it with the char 2 steps to the ...
Inspired by this badly received migrated post. The head of security at your company is concerned about your PIN generating system after it gave him 12345. He also didn't really appreciate the Spaceballs joke you made at his expense, so you've been delegated to re-write the PIN generator. Since it has to fit on some spe...
Here is a concise Python solution for the PIN generator based on the given requirements. This code generates valid PINs while adhering to the restrictions outlined. ```python from random import sample, choice n,d=int(input()),int(input()) p=set() while len(p)<n: r=''.join(sample('0123456789',d)) if (all(r[i]==r[i+1]...
16,043
[ { "from": "human", "value": "Inspired by this badly received migrated post.\nThe head of security at your company is concerned about your PIN generating system after it gave him 12345. He also didn't really appreciate the Spaceballs joke you made at his expense, so you've been delegated to re-write the PIN ...
AKA: Generate Clickbait From an Array. Given an array of integers, generate some cringe-worthy clickbait based on its arrangement and length: If it's 20 elements or less, you can make a Top X List. Parameters: length of the array. Prime numbers are celebrities, so anytime two of them are next to each other it'll pass ...
Here's a concise solution in Python to generate clickbait from the specified rules: ```python def clickbait(arr): from collections import Counter c=Counter(arr) r=[] if len(arr)<=20:r.append(f'Top {len(arr)} Array Elements') for x in c: if c[x]>1:r.append(f'These {c[x]} Elements Will Blow ...
9,443
[ { "from": "human", "value": "AKA: Generate Clickbait From an Array.\nGiven an array of integers, generate some cringe-worthy clickbait based on its arrangement and length:\n\nIf it's 20 elements or less, you can make a Top X List. Parameters: length of the array.\nPrime numbers are celebrities, so anytime t...
Given an input n where 3 <= n <= 25, perform the following steps, starting with a single n-sided die (faces in the range [1, n], inclusive): Print the result of rolling the current n-sided dice in play, in the form kdn: X (where X is the result and k is the number of dice in play). If X is greater than or equal to n/2...
## Python, 191 bytes ```python import random n=int(input()) d=1 while d>0and d<n: x=sum(random.randint(1,n)for _ in range(d)) print(f"{d}d{n}: {x}") d+=1 if x>=n/2*d else -1 ``` ### Explanation: - The code begins by importing the `random` module to simulate dice rolls. - It reads an integer input `n` which specifi...
16,413
[ { "from": "human", "value": "Given an input n where 3 <= n <= 25, perform the following steps, starting with a single n-sided die (faces in the range [1, n], inclusive):\n\nPrint the result of rolling the current n-sided dice in play, in the form kdn: X (where X is the result and k is the number of dice in ...
This challenge will have you count pseudo-polyforms on the snub square tiling. I think that this sequence does not yet exist on the OEIS, so this challenge exists to compute as many terms as possible for this sequence. Update: this is now on the OEIS as A309159: Number of generalized polyforms on the snub square tiling...
To compute the number of pseudo-polyforms on the snub square tiling, we'll approach the problem using a systematic enumeration strategy. The snub square tiling consists of squares and triangles, and each pseudo-polyform can be created by connecting these shapes along shared edges. Below is a Python implementation that...
10,585
[ { "from": "human", "value": "This challenge will have you count pseudo-polyforms on the snub square tiling.\nI think that this sequence does not yet exist on the OEIS, so this challenge exists to compute as many terms as possible for this sequence.\nUpdate: this is now on the OEIS as A309159: Number of gene...
Mash Up Time! This is instalment #5 of both my Random Golf of the Day and Optimizer's ASCII Art of the Day series. Your submission(s) in this challenge will count towards both leaderboards (which you can find the linked posts). Of course, you may treat this like any other code golf challenge, and answer it without worr...
# Python, 164 bytes Here is a solution that randomly generates a diamond tiling for a hexagon of side length N. ```python import random def hexagon_tiling(n): a=' ____\n /\\_\\_\\\n /\\/\\_\\_\\\n \\/\\/\\_/_/\n \\_/_/\n' b=' /_/_/\\\n /\\/__\\/\n \\/\\/\\_\\\n \\_\\_/\n' retur...
15,400
[ { "from": "human", "value": "Mash Up Time!\nThis is instalment #5 of both my Random Golf of the Day and Optimizer's ASCII Art of the Day series. Your submission(s) in this challenge will count towards both leaderboards (which you can find the linked posts). Of course, you may treat this like any other code ...
Background The game of Morra is a simple game. In the "original" version, several players simultaneously throw out a number 0-5 with their hands while guessing the total sum of everyone's hands. The version I'll use here has been modified to increase the potential for non-trivial strategy, and it is described below: ...
Here's a Python bot for the Morra game that adheres to the specifications you provided. This bot will be simple yet slightly strategic by using a mix of randomness and the previous moves of the opponent. ### Python Bot Code ```python import sys import random # Define the bot class class MorraBot: def __init__(se...
14,947
[ { "from": "human", "value": "Background\nThe game of Morra is a simple game. In the \"original\" version, several players simultaneously throw out a number 0-5 with their hands while guessing the total sum of everyone's hands. The version I'll use here has been modified to increase the potential for non-t...
You are an evil wizard, doing evil wizard business, when suddenly your crystal ball alerts you of a hero on their way to defeat you. To crush their hopes and dreams, you decide to trap the hero in a maze. You could just make a big maze but where would be the fun in that? Instead, you decide you want to make the maze as...
Here’s how the maze is structured based on the given list of directions that the hero will navigate. The hero's movements have been carefully interpreted to create the smallest maze possible where they will eventually give up. ### Input ```python hero_moves = ["LR", "RS", "LR", "RS", "SR", "RS", "RS", "LR", "RS", "SR"...
12,751
[ { "from": "human", "value": "You are an evil wizard, doing evil wizard business, when suddenly your crystal ball alerts you of a hero on their way to defeat you. To crush their hopes and dreams, you decide to trap the hero in a maze. You could just make a big maze but where would be the fun in that? Instead...
The Method of Finite Differences is a technique used to find the next term in a sequence of numbers, given that the sequence is governed by consecutive values of a certain polynomial. Given a list of n terms, the Method will be able to determine the degree of the polynomial, which is a maximum of n+1. The Method works ...
Here's a Python solution to generate the finite differences table based on the provided specifications. This code aims to be as concise as possible for the code golf challenge. ```python a=list(map(int,input().split())) b=[];print(*a,end=' | ') while len(a)>1:b.append([x-y for x,y in zip(a,a[1:])]);a=b[-1];print(a);b=...
16,371
[ { "from": "human", "value": "The Method of Finite Differences is a technique used to find the next term in a sequence of numbers, given that the sequence is governed by consecutive values of a certain polynomial. Given a list of n terms, the Method will be able to determine the degree of the polynomial, whi...
Monday numbers, as defined by Gamow in this question over on Puzzling, are positive integers N with the following three properties: The decimal representation of N does not contain the digit 0 The decimal representation of N does not contain any digit twice N is divisible by every digit D that occurs in its decimal re...
Here is a concise Python implementation that generates the sequence of Monday numbers up to 9867312: ```python def is_monday_number(n): s = str(n) digits = set(s) if '0' in digits or len(digits) < len(s): # Condition 1 and 2 return False return all(n % int(d) == 0 for d in digits) # Condition...
15,961
[ { "from": "human", "value": "Monday numbers, as defined by Gamow in this question over on Puzzling, are positive integers N with the following three properties:\n\nThe decimal representation of N does not contain the digit 0\nThe decimal representation of N does not contain any digit twice\nN is divisible b...
Introduction When solving a rubiks cube, one often write down the times like this 11.91, (11.28), (12.32) This is called a average of 3, while a average of 5 looks like this 13.36, (11.89), 12.31, (16.44), 12.26 Note how the worst and best times have parenthesis around them. When calculating the average of 5 these ti...
Here's a code-golf solution in Python that fulfills the requirements specified in the challenge. The program processes a list of times and calculates either the average or standard deviation based on the rules provided, while correctly formatting the output. ```python def rubik_analysis(l, n, method): if not isins...
4,312
[ { "from": "human", "value": "Introduction\nWhen solving a rubiks cube, one often write down the times like this\n11.91, (11.28), (12.32)\n\nThis is called a average of 3, while a average of 5 looks like this\n13.36, (11.89), 12.31, (16.44), 12.26\n\nNote how the worst and best times have parenthesis around ...
Given an input string only containing the characters A-Z, a-z, and spaces, remove all occurrences of the uppercase and lowercase versions of the first character of the string (if the first character is A remove all As and as, if the first character is (space) remove all spaces), and print the output. Example cases: T...
Here's a concise solution in Python to achieve the task you described, using the approach of removing the first character (and its variations) from the input string. ```python def clean_string(s): return s.replace(s[0], '').replace(s[0].lower(), '') # Test cases print(clean_string("Testing Testing One Two Three")...
16,121
[ { "from": "human", "value": "Given an input string only containing the characters A-Z, a-z, and spaces, remove all occurrences of the uppercase and lowercase versions of the first character of the string (if the first character is A remove all As and as, if the first character is (space) remove all spaces),...
In this challenge, you will write a program which outputs a program which is the double the length of the original program. The outputted program should output a new program a program double its length. Examples If my program is a: < a > aa < aa > aaaa < aaaa > aaaaaaaa Rules No quine built-ins The original program...
Here's a simple solution to the challenge using a minimal programming language (like Python, but you can adapt the concept to any language): ```python def double_length_program(): original_program = '< ' # Generate the next program, which is double the length of the original new_program = '>' + 'a' * (len(...
16,698
[ { "from": "human", "value": "In this challenge, you will write a program which outputs a program which is the double the length of the original program. The outputted program should output a new program a program double its length.\nExamples\nIf my program is a:\n< a\n> aa\n\n< aa\n> aaaa\n\n< aaaa\n> aaaaa...
Pipe a short stream to the following Java program run with accompanying command line options, such that it prints true. class Code implements java.io.Serializable { private static final long serialVersionUID = 0L; private static long count; @Override public int hashCode() { ++count; return...
To achieve the goal of printing `true` with the given Java program and command line options, we need to create a serialized object that will trigger a certain behavior in the `hashCode()` method of the `Code` class. We need to ensure that the `count` variable is incremented and that the printed value is not equal to th...
11,136
[ { "from": "human", "value": "Pipe a short stream to the following Java program run with accompanying command line options, such that it prints true.\nclass Code implements java.io.Serializable { \n private static final long serialVersionUID = 0L;\n private static long count; \n @Override public int...
Part of Code Golf Advent Calendar 2022 event. See the linked meta post for details. Oh no, Santa spilled wine all over his great book. Now most of the letters are illegible. How will Santa now know who is groovy and who is unspeakable? Challenge There was once a sequence of words, like this: groovy groovy groovy unspe...
To solve the problem of recovering the shortest sequence of words from the given damaged string, we can use a greedy approach combined with backtracking. The key steps are as follows: 1. **Identify the inputs:** We have two words `A` and `B`, along with a `damaged_string` formed by concatenating the letters of these w...
13,368
[ { "from": "human", "value": "Part of Code Golf Advent Calendar 2022 event. See the linked meta post for details.\n\nOh no, Santa spilled wine all over his great book. Now most of the letters are illegible. How will Santa now know who is groovy and who is unspeakable?\nChallenge\nThere was once a sequence of...
Given an positive even integer \$ n \$, output the set of "ways to pair up" the set \$ [1, n] \$. For example, with \$ n = 4 \$, we can pair up the set \$ \{1, 2, 3, 4\} \$ in these ways: \$ \{\{1, 2\}, \{3, 4\}\} \$ \$ \{\{1, 3\}, \{2, 4\}\} \$ \$ \{\{1, 4\}, \{2, 3\}\} \$ This can more formally be described as the ...
Here's a compact Python implementation that generates all the unique ways to pair up a set of integers from 1 to `n` (where `n` is an even integer). The code employs recursion and backtracking to find all possible pairings. ```python def pairings(n): from itertools import combinations def backtrack(remaining,...
13,129
[ { "from": "human", "value": "Given an positive even integer \\$ n \\$, output the set of \"ways to pair up\" the set \\$ [1, n] \\$. For example, with \\$ n = 4 \\$, we can pair up the set \\$ \\{1, 2, 3, 4\\} \\$ in these ways:\n\n\\$ \\{\\{1, 2\\}, \\{3, 4\\}\\} \\$\n\\$ \\{\\{1, 3\\}, \\{2, 4\\}\\} \\$\n...
This is what I thought this question was going to be, before I fully read it. A group of code golfers walk into The Nineteenth Bite Pizzeria and order a pizza. It comes in an irregular shape, made of unit squares. Your task is to help them cut it into identical slices. That is, the slices must have the exact same sha...
To solve the problem of cutting the pizza (represented as a grid of '#' characters) into identical slices for a group of people, we need to implement a strategy that considers the constraints of connected components and uniformity of shape. Here's a Python implementation that accomplishes this task: ```python def read...
3,750
[ { "from": "human", "value": " \nThis is what I thought this question was going to be, before I fully read it.\nA group of code golfers walk into The Nineteenth Bite Pizzeria and order a pizza. It comes in an irregular shape, made of unit squares. Your task is to help them cut it into identical slices. That ...
Given a directed network, with a single source and a single sink, it is possible to find the maximum flow through this network, from source to sink. For example, take the below network, \$G\$: Here, the source is node 0 and the sink 5. We can see, from the minimum cut-maximum flow theorem, that the maximum flow throu...
Here is a concise Python function that calculates the maximum flow in a directed network using the Edmonds-Karp algorithm, which is an implementation of the Ford-Fulkerson method for computing maximum flow in a flow network. This implementation takes an adjacency matrix as input and outputs the maximum flow from the ...
11,577
[ { "from": "human", "value": "Given a directed network, with a single source and a single sink, it is possible to find the maximum flow through this network, from source to sink. For example, take the below network, \\$G\\$:\n\nHere, the source is node 0 and the sink 5. We can see, from the minimum cut-maxim...
If you convert a chemical formula to lower case, it may become ambiguous: co can be both CO or Co. Given an input consisting of a-z0-9, where 0 can only stand behind 0-9. Check whether it's ambiguous, unambiguous, or impossible. Return 3 different values for them. Shortest code wins. Examples: co - ambiguous 2h83o6...
Here's a concise Python solution to determine if the input is ambiguous, unambiguous, or impossible based on the given criteria: ```python def classify_formula(s): elements = {'h', 'he', 'li', 'be', 'b', 'c', 'n', 'o', 'f', 'ne', 'na', 'mg', 'al', 'si', 'p', 's', 'cl', 'ar', 'k', 'ca', 'sc', 'ti', 'v', 'cr', 'mn',...
12,223
[ { "from": "human", "value": "If you convert a chemical formula to lower case, it may become ambiguous: co can be both CO or Co.\nGiven an input consisting of a-z0-9, where 0 can only stand behind 0-9. Check whether it's ambiguous, unambiguous, or impossible. Return 3 different values for them. Shortest code...
Let's plot a function f(x) = sin(πx) + 0.5 sin(3πx) over the domain [-3,3]. We can interpret this as a loose string lying on a board. Now let's drive n nails into the board at positions (x1, y1) to (xn, yn), where the xi ∈ (-3,3) and yi ∈ [-1,1]. Imagine that there are two eyelets at the end of the string, that is at p...
Here's a concise solution using Python with `matplotlib` to plot the function and the nails as described in the challenge. ```python import numpy as np import matplotlib.pyplot as plt # Function definition def f(x): return np.sin(np.pi * x) + 0.5 * np.sin(3 * np.pi * x) # Define nails positions nails = np.array(...
14,519
[ { "from": "human", "value": "Let's plot a function f(x) = sin(πx) + 0.5 sin(3πx) over the domain [-3,3]. We can interpret this as a loose string lying on a board. Now let's drive n nails into the board at positions (x1, y1) to (xn, yn), where the xi ∈ (-3,3) and yi ∈ [-1,1]. Imagine that there are two eyele...
A man from the stars has come to Earth! Luckily the president of the United States, Donald Trump, has an infinity-sided die. Using this die, he can conjure up a number which you, the mayor of Podunk, must use to determine who should be sent to stop the invader! But be careful, you can only send a limited amount of byte...
Here's a Python solution to your problem that meets the requirements you've outlined. It's designed to be as short as possible while maintaining clarity. ```python def f(n): if n==2016:return'Trump' a,b=0,1 while b<n:a,b=b,a+b fib=b==n a,b=2,1 while b<n:a,b=b,a+b luc=b==n return'Pippi'i...
16,306
[ { "from": "human", "value": "A man from the stars has come to Earth! Luckily the president of the United States, Donald Trump, has an infinity-sided die. Using this die, he can conjure up a number which you, the mayor of Podunk, must use to determine who should be sent to stop the invader! But be careful, y...
Background A checkered tiling of a rectangular grid is a tiling using some polyominoes, where each region can be colored either black or white so that no two polyominoes sharing an edge has the same color. In graph-theoretic terms, the chromatic number of the adjacency graph is 2. Terminology adapted from a Fillomino v...
To determine if a given tiling is a checkered tiling, we can represent the problem using a graph approach. Each unique region represented by its character or number can be viewed as a node in a graph. An edge exists between nodes if the respective regions share an edge in the tiling. The objective is to check whether t...
12,291
[ { "from": "human", "value": "Background\nA checkered tiling of a rectangular grid is a tiling using some polyominoes, where each region can be colored either black or white so that no two polyominoes sharing an edge has the same color. In graph-theoretic terms, the chromatic number of the adjacency graph is...
This challenge is based on a sandbox post by user48538. Since he is no longer active on this site, I took over this challenge. apgsearch, the distributed soup search program for Conway's Game of Life and the search results database, Catagolue use apgcodes to classify and denote patterns. apgcodes themselves use the ex...
Here's a solution to parse a string in the extended Wechsler format and convert it into a 2D list representing the corresponding pattern: ```python def parse_wechsler(s): def decode_char(c): if c.isdigit(): # 0-9 return [int(b) for b in format(int(c), '05b')] elif 'a' <= c <= 'v': # a...
9,765
[ { "from": "human", "value": "This challenge is based on a sandbox post by user48538. Since he is no longer active on this site, I took over this challenge.\n\napgsearch, the distributed soup search program for Conway's Game of Life and the search results database, Catagolue use apgcodes to classify and deno...
Using one programming language write 5 single-line programs, each of which outputs a different line of the first verse to Harry Nilsson's 1972 song "Coconut" when run individually: Brother bought a coconut, he bought it for a dime His sister had another one, she paid it for a lime She put the lime in the coconut, she ...
Here are five single-line programs written in Python that output different lines from the first verse of Harry Nilsson's song "Coconut". The programs are optimized such that they can be arranged in multiple combinations while still producing the correct order of the verse when executed. ```python print('Brother bought...
14,874
[ { "from": "human", "value": "Using one programming language write 5 single-line programs, each of which outputs a different line of the first verse to Harry Nilsson's 1972 song \"Coconut\" when run individually:\n\nBrother bought a coconut, he bought it for a dime\nHis sister had another one, she paid it fo...