instruction
stringlengths
34
53.1k
completion
stringlengths
5
524k
__original_row_idx
int64
0
50k
conversations
listlengths
2
2
A SMILES (Simplified molecular-input line-entry system) string is a string that represents a chemical structure using ASCII characters. For example, water (\$H_2O\$) can be written in SMILES as H-O-H. However, for simplicity, the single bonds (-) and hydrogen atoms (H) are frequently omitted. Thus, a molecules with on...
Below is a short Python code that checks whether a given substructure in SMILES format is found within a larger molecule represented by a SMILES string. The code uses simple string containment checks to determine if the substructure exists in the molecule. ```python def is_substructure(molecule, substructure): ret...
34,994
[ { "from": "human", "value": "A SMILES (Simplified molecular-input line-entry system) string is a string that represents a chemical structure using ASCII characters. For example, water (\\$H_2O\\$) can be written in SMILES as H-O-H. \nHowever, for simplicity, the single bonds (-) and hydrogen atoms (H) are f...
This challenge is about the number of orderings which contain at most \$n\$ classes and at most \$k\$ of the \$k^{\text{th}}\$ class. One way to represent such an ordering is as a sequence of positive integers with these three restrictions: A number may only appear after all lower numbers have appeared All numbers whi...
Here's a Python solution that computes the values of the sequence \( a(n) \) as described in your challenge. The function `a(n)` generates the sequence up to \( n \) and returns it in a list. ```python def a(n): seq = [1] # a(0) for i in range(1, n + 1): seq.append(sum(seq[j] * (i ** (i - j)) for j in...
34,614
[ { "from": "human", "value": "This challenge is about the number of orderings which contain at most \\$n\\$ classes and at most \\$k\\$ of the \\$k^{\\text{th}}\\$ class.\nOne way to represent such an ordering is as a sequence of positive integers with these three restrictions:\n\nA number may only appear af...
I have a counter. It's a small device that looks like this: The display goes from 0000 to 9999. It has a little push-button at the top that increases the count by 1, and a little knob at the right whose purpose is to reset the counter back to 0. Now, the thing about the little knob is that if you turn it backwards, y...
To solve the problem of efficiently setting a counter to a desired 4-digit number using a combination of button pushes and knob advancements, we can think of this as a state-space search problem. The state consists of the current value of the counter, and we want to reach a target value with the least number of operati...
28,667
[ { "from": "human", "value": "I have a counter. It's a small device that looks like this: \n\nThe display goes from 0000 to 9999. It has a little push-button at the top that increases the count by 1, and a little knob at the right whose purpose is to reset the counter back to 0.\nNow, the thing about the lit...
Your program is given a string consisting entirely of lowercase letters at STDIN (or closest alternative). The program must then output a truthy or falsey value, depending on whether the input is valid romaji. Rules: It must be possible to divide the entire string into a sequence of kana without any leftover characte...
Here’s a concise solution in Python to check if a given string is valid romaji according to the rules you've specified: ```python def is_valid_romaji(s): # Define the valid kana sets valid_kana = set([ 'a', 'i', 'u', 'e', 'o', 'n', 'ba', 'bu', 'be', 'bo', 'bi', 'ga', 'gu', 'ge', 'go', '...
31,132
[ { "from": "human", "value": "Your program is given a string consisting entirely of lowercase letters at STDIN (or closest alternative). The program must then output a truthy or falsey value, depending on whether the input is valid romaji. \nRules:\n\nIt must be possible to divide the entire string into a se...
In this challenge, an infinitely proportional sequence is defined as a infinite sequence of positive integers such that: All positive integers are contained infinitely many times within the sequence. As more and more terms are added to the sequence, for all positive integers \$n\$, the ratio of the number of \$n\$s to...
Here's a solution in Python that generates an infinitely proportional sequence: ```python def seq(n): if n < 1: return 1 k = 1 while n >= k * k: n -= k * k k += 1 return k # To generate the first 100 terms of the sequence print([seq(i) for i in range(1, 101)]) ``` In this code...
37,436
[ { "from": "human", "value": "In this challenge, an infinitely proportional sequence is defined as a infinite sequence of positive integers such that:\n\nAll positive integers are contained infinitely many times within the sequence.\nAs more and more terms are added to the sequence, for all positive integers...
Given a positive integer as input, output that integer, but with its bits rotated two times to the right. Also, think of the number as a donut of bits, eg. 21 -> (10101). If all of the bits suddenly decided to move to the right, they would wrap around. eg. rRot(21) -> (11010) = 26. Do what i explained 2 times (at the s...
Here's a compact solution in Python that performs the desired bit rotation operation twice to the right on a positive integer input. This code efficiently rotates the bits and is designed for code-golfing, focusing on minimizing the byte count: ```python f=lambda n,n=n:0if n<1else((n>>2)+(n<<~(n.bit_length()-1)&3))%2*...
36,428
[ { "from": "human", "value": "Given a positive integer as input, output that integer, but with its bits rotated two times to the right. Also, think of the number as a donut of bits, eg. 21 -> (10101). If all of the bits suddenly decided to move to the right, they would wrap around. eg. rRot(21) -> (11010) = ...
Challenge For any two non-empty strings A and B, we define the following sequence : F(0) = A F(1) = B F(n) = F(n-1) + F(n-2) Where + denotates the standard string concatenation. The sequence for strings "A" and "B" starts with the following terms: A, B, BA, BAB, BABBA, ... Create a function or program that, when given...
Here is a Python solution that retrieves the I-th character of the infinite string sequence F(∞) defined by the problem statement. The program uses a recursive approach to calculate the lengths of the strings in the sequence without actually concatenating them, which helps in efficiently finding the character without c...
35,602
[ { "from": "human", "value": "Challenge\nFor any two non-empty strings A and B, we define the following sequence :\nF(0) = A\nF(1) = B\nF(n) = F(n-1) + F(n-2)\n\nWhere + denotates the standard string concatenation.\nThe sequence for strings \"A\" and \"B\" starts with the following terms: A, B, BA, BAB, BABB...
If you're sad, that's wrong. We need to scrub out ALL sadness. This is a sad face, for reference: ...... .S..S. ........ ...SS... ..SS..SS.. .S......S. ........ Where S is a consistent pixel, . is any pixel other than S, and is any pixel. Note that the sad face is not a perfect square, only the . shoul...
To tackle the problem of scrubbing out all "sad faces" from an image, we can approach it in a structured way. Below is a Python-based solution to identify and replace the "S" characters in the sad face pattern with random data. This code assumes the input is a 2D list or a similar structure representing an image, where...
32,403
[ { "from": "human", "value": "If you're sad, that's wrong. We need to scrub out ALL sadness.\nThis is a sad face, for reference:\n ...... \n .S..S. \n ........ \n ...SS... \n..SS..SS..\n.S......S.\n ........ \n\nWhere S is a consistent pixel, . is any pixel other than S, and is any pixel. Note that the...
Not to be confused with Find the factorial! Introduction The factorial of an integer n can be calculated by $$n!=n\times(n-1)\times(n-2)\times(...)\times2\times1$$ This is relatively easy and nothing new. However, factorials can be extended to double factorials, such that $$n!!=n\times(n-2)\times(n-4)\times(...)\times4...
Here's a Python implementation of the repeated factorial function that follows the rules outlined in the challenge. The implementation reads input either as a string with factorials or as two integers, calculates the repeated factorial, and prints the result. ### Implementation ```python def repeated_factorial(n, k=N...
34,177
[ { "from": "human", "value": "Not to be confused with Find the factorial!\nIntroduction\nThe factorial of an integer n can be calculated by\n$$n!=n\\times(n-1)\\times(n-2)\\times(...)\\times2\\times1$$\nThis is relatively easy and nothing new. However, factorials can be extended to double factorials, such th...
Suppose you have two six-sided dice. Roll the pair 100 times, calculating the sum of each pair. Print out the number of times each sum occurred. If a sum was never rolled, you must include a zero or some way to identify that that particular sum was never rolled. Example Output: [3, 3, 9, 11, 15, 15, 11, 15, 7, 8, 3] ...
To simulate rolling two six-sided dice 100 times and counting the sums, we first need to understand the possible sums that can occur when rolling two dice. The sums can range from 2 (1+1) to 12 (6+6). When calculating the frequency of each possible sum, the index in the resulting list will correspond to the sum minus...
31,137
[ { "from": "human", "value": "Suppose you have two six-sided dice. Roll the pair 100 times, calculating the sum of each pair. Print out the number of times each sum occurred. \nIf a sum was never rolled, you must include a zero or some way to identify that that particular sum was never rolled.\nExample Outpu...
If you cannot see this post, you can use this image Your task is to create a markdown parser that outputs Unicode. It should support , , , and ̲̲̲̲̲̲̲̲̲. Every alphabetical character should be converted into Math Sans. This includes the characters before an underline character. Underlines: Add a ̲ character (code point...
Certainly! Below is a Python implementation of a markdown parser that converts text according to the rules you specified: ```python def md_parser(text): # Helper functions for conversion def to_math_sans(c): return chr(120224 + ord(c) - ord('a')) if 'a' <= c <= 'z' else \ chr(120224 + or...
32,793
[ { "from": "human", "value": "If you cannot see this post, you can use this image\nYour task is to create a markdown parser that outputs Unicode. It should support , , , and ̲̲̲̲̲̲̲̲̲.\nEvery alphabetical character should be converted into Math Sans. This includes the characters before an underline character...
Consider, for a given positive integer \$k\$, the sequence \$(a, a+1, a+2, ..., a+k)\$, where \$a\$ is some positive integer. Is there ever a pair \$a, k\$ such that for each element \$a+i\$ in the sequence, either \$\gcd(a, a+i)\$ or \$\gcd(a+i, a+k)\$ are greater than 1? This was investigated by Alan R. Woods as part...
Here’s a Python solution to generate an Erdős–Woods number \( a \) for a given \( k \). The solution leverages a precomputed list of \( a \) values for known Erdős–Woods numbers. Given that finding an Erdős–Woods number can be computationally intensive, this approach allows you to quickly retrieve results from predefin...
35,831
[ { "from": "human", "value": "Consider, for a given positive integer \\$k\\$, the sequence \\$(a, a+1, a+2, ..., a+k)\\$, where \\$a\\$ is some positive integer. Is there ever a pair \\$a, k\\$ such that for each element \\$a+i\\$ in the sequence, either \\$\\gcd(a, a+i)\\$ or \\$\\gcd(a+i, a+k)\\$ are great...
No, I don't mean \$\phi = 1.618...\$ and \$π = 3.14159...\$. I mean the functions. \$\phi(x)\$ is the number of integers less than or equal to \$x\$ that are relatively prime to \$x\$. \$π(x)\$ is the number of primes less than or equal to \$x\$. Let's say that "not pi" is then \$\bar{\pi}(x)\$ and define it to be the...
## Python, 126 bytes ```python def φ(n):c=0 for i in range(1,n+1): if n%i==0: c+=1 if i==1 or i==n:c-=1 return c def π(n):c=0 for i in range(2,n+1): if all(i%j for j in range(2,int(i**.5)+1)):c+=1 return c def notπ(n):return n-π(n) for x in range(1,101):print(x,φ(notπ(x))) ``` This Python code implement...
37,842
[ { "from": "human", "value": "No, I don't mean \\$\\phi = 1.618...\\$ and \\$π = 3.14159...\\$. I mean the functions.\n\n\\$\\phi(x)\\$ is the number of integers less than or equal to \\$x\\$ that are relatively prime to \\$x\\$.\n\\$π(x)\\$ is the number of primes less than or equal to \\$x\\$.\nLet's say t...
(This is A065825.) The sequence defaults apply, so you can pick another format other than this one. Given an input integer n, find the smallest number k so that there exists an n-item subset of {1,...,k} where no three items form an arithmetic progression. Procedure Here, we calculate A065825(9). We assume you have alr...
To solve the problem of finding the smallest number \( k \) such that there exists an \( n \)-item subset of \( \{1, 2, \ldots, k\} \) with no three items forming an arithmetic progression, we will utilize the provided reference program output of the sequence \( A065825(n) \). The sequence \( A065825(n) \) specifies t...
34,871
[ { "from": "human", "value": "(This is A065825.) The sequence defaults apply, so you can pick another format other than this one.\nGiven an input integer n, find the smallest number k so that there exists an n-item subset of {1,...,k} where no three items form an arithmetic progression.\nProcedure\nHere, we ...
Definition If you take the sequence of positive integer squares, and concatenate them into a string of digits (i.e. 149162536496481100...), an "early bird" square is one that can be found in this string ahead of its natural position. For example, 72 (the number 49), can be found at an offset of 2 in the string, althoug...
To solve the problem of finding the nth "early bird" square, we need to follow these steps: 1. **Generate the sequence of squares:** We start by creating a sequence of perfect squares, i.e., \(1^2, 2^2, 3^2, \ldots\), and concatenate their decimal representations into a single string. 2. **Track the positions:** For ...
32,345
[ { "from": "human", "value": "Definition\nIf you take the sequence of positive integer squares, and concatenate them into a string of digits (i.e. 149162536496481100...), an \"early bird\" square is one that can be found in this string ahead of its natural position.\nFor example, 72 (the number 49), can be f...
This is the cops' thread. The robbers' thread goes here. The last cops-and-robbers thread was already 4 months ago. The cop's task The cop's task is to write a program/function that takes a positive (or non-negative) integer and outputs/returns another integer. The cop must state it if the program is intolerant toward...
Lua, 80 bytes Output: a(0) returns 1 a(5) returns 5 Code (# marks unrevealed characters): function a(n) if n==0 then return # else return a(n-1) + a(n-2) end end This sequence corresponds to the Fibonacci sequence as defined in the On-Line Encyclopedia of Integer Se...
38,852
[ { "from": "human", "value": "This is the cops' thread. The robbers' thread goes here.\nThe last cops-and-robbers thread was already 4 months ago.\nThe cop's task\n\nThe cop's task is to write a program/function that takes a positive (or non-negative) integer and outputs/returns another integer.\nThe cop mus...
Inspired by the recent 3Blue1Brown video Consider, for some positive integer \$n\$, the set \$\{1, 2, ..., n\}\$ and its subsets. For example, for \$n = 3\$, we have $$\emptyset, \{1\}, \{2\}, \{3\}, \{1,2\}, \{1,3\}, \{2,3\}, \{1,2,3\}$$ If we take the sum of these subsets, we can then ask ourselves the following ques...
Here's a short Python solution that counts the number of subsets of the set \(\{1, 2, \ldots, n\}\) whose sums are divisible by a given integer \(k\). This solution uses dynamic programming to efficiently compute the required count: ```python def count_subsets_divisible_by_k(n, k): dp = [0] * k dp[0] = 1 # Th...
36,553
[ { "from": "human", "value": "Inspired by the recent 3Blue1Brown video\nConsider, for some positive integer \\$n\\$, the set \\$\\{1, 2, ..., n\\}\\$ and its subsets. For example, for \\$n = 3\\$, we have\n$$\\emptyset, \\{1\\}, \\{2\\}, \\{3\\}, \\{1,2\\}, \\{1,3\\}, \\{2,3\\}, \\{1,2,3\\}$$\nIf we take the...
Introduction Let's define a new arithmetical operation, which I call zipper multiplication. To zipper multiply two nonnegative integers, you add leading zeros to make the lengths match, multiply the corresponding base-10 digits of the numbers, add leading zeros to the results to get 2-digit numbers, concatenate them, a...
Here's a Python function that implements the described "zipper multiplication" for two integers, including support for arbitrary large integers: ```python def zipper_multiply(a, b): # Convert to strings to handle digit-wise operations sa, sb = str(a).lstrip('-'), str(b).lstrip('-') # Determine the sig...
30,077
[ { "from": "human", "value": "Introduction\nLet's define a new arithmetical operation, which I call zipper multiplication.\nTo zipper multiply two nonnegative integers, you add leading zeros to make the lengths match, multiply the corresponding base-10 digits of the numbers, add leading zeros to the results ...
Background A snake is a path over the cells of a square grid, such that it doesn't touch itself on a side of a unit square. Touching at a corner is allowed. An example snake: ##.#. .#.## ##..# #.### ###.. Some example non-snakes: ###.# #.#.# ##### .#... .#### ### .#. ## ## Challenge Given an empty grid with the two...
Here's a solution in Python that finds the longest snake in a given grid with specified endpoints. The implementation leverages Depth-First Search (DFS) to explore potential snake paths while respecting the "no touching" rule. ```python def longest_snake(grid): from collections import deque # Directions f...
34,969
[ { "from": "human", "value": "Background\nA snake is a path over the cells of a square grid, such that it doesn't touch itself on a side of a unit square. Touching at a corner is allowed.\nAn example snake:\n##.#.\n.#.##\n##..#\n#.###\n###..\n\nSome example non-snakes:\n###.#\n#.#.#\n#####\n.#...\n.####\n\n#...
You want to see how quickly the ratio of two consecutive Fibonacci numbers converges on φ. Phi, known by the nickname "the golden ratio" and written as \$φ\$, is an irrational number, almost as popular as π and e. The exact value of \$φ\$ is \$\frac {1 + \sqrt 5} 2 = 1.618...\$ The Fibonacci sequence is a recursive ser...
Here’s a concise solution in Python to determine how closely the ratio of two consecutive Fibonacci numbers converges to the golden ratio (φ). The code is designed to be as short as possible while still being functional and readable. ```python n=int(input()) a,b=0,1 for _ in range(n):a,b=b,a+b φ=(1+5**.5)/2 r=b/a x=0 ...
35,669
[ { "from": "human", "value": "You want to see how quickly the ratio of two consecutive Fibonacci numbers converges on φ.\nPhi, known by the nickname \"the golden ratio\" and written as \\$φ\\$, is an irrational number, almost as popular as π and e. The exact value of \\$φ\\$ is \\$\\frac {1 + \\sqrt 5} 2 = 1...
The title pretty much describes it all. Given as input a \$n \times m\$ matrix and an integer \$i\$ create a complete function/program that returns the matrix \$i\$ times clockwise rotated by \$90^\circ\$. Rules: as matrix you can use any convenient representation you like e.g. a list of lists etc... matrix values can...
Here’s a Python function that rotates a given \(n \times m\) matrix \(i\) times clockwise by \(90^\circ\): ```python def rotate_matrix(i, matrix): # Calculate effective rotations since 4 rotations is a full circle i %= 4 if i == 0: return matrix for _ in range(i): matrix = [list(row) fo...
34,490
[ { "from": "human", "value": "The title pretty much describes it all. Given as input a \\$n \\times m\\$ matrix and an integer \\$i\\$ create a complete function/program that returns the matrix \\$i\\$ times clockwise rotated by \\$90^\\circ\\$.\nRules:\n\nas matrix you can use any convenient representation ...
For the purposes of this question, a deck of cards is formatted in this way: [ "AS", "2S", "3S", "4S", "5S", "6S", "7S", "8S", "9S", "10S", "JS", "QS", "KS", "AD", "2D", "3D", "4D", "5D", "6D", "7D", "8D", "9D", "10D", "JD", "QD", "KD", "AH", "2H", "3H", "4H", "5H", "6H", "7H", "8H", "9H", "10H", "JH", "QH", "K...
Below is a Python implementation of a Superb Shuffle™ for a deck of cards. This implementation ensures that no two cards of the same suit are adjacent, no two cards of the same value are adjacent, and no adjacent values are in succession as defined in the prompt. ```python import random def superb_shuffle(deck): ...
33,159
[ { "from": "human", "value": "For the purposes of this question, a deck of cards is formatted in this way:\n[\n \"AS\", \"2S\", \"3S\", \"4S\", \"5S\", \"6S\", \"7S\", \"8S\", \"9S\", \"10S\", \"JS\", \"QS\", \"KS\", \n \"AD\", \"2D\", \"3D\", \"4D\", \"5D\", \"6D\", \"7D\", \"8D\", \"9D\", \"10D\", \"JD\"...
Background We've studied at least five different types of numbers based on the IDs of different users on this site. Why not study another? My user ID is \$91030_{10}\$. Its binary representation is \$10110001110010110_2\$, a representation which has an interesting property of its own: One option for the longest palind...
Here is a Python solution to check if a number is a sporeball number according to the defined properties: ```python def is_sporeball(n): b = bin(n)[2:] def longest_palindrome(s): l = len(s) longest = [] for i in range(l): for j in range(i + 1, l + 1): sub = s...
35,200
[ { "from": "human", "value": "Background\nWe've studied at least five different types of numbers based on the IDs of different users on this site. Why not study another?\nMy user ID is \\$91030_{10}\\$. Its binary representation is \\$10110001110010110_2\\$, a representation which has an interesting property...
Introduction A hypercube/tesseract is the 4 dimensional equivalent of a normal cube. It's made by taking a cube net, extending it to the 3rd dimension, then – using the 4th dimension – folding it into a hypercube. It's basically a cube, where each side is a cube. To create a hypercube, you need 16 4d vectors (a vector ...
Here's a Python implementation to visualize the hypercube based on the specifications provided. The code will generate an image of the hypercube after applying the specified rotations. This solution uses the `numpy` library for matrix operations and the `matplotlib` library for visualization. ```python import numpy as...
29,037
[ { "from": "human", "value": "Introduction\nA hypercube/tesseract is the 4 dimensional equivalent of a normal cube. It's made by taking a cube net, extending it to the 3rd dimension, then – using the 4th dimension – folding it into a hypercube. It's basically a cube, where each side is a cube.\nTo create a h...
A rigid transformation of a square array is a mapping from square arrays of a certain size to square arrays of the same size, which rearranges the elements of the array such that the distance to each other element remains the same. If you printed out the matrix on a sheet of paper these are the transforms you could do ...
Here’s a concise solution in Python that counts the number of unique rigid transformations (considering rotations and flips) of a square matrix: ```python def unique_transforms(m): def rotate(a): return [list(row) for row in zip(*a[::-1])] def mirror(a): return [row[::-1] for row in a] ...
36,282
[ { "from": "human", "value": "A rigid transformation of a square array is a mapping from square arrays of a certain size to square arrays of the same size, which rearranges the elements of the array such that the distance to each other element remains the same.\nIf you printed out the matrix on a sheet of pa...
When I write documentation, comments, etc. I love making ASCII tables. They usually end up looking pretty good, but I always feel that they could look even better - especially since UTF-8/Unicode includes the box drawing characters. However, these characters are very burdensome to use, requiring several key presses to ...
Here is a Python solution to the challenge, which converts ASCII tables to their corresponding UTF-8 box-drawing character representations. The solution has been optimized for brevity while maintaining functionality. ```python def convert_table(ascii_table): table = ascii_table.splitlines() result = [] for...
33,505
[ { "from": "human", "value": "When I write documentation, comments, etc. I love making ASCII tables. They usually end up looking pretty good, but I always feel that they could look even better - especially since UTF-8/Unicode includes the box drawing characters. However, these characters are very burdensome ...
Ohm's law tells us that the current (I) in amps flowing through a resistance (R) in Ohms when a voltage (V) is applied across it is given as follows: V = I / R Similarly the power (P) in watts dissipated by that resistance is given by: P = V * I By rearrangement and substitution, formulae may be derived for calculati...
To solve the problem of calculating the two missing electrical quantities given two known quantities (Voltage, Current, Power, and Resistance), we can derive the necessary equations from Ohm's law and the power formula. Let's break it down step by step: 1. **Understanding the Relationships**: - Ohm's Law: \( V = I ...
28,537
[ { "from": "human", "value": "Ohm's law tells us that the current (I) in amps flowing through a resistance (R) in Ohms when a voltage (V) is applied across it is given as follows:\nV = I / R\n\nSimilarly the power (P) in watts dissipated by that resistance is given by:\nP = V * I\n\nBy rearrangement and subs...
How many atoms in the hydrocarbon? A hydrocarbon is a chemical compound which consists of only hydrogen and carbon atoms. For this challenge, we will only consider the three simplest kinds of hydrocarbons: alkanes, alkenes, and alkynes with no branches. An alkane with \$n\$ carbon atoms contains \$2n+2\$ hydrogen atoms...
Here's a Python function that meets the requirements of your challenge. This function takes a hydrocarbon name as input and outputs the number of carbon and hydrogen atoms based on the hydrocarbon type. ```python def hydrocarbon_count(name): name = name.lower() prefixes = {'meth': 1, 'eth': 2, 'prop': 3, 'but'...
34,506
[ { "from": "human", "value": "How many atoms in the hydrocarbon?\nA hydrocarbon is a chemical compound which consists of only hydrogen and carbon atoms. For this challenge, we will only consider the three simplest kinds of hydrocarbons: alkanes, alkenes, and alkynes with no branches.\nAn alkane with \\$n\\$ ...
Background Binary Sudoku, also known as Takuzu, Binario, and Tic-Tac-Logic, is a puzzle where the objective is to fill a rectangular grid with two symbols (0s and 1s for this challenge) under the following constraints: Each row/column cannot have a substring of 000 or 111, i.e. one symbol cannot appear three times in ...
Here is a concise implementation in Python to compute the number of distinct valid Binary Sudoku rows of length \(2n\) without any three consecutive 0s or 1s: ```python def binary_sudoku(n): if n == 1: return 2 dp = [[0] * 3 for _ in range(n + 1)] dp[1][0] = dp[1][1] = 1 for i in range(2, n + 1...
34,743
[ { "from": "human", "value": "Background\nBinary Sudoku, also known as Takuzu, Binario, and Tic-Tac-Logic, is a puzzle where the objective is to fill a rectangular grid with two symbols (0s and 1s for this challenge) under the following constraints:\n\nEach row/column cannot have a substring of 000 or 111, i...
A polyglot is a program that runs in several languages. Your challenge is to: Choose at least two languages (Different versions count as different languages) Create a program or function that takes several positive integers (one for each language you chose) and returns a program that: Is a valid program in all of those...
Let's create a polyglot program using Python and JavaScript. The generated program will print different numbers depending on the language it's executed in. ### Chosen Languages: 1. **Python** 2. **JavaScript** ### Requirements: - The program will take two integers, one for each language. - When run in Python, it wil...
35,716
[ { "from": "human", "value": "A polyglot is a program that runs in several languages.\nYour challenge is to:\nChoose at least two languages (Different versions count as different languages)\nCreate a program or function that takes several positive integers (one for each language you chose) and returns a prog...
We all know scoring by characters is ripe for abuse. Let's prove this. The Challenge Output the following: "m8V}G=D@7G1lAI,v08` #(hNb0A8T!g;==SVaG5~ g"jUF!bmRY(3I@na?2S{ fJVzo/GQYU%ybpfUq3aG Yza[jc,WJ$bP^7r};Da} V-!Z+Nk:`/poc}d/X:G\ sWX{dbAUv6,i]%RG$hRp ),bd+?/{U1tU[;<;u.Nk ZFPIOzJ/HimL!nexc,ls HM%k3D$n2|R,8L?'eI_n qs....
To tackle this challenge, we can create a function in Python that outputs the required string. Python uses UTF-8 encoding by default, which is beneficial for our purposes. Here is the solution: ```python def output_string(): return ( "m8V}G=D@7G1lAI,v08`\n" "#(hNb0A8T!g;==SVaG5~\n" 'g"jUF!b...
35,307
[ { "from": "human", "value": "We all know scoring by characters is ripe for abuse. Let's prove this.\nThe Challenge\nOutput the following:\n\"m8V}G=D@7G1lAI,v08`\n#(hNb0A8T!g;==SVaG5~\ng\"jUF!bmRY(3I@na?2S{\nfJVzo/GQYU%ybpfUq3aG\nYza[jc,WJ$bP^7r};Da}\nV-!Z+Nk:`/poc}d/X:G\\\nsWX{dbAUv6,i]%RG$hRp\n),bd+?/{U1tU...
Determining whether a Language is Turing Complete is very important when designing a language. It is a also a pretty difficult task for a lot of esoteric programming languages to begin with, but lets kick it up a notch. Lets make some programming languages that are so hard to prove Turing Complete that even the best ...
## Language: "CollatzScript" ### Specification **Overview:** CollatzScript is an esoteric programming language that operates on the Collatz Conjecture, a famous unsolved problem in mathematics. The language's Turing completeness is directly tied to the truth of the Collatz Conjecture. If the conjecture holds (i.e., e...
30,532
[ { "from": "human", "value": "Determining whether a Language is Turing Complete is very important when designing a language. It is a also a pretty difficult task for a lot of esoteric programming languages to begin with, but lets kick it up a notch. Lets make some programming languages that are so hard to ...
In Minecraft, the default item textures are all reasonably simple 16×16 pixel images, which makes them seem ideal for golfing. Below are simplified textures of the five "core" diamond tools in Minecraft: pickaxe, shovel, axe, sword, and hoe. The images shown are enlarged to show their detail. Click on an image to view ...
Here's a simple Python program that generates a PNG image of a Minecraft diamond pickaxe with the specified colors. You can run this code in a Python environment with the `Pillow` library installed to generate the image. ```python from PIL import Image # Define the colors in RGB format colors = { 'background': (7...
26,882
[ { "from": "human", "value": "In Minecraft, the default item textures are all reasonably simple 16×16 pixel images, which makes them seem ideal for golfing.\nBelow are simplified textures of the five \"core\" diamond tools in Minecraft: pickaxe, shovel, axe, sword, and hoe.\nThe images shown are enlarged to ...
The title is an homage of the Natural Number Game, which is a nice interactive tutorial into proving certain properties of natural numbers in Lean. Given that the previous two were slightly too involved (either mathematically or technically) for newcomers to Lean (i.e. the vast majority of CGCC community), I decided to...
To prove the theorem `rev_rev` stating that reversing a list twice gives back the original list, we can leverage the lemmas you suggested: `append_nil`, `append_assoc`, and `rev_append`. Here’s the solution that incorporates these lemmas to prove `rev_rev` in a concise manner. The code assumes the provided definition...
36,022
[ { "from": "human", "value": "The title is an homage of the Natural Number Game, which is a nice interactive tutorial into proving certain properties of natural numbers in Lean.\nGiven that the previous two were slightly too involved (either mathematically or technically) for newcomers to Lean (i.e. the vast...
Challenge This challenge is pretty simple: Output the total number of possible Tweets. Given the fact that \$1{,}114{,}112\$ Unicode characters exist, and Tweets can be up to \$280\$ characters long, we calculate this number like so: $$\sum_{l=1}^{280}1{,}114{,}112^l$$ Calculated, this number becomes: 13806352273767118...
To calculate the total number of possible Tweets up to 280 characters long using 1,114,112 Unicode characters, we use the formula: \[ \text{Total Tweets} = \sum_{l=1}^{280} 1{,}114{,}112^l = 1{,}114{,}112^1 + 1{,}114{,}112^2 + \ldots + 1{,}114{,}112^{280} \] This is a geometric series where the first term \(a = 1{,}1...
35,531
[ { "from": "human", "value": "Challenge\nThis challenge is pretty simple: Output the total number of possible Tweets. Given the fact that \\$1{,}114{,}112\\$ Unicode characters exist, and Tweets can be up to \\$280\\$ characters long, we calculate this number like so:\n$$\\sum_{l=1}^{280}1{,}114{,}112^l$$\nC...
We say a string is non-discriminating if each of the string's characters appears the same number of times and at least twice. Examples "aa!1 1 !a !1" is non-discriminating because each of the characters , !, a and 1 appear three times. "abbaabb" is not non-discriminating because b appears more often than a. "abc" is ...
To create a function that checks if a given string is non-discriminating, we need to ensure that each character in the string appears the same number of times, and that each character appears at least twice. The following Python code achieves this: ```python def is_non_discriminating(s): from collections import Co...
32,746
[ { "from": "human", "value": "We say a string is non-discriminating if each of the string's characters appears the same number of times and at least twice.\nExamples\n\n\"aa!1 1 !a !1\" is non-discriminating because each of the characters , !, a and 1 appear three times.\n\"abbaabb\" is not non-discriminati...
Inspired by: Find an Unrelated Number Challenge Given two positive integers as input, output the mathematical operations that can be used on those inputs to generate every number from 1 to n inclusive where n is the smallest prime greater than the sum of the two inputs. If the number cannot be generated using the list...
Here's a Python solution to the "Find an Unrelated Number" challenge that generates the required output. The program calculates the smallest prime greater than the sum of two given integers, performs various operations, and determines which numbers from 1 to that prime can be generated. ```python def is_prime(num): ...
31,149
[ { "from": "human", "value": "Inspired by: Find an Unrelated Number\n\nChallenge\nGiven two positive integers as input, output the mathematical operations that can be used on those inputs to generate every number from 1 to n inclusive where n is the smallest prime greater than the sum of the two inputs. If t...
Introduction to Mahjong tiles Mahjong (麻雀) is a board game that originates from China. Mahjong tiles used in this challenge are in Unicode points U+1F000 – U+1F021: They are categorized as: Winds (風牌): (East Wind), (South Wind), (West Wind), (North Wind) Dragons (三元牌): (Red Dragon), (Green Dragon), (White Dragon) Te...
To create a program that determines the number of shantens for a given set of Mahjong tiles, we can outline the steps required to achieve this in a concise manner. Here’s a conceptual breakdown of the task. ### Steps to Determine Shantens in Mahjong: 1. **Input Validation:** - Ensure exactly 13 tiles are provided....
34,648
[ { "from": "human", "value": "Introduction to Mahjong tiles\nMahjong (麻雀) is a board game that originates from China. Mahjong tiles used in this challenge are in Unicode points U+1F000 – U+1F021:\n\n\nThey are categorized as:\n\nWinds (風牌): (East Wind), (South Wind), (West Wind), (North Wind)\nDragons (三元牌):...
As someone who can't be bothered to look at their pentominos to see if it makes a rectangular shape, I've decided to make you write a program that does it. Your task Given some input split by newlines containing 12 unique characters, decide if it is a valid solution. A valid solution MUST Have 5 of each character (exc...
To solve the problem of validating a configuration of pentominos, we will create a Python function that will check the conditions you've specified. Here's a detailed breakdown of how to approach this problem: 1. **Input Reading**: We need to read multiline input and ensure it contains exactly 12 unique characters. 2....
27,711
[ { "from": "human", "value": "As someone who can't be bothered to look at their pentominos to see if it makes a rectangular shape, I've decided to make you write a program that does it.\nYour task\nGiven some input split by newlines containing 12 unique characters, decide if it is a valid solution.\nA valid ...
Part of Advent of Code Golf 2021 event. See the linked meta post for details. Related to AoC2017 Day 16. I'm using the wording from my Puzzling SE puzzle based on the same AoC challenge instead of the original AoC one for clarity. \$n\$ people numbered \$1, 2, \cdots, n\$ are standing in line in the order of their cor...
Here's a concise solution to determine if a program can have a given period \(m\) for \(n\) people using Python: ```python def f(n,m): return m>0and m<=n*(n-1)//2and(n&-n)%(m&-m)<1 ``` ### Explanation: 1. **`m > 0`**: The period must be a positive integer. 2. **`m <= n*(n-1)//2`**: The maximum number of swaps is ach...
36,136
[ { "from": "human", "value": "Part of Advent of Code Golf 2021 event. See the linked meta post for details.\nRelated to AoC2017 Day 16. I'm using the wording from my Puzzling SE puzzle based on the same AoC challenge instead of the original AoC one for clarity.\n\n\\$n\\$ people numbered \\$1, 2, \\cdots, n\...
Problem Starting with a set of 10 coins at the start where all coins are tails up, and given n number of integers \$x_1, x_2, x_3... x_n\$ representing n rounds of coin flipping. At each round, we randomly flip \$x_i\$ number of coins at random. i.e Coins that were heads become tails, and vice versa. Within each round,...
To solve this problem, we need to calculate the expected number of heads after performing a series of coin flips based on the given list of integers. Each integer represents the number of coins to flip in that round, and every coin starts in the tails position (0 heads initially). The key insight is that when we flip...
35,978
[ { "from": "human", "value": "Problem\nStarting with a set of 10 coins at the start where all coins are tails up, and given n number of integers \\$x_1, x_2, x_3... x_n\\$ representing n rounds of coin flipping.\nAt each round, we randomly flip \\$x_i\\$ number of coins at random. i.e Coins that were heads b...
Input is a single integer in ascending digit order. The only valid inputs are: 12 123 1234 12345 123456 1234567 12345678 123456789 The only valid output is an array (set; list) of length equal to the factorial of input: Input - Factorial of input - Output array length 12 -> 1*2 -> 2 123 -> 1*2*3 -> 6 1234 -> 1*2*3*4 ->...
To tackle this problem, we need to generate all permutations of a given integer represented as a string of digits in ascending order. We'll then filter these permutations to ensure they fall within the required range and meet the criteria outlined. Let's go through the algorithm step-by-step. ### Steps of the Algorith...
33,557
[ { "from": "human", "value": "Input is a single integer in ascending digit order.\nThe only valid inputs are:\n12\n123\n1234\n12345\n123456\n1234567\n12345678\n123456789\nThe only valid output is an array (set; list) of length equal to the factorial of input:\nInput - Factorial of input - Output array length...
Write a program or function that takes an array of non-negative integers as input and outputs a set of vectors/arrays with the elements of the input array in order, split so that each vector sums up to 15. If the sum of the first N elements doesn't "hit 15", then the number that made it pass 15 must be cut off, and the...
## Python, 141 bytes ```python def split_to_fifteen(arr): res, curr, rem = [], [], 0 for x in arr: if curr and sum(curr) + x > 15: rem = sum(curr) + x - 15 curr.append(x) curr = curr[:-1] + [rem] curr.append(x) if sum(curr) == 15: res.appe...
37,971
[ { "from": "human", "value": "Write a program or function that takes an array of non-negative integers as input and outputs a set of vectors/arrays with the elements of the input array in order, split so that each vector sums up to 15. If the sum of the first N elements doesn't \"hit 15\", then the number th...
Given a positive number \$n\$, find the number of alkanes with \$n\$ carbon atoms, ignoring stereoisomers; or equivalently, the number of unlabeled trees with \$n\$ nodes, such that every node has degree \$\le 4\$. This is OEIS sequence A000602. See also: Paraffins - Rosetta Code Example For \$n = 7\$, the answer is \...
To find the number of alkanes (or unlabeled trees) with a given number of carbon atoms \( n \) (up to 20, based on your input), we can simply map each value of \( n \) to its corresponding count of alkane isomers as given in the OEIS sequence A000602. Here are the counts for \( n = 0 \) to \( n = 20 \): ```plaintext ...
33,733
[ { "from": "human", "value": "Given a positive number \\$n\\$, find the number of alkanes with \\$n\\$ carbon atoms, ignoring stereoisomers; or equivalently, the number of unlabeled trees with \\$n\\$ nodes, such that every node has degree \\$\\le 4\\$.\nThis is OEIS sequence A000602. \nSee also: Paraffins -...
You must write a program that takes an encrypted string and decrypt it according to specific rules and then print it out. Decryption will occur by performing two operations. Sample Input Argument 1 (the encrypted string) HGJILKBADCFE Operation 1: Swap the first half of the string with the second half, which should lea...
Your attempt to solve the decryption problem is on the right track, but there are a few adjustments needed to ensure it works correctly. Below is the revised Python program that performs the necessary decryption steps as outlined in your prompt: 1. **Swap the first half of the string with the second half.** 2. **Swap ...
35,206
[ { "from": "human", "value": "You must write a program that takes an encrypted string and decrypt it according to specific rules and then print it out. Decryption will occur by performing two operations.\nSample Input Argument 1 (the encrypted string)\nHGJILKBADCFE\n\nOperation 1:\nSwap the first half of the...
Introduction A picross, also known as a nonogram, is a logic puzzle in which the player is given an initially blank grid and must shade in particular boxes on the grid to reveal an image. Numbers are written on the top and the left side, and they explain the image's coloration: each number corresponds to an unbroken li...
Here's a solution to the Picross logic puzzle problem using Python: ```python def solve(hints, row): n = len(row) m = sum(hints) + len(hints) - 1 # Create a function to check the possible positions for the hints def can_place(start, hints): if start + sum(hints) + len(hints) - 1 > n: ...
34,899
[ { "from": "human", "value": "Introduction\nA picross, also known as a nonogram, is a logic puzzle in which the player is given an initially blank grid and must shade in particular boxes on the grid to reveal an image. Numbers are written on the top and the left side, and they explain the image's coloration:...
Given a level from a simple platform game, your task is to make a program or function to determine if a level is winnable. Platform game levels are 4 characters tall and any number of characters wide. There is exactly one platform for each horizontal space in a level: ======= = == = = ...
Here's a solution in Python that determines if a given platform game level is winnable. The input is provided as a list of strings, where each string represents a row of the level. The program uses a breadth-first search (BFS) approach to explore possible jumps from the starting platform to the ending platform. ```pyt...
34,500
[ { "from": "human", "value": "Given a level from a simple platform game, your task is to make a program or function to determine if a level is winnable. Platform game levels are 4 characters tall and any number of characters wide. There is exactly one platform for each horizontal space in a level:\n ...
Introduction On 30 May 2020, NASA and SpaceX launched a crewed rocket to the international space station on the SpaceX Demo 2 mission. This is the first time humans have been launched into orbit from American soil since the retiring of the Space Shuttle in 2011, and the first time ever that a private company has launch...
Here's a concise SVG representation of the NASA worm logo that adheres to your specifications. You can simply copy and paste this code into an HTML file and open it in a web browser to view the logo. ```html <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 2000 700" fill="#d50000"> <path d="M110 600V215a125 125 ...
34,980
[ { "from": "human", "value": "Introduction\nOn 30 May 2020, NASA and SpaceX launched a crewed rocket to the international space station on the SpaceX Demo 2 mission. This is the first time humans have been launched into orbit from American soil since the retiring of the Space Shuttle in 2011, and the first t...
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 Python solution that implements the generalized XOR for two positive double-precision floating-point numbers as described in the challenge: ```python def xor_floats(a, b): # Get the binary representation of the floats bin_a = bin(int.from_bytes(a.hex().encode(), 'big')) bin_b = bin(int.from_bytes...
36,526
[ { "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...
I have a cake shop that specialises in birthday cakes. The cakes that I sell must have candles placed in a circle. You would probably think I can just divide 360° by the number of candles, but the machine for placing candles is quite unique; it uses a list of numbers representing positions of candles, placing them one-...
Here is a Python function to generate the sequence based on your requirements. The function can return either a list of the first `n` terms or the `n`th term based on the input: ```python def candle_positions(n): positions = [] for i in range(n): if i == 0: positions.append("0") els...
36,504
[ { "from": "human", "value": "I have a cake shop that specialises in birthday cakes. The cakes that I sell must have candles placed in a circle. You would probably think I can just divide 360° by the number of candles, but the machine for placing candles is quite unique; it uses a list of numbers representin...
Well... there are 59 (now 60) questions tagged sorting, but no simple quicksorts. That must be fixed. For those unfamiliar with quicksort, here is a breakdown, courtesy of Wikipedia- Pick an element, called a pivot, from the array. Reorder the array so that all elements with values less than the pivot come before the...
## Python, 150 bytes Here's a quicksort implementation in Python that uses the median-of-three method to select the pivot and implements insertion sort for small sub-arrays: ```python import random def qsort(arr): if len(arr) <= 5: return sorted(arr) p = sorted([arr[0], arr[len(arr)//2], arr[-1]...
37,758
[ { "from": "human", "value": "Well... there are 59 (now 60) questions tagged sorting, but no simple quicksorts. \nThat must be fixed.\nFor those unfamiliar with quicksort, here is a breakdown, courtesy of Wikipedia-\n\nPick an element, called a pivot, from the array.\nReorder the array so that all elements w...
The Challenge Given a n x n matrix of integers with n >= 2 1 2 3 4 and a list of integers with exactly 2nelements [1,2,-3,-1] output the rotated matrix. This matrix is contructed in the following way: Take the first integer in the list and rotate the first row to the right by this value. Take the next integer and ...
Here's a Python solution that implements the challenge. This code reads an n x n matrix and a list of integers to perform the described rotations. The rotations can be both right/down and left/up depending on the integer values. ```python def rotate_matrix(matrix, rotations): n = len(matrix) def rotate_r...
28,518
[ { "from": "human", "value": "The Challenge\nGiven a n x n matrix of integers with n >= 2\n\n1 2\n3 4\n\nand a list of integers with exactly 2nelements\n\n[1,2,-3,-1]\n\noutput the rotated matrix. This matrix is contructed in the following way:\n\nTake the first integer in the list and rotate the first row t...
This challenge is based on the following puzzle: You are given an n by n grid with n cells marked. Your job is to the partition the grid into n parts where each part consists of exactly n cells, each containing exactly one marked cell. Example Here is a puzzle on the left and its (unique) solution on the right: Chall...
Here's a Python implementation of the described challenge. This solution effectively finds a valid partitioning of the grid based on the given marked cell coordinates: ```python def partition_grid(coords): n = len(coords) grid = set((x, y) for x in range(n) for y in range(n)) parts = [[] for _ in range(n)]...
33,752
[ { "from": "human", "value": "This challenge is based on the following puzzle: You are given an n by n grid with n cells marked. Your job is to the partition the grid into n parts where each part consists of exactly n cells, each containing exactly one marked cell.\nExample\nHere is a puzzle on the left and ...
Dropsort, designed by David Morgan-Mar, is an example of a linear-time "sorting algorithm" that produces a list that is, in fact, sorted, but contains only some of the original elements. Any element that is not at least as large as the maximum of the elements preceding it is simply removed from the list and discarded. ...
Here is a concise Python implementation of the Dropsort algorithm. This program takes a list of integers as input, applies the Dropsort logic, and outputs the remaining sorted elements. ```python def dropsort(arr): result = [] for x in arr: if not result or x >= result[-1]: result.append(x)...
37,721
[ { "from": "human", "value": "Dropsort, designed by David Morgan-Mar, is an example of a linear-time \"sorting algorithm\" that produces a list that is, in fact, sorted, but contains only some of the original elements. Any element that is not at least as large as the maximum of the elements preceding it is s...
We've had lots of questions about quines, programs where the source code and output are identical. For compiled languages, there are other combinations: we've already had a question about writing a program where the executable and output are identical. But there's one combination left. The task Using a compiled languag...
To tackle the challenge of writing a program in a compiled language that, when compiled, produces an executable that is bit-for-bit identical to the source code, we can utilize the programming language C in conjunction with some clever techniques. The idea is to create a C program that, when compiled, outputs exactly...
34,815
[ { "from": "human", "value": "We've had lots of questions about quines, programs where the source code and output are identical. For compiled languages, there are other combinations: we've already had a question about writing a program where the executable and output are identical. But there's one combinatio...
Let's consider a list \$L\$ (initially empty) and a pointer \$p\$ into this list (initialized to \$0\$). Given a pair of integers \$(m,n)\$, with \$m\ge 0\$ and \$n>0\$: We set all uninitialized values in \$L\$ up to \$p+m+n\$ (excluded) to \$0\$. We advance the pointer by adding \$m\$ to \$p\$. We create a vector \$[...
Here's a concise implementation of the described algorithm in Python, structured to take input as a list of pairs (m, n) and produce the final state of the list L: ```python def process_pairs(pairs): L = [] p = 0 for m, n in pairs: # Extend L with zeros if necessary if p + m + n > len(...
34,394
[ { "from": "human", "value": "Let's consider a list \\$L\\$ (initially empty) and a pointer \\$p\\$ into this list (initialized to \\$0\\$).\nGiven a pair of integers \\$(m,n)\\$, with \\$m\\ge 0\\$ and \\$n>0\\$:\n\nWe set all uninitialized values in \\$L\\$ up to \\$p+m+n\\$ (excluded) to \\$0\\$.\nWe adva...
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 is a Python solution that determines whether the input is Incorrect, Basic, or Standard Pilish based on the specified criteria. The solution leverages a concise structure to achieve the task efficiently: ```python def pilish(s, pi='3.141592653589793238462643383279'): pi_digits = [int(d) for d in pi if d.isdig...
33,863
[ { "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...
An Egyptian fraction is a representation of a rational number using the sum of distinct unit fractions (a unit fraction is of the form \$ \frac 1 x \$ where \$ x \$ is a positive integer). For all[1] positive integers \$ n \ne 2 \$, there exists at least one Egyptian fraction of \$ n \$ distinct positive integers whose...
Here's a concise Python solution that generates an Egyptian fraction for a given \( n \) using distinct positive integers: ```python def egyptian_fraction(n): if n == 1: return [1] elif n == 3: return [2, 3, 6] else: return [i + 1 for i in range(n)] n = int(input()) print(egyptian_...
36,245
[ { "from": "human", "value": "An Egyptian fraction is a representation of a rational number using the sum of distinct unit fractions (a unit fraction is of the form \\$ \\frac 1 x \\$ where \\$ x \\$ is a positive integer).\nFor all[1] positive integers \\$ n \\ne 2 \\$, there exists at least one Egyptian fr...
Challenge Let's imagine an N-tuple of integers between 0 and M inclusive, and let's call it F. There are (M + 1) ** N possible Fs in total. How many such Fs satisfy all of the following inequalities (index is one-based)? F[n] + F[n+1] <= M for 1 <= n < N F[N] + F[1] <= M Write a program or function that takes two pos...
To solve the problem of counting the N-tuples \( F \) that satisfy the given conditions, we can use a dynamic programming approach rather than generating all possible tuples, which would be computationally expensive. ### Approach Explanation 1. **Dynamic Programming Table**: We'll create a dynamic programming table `...
33,036
[ { "from": "human", "value": "Challenge\nLet's imagine an N-tuple of integers between 0 and M inclusive, and let's call it F.\nThere are (M + 1) ** N possible Fs in total.\nHow many such Fs satisfy all of the following inequalities (index is one-based)?\n\nF[n] + F[n+1] <= M for 1 <= n < N\nF[N] + F[1] <= M\...
In this challenge you will remove one of my least favorite features, operator precedence from traditional math notation, to acheive the syntax of one of my favorite languages, APL. The APL subset we will be working with includes only a few functions and single digit numbers. (No arrays!) Here is the grammar of the inpu...
Here's a concise Python solution to transform an expression from traditional math notation to the desired APL-like syntax. The program utilizes recursion to parse the input expression while keeping track of operators and their respective precedence. ```python def transform(expr): def parse(expr): if expr[0...
35,671
[ { "from": "human", "value": "In this challenge you will remove one of my least favorite features, operator precedence from traditional math notation, to acheive the syntax of one of my favorite languages, APL. The APL subset we will be working with includes only a few functions and single digit numbers. (No...
Gaussian integers are complex numbers of the form a+bi where a and b are both integers. In base -1+i, all Gaussian integers can be uniquely represented using the digits 0 and 1, without the need for a symbol to denote sign. For instance, 1100 in base -1+i represents the decimal number 2, since 1*(-1+i)^3 + 1*(-1+i)^2 +...
To solve the problem of adding two Gaussian integers represented in base -1+i, we need to follow these steps: 1. **Convert the base -1+i representation to the standard Gaussian integer (a + bi)**. 2. **Perform the addition of the two Gaussian integers**. 3. **Convert the resulting Gaussian integer back into the base -...
28,610
[ { "from": "human", "value": "Gaussian integers are complex numbers of the form a+bi where a and b are both integers. In base -1+i, all Gaussian integers can be uniquely represented using the digits 0 and 1, without the need for a symbol to denote sign.\nFor instance, 1100 in base -1+i represents the decimal...
Background Mastermind is a game of code-breaking for two players. One of the players is codemaker (Alice) and the other is codebreaker (Bob). 4x4 means that the player should guess the length-4 sequence made of four alphabets (say RGBY). The hidden sequence may have duplicate letters, so there are \$4^4 = 256\$ possibi...
Here is a Python solution to the challenge of determining the hidden code from the four guesses and their outcomes in the Mastermind game: ```python def mastermind(a, b, c, d): gs = ['R G G R', 'B B R R', 'Y Y G R', 'G B B Y'] poss = [] def feedback(code, guess): correct = sum(c == g for c, g ...
35,233
[ { "from": "human", "value": "Background\nMastermind is a game of code-breaking for two players. One of the players is codemaker (Alice) and the other is codebreaker (Bob).\n4x4 means that the player should guess the length-4 sequence made of four alphabets (say RGBY). The hidden sequence may have duplicate ...
Similar in spirit to Number of distinct tilings of an n X n square with free n-polyominoes and Partition a square grid into parts of equal area, this challenge will have you count ways of partitioning a triangle in a triangular grid. The goal of this code-golf challenge is to write a program that outputs \$ a(n,m)\$, t...
Here is a Python solution that accomplishes the task of counting the number of ways to partition a triangular grid into equal parts. The program uses recursion and memoization to efficiently count the partitions while taking into account rotations and reflections. ```python def a(n, m): if m <= 0 or m > n*(n+1)//2...
35,156
[ { "from": "human", "value": "Similar in spirit to Number of distinct tilings of an n X n square with free n-polyominoes and Partition a square grid into parts of equal area, this challenge will have you count ways of partitioning a triangle in a triangular grid. The goal of this code-golf challenge is to wr...
In this challenge you will take two lists as input and you will zip them. The zip can be defined with this recursive expression: \$ \mathrm{zip}(a,b) = \begin{cases} \left[\,\,\right] & a = \left[\,\,\right] \\ [a_0]\mid\mid\mathrm{zip}(b, t) & a = [a_0] \mid\mid t \end{cases} \$ or this Haskell program if you would l...
Here is a Python solution for zipping two lists of positive integers according to the specified requirements. This solution does not use any built-in zip function, keeping it as minimal and efficient as possible for the task. ```python def zip_lists(a, b): return [x for pair in zip(a, b) for x in pair] + a[len(b):...
36,423
[ { "from": "human", "value": "In this challenge you will take two lists as input and you will zip them. The zip can be defined with this recursive expression:\n\\$\n\\mathrm{zip}(a,b) = \\begin{cases}\n\\left[\\,\\,\\right] & a = \\left[\\,\\,\\right] \\\\\n[a_0]\\mid\\mid\\mathrm{zip}(b, t) & a = [a_0] \\m...
Challenge My challenge, is for you to generate a Menger Sponge based on the level/iteration given. You need to draw it in 3d, anyway you can. Examples Inputs: 0, 1, 2, 3 Outputs: Background Information What is a Menger Sponge In mathematics, the Menger sponge (also known as the Menger universal curve) is a fractal c...
Creating a Menger Sponge in 3D can be quite a challenge, especially in code-golf format where brevity is key. Below is a Python implementation that uses the `matplotlib` library to visualize the Menger Sponge up to a specified level of iteration. Here’s a simple implementation for generating and visualizing a Menger S...
31,356
[ { "from": "human", "value": "Challenge\nMy challenge, is for you to generate a Menger Sponge based on the level/iteration given. You need to draw it in 3d, anyway you can.\nExamples\nInputs: 0, 1, 2, 3\nOutputs:\n\n\nBackground Information\nWhat is a Menger Sponge\n\nIn mathematics, the Menger sponge (also ...
Task Given two strictly positive integers n and d as input, determine whether n is evenly divisible by d, i.e., if there exists an integer q such that n = qd. You may write a program or a function and use any of the our standard methods of receiving input and providing output. The output should be a truthy or a falsy v...
## Python, 37 bytes ```python def f(n,d):return n%d<1 ``` This function takes two strictly positive integers `n` and `d` as input and returns `True` if `n` is evenly divisible by `d`, otherwise it returns `False`.
39,350
[ { "from": "human", "value": "Task\nGiven two strictly positive integers n and d as input, determine whether n is evenly divisible by d, i.e., if there exists an integer q such that n = qd.\nYou may write a program or a function and use any of the our standard methods of receiving input and providing output....
Hermite polynomials refer to two sequences of polynomials: The "probabilist's Hermite polynomials", given by $${He}_n(x) = (-1)^n e ^ \frac {x^2} 2 \frac {d^n} {dx^n} e ^ {-\frac {x^2} 2}$$ where \$\frac {d^n} {dx^n} f(x)\$ refers to the \$n\$th derivative of \$f(x)\$ The "physicist's Hermite polynomials", given by $...
Here is a polyglot program that outputs the Hermite polynomials for both definitions: ```python n=int(input()) H=[0]*(n+1) H[0]=1 if n>0:H[1]=2 for i in range(2,n+1):H[i]=2*i*H[i-1]-2*(i-1)*H[i-2] print(H) He=[0]*(n+1) He[0]=1 if n>0:He[1]=1 for i in range(2,n+1):He[i]=x*He[i-1]-i*He[i-2] print(He) ``` ### Explanati...
35,899
[ { "from": "human", "value": "Hermite polynomials refer to two sequences of polynomials:\n\nThe \"probabilist's Hermite polynomials\", given by\n$${He}_n(x) = (-1)^n e ^ \\frac {x^2} 2 \\frac {d^n} {dx^n} e ^ {-\\frac {x^2} 2}$$\nwhere \\$\\frac {d^n} {dx^n} f(x)\\$ refers to the \\$n\\$th derivative of \\$f...
NB : Everything presented in the situation is totally fake and had just been put here to make the challenge a little more fun ;) ... Or maybe not ;) === === BEGINNING TRANSMISSION === === Hello, I recently had a disk failure. I hopefully had backups and I now want my photos back. However, EVERY backup looks corrupted ...
Here is a short Python script that fulfills the requirements laid out in your challenge. The script reads from a file named `list.txt`, checks for lines containing camera model data, and moves the corresponding images to the directory `./withmodel/`. ```python import os,shutil os.makedirs('withmodel',exist_ok=True) wi...
37,587
[ { "from": "human", "value": "NB : Everything presented in the situation is totally fake and had just been put here to make the challenge a little more fun ;) ... Or maybe not ;)\n\n=== === BEGINNING TRANSMISSION === ===\nHello,\nI recently had a disk failure. I hopefully had backups and I now want my photos...
Lets define a non-empty, unsorted and finite matrix with unique numbers as follow: $$N = \begin{Bmatrix} 4&5&7\\1&3&6 \end{Bmatrix}$$ Lets define 4 matrix moves as: ↑* (up): Moves a column up ↓* (down): Moves a column down →* (right): Moves a row to the right ←* (left): Moves a row to the left The asterisk(*) repre...
To tackle this challenge, we'll take the given matrix \( N \) and create a sequence of moves that will eventually sort the matrix in ascending order. We'll consider the 0-indexed approach for the moves and use unique symbols to represent the moves. Let's define our moves as follows: - **↑**: up (move column up) - **↓...
33,743
[ { "from": "human", "value": "Lets define a non-empty, unsorted and finite matrix with unique numbers as follow:\n $$N = \\begin{Bmatrix} 4&5&7\\\\1&3&6 \\end{Bmatrix}$$\nLets define 4 matrix moves as:\n\n↑* (up): Moves a column up\n↓* (down): Moves a column down\n→* (right): Moves a row to the right \n←* (l...
A stack state diagram shows how the values on one stack are changed into the other. For example, this is a stack state diagram: 3 0 2 1 0 This means that there is a stack initially containing 3 values (the 3 part). These values are indexed from 0 to 2, with 0 at the top: 2 1 0. The next part 0 2 1 0 describes the fina...
Here is a Python solution that implements the operations defined for the stack transformation problem. The approach uses a depth-first search (DFS) to find the sequence of commands that will transform the initial stack state into the desired final stack state. ```python def stack_operations(start, end): commands =...
30,155
[ { "from": "human", "value": "A stack state diagram shows how the values on one stack are changed into the other. For example, this is a stack state diagram:\n3 0 2 1 0\n\nThis means that there is a stack initially containing 3 values (the 3 part). These values are indexed from 0 to 2, with 0 at the top: 2 1...
Let's define the a function on natural numbers \$n\$, written as base 10 digits \$d_k\; d_{k-1}\; \dotsc\; d_1\; d_0\$, as follows: As long as there are equal adjacent digits \$d_i\;d_{i-1}\$, replace them by their sum \$d_i+d_{i-1}\$ from left to right. If there were any such digits, repeat the same procedure. In othe...
To solve the problem of generating the sequence as defined, we can break it down into several steps. We will define a function that takes a natural number and generates the corresponding number in the sequence based on the rules provided. The goal is to process numbers according to the replacement rules until no more r...
33,713
[ { "from": "human", "value": "Let's define the a function on natural numbers \\$n\\$, written as base 10 digits \\$d_k\\; d_{k-1}\\; \\dotsc\\; d_1\\; d_0\\$, as follows:\nAs long as there are equal adjacent digits \\$d_i\\;d_{i-1}\\$, replace them by their sum \\$d_i+d_{i-1}\\$ from left to right. If there ...
There's quite a few challenges on this site that ask you to print out a sequence, and this is no exception. (The following explanation of the sequence for this challenge assumes the symbols in the sequence are 0 and 1.) The recursive definition of the Thue-Morse sequence is that T_0 = 0 T_2n = T_n T_2n+1 = 1 - T_n A ...
Here is a compact solution in Python that generates the Thue-Morse sequence for the first `n` elements, using the symbols `0` and `1`: ```python def tm(n): print(bin(n).count('1') % 2, end='') tm(20) # Example usage ``` ### Explanation: - The function `tm` takes an integer `n` as input. - `bin(n).count('1')` co...
37,969
[ { "from": "human", "value": "There's quite a few challenges on this site that ask you to print out a sequence, and this is no exception.\n(The following explanation of the sequence for this challenge assumes the symbols in the sequence are 0 and 1.)\nThe recursive definition of the Thue-Morse sequence is th...
Write three different programs such that when any one program is provided as input to one of the other two, you get the source of the remaining program as output. More explicitly, given programs \$A\$, \$B\$, and \$C\$, where \$f(g)\$ denotes the output obtained from inputting the text of program \$g\$ into program \$f...
Creating a set of three programs that satisfy the given conditions can be quite challenging, but here’s a solution using Python. The programs A, B, and C will be defined as follows: ### Program A (program_a.py) ```python def A(input): return C if input == B else B B = "def B(input): return A if input == C else C" ...
35,137
[ { "from": "human", "value": "Write three different programs such that when any one program is provided as input to one of the other two, you get the source of the remaining program as output. More explicitly, given programs \\$A\\$, \\$B\\$, and \\$C\\$, where \\$f(g)\\$ denotes the output obtained from inp...
A portmanteau word is a combination of two words that takes part of each word and makes them into a single new word. For example, lion + tiger => liger. Let's write a program to generate portmanteaus from a pair of input words. Computers aren't the best at English, so we'll need to establish some rules to ensure that t...
Here's a Python solution for generating portmanteaus based on the specified rules. In this implementation, we treat 'y' as a consonant. ```python def is_vowel(c): return c in 'aeiou' def generate_portmanteaus(word1, word2): portmanteaus = set() len1, len2 = len(word1), len(word2) for i in range(1, l...
33,199
[ { "from": "human", "value": "A portmanteau word is a combination of two words that takes part of each word and makes them into a single new word. For example, lion + tiger => liger.\nLet's write a program to generate portmanteaus from a pair of input words. Computers aren't the best at English, so we'll nee...
Write a function that accepts a rectangular grid of ids in any reasonable format, for example a multi-line string: IIILOO ILLLOO and a string or list of box drawing charcters such as: ' ═║╔╗╚╝╠╣╦╩╬' or [0x20, 0x2550, 0x2551, 0x2554, 0x2557, 0x255a, 0x255d, 0x2560, 0x2563, 0x2566, 0x2569, 0x256c'] (see below for more...
Here’s a Python function that formats a grid of unique identifiers into a pretty printed version using box drawing characters. The function takes a rectangular grid in the form of a multi-line string and a list of box drawing characters. ```python def pretty_print(grid, box_chars): # Mapping box drawing characters...
24,604
[ { "from": "human", "value": "Write a function that accepts a rectangular grid of ids in any reasonable format, for example a multi-line string:\nIIILOO\nILLLOO\n\nand a string or list of box drawing charcters such as:\n' ═║╔╗╚╝╠╣╦╩╬'\n\nor\n[0x20, 0x2550, 0x2551, 0x2554, 0x2557, 0x255a, 0x255d, 0x2560, 0x25...
You'll get a human-readable question matching one of the following syntaxes, and are expected to print/return the corresponding result. Finding similarities between the human-readable inputs and matching them with minimum size code is explicitly part of the task, so I won't give a formal definition. "Will October begi...
To solve this problem, we can create a function in Python that handles the calendar calculations based on the given conditions. Here's a succinct solution that takes a description of the problem and returns the correct answer: ```python def will_start_on(day, month, leap, start_day): days_in_month = [31, 29 if lea...
35,281
[ { "from": "human", "value": "You'll get a human-readable question matching one of the following syntaxes, and are expected to print/return the corresponding result. Finding similarities between the human-readable inputs and matching them with minimum size code is explicitly part of the task, so I won't give...
Your task is to write a program that, given a number n, returns a list of all valid, halting Smallfuck programs of length n, in any order. Actually, we're using a variation of Smallfuck called F2, which is just Smallfuck with a right-unbounded tape. For the purposes of this challenge, a program that moves left from the...
Creating a program that generates all valid and halting F2 (a variant of Smallfuck) programs of a given length `n` is an interesting challenge! Below is a Python implementation that achieves this task. The program generates all combinations of valid F2 instructions, filters out invalid ones, and ensures that they halt ...
31,284
[ { "from": "human", "value": "Your task is to write a program that, given a number n, returns a list of all valid, halting Smallfuck programs of length n, in any order.\nActually, we're using a variation of Smallfuck called F2, which is just Smallfuck with a right-unbounded tape. For the purposes of this cha...
Background The computer game NetHack dates from 1987, before the use of graphics in computer games was widely established. There are lots of monsters in the game, and potentially a lot need to fit on screen at once, so monsters are drawn in a very minimal way: a monster is simply drawn as an ASCII character on screen. ...
Here's a solution for this challenge in Python that maps the monster names to their respective ASCII characters using a dictionary. This implementation is compact and meets the requirements of code-golf. ```python def nethack_monster_ascii(name): return { "Aleax": "A", "Angel": "A", "Arch Priest": "@", "Ar...
30,236
[ { "from": "human", "value": "Background\nThe computer game NetHack dates from 1987, before the use of graphics in computer games was widely established. There are lots of monsters in the game, and potentially a lot need to fit on screen at once, so monsters are drawn in a very minimal way: a monster is simp...
Your task is to take an array of numbers and a real number and return the value at that point in the array. Arrays start at \$\pi\$ and are counted in \$\pi\$ intervals. Thing is, we're actually going to interpolate between elements given the "index". As an example: Index: 1π 2π 3π 4π 5π 6π Array: [ 1.1, 1...
To solve the problem of interpolating between values in an array at specific indices, we can follow these steps: 1. **Identify the surrounding indices:** For an input index \( i \), determine the integer part of the index to find the positions of the elements in the array. 2. **Calculate the fractional part:** This wi...
33,833
[ { "from": "human", "value": "Your task is to take an array of numbers and a real number and return the value at that point in the array. Arrays start at \\$\\pi\\$ and are counted in \\$\\pi\\$ intervals. Thing is, we're actually going to interpolate between elements given the \"index\". As an example:\nInd...
Background MQTT (Message Queuing Telemetry Transport) is an ISO standard publish-subscribe-based messaging protocol (Wikipedia). Each message has a topic, such as the following examples: myhome/groundfloor/livingroom/temperature USA/California/San Francisco/Silicon Valley 5ff4a2ce-e485-40f4-826c-b1a5d81be9b6/status Ge...
To solve the problem of determining if a subject topic matches a criteria topic using MQTT's subscription syntax, we need to implement a function that can handle the two types of wildcards: the single-level wildcard (`+`) and the multi-level wildcard (`#`). Here's how we can implement this function in Python: 1. Spl...
34,148
[ { "from": "human", "value": "Background\nMQTT (Message Queuing Telemetry Transport) is an ISO standard publish-subscribe-based messaging protocol (Wikipedia).\nEach message has a topic, such as the following examples:\n\nmyhome/groundfloor/livingroom/temperature\nUSA/California/San Francisco/Silicon Valley\...
(a paradox, a paradox, a most ingenious paradox) This is the first part of a multipart series inspired by different R functions. The Task Given a dataset \$D\$ of positive integers, I need you to compute the 5 number summary of \$D\$. However, I'm working on large datasets, so I need your code to be as small as possibl...
Here's a concise implementation of the five-number summary in Python, which handles the computation according to the R-style quartile definitions you specified. The input is assumed to be sorted in ascending order. ```python def five_num_summary(D): n = len(D) minimum = D[0] maximum = D[-1] median...
34,128
[ { "from": "human", "value": "(a paradox, a paradox, a most ingenious paradox)\nThis is the first part of a multipart series inspired by different R functions.\nThe Task\nGiven a dataset \\$D\\$ of positive integers, I need you to compute the 5 number summary of \\$D\\$. However, I'm working on large dataset...
The (slightly harder, but still easy) sequel of Generate input for this hardware. Background I have a hardware that has a 32-bit input register. The register has the following characteristics: The 32-bit register consists of eight 4-bit fields. Each 4-bit field holds a value in signed-magnitude; it can hold an integer...
Here's a solution in Python that checks if the given 32-bit register value represents a valid input according to the specified rules. ```python def is_valid_input(value): # Convert the input value to hexadecimal, strip '0x', and fill with leading zeros hex_str = f"{value:08X}" # Create the 8 signed m...
34,418
[ { "from": "human", "value": "The (slightly harder, but still easy) sequel of Generate input for this hardware.\nBackground\nI have a hardware that has a 32-bit input register. The register has the following characteristics:\n\nThe 32-bit register consists of eight 4-bit fields.\nEach 4-bit field holds a val...
Traditionally presents are kept secret in boxes wrapped in paper. Since the ice caps are melting Santa Claus has begun to investigate some ways they might make the whole gift wrapping operation a little more eco-friendly. The first thing they've decided to do is to put all presents in perfectly cubic boxes. This makes...
Here is a compact Python solution that determines if a given scrap can be used for wrapping a cube according to the specified conditions: ```python def w(s): d,s=[len(x)for x in s.split()],set() for i in range(1<<4): r=t=6 for j in range(4): if i&1<<j: r-=1 t-=d[j] if t<0: continue s.add(r) ...
36,882
[ { "from": "human", "value": "Traditionally presents are kept secret in boxes wrapped in paper. Since the ice caps are melting Santa Claus has begun to investigate some ways they might make the whole gift wrapping operation a little more eco-friendly. The first thing they've decided to do is to put all prese...
Background A338268 is a sequence related to a challenge by Peter Kagey. It defines a two-parameter function \$T(n,k)\$, which counts the number of integer sequences \$b_1, \cdots, b_t\$ where \$b_1 + \cdots + b_t = n\$ and \$\sqrt{b_1 + \sqrt{b_2 + \cdots + \sqrt{b_t}}} = k\$. Since \$k\$ cannot be larger than \$\sqrt{...
Here is a Python solution that computes the sequence as described in the problem statement, supporting both one-based and zero-based indexing. The code defines a function that can output a term at a specified index or generate the first `i` terms of the sequence. ```python def seq(i): n, k = 0, 1 result = [] ...
35,913
[ { "from": "human", "value": "Background\nA338268 is a sequence related to a challenge by Peter Kagey. It defines a two-parameter function \\$T(n,k)\\$, which counts the number of integer sequences \\$b_1, \\cdots, b_t\\$ where \\$b_1 + \\cdots + b_t = n\\$ and \\$\\sqrt{b_1 + \\sqrt{b_2 + \\cdots + \\sqrt{b...
quintopia has posted here a challenge to compute multinomial coefficients (some of the text here is copied from there). There is a fun algorithm to compute multinomial coefficients mod 2. Given a list of numbers, k1, k2, ... ,km, output the residue of the multinomial coefficient: reduced mod 2. The following algorith...
Here's a Python function to compute the multinomial coefficient mod 2 based on the described algorithm. The solution checks for overlapping '1's in the binary representation of the given numbers. ```python def multinomial_mod_2(nums): bits = [0] * 64 # To store counts of bits in positions 0 to 63 for num in n...
32,582
[ { "from": "human", "value": "quintopia has posted here a challenge to compute multinomial coefficients (some of the text here is copied from there). There is a fun algorithm to compute multinomial coefficients mod 2. \nGiven a list of numbers, k1, k2, ... ,km, output the residue of the multinomial coefficie...
!!!Batch is another derivative of the Windows Batch programming language, its wiki is here Your challenge is to create an compiler/translator that reads a !!!Batch program and returns a Windows Batch program. In !!!Batch each token braced in two question marks like ?!!!? is converted to another ASCII character, like '?...
Here's a concise Python implementation of a compiler/translator for !!!Batch to Windows Batch. The following code uses a dictionary for mapping the ???Batch tokens to ASCII characters, which allows for efficient translation. ```python s=input().strip() m = {f'?{"!"*i}{"-?" if i > 0 else "?"}': c for i, c in zip(range(...
35,461
[ { "from": "human", "value": "!!!Batch is another derivative of the Windows Batch programming language, its wiki is here\nYour challenge is to create an compiler/translator that reads a !!!Batch program and returns a Windows Batch program.\nIn !!!Batch each token braced in two question marks like ?!!!? is co...
Hamming number (also known as regular number) is a number that evenly divides powers of 60. We already have a task to do something with it. This time we are going to do the opposite. I define non-Hamming number as in: \$n\$ is non-Hamming number if and only if it satisfies following two conditions: \$n\$ is positive i...
Here's a Python function that generates non-Hamming numbers and satisfies the requirement of returning the first `n` non-Hamming numbers. Non-Hamming numbers, by definition, do not divide any power of 60. The function checks if a number is a non-Hamming number and collects the required number of them: ```python def i...
35,626
[ { "from": "human", "value": "Hamming number (also known as regular number) is a number that evenly divides powers of 60.\nWe already have a task to do something with it.\nThis time we are going to do the opposite.\nI define non-Hamming number as in: \\$n\\$ is non-Hamming number if and only if it satisfies ...
Introduction I have recently started playing clickerheroes again. In the recent patch they introduced a new mechanic to mercenaries: their lifetime. Instead of having a random chance at dying now they have a certain lifespan given by a geometric distribution of p = 0.2. They can be sent on quests to accumulate a premiu...
To tackle the challenge of optimizing mercenary revival in Clicker Heroes, we will simulate the process and identify the level at which it becomes more beneficial to hire a new mercenary instead of reviving an existing one. The goal is to maximize the ruby return per day based on the provided mechanics. Below is a sim...
28,342
[ { "from": "human", "value": "Introduction\nI have recently started playing clickerheroes again. In the recent patch they introduced a new mechanic to mercenaries: their lifetime. Instead of having a random chance at dying now they have a certain lifespan given by a geometric distribution of p = 0.2. They ca...
Related: Cleaning up decimal numbers Background A continued fraction is a way to represent a real number as a sequence of integers in the following sense: $$ x = a_0 + \cfrac{1}{a_1 + \cfrac{1}{a_2 + \cfrac{1}{\ddots + \cfrac{1}{a_n}}}} = [a_0; a_1,a_2,\cdots,a_n] $$ Finite continued fractions represent rational number...
Here’s a Python solution to the problem of finding the best approximation of a rational number represented as a finite continued fraction: ```python def best_approximation(cf, D): n = len(cf) p, q = [0, 1], [1, 0] # p and q for convergents best = (0, 1) # initial best approximation for i in range(n)...
35,585
[ { "from": "human", "value": "Related: Cleaning up decimal numbers\nBackground\nA continued fraction is a way to represent a real number as a sequence of integers in the following sense:\n$$\nx = a_0 + \\cfrac{1}{a_1 + \\cfrac{1}{a_2 + \\cfrac{1}{\\ddots + \\cfrac{1}{a_n}}}} = [a_0; a_1,a_2,\\cdots,a_n]\n$$\...
(This challenge exists to extend sequence A276272 in the On-Line Encyclopedia of Integer Sequences, and perhaps create a new OEIS sequence1.) This is a code-challenge, which will have you write code to compute as many terms of this sequence as possible. Background A polytet is a kind of polyform which is construct...
To compute the terms of the sequence A276272, we'll need to define a way to build polytets from tetrahedra, and systematically generate all configurations while taking care to count them correctly according to the rules of symmetry and chirality. Below is an implementation in Python that uses a recursive backtracking ...
35,275
[ { "from": "human", "value": "(This challenge exists to extend sequence A276272 in the On-Line Encyclopedia of Integer Sequences, and perhaps create a new OEIS sequence1.)\nThis is a code-challenge, which will have you write code to compute as many terms of this sequence as possible.\n\nBackground\n\n\n\n\nA...
Let's start by defining a Two Bit Number™: It is a positive integer When expressed as a binary string it has exactly 2 true bits OR When expressed as a decimal number, it has exactly 2 of the numeral one, and all other numerals are zero. Or as a sentence A Two Bit Number™ is a number which contains exactly 2 of the n...
Here’s a concise Python solution that determines if a number is a Two Bit Number™. The code checks if the input number meets the criteria you provided: ```python def is_two_bit_number(n): return n > 0 and (bin(n).count('1') == 2 or str(n).count('1') == 2 and all(d in '01' for d in str(n))) # Test Cases print(is_t...
35,224
[ { "from": "human", "value": "Let's start by defining a Two Bit Number™:\n\nIt is a positive integer\nWhen expressed as a binary string it has exactly 2 true bits OR\nWhen expressed as a decimal number, it has exactly 2 of the numeral one, and all other numerals are zero.\n\nOr as a sentence\nA Two Bit Numbe...
The Biham-Middleton-Levine traffic model is a self-organizing cellular automaton that models simplified traffic. It consists of a number of cars represented by points on a lattice with a random starting position, where each car may be one of two types: those that only move downwards (shown as blue in this article), a...
To visualize the Biham-Middleton-Levine (BML) traffic model, we can create a simple Python program that generates an animation of this self-organizing cellular automaton. We will use the Pygame library to create a graphical representation of the grid. Below is a step-by-step breakdown of how to implement this. ### Ste...
30,200
[ { "from": "human", "value": "The Biham-Middleton-Levine traffic model is a self-organizing cellular automaton that models simplified traffic. \n\nIt consists of a number of cars represented by points on a lattice with a random starting position, where each car may be one of two types: those that only move d...
In this challenge, you will be "reversing" the alphabet or swapping a-z with z-a. This is commonly known as the Atbash cypher. Because this transformation makes the output look like some foreign language, your code will need to be as short as possible. Examples abcdefghijklmnopqrstuvwxyz zyxwvutsrqponmlkjihgfedcba Pr...
Here's a Python implementation of the Atbash cipher that adheres to the specifications, keeping it as short as possible for code-golf purposes: ```python print(''.join(chr(219 - ord(c)) if c.islower() else chr(155 - ord(c)) if c.isupper() else c for c in input())) ``` ### Explanation: - We read input using `input()`....
38,189
[ { "from": "human", "value": "In this challenge, you will be \"reversing\" the alphabet or swapping a-z with z-a. This is commonly known as the Atbash cypher.\nBecause this transformation makes the output look like some foreign language, your code will need to be as short as possible.\n\nExamples\nabcdefghij...
The challenge is simple: Write a function or program that takes an input x, and outputs the lower case alphabet if x is part of the lower case alphabet, outputs the upper case alphabet if x is part of the upper case alphabet and outputs just x if it's not part of either. Rules: The input can be function argument or fr...
## Python, 51 bytes ```python def f(x):return x.lower()if x.islower()else x.upper()if x.isupper()else x ``` ### Explanation - The function `f` takes a single input `x`. - It checks if `x` is a lowercase letter using `islower()`, returning the lowercase version of `x` if true. - If `x` is not a lowercase letter, it ch...
38,105
[ { "from": "human", "value": "The challenge is simple:\nWrite a function or program that takes an input x, and outputs the lower case alphabet if x is part of the lower case alphabet, outputs the upper case alphabet if x is part of the upper case alphabet and outputs just x if it's not part of either.\nRules...
You are a web developer, and your boss has decided to update the company's website. He has decided that less color is better, but he wants the site to look the same. You justly decide that he has no idea what he's talking about, but you're going to try anyway, because you're bored. Since the company has thousands of we...
Here's a Python solution that takes RGB values as input and returns the shortest string representation of the color as required. This implementation directly converts RGB values to their corresponding CSS color keywords or hex values. ```python def rgb_to_css_color(r, g, b): # CSS color keyword dictionary colo...
16,001
[ { "from": "human", "value": "You are a web developer, and your boss has decided to update the company's website. He has decided that less color is better, but he wants the site to look the same. You justly decide that he has no idea what he's talking about, but you're going to try anyway, because you're bor...
The brainiacs at New Scientist tweeted this morning that "The word STABLE has the neat property that you can cycle the first letter to the end to make a new word: TABLES. And you can do it again to make ABLEST." (https://twitter.com/newscientist/status/1379751396271124480) This is of course correct. It is not, however,...
Here's a Python implementation that finds words that meet the criteria you've described. This code processes the provided dictionary to find words with all valid rotations also being present in the dictionary, as well as identifying the words with the maximum number of valid rotations. ```python def find_rotatable_wor...
35,590
[ { "from": "human", "value": "The brainiacs at New Scientist tweeted this morning that \"The word STABLE has the neat property that you can cycle the first letter to the end to make a new word: TABLES. And you can do it again to make ABLEST.\" (https://twitter.com/newscientist/status/1379751396271124480)\nTh...
Background: The current Perfect Numbers challenge is rather flawed and complicated, since it asks you to output in a complex format involving the factors of the number. This is a purely decision-problem repost of the challenge. Challenge Given a positive integer through any standard input format, distinguish between wh...
To solve the problem of determining whether a given positive integer is a perfect number, we can follow these steps: 1. **Understand the definition of a perfect number**: A perfect number is equal to the sum of its proper divisors, excluding itself. 2. **Identify the proper divisors**: For a given integer \( n \), p...
33,856
[ { "from": "human", "value": "Background:\nThe current Perfect Numbers challenge is rather flawed and complicated, since it asks you to output in a complex format involving the factors of the number. This is a purely decision-problem repost of the challenge.\nChallenge\nGiven a positive integer through any s...
Output coordinates of the vertices of a cube. Then, output a list of twelve triangles that will cover the cube, each triangle being a list of three vertex-indexes, consistently oriented. Output must be an ASCII string of distinct decimal numbers. This golf has no input. Winner is the fewest characters, where the charac...
Here's a concise output for the vertices of a cube and the twelve triangles that cover it: ```plaintext 0 0 0 0 0 1 0 1 0 1 1 1 1 1 0 0 1 0 0 0 1 1 1 0 0 1 1 0 1 0 0 1 1 1 1 1 1 0 0 1 0 1 1 1 0 1 1 0 0 1 2 2 3 0 6 5 4 4 7 6 5 2 1 2 5 6 0 3 4 4 3 7 2 6 3 3 6 7 0 4 1 1 4 5 ``` This output consists of the vertex coordi...
37,673
[ { "from": "human", "value": "Output coordinates of the vertices of a cube. Then, output a list of twelve triangles that will cover the cube, each triangle being a list of three vertex-indexes, consistently oriented. Output must be an ASCII string of distinct decimal numbers. This golf has no input. Winner i...
You have a phone plan that lets you talk 180 minutes a day. Every day that you go over your daily limit you have to pay a fine of F = Men, where M is the number of minutes you went over and n is the number of days you have gone over (e.g if I went 20 minutes over the daily limit and it's my 2nd day going over, I have t...
To calculate the total fines based on the given call times and the overage rules, we need to break down the time into manageable parts, calculate the duration of each call, and then assess the overages. Let's walk through the logic step-by-step: 1. **Convert Time**: Convert 12-hour clock times into a format that make...
28,153
[ { "from": "human", "value": "You have a phone plan that lets you talk 180 minutes a day. Every day that you go over your daily limit you have to pay a fine of F = Men, where M is the number of minutes you went over and n is the number of days you have gone over (e.g if I went 20 minutes over the daily limit...
Peano numbers represent nonnegative integers as zero or successors of other Peano numbers. For example, 1 would be represented as Succ(Zero) and 3 would be Succ(Succ(Succ(Zero))). Task Implement the following operations on Peano numbers, at compile time: Addition Subtraction - You will never be required to subtract a ...
Here's a concise implementation of Peano numbers with addition, subtraction, multiplication, and division using Scala. This implementation includes the necessary operations all handled at compile time, adhering to the rules of Peano arithmetic. ```scala sealed trait Num { type Plus[N <: Num] <: Num type Minus[N <:...
35,418
[ { "from": "human", "value": "Peano numbers represent nonnegative integers as zero or successors of other Peano numbers. For example, 1 would be represented as Succ(Zero) and 3 would be Succ(Succ(Succ(Zero))).\nTask\nImplement the following operations on Peano numbers, at compile time:\n\nAddition\nSubtracti...