instruction
stringlengths
34
53.1k
completion
stringlengths
5
524k
__original_row_idx
int64
0
50k
conversations
listlengths
2
2
The knight is a chess piece that, when placed on the o-marked square, can move to any of the x-marked squares (as long as they are inside the board): .x.x. x...x ..o.. x...x .x.x. Eight knights, numbered from 1 to 8, have been placed on a 3×3 board, leaving one single square empty .. They can neither attack each other...
Here is a concise Python solution that computes the minimum number of valid moves required to reach the ordered configuration in a 3x3 chessboard with knights. The code uses breadth-first search (BFS) to explore the possible configurations and their corresponding moves. ```python from collections import deque def bfs...
36,353
[ { "from": "human", "value": "The knight is a chess piece that, when placed on the o-marked square, can move to any of the x-marked squares (as long as they are inside the board):\n.x.x.\nx...x\n..o..\nx...x\n.x.x.\n\nEight knights, numbered from 1 to 8, have been placed on a 3×3 board, leaving one single sq...
Starting with a binary list (just 1s and 0s) we are going to roll a ball over it. The ball has a position and a direction. At every step the ball does the following: If the number at it's position is 1, then flip the direction. It "bounces". Flip the number, if it's 0 replace it with 1, if it's 1 replace it with 0....
Here is a compact Python solution that follows the rules you've described: ```python def roll(ball): p,d=0,1 while 0<=p<len(ball): ball[p]^=1 d*=-1 if ball[p] else d p+=d return ball ``` ### Explanation: 1. **Initialization**: The variables `p` (position) is set to `0`, and `d` (di...
36,336
[ { "from": "human", "value": "Starting with a binary list (just 1s and 0s) we are going to roll a ball over it. The ball has a position and a direction. At every step the ball does the following:\n\nIf the number at it's position is 1, then flip the direction. It \"bounces\".\nFlip the number, if it's 0 r...
You probably do know that the different reputation levels on Stack Exchange are formatted differently when seen from the questions page / a post. There're all the rep-formatting rules: if a user has 1 to 999 (one to three digits) rep, it's left as-is. if a user has 1000 to 9999 rep (four digits), it receives the comma...
You can achieve the desired formatting of reputation levels using a simple function in Python. Below is a concise implementation that covers all the cases you mentioned: ```python def format_reputation(rep): if rep < 1000: return str(rep) elif rep < 10000: return f"{rep:,}" elif rep < 10000...
38,260
[ { "from": "human", "value": "You probably do know that the different reputation levels on Stack Exchange are formatted differently when seen from the questions page / a post. There're all the rep-formatting rules:\n\nif a user has 1 to 999 (one to three digits) rep, it's left as-is.\nif a user has 1000 to 9...
The task is simple. You're given an arbitrary string message. Return that message prefixed with a number, such that the length of that number plus the message equals the number. In other words, the length in your output must be the total length of your output. If multiple candidates exist, you can output any of them. F...
Here's a Python function that accomplishes the task of prepending a number to a given message such that the length of the number plus the message equals the total output length. In this implementation, I will use base-10 encoding for simplicity: ```python def prepend_length(message): # Calculate the length of the ...
36,869
[ { "from": "human", "value": "The task is simple. You're given an arbitrary string message. Return that message prefixed with a number, such that the length of that number plus the message equals the number. In other words, the length in your output must be the total length of your output.\nIf multiple candi...
So, you're browsing Programming Puzzles & Code Golf, and you see a new challenge. The author (gasp) forgot to say "No standard Loopholes". You decide to take advantage of this situation, and you read the answer from a file/network. However, you need to make sure that your answer is actually shorter than the legitimate ...
Here’s a Python solution that reads the content of a specified file and prints it to STDOUT. This solution assumes that the user will provide the file location as an argument from the command line. ```python import sys print(open(sys.argv[1]).read()) ``` ### Explanation: 1. `import sys`: This imports the `sys` module...
37,610
[ { "from": "human", "value": "So, you're browsing Programming Puzzles & Code Golf, and you see a new challenge. The author (gasp) forgot to say \"No standard Loopholes\". You decide to take advantage of this situation, and you read the answer from a file/network. However, you need to make sure that your answ...
The problem Given a binary number from 0 to 111111 convert it to trinary. (Base 3). Then print the result. Rules No using a list of conversions. Don't cheat You must use a string as the number No compressing the input string As I will be testing the code with several different numbers I can't use compressed strings Not...
Here's a compact Python solution that converts a binary number (as a string) to a trinary number (base 3) while adhering to the specified rules of code golf: ```python def code(b): return tr(b, 3) def tr(n, b): return "" if n == "0" else tr(bin(int(n, 2) // b, 2), b) + str(int(n, 2) % b) # Example usage prin...
40,282
[ { "from": "human", "value": "The problem\nGiven a binary number from 0 to 111111 convert it to trinary. (Base 3). Then print the result.\nRules\nNo using a list of conversions.\nDon't cheat\nYou must use a string as the number\nNo compressing the input string As I will be testing the code with several diffe...
Write a quine, that when run, creates itself in the current directory, in a source file named itself. We will be using Windows in this, so the file name (and therefore quine) must have the following limitations: None of these characters \ / : ? * < > | Fewer than 211 255 characters Limitations and assumptions Your c...
Here's a simple Python quine that adheres to the restrictions you provided. It creates a source file with the name of the quine itself in the current directory: ```python s='s=%r;open("quine.py","w").write(s%%s)';open("quine.py","w").write(s%s) ``` ### Explanation - The variable `s` contains the string of the program...
40,578
[ { "from": "human", "value": "Write a quine, that when run, creates itself in the current directory, in a source file named itself. We will be using Windows in this, so the file name (and therefore quine) must have the following limitations:\n\nNone of these characters \\ / : ? * < > |\nFewer than 211 255 ch...
The challenge is to calculate the digit sum of the factorial of a number. Example Input: 10 Output: 27 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27 You can expect the input to be an integer above 0. Output can be of any type, but the answer sh...
Here is a Python solution that calculates the digit sum of the factorial of a number: ```python def digit_sum_factorial(n): from math import factorial return sum(int(d) for d in str(factorial(n))) # Example usage print(digit_sum_factorial(10)) # Output: 27 ``` ### Explanation: 1. `from math import factorial...
40,102
[ { "from": "human", "value": "The challenge is to calculate the digit sum of the factorial of a number.\n\nExample\nInput: 10\nOutput: 27\n\n10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,\nand the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27\nYou can expect the input to be an integer abov...
You and your friend want to send each other secret messages. However, because you are conspiracy theorists and think that the government has a quantum computer that can crack any standard encryption. Therefore, you are inventing one of your own. The first step of this is as follows: taking an input string, you check...
Here's a concise Python solution to encode messages using the symbols of the periodic table: ```python def encode(s): e={"H":"Hydrogen","He":"Helium","Li":"Lithium","Be":"Beryllium","B":"Boron","C":"Carbon","N":"Nitrogen","O":"Oxygen","F":"Fluorine","Ne":"Neon","Na":"Sodium","Mg":"Magnesium","Al":"Aluminum","Si":"...
31,726
[ { "from": "human", "value": "You and your friend want to send each other secret messages. However, because you are conspiracy theorists and think that the government has a quantum computer that can crack any standard encryption. Therefore, you are inventing one of your own. The first step of this is as f...
There's a question on this site that is similar to this question, but I have added a twist. You have three inputs, the number of people in the circle n, the k-th person counted out at each step, and the q-th person that survives. The people in the circle are numbered 1 to n. For example, in a circle of 20 people, the 2...
The problem you're describing can be solved using a modified approach to the classic Josephus problem. The idea is to simulate the elimination of people in a circle based on the given step `k` and return the position of the `q-th` survivor. Here's a concise implementation in Python: ```python def josephus(n, k, q): ...
37,909
[ { "from": "human", "value": "There's a question on this site that is similar to this question, but I have added a twist.\nYou have three inputs, the number of people in the circle n, the k-th person counted out at each step, and the q-th person that survives. The people in the circle are numbered 1 to n.\nF...
Who needs to compare things case insensitively when you're able to generate every permutation of uppercase and lowercase? No one! That's the answer. No one does. Your task is to achieve this feat; generate all possible permutations of uppercase/lowercase for a given input. Input A string of printable standard ascii cha...
Here's a concise Python solution that generates all possible permutations of uppercase and lowercase for a given input string, handling only the alphabetic characters: ```python from itertools import product def letter_case_permutations(s): return [''.join(p) for p in product(*(c.lower() if c.isalpha() else c for...
39,108
[ { "from": "human", "value": "Who needs to compare things case insensitively when you're able to generate every permutation of uppercase and lowercase? No one! That's the answer. No one does. Your task is to achieve this feat; generate all possible permutations of uppercase/lowercase for a given input.\nInpu...
Challenge Write a program or function that given a string, returns a valid Brainfuck program that when compiled and executed as Brainfuck, returns that string.. Assume all inputs are encoded as ASCII. Assume the outputted BF program will execute in an environment with an infinite tape. Assume the pointer starts at c...
Here's a solution in Python that generates a Brainfuck program for a given string: ```python def brainfuck_generator(s): bf_code = [] last_value = 0 for char in s: value = ord(char) if value >= last_value: bf_code.append('+' * (value - last_value)) else: ...
39,219
[ { "from": "human", "value": "Challenge\nWrite a program or function that given a string, returns a valid Brainfuck program that when compiled and executed as Brainfuck, returns that string..\n\nAssume all inputs are encoded as ASCII.\n\nAssume the outputted BF program will execute in an environment with an ...
Can you decrypt me? Robbers Find any combination of \$n\$ working chars to change and what they should change into, where \$n\$ is chosen by the cop. You cannot change less than n chars, only exactly \$n\$. Example print(2) N is 1. Robbers' post: print(1) Scoring For the robbers, the user with the most cracks wins. ...
The problem you presented appears to involve a code or puzzle involving robbers and cops, where the robbers must alter a string (or "post") by changing exactly \( n \) characters to win a competition. Here's how we can interpret and solve this problem. ### Problem Breakdown 1. **Input:** The cop chooses a number \( n...
37,463
[ { "from": "human", "value": "Can you decrypt me?\nRobbers\nFind any combination of \\$n\\$ working chars to change and what they should change into, where \\$n\\$ is chosen by the cop. You cannot change less than n chars, only exactly \\$n\\$.\nExample\nprint(2)\n\nN is 1.\n\nRobbers' post:\nprint(1)\n\nSco...
We will say a string \$x\$ is cyclic maximal if there is no way to cycle its elements to get a lexicographically larger string. In other words there is no \$a\$ and \$b\$ such that \$a \oplus b = x\$ and \$b \oplus a > x\$, where \$\oplus\$ is concatenation. For example [3,2,3,3] is not cyclic maximal because you can c...
Here is a solution in Python that satisfies the problem's requirements for generating a lexicographically largest suffix that, when concatenated with a given prefix, results in a cyclic maximal list: ```python def cyclic_max_suffix(p, n): m = max(p) s = [m] * n k = n - 1 while k >= 0 and s[k] == m: ...
37,555
[ { "from": "human", "value": "We will say a string \\$x\\$ is cyclic maximal if there is no way to cycle its elements to get a lexicographically larger string. In other words there is no \\$a\\$ and \\$b\\$ such that \\$a \\oplus b = x\\$ and \\$b \\oplus a > x\\$, where \\$\\oplus\\$ is concatenation.\nFor ...
Your task is to write a program or a function that prints an ASCII triangle. They look like this: |\ | \ | \ ---- Your program will take a single numeric input n, with the constraints 0 <= n <= 1000. The above triangle had a value of n=3. The ASCII triangle will have n backslashes (\) and vertical bars (|), n+1 line...
Here's a short Python function that prints the specified ASCII triangle based on the input `n`. The function adheres to the format you've described and includes the constraints: ```python def draw_triangle(n): for i in range(n): print(' ' * i + '|\\') if n > 0: print('-' * (n + 1)) # Example u...
40,590
[ { "from": "human", "value": "Your task is to write a program or a function that prints an ASCII triangle. They look like this:\n|\\\n| \\\n| \\\n----\n\nYour program will take a single numeric input n, with the constraints 0 <= n <= 1000. The above triangle had a value of n=3. \nThe ASCII triangle will hav...
In this challenge, you need to partition a list, where partitions have a max size, a min size, and a preferred size. I'll be using the notation (min,pref,max) to indicate the sizes in this challenge. For those unfamiliar with partitioning, the following list has been partitioned into parts of 3: [0..9] -> [[0,1,2],[3...
Here's a solution in Python that meets the challenge requirements while keeping it concise: ```python def part(l, s): m,p,n=s r,s=[],[] for i in l: if len(s)<m or len(s)==p and len(s)<n: s.append(i) else: r.append(s) s=[i] if len(s)<m or len(s)>n: ret...
38,773
[ { "from": "human", "value": "In this challenge, you need to partition a list, where partitions have a max size, a min size, and a preferred size. I'll be using the notation (min,pref,max) to indicate the sizes in this challenge.\nFor those unfamiliar with partitioning, the following list has been partitio...
Inspired (you don't need to know them for this challenge) by the Pumping Lemma for various languages, I propose the following challenge: choose some basis \$B \geq 2\$ and an integer \$n \geq 0\$ write a program/function \$P\$ partition* \$P\$ into some strings \$s_i \neq \epsilon\$, st. \$P = s_n | \cdots | s_i | \cd...
Here's a Python implementation of the described challenge. The implementation takes a program `P`, partitions it into specified chunks, and evaluates input strings based on the defined rules. ### Python Implementation ```python def evaluate_string(P, n, B, input_string): # Partition P into n+1 strings # The l...
33,704
[ { "from": "human", "value": "Inspired (you don't need to know them for this challenge) by the Pumping Lemma for various languages, I propose the following challenge:\n\nchoose some basis \\$B \\geq 2\\$ and an integer \\$n \\geq 0\\$\nwrite a program/function \\$P\\$\npartition* \\$P\\$ into some strings \\...
I have a list of images grouped numerically (YI0.png, YI1.png...YI20479.png). I want them sorted alphabetically, like so: YI0.png -> YIA.png YI1.png -> YIAA.png without my last image having 20479 As in it. Input A directory name. Output All files in that directory will be alphabetically renamed. Constraints The patte...
Here's a solution to the problem described, written in Python. It renames files in the specified directory according to your requirements: ```python import os import sys d=sys.argv[1] for f in os.listdir(d): k=int(f[3:-4]) n='' while k: n=chr(65+(k%26))+n k//=26 os.rename(os.path.join(d,f), os.path.join(d,f[:...
39,635
[ { "from": "human", "value": "I have a list of images grouped numerically (YI0.png, YI1.png...YI20479.png). I want them sorted alphabetically, like so:\nYI0.png -> YIA.png\nYI1.png -> YIAA.png\n\nwithout my last image having 20479 As in it.\nInput\nA directory name.\nOutput\nAll files in that directory will ...
Display the emoji of the eastern zodiac of given time, according to given country. The eastern zodiac is a classification scheme that assigns an animal and its reputed attributes to each year in a repeating 12-year cycle. It is also assigned to hours. Rules: The country must be given as ISO 3166-1 alpha-3 code. The li...
Here's a solution in Python that processes the input according to the rules specified: ```python def zodiac(s): m = { 'IRN': {23: '🐁', 0: '🐀', 1: '🐂', 2: '🐄', 3: '🐅', 4: '🐆', 5: '🐇', 6: '🐈', 7: '🐉', 8: '🐊', 9: '🐍', 10: '🐎', 11: '🐏', 12: '🐐', 13: '🐒', 14: '🐓', 15: '🐕', 16: '🐖', 17: '🐗', 1...
34,348
[ { "from": "human", "value": "Display the emoji of the eastern zodiac of given time, according to given country.\nThe eastern zodiac is a classification scheme that assigns an animal and its reputed attributes to each year in a repeating 12-year cycle. It is also assigned to hours.\nRules:\n\nThe country mus...
You are given a matrix of size m x n where each cell can contain either 1 or 0. You need to find the largest square submatrix that contains only 1's. The output should be the area of the largest square submatrix. For example, given the following matrix: 1 0 1 1 1 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0 The largest square submat...
To solve the problem of finding the largest square submatrix containing only 1's, we can use dynamic programming. The approach is to create a 2D array `dp` where `dp[i][j]` represents the size of the largest square submatrix that ends at cell `(i, j)`. ### Steps: 1. Initialize a 2D array `dp` with the same dimensions ...
36,986
[ { "from": "human", "value": "You are given a matrix of size m x n where each cell can contain either 1 or 0. You need to find the largest square submatrix that contains only 1's. The output should be the area of the largest square submatrix.\nFor example, given the following matrix:\n1 0 1 1 1\n1 0 1 1 1\n1...
You will be given a list of radii, you must output the area of the smallest rectangle which they will all fit in. For example, given the list [5,3,1.5] you would output 157.460. This is the image: The width is 15.7460 and the height is 10, so the area is 157.460 Rules: You get the list via stdin or function argument,...
Here is a Python function that computes the area of the smallest rectangle that can contain circles given their radii. The function takes a list of radii as input, calculates the required dimensions of the rectangle, and then computes and returns the area: ```python def smallest_rectangle_area(radii): from math im...
39,592
[ { "from": "human", "value": "You will be given a list of radii, you must output the area of the smallest rectangle which they will all fit in.\nFor example, given the list [5,3,1.5] you would output 157.460.\nThis is the image:\n\nThe width is 15.7460 and the height is 10, so the area is 157.460\nRules:\n\n...
In this question each answer will get a "toolbox" that can be used to construct a program/function. The toolbox will consist of two things: a list of programming languages a list of valid characters You must write a valid program/function in one of the languages provided using only the characters in the toolbox. Yo...
```python # Python program to output the number of answers already present print(1) ``` (Note: This is the first answer to the question, hence it outputs `1`.)
41,614
[ { "from": "human", "value": "In this question each answer will get a \"toolbox\" that can be used to construct a program/function. The toolbox will consist of two things:\n\na list of programming languages\na list of valid characters\n\nYou must write a valid program/function in one of the languages provid...
Palindromic dates are dates that appear as palindromes: the string of digits can be read the same way backwards as forwards. For the North American date format (MM/DD/YYYY), the next few palindromic dates are: 02/02/2020 12/02/2021 03/02/2030 The Challenge Create a function that returns all palindromic dates in a consi...
Here's a concise Python function that finds all palindromic dates within a specified range using the date format MM/DD/YYYY: ```python from datetime import datetime, timedelta def date_palindrome(start, end): date_format = '%m/%d/%Y' start_date = datetime.strptime(start, date_format) end_date = datetime.s...
39,209
[ { "from": "human", "value": "Palindromic dates are dates that appear as palindromes: the string of digits can be read the same way backwards as forwards. For the North American date format (MM/DD/YYYY), the next few palindromic dates are:\n02/02/2020\n12/02/2021\n03/02/2030\nThe Challenge\nCreate a function...
Introduction: In Dutch, the words leading and suffering, being 'leiden' and 'lijden' respectively, are pronounced the same way. One is written with a "short ei", and one with a "long ij", as we Dutchman would say, but both 'ei' and 'ij' are pronounced [ɛi]. Challenge: Given a list of numbers, determine which (if any) a...
Here's a Python solution that determines which numbers are leading and which are suffering based on the criteria provided. The implementation reads a list of integers and outputs two separate lists for leading and suffering numbers. ```python def classify_numbers(nums): # Separate positive and negative numbers and...
34,026
[ { "from": "human", "value": "Introduction:\nIn Dutch, the words leading and suffering, being 'leiden' and 'lijden' respectively, are pronounced the same way. One is written with a \"short ei\", and one with a \"long ij\", as we Dutchman would say, but both 'ei' and 'ij' are pronounced [ɛi].\nChallenge:\nGiv...
This challenge is inspired by this app. The test cases are borrowed from that app. This is a fastest-code challenge, where the objective is to solve the largest test cases in the least amount of time. There are provided some smaller test cases, so that people might test their algorithms faster. You'll be given a squa...
To solve the challenge of placing 2*n trees in an n-by-n grid while adhering to the provided rules, we can use a backtracking approach. This method allows us to systematically explore all valid configurations of tree placements while ensuring that the constraints are met. Here’s a structured plan for implementing this ...
31,446
[ { "from": "human", "value": "This challenge is inspired by this app. The test cases are borrowed from that app.\n\nThis is a fastest-code challenge, where the objective is to solve the largest test cases in the least amount of time. There are provided some smaller test cases, so that people might test their...
Do you have any code-golf tips for writing in SOGL, a golfing language created by dzaima? Your tips should be at least somewhat specific to SOGL. Please post one tip per answer.
One tip for coding in SOGL is to take advantage of its ability to use single-character variable names. Instead of using longer descriptive variable names, use single letters or symbols to represent your data. This can significantly reduce the character count of your code, especially in loops or when defining functions....
41,019
[ { "from": "human", "value": "Do you have any code-golf tips for writing in SOGL, a golfing language created by dzaima?\nYour tips should be at least somewhat specific to SOGL.\nPlease post one tip per answer.\n" }, { "from": "gpt", "value": "One tip for coding in SOGL is to take advantage of it...
Quell is a single-player grid-based puzzle game. Pearls are scattered across a 2D map and the aim is to collect them all by rolling a drop of water over them. For this challenge we will only consider basic maps containing the drop, pearls, walls, and empty spaces. (The full game includes a variety of additional objects...
Here's a Python implementation for the problem that determines whether all pearls on a given map can be collected by rolling a drop of water: ```python def can_collect_all_pearl(map_str): # Parse the map grid = [list(line) for line in map_str.splitlines() if line] h, w = len(grid), len(grid[0]) # ...
36,062
[ { "from": "human", "value": "Quell is a single-player grid-based puzzle game. Pearls are scattered across a 2D map and the aim is to collect them all by rolling a drop of water over them. For this challenge we will only consider basic maps containing the drop, pearls, walls, and empty spaces. (The full game...
This challenge is a riff on Dion's challenge "Is this a rectangle?". The goal of this challenge is to write a program to decide whether or not some collection of tuples of integers represents a hypercube of some dimension. Background A hypercube is a generalization of a square. A \$0\$-cube is a single point. A \$1\$...
To determine whether a given set of tuples represents a hypercube, we can follow these steps in Python: 1. Count the number of points (tuples). 2. Determine the expected number of vertices for the hypercube based on the dimension (which can be derived from the number of coordinates in each point). For a hypercube of d...
34,908
[ { "from": "human", "value": "This challenge is a riff on Dion's challenge \"Is this a rectangle?\". The goal of this challenge is to write a program to decide whether or not some collection of tuples of integers represents a hypercube of some dimension.\nBackground\nA hypercube is a generalization of a squa...
Given a directed graph on the nodes 0, 1, ..n, where each edge has two non-negative integer costs, return the set of all possible Pareto Optimal path costs between node 0 and node n. These are the costs of paths for which you cannot decrease the first component of the cost without increasing the second component, and c...
The problem requires finding all Pareto optimal paths from a source node (0) to a target node (n) in a directed graph where each edge has two non-negative integer costs. A path is Pareto optimal if you cannot reduce one of the costs without increasing the other. To solve this problem, we can utilize a breadth-first se...
26,081
[ { "from": "human", "value": "Given a directed graph on the nodes 0, 1, ..n, where each edge has two non-negative integer costs, return the set of all possible Pareto Optimal path costs between node 0 and node n.\nThese are the costs of paths for which you cannot decrease the first component of the cost with...
Introduction This challenge is similar to Project Euler problems. I came up with it because I was playing a deceivingly simple board game and couldn't come up with an efficient solution to answer a simple question about its mechanics. Quarto is a fun variant of 4 in a row. It is played on a 4 by 4 board with 16 unique ...
To tackle the problem of counting the number of draw positions in the game of Quarto, we need to consider several key aspects of the game mechanics and structure. Below is a comprehensive approach that explains the logic, the calculations, and presents a working solution in Python. ### Understanding the Problem 1. **...
32,628
[ { "from": "human", "value": "Introduction\nThis challenge is similar to Project Euler problems. I came up with it because I was playing a deceivingly simple board game and couldn't come up with an efficient solution to answer a simple question about its mechanics.\nQuarto is a fun variant of 4 in a row. It ...
Introduction As an example, let's take the number 7. We then duplicate this and place 7 spaces in between. We get this: 7_______7 After that, we are going to decrease the number, until there are no spaces left. We get the following for the number 7: 7_______7 6543210 Then, we just merge the two of them, so: 7___...
Here's a concise solution in Python that generates the output as described: ```python n=int(input());print(str(n)+''.join(map(str,range(n-1,-1,-1)))+str(n)) ``` ### Explanation: 1. `n=int(input())`: Reads an integer input. 2. `map(str, range(n-1, -1, -1))`: Creates a list of descending numbers from `n-1` to `0` (incl...
38,608
[ { "from": "human", "value": "Introduction\nAs an example, let's take the number 7. We then duplicate this and place 7 spaces in between. We get this:\n7_______7\n\nAfter that, we are going to decrease the number, until there are no spaces left. We get the following for the number 7:\n7_______7 \n 6543210...
The goal of this challenge is to determine if a move is a legal English Checkers move. This challenge will use an 8x8 board. A moved piece should be treated as a man (not a king) that can only move diagonally forward. The board will have 0 or more black pieces and 1 or more white piece. One white piece will be current...
To determine the legality of a move in English Checkers based on the provided rules, we can implement a function in Python. This function will check if a white piece can move to a specified ending position, considering the mandatory jump rule and the requirement to not jump over its own pieces. Here’s the concise imp...
32,992
[ { "from": "human", "value": "The goal of this challenge is to determine if a move is a legal English Checkers move. \nThis challenge will use an 8x8 board. A moved piece should be treated as a man (not a king) that can only move diagonally forward. The board will have 0 or more black pieces and 1 or more wh...
Challenge To quote Wikipedia: An octave-repeating scale can be represented as a circular arrangement of pitch classes, ordered by increasing (or decreasing) pitch class. For instance, the increasing C major scale is C–D–E–F–G–A–B–[C], with the bracket indicating that the last note is an octave higher than the first no...
Here's a Python solution to the challenge that takes a musical scale as input (either major or minor) and outputs the corresponding notes: ```python def scale_notes(s): p, o = 'CDEFGAB', 'CDEFGAB' m = {'': [2, 2, 1, 2, 2, 2, 1], 'm': [2, 1, 2, 2, 1, 2, 2]} r = {p[i]: o[(i + j) % 7] for i in range(7) for j ...
36,949
[ { "from": "human", "value": "Challenge\nTo quote Wikipedia:\n\nAn octave-repeating scale can be represented as a circular arrangement\nof pitch classes, ordered by increasing (or decreasing) pitch class. For instance, the increasing C major scale is C–D–E–F–G–A–B–[C], with the bracket indicating that the la...
Sandbox Post Intro The information panels are everywhere. When the technology became cheaper, the paper posters were transformed into luminous signs that show words that appear on one side and come out on the other, like the one on the figure: When one of these signs starts up, it usually starts empty and the text lea...
To solve the problem of calculating the number of light changes required to display a number on a 7-segment display sign, we need to follow these steps: 1. **Understanding the 7-Segment Representation**: Each digit from 0 to 9 can be represented using a combination of 7 segments (labeled a through g). Each digit light...
33,351
[ { "from": "human", "value": "Sandbox Post\nIntro\nThe information panels are everywhere. When the technology became cheaper, the paper posters were transformed into luminous signs that show words that appear on one side and come out on the other, like the one on the figure:\n\nWhen one of these signs starts...
inspired by Longest Increasing Substring Task Given a list of non-negative integers, output the length of its longest alternating subsequence. An alternating sequence is a sequence of numbers which alternates between strictly increasing and strictly decreasing. [], [999], [9, 1], and [0, 5, 0, 3, 2, 4] are examples of ...
Here’s a Python implementation to find the length of the longest alternating subsequence from a list of non-negative integers. The code attempts to be concise while effectively solving the problem. ```python def longest_alternating_subsequence(arr): if not arr: return 0 n = len(arr) if n == 1: ...
36,786
[ { "from": "human", "value": "inspired by Longest Increasing Substring\nTask\nGiven a list of non-negative integers, output the length of its longest alternating subsequence.\nAn alternating sequence is a sequence of numbers which alternates between strictly increasing and strictly decreasing. [], [999], [9,...
Steve Ballmer is the ex-CEO of Microsoft, and in a recent article, claimed that he "still does not know what he did wrong with mobile". As CodeProject's newsletter pointed out, "That article's title could be ended at so many spots and still be accurate". Given no input, output the following: Steve Ballmer still does no...
Here is a solution in Python: ```python print("Steve Ballmer still does not know.\nSteve Ballmer still does not know what he did.\nSteve Ballmer still does not know what he did wrong.\nSteve Ballmer still does not know what he did wrong with mobile.") ```
41,368
[ { "from": "human", "value": "Steve Ballmer is the ex-CEO of Microsoft, and in a recent article, claimed that he \"still does not know what he did wrong with mobile\".\nAs CodeProject's newsletter pointed out, \"That article's title could be ended at so many spots and still be accurate\".\nGiven no input, ou...
Your goal is to create an alphabet song as text in the following form (in order): A is for <word starting with A> B is for <word starting with B> C is for <word starting with C> ... Z is for <word starting with Z> Example output: A is for Apple B is for Banana C is for Carrot D is for Door E is for Elephant F is for F...
Here's the alphabet song in the specified format: ``` A is for Apple B is for Butterfly C is for Cookie D is for Dinosaur E is for Elephant F is for Firefly G is for Giraffe H is for Honey I is for Igloo J is for Jungle K is for Kitten L is for Lantern M is for Mountain N is for Nectar O is for Octopus P is for Pengui...
40,591
[ { "from": "human", "value": "Your goal is to create an alphabet song as text in the following form (in order):\nA is for <word starting with A>\nB is for <word starting with B>\nC is for <word starting with C>\n...\nZ is for <word starting with Z>\n\nExample output:\nA is for Apple\nB is for Banana\nC is fo...
Take an array which consists of positive integers or arrays, output if it only contains 2s. Output should be a truthy or falsey value (Sorry if this destroys answers) Truthy Test Cases [2] [2,2] [[2],[2,2],2] [] [[],[]] Falsey Test Cases [1] [22] [2,2,2,1] [[1,2],2] Standard Loopholes Are forbidden. Default IO rules ...
Here's a concise solution in Python: ```python def f(a): return all(isinstance(x, list) and f(x) or x == 2 for x in a) ``` This function checks if every element in the array is either a 2 or an array that only contains 2s. It will return `True` (truthy) if all elements satisfy the condition and `False` (falsey) o...
41,183
[ { "from": "human", "value": "Take an array which consists of positive integers or arrays, output if it only contains 2s.\nOutput should be a truthy or falsey value (Sorry if this destroys answers)\nTruthy Test Cases\n[2]\n[2,2]\n[[2],[2,2],2]\n[]\n[[],[]]\n\nFalsey Test Cases\n[1]\n[22]\n[2,2,2,1]\n[[1,2],2...
Note: The title of this question should be "Loop It", but because title needs to be at least 15 characters, there are some invisible spaces. This note is such that the challenge can be searched for. Challenge Given a finite list of unique integral points in the plane, find a polygon whose vertices are exactly those...
To solve the problem of finding a simple polygon from a list of unique integral points in the plane, we can use the concept of the convex hull. The convex hull is the smallest convex polygon that can enclose all given points, and it ensures that the polygon does not self-intersect. Here's how we can approach the proble...
32,562
[ { "from": "human", "value": "\nNote: The title of this question should be \"Loop It\", but because title needs to be at least 15 characters, there are some invisible spaces. This note is such that the challenge can be searched for. \n\n\nChallenge\nGiven a finite list of unique integral points in the plane,...
Cross posted from my anagolf post (note: may contain spoilers, post mortem). Output the following text exactly. You may have additional trailing whitespace on each line, and trailing newlines as well. Shortest code, in bytes, wins. ...
``` You may have additional trailing whitespace on each line, and trailing newlines as well. Shortest code, in bytes, wins. !"! "#$#" #...
32,995
[ { "from": "human", "value": "Cross posted from my anagolf post (note: may contain spoilers, post mortem).\nOutput the following text exactly.\n\nYou may have additional trailing whitespace on each line, and trailing newlines as well.\nShortest code, in bytes, wins.\n\n ...
Imagine an arsonist walking around the town and picking its victims according to a very specific pattern (Or, alternatively, Imagine a bee flying around the garden and picking its flowers to pollenize according to a very specific pattern). Let's say the town is an N × N matrix, where N is an integer higher than or equa...
Here is a Python solution that implements the logic of the arsonist moving through the town represented by an N × N matrix according to the specified pattern: ```python def lullaby(matrix): N = len(matrix) direction = [(0, 1), (1, 0), (0, -1), (-1, 0)] # East, South, West, North x, y = 0, 0 # Starting po...
33,041
[ { "from": "human", "value": "Imagine an arsonist walking around the town and picking its victims according to a very specific pattern (Or, alternatively, Imagine a bee flying around the garden and picking its flowers to pollenize according to a very specific pattern). Let's say the town is an N × N matrix, ...
I didn't check the sandbox before posting this challenge - it looks like this challenge was proposed by Cᴏɴᴏʀ O'Bʀɪᴇɴ. Given an integer input, write a program that prints the "four is a magic number" riddle Four is the magic number Five is four and four is the magic number Six is three and three is five and five is fo...
## Python, 176 bytes ```python n={"zero":4,"one":3,"two":3,"three":5,"four":4,"five":4,"six":3,"seven":5,"eight":5,"nine":4,"ten":3,"eleven":6,"twelve":6,"thirteen":8,"fourteen":8,"fifteen":7,"sixteen":7,"seventeen":9,"eighteen":8,"nineteen":6,"twenty":6,"thirty":6,"forty":5,"fifty":5,"sixty":5,"seventy":7,"eighty":6,...
38,103
[ { "from": "human", "value": "I didn't check the sandbox before posting this challenge - it looks like this challenge was proposed by Cᴏɴᴏʀ O'Bʀɪᴇɴ.\nGiven an integer input, write a program that prints the \"four is a magic number\" riddle\n\nFour is the magic number\nFive is four and four is the magic numbe...
Task You will be given a string in the input consisting only of the characters from a to z, i.e. the input will match the regex /^[a-z]*$/. Your output should be a complete program in the same language, whose source code contains the input, and is a proper quine. Example Your program would receive the input abc and out...
Here's a simple quine in Python that takes your input string and outputs itself: ```python s='abc';print(s.replace('abc',s)) ``` This will output the entire program including the string `abc` when run. Just replace `'abc'` with your desired input string, and it will work accordingly as a proper quine.
41,082
[ { "from": "human", "value": "Task\nYou will be given a string in the input consisting only of the characters from a to z, i.e. the input will match the regex /^[a-z]*$/.\nYour output should be a complete program in the same language, whose source code contains the input, and is a proper quine.\nExample\nYou...
Given a string consisting of printable ASCII chars, produce an output consisting of its unique chars in the original order. In other words, the output is the same as the input except that a char is removed if it has appeared previously. No built-ins for finding unique elements in an array can be used (for example, MATL...
Here's a concise Python solution that retains only the unique characters from the input string while maintaining their original order: ```python def unique_chars(s): u = "" for c in s: if c not in u: u += c return u # Example usage print(unique_chars("Type unique chars!")) print(unique...
37,579
[ { "from": "human", "value": "Given a string consisting of printable ASCII chars, produce an output consisting of its unique chars in the original order. In other words, the output is the same as the input except that a char is removed if it has appeared previously.\nNo built-ins for finding unique elements ...
Given a non-negative integer input, write a program that converts the number to hexadecimal and returns a truthy value if the hexadecimal form of the number contains only the characters A through F and a falsey value otherwise. Test cases 10 ==> True (A in hexadecimal) 100 ==> False (64 in hexadecimal) 161 ==> False...
Here's a concise Python solution for your problem: ```python def hex_check(n): h=hex(n)[2:].upper() return all(c in 'ABCDEF' for c in h),h ``` You can test this function with the provided test cases: ```python print(hex_check(10)) # (True, 'A') print(hex_check(100)) # (False, '64') print(hex_che...
38,037
[ { "from": "human", "value": "Given a non-negative integer input, write a program that converts the number to hexadecimal and returns a truthy value if the hexadecimal form of the number contains only the characters A through F and a falsey value otherwise.\n\nTest cases\n10\n==> True (A in hexadecimal)\n\n1...
Task Inputs \$b \leq 100\$ and \$n \geq 2\$. Consider \$n\$ binary strings, each of length \$b\$ sampled uniformly and independently. We would like to compute the expected minimum Hamming distance between any pair. If \$n = 2\$ the answer is always \$b/2\$. Correctness Your code should ideally be within \$\pm0.5\$ o...
To solve the problem of computing the expected minimum Hamming distance between pairs of binary strings, we need to break down the problem mathematically. Here's how you could approach the calculation and its implementation. ### Mathematical Background 1. **Hamming Distance**: The Hamming distance between two binary ...
34,645
[ { "from": "human", "value": "Task\nInputs \\$b \\leq 100\\$ and \\$n \\geq 2\\$. Consider \\$n\\$ binary strings, each of length \\$b\\$ sampled uniformly and independently. We would like to compute the expected minimum Hamming distance between any pair. If \\$n = 2\\$ the answer is always \\$b/2\\$. \nCo...
Write a function or program that takes as its input a string and prints a truthy value if the string is a pangram (a sequence of letters containing at least one of each letter in the English alphabet) and a falsey value otherwise. Case of letters should be ignored; If the string is abcdefghijklmnopqrstuvwXYZ, then the ...
Here’s a concise implementation in Python that checks whether a given string is a pangram. This implementation is designed to be short and efficient for code golf purposes: ```python def is_pangram(s): return len(set(s.lower()) & set('abcdefghijklmnopqrstuvwxyz')) == 26 ``` ### Explanation: 1. **`s.lower()`**: Co...
38,021
[ { "from": "human", "value": "Write a function or program that takes as its input a string and prints a truthy value if the string is a pangram (a sequence of letters containing at least one of each letter in the English alphabet) and a falsey value otherwise.\nCase of letters should be ignored; If the strin...
Context: Gynvael Coldwind, a famous security researcher, published a contest in his blog post (that is now complete). The goal was similar to the one described here, but with certain restrictions depending on which of the three allowed programming languages was chosen. I found the exercise fun and wanted to extend the ...
Creating a golf program that generates a PNG file with specific pixel values requires a compact and efficient approach. Below are examples in different programming languages to achieve this goal. Each example is written to produce the same output image specified in the task. ### Python ```python from PIL import Image...
34,025
[ { "from": "human", "value": "Context:\nGynvael Coldwind, a famous security researcher, published a contest in his blog post (that is now complete). The goal was similar to the one described here, but with certain restrictions depending on which of the three allowed programming languages was chosen. I found ...
The goal of this challenge is to fill a niche that is mostly lacking on this site. In my observations there most parsing verification challenges fall into two categories: Super easy parsing. This parsing can usually be done with a regex, and regex based answers usually do well. Super complex parsing. These are cha...
This challenge involves validating a lisp-like lambda expression based on specific rules, which requires a parser that can handle context-sensitive grammar. Below is a Python implementation to validate the provided lambda expressions according to the given specifications. ```python def is_valid_lambda(expr): def p...
35,940
[ { "from": "human", "value": "The goal of this challenge is to fill a niche that is mostly lacking on this site. In my observations there most parsing verification challenges fall into two categories:\n\nSuper easy parsing. This parsing can usually be done with a regex, and regex based answers usually do w...
There's something (well, many things ) that really annoys me. It is when dictionaries (English, not Pythonic) use the defining word itself to define the word, also called circular definitions. Example: reticence: the quality of being reticent -- Apple Dictionary Circular definition: a definition that is circular --...
# Python, 131 bytes ```python def c(d):return sum(any(x in y for x in[1,'ing','ed','ly'])for k,y in d.items()for p in[k,k+z for z in ['','ing','ed','ly']]if p in y) d={input().split(':')[0]:input().split(':')[1]for _ in range(int(input()))} print(c(d)) ``` ## Explanation - The function `c(d)` counts the circular defi...
40,054
[ { "from": "human", "value": "There's something (well, many things ) that really annoys me. It is when dictionaries (English, not Pythonic) use the defining word itself to define the word, also called circular definitions. Example:\n\nreticence: the quality of being reticent\n\n-- Apple Dictionary\n\nCircula...
Github You have probably played, and may even have written a program to play, a simple number guessing game. If so, this probably looks familiar: Try to guess my number (1 to 100)! Please enter a guess: 50 Too small, guess again! Please enter a guess: 75 Too big, guess again! Please enter a guess: 63 Correct! (Obvious...
Here’s a solution for both the Liar and Guesser components of the challenge: ### Liar Implementation The liar will maintain a count of the lies it has told and will strategically lie a few times to prolong the game. In this implementation, the liar will alternate between returning the correct relationship and lying b...
35,512
[ { "from": "human", "value": "Github\nYou have probably played, and may even have written a program to play, a simple number guessing game. If so, this probably looks familiar:\nTry to guess my number (1 to 100)!\nPlease enter a guess: 50\nToo small, guess again!\nPlease enter a guess: 75\nToo big, guess aga...
GolfScript automatically coerces values, according to the following ‘priority’ sequence: integer → array → string → block (listed from lowest to highest.) This means that "1"7+ leaves the string "17" on the stack (and not 8), because strings have a higher priority than integers. [To those GolfScript veterans – apolog...
In GolfScript, to coerce a string into an integer, you can use the `to` command followed by the type you want to convert to. In this case, you want to convert a string to an integer. Here's how you can do it: ```golfscript "42" to i ``` In this example, the string `"42"` is coerced to the integer `42` using the `to i...
39,320
[ { "from": "human", "value": "GolfScript automatically coerces values, according to the following ‘priority’ sequence:\n\ninteger → array → string → block\n\n(listed from lowest to highest.)\nThis means that \"1\"7+ leaves the string \"17\" on the stack (and not 8), because strings have a higher priority tha...
You must write a program or function that takes a string of brackets and outputs whether or not that string is fully matched. Your program should print a truthy or falsy value, and IO can be in any reasonable format. Rules and definitions: For the purpose of this challenge, a "bracket" is any of these characters: ()[]...
Here’s a concise implementation of a function in Python that checks whether a string of brackets is fully matched according to your specified rules: ```python def matched(s): if not all(c in '()[]{}<>' for c in s): return False stack = [] pairs = {')':'(', ']':'[', '}':'{', '>':'<'} for c in s: ...
38,832
[ { "from": "human", "value": "You must write a program or function that takes a string of brackets and outputs whether or not that string is fully matched. Your program should print a truthy or falsy value, and IO can be in any reasonable format.\nRules and definitions:\n\nFor the purpose of this challenge, ...
Given a string, find the first word starting with each letter (case insensitive). Sample Using Ferulas flourish in gorgeous gardens. as input: "Ferulas flourish in gorgeous gardens." ^^^^^^^ ^^ ^^^^^^^^ | | | | | --> is the first word starting with `g` | --> i...
Here is a concise Python solution to the problem, using regular expressions for word extraction and a dictionary to track the first occurrences: ```python def first_words(s): import re words = re.findall(r'\w+', s) seen = {} for w in words: c = w[0].lower() if c not in seen: ...
38,842
[ { "from": "human", "value": "Given a string, find the first word starting with each letter (case insensitive).\nSample\nUsing Ferulas flourish in gorgeous gardens. as input:\n\"Ferulas flourish in gorgeous gardens.\"\n ^^^^^^^ ^^ ^^^^^^^^\n | | |\n | | --> is the fir...
Inspired by the fact that a few related challenges to this could be answered by Vyxal in 0 Bytes using a special flag combination. Given only one input integer \$n\$, calculate \$f(n,n)\$ where $$ f(x,y)= \begin{cases} x & \text{if } y=0 \\ f(\left(\sum_{k=1}^xk\right),\text{ }y-1) & \text{otherwise} \end{cases} $$ If ...
Here is a Python implementation to calculate \( f(n, n) \) as defined in your problem. This code uses recursion to compute the triangular number and iterates it \( n \) times. ```python def triangular(k): return k * (k + 1) // 2 def f(n): result = n for _ in range(n): result = triangular(result) ...
37,168
[ { "from": "human", "value": "Inspired by the fact that a few related challenges to this could be answered by Vyxal in 0 Bytes using a special flag combination.\nGiven only one input integer \\$n\\$, calculate \\$f(n,n)\\$ where\n$$ f(x,y)=\n\\begin{cases}\nx & \\text{if } y=0 \\\\\nf(\\left(\\sum_{k=1}^xk\\...
Note: This is a more limited version of a challenge from 2014 that only received one answer. That challenge required participants write two programs; this challenge is essentially one half of that. The text here is original, but credit for the idea goes to Matthew Butterick, who is no longer active on the site. Given...
Here's a Python solution for the given problem that identifies the smallest submatrix containing all unique elements of a provided matrix. This implementation is designed for code-golf, prioritizing brevity. ```python def smallest_submatrix(M): from itertools import product unique_elements = set(elem for row i...
36,878
[ { "from": "human", "value": "\nNote: This is a more limited version of a challenge from 2014 that only received one answer. That challenge required participants write two programs; this challenge is essentially one half of that. The text here is original, but credit for the idea goes to Matthew Butterick, w...
Challenge Given two numbers, output their quotient. In other words, integer divide one number by another. Both divisor/dividend will be under 10001. Division must be performed using integer division, rounding down. Here are some example inputs and outputs: 5 1 5 -4 2 -2 4 -2 -2 6 ...
Here's a concise solution to the challenge using Python, which is not esoteric but provides a clear approach to integer division: ```python a,b=map(int,input().split()) print(a//b) ``` This code reads two integers from input, performs integer division (using `//`), and prints the result. If you're looking for an eso...
40,866
[ { "from": "human", "value": "Challenge\nGiven two numbers, output their quotient. In other words, integer divide one number by another.\nBoth divisor/dividend will be under 10001. Division must be performed using integer division, rounding down.\nHere are some example inputs and outputs:\n5 1 5\...
This question is part of a series Brain-flak Birthday challenges designed to celebrate Brain-Flak's first Birthday. You can find more information about Brain-Flak's Birthday here. Today is Brain-Flak's first Birthday! So I thought we would throw it a surprise birthday party. So in your favorite language print Surp...
Here’s a solution in Python that satisfies the requirements of the Brain-Flak Birthday challenge: ```python print("Surprise!\nHappy Birthday, Brain-Flak!") ``` **Explanation:** - The solution uses the `print` function to output the two lines of text. - The newline character `\n` is used to separate the two lines with...
41,070
[ { "from": "human", "value": "\nThis question is part of a series Brain-flak Birthday challenges designed to celebrate Brain-Flak's first Birthday. You can find more information about Brain-Flak's Birthday here.\n\nToday is Brain-Flak's first Birthday! So I thought we would throw it a surprise birthday part...
Challenge The primitive circle problem is the problem of determining how many coprime integer lattice points \$x,y\$ there are in a circle centered at the origin and with radius \$r \in \mathbb{Z}^+ \$ such that \$x^2+y^2 \le r^2 \$. It's a generalization of Code-Golf: Lattice Points inside a Circle. Input Radius \$r...
To solve the primitive circle problem, we need to count the number of coprime integer lattice points \((x, y)\) that lie within a circle of radius \(r\), centered at the origin. This requires that \(x^2 + y^2 \leq r^2\) and that the greatest common divisor (gcd) of \(x\) and \(y\) is 1 (i.e., \(\text{gcd}(x, y) = 1\))....
37,512
[ { "from": "human", "value": "Challenge\nThe primitive circle problem is the problem of determining how many coprime integer lattice points \\$x,y\\$ there are in a circle centered at the origin and with radius \\$r \\in \\mathbb{Z}^+\n\\$ such that \\$x^2+y^2 \\le r^2 \\$. It's a generalization of Code-Gol...
We all often hear the idiom "walk through the array" to mean "map the function over the following array". However, I need it done (now!), so I want you to run through the array. How do I run? Imagine there's a wild pack of wolves behind you Running through an array is like walking through one, except you can skip over...
Here's a concise solution in Python that adheres to your requirements. The program "runs through" the array while adding a given value \( K \) to random elements based on the specified conditions. ```python import random def run_through_array(A, K): return [x + K if random.random() >= 0.5 else x for x in A] ``` ...
38,940
[ { "from": "human", "value": "We all often hear the idiom \"walk through the array\" to mean \"map the function over the following array\". However, I need it done (now!), so I want you to run through the array.\nHow do I run?\nImagine there's a wild pack of wolves behind you\nRunning through an array is lik...
You have been chosen to make a program that creates some pretty ASCII bar charts. Here is the input format: [List of words (they can have spaces)] [an integer >= 0] Bar 3 This is so cool 4 IDK-Why 6 The input will have multiple lines in this format, each one representing one bar in the graph. The output format of a gr...
Here's a Python program that takes input in the specified format and produces an ASCII bar chart as output. ```python def create_bar_chart(data): # Find the maximum height of the bars max_height = max(count for _, count in data) # Prepare the chart levels chart = [] # Create the graph fro...
38,198
[ { "from": "human", "value": "You have been chosen to make a program that creates some pretty ASCII bar charts. Here is the input format:\n[List of words (they can have spaces)] [an integer >= 0]\nBar 3\nThis is so cool 4\nIDK-Why 6\n\nThe input will have multiple lines in this format, each one representing ...
Given a nonzero polynomial with integer coefficients and roots that are on the imaginary and on the real line such that if a is a root then so is -a, return another polynomial with the roots rotated by 90 degrees. Details The polynomial can be given in any reasonable format, e.g. as a list of coefficients. The symmetry...
To rotate the roots of a polynomial by 90 degrees, we can substitute \( x \) with \( ix \) in the polynomial. This operation transforms the roots from \( r \) to \( ir \) for every root \( r \) of the polynomial. The resulting polynomial will also have real coefficients, as the original polynomial has the symmetry cond...
31,050
[ { "from": "human", "value": "Given a nonzero polynomial with integer coefficients and roots that are on the imaginary and on the real line such that if a is a root then so is -a, return another polynomial with the roots rotated by 90 degrees.\nDetails\nThe polynomial can be given in any reasonable format, e...
Now that we're graduating, it's time to tally up the number of times someone suggested that PPCG was graduating, even before the annoucement! (see here) Your program will receive a list of chat messages. Each message has three pieces of data: the user (e.g. Geobits), the timestamp (e.g. Aug 19 '15 2:41 PM), and the mes...
To solve the problem of counting chat messages related to PPCG's graduation prior to the official announcement, we can follow a structured approach. The task will involve filtering messages based on specific criteria and counting occurrences by users. Below is a Python implementation to achieve this: ```python import ...
28,539
[ { "from": "human", "value": "Now that we're graduating, it's time to tally up the number of times someone suggested that PPCG was graduating, even before the annoucement! (see here)\nYour program will receive a list of chat messages. Each message has three pieces of data: the user (e.g. Geobits), the timest...
Task Make code given on the command line that takes an unpacked hex value as input and evals that in Perl. Like this: perl -e 'map{eval}pack q/h*/,q/072796e6470222458656275672370202d6f62756020222b302072796e6470222478616e60202f6e6560202771697020247f6020246f602029647e2c5e622/' But with one additional restriction: Your c...
To create a Perl command that meets the specified requirements and can survive multiple levels of SSH, we need to avoid any spaces that would require additional quoting when run in a shell. Here's a solution: ```bash perl -e 'print eval pack("H*", "072796e6470222458656275672370202d6f62756020222b302072796e6470222478616...
36,269
[ { "from": "human", "value": "Task\nMake code given on the command line that takes an unpacked hex value as input and evals that in Perl. Like this:\nperl -e 'map{eval}pack q/h*/,q/072796e6470222458656275672370202d6f62756020222b302072796e6470222478616e60202f6e6560202771697020247f6020246f602029647e2c5e622/'\n...
The winner (pretty obviously) is Dennis ♦, who used Jelly with 10 bytes! This challenge will still be up here, however results won't be taken anymore. The powertrain of a number is a concept by John Conway (who is also notable for making Conway's Game of Life, but that's not the point). It is defined as so: For any nu...
Here's a Python solution to the problem of computing the powertrain of a number, following the rules specified in your challenge. This implementation aims for clarity while still being concise. ```python def powertrain(n): if n < 10: return n while True: d = str(n) if len(d) == 1: break ...
38,670
[ { "from": "human", "value": "The winner (pretty obviously) is Dennis ♦, who used Jelly with 10 bytes!\nThis challenge will still be up here, however results won't be taken anymore.\n\nThe powertrain of a number is a concept by John Conway (who is also notable for making Conway's Game of Life, but that's not...
A fun programming exercise is to write a program that quizzes the user from a set list of questions and answers. However, this task goes a level beyond that. Your task Write a program/func/etc. that takes two lists: A list of questions and a list of answers. Output a program that quizzes the user. The output program s...
Here’s a simple code-golf solution written in Python that creates a quiz program based on the requirements you've specified. The solution is designed to be concise, achieving the functionality in as few bytes as possible. ```python q,a=input().split(),input().split() exec("r=0\nfor i in range(len(q)):\n d=input(q[i]+'...
37,913
[ { "from": "human", "value": "A fun programming exercise is to write a program that quizzes the user from a set list of questions and answers. However, this task goes a level beyond that.\nYour task\n\nWrite a program/func/etc. that takes two lists: A list of questions and a list of answers.\nOutput a progra...
Introduction Of course, we've got a lot of sequence challenges, so here is another one. The Kimberling sequence (A007063) goes as following: 1, 3, 5, 4, 10, 7, 15, 8, 20, 9, 18, 24, 31, 14, 28, 22, ... This is produced by shuffling the normal iteration: [1] 2 3 4 5 6 7 8 The first term of the sequence is 1. Aft...
Here is a concise Python solution to generate the first `n` terms of the Kimberling sequence, implemented in a code-golf style: ```python def k(n): a,c=[1],[2] for i in range(1,n): a.append(c.pop(i)) b=c[:i][::-1]+c[i:] c=b return a ``` To run the function and output the result for...
38,117
[ { "from": "human", "value": "Introduction\nOf course, we've got a lot of sequence challenges, so here is another one.\nThe Kimberling sequence (A007063) goes as following:\n1, 3, 5, 4, 10, 7, 15, 8, 20, 9, 18, 24, 31, 14, 28, 22, ...\n\nThis is produced by shuffling the normal iteration:\n[1] 2 3 4 5 6 ...
Your task is to program a mathematical function \$s\$, that takes a nonempty finite set \$A\$ of points in the 2D plane, and outputs an uncircularity score \$s(A)\$ that satisfies following properties: Positive Definiteness: If there is a circle or a straight line that contains all points of \$A\$, then \$s(A) = 0\$. ...
To define a mathematical function \( s \) that fulfills the specified properties for the uncircularity score of a non-empty finite set \( A \) of points in the 2D plane, we can utilize the concept of the "convex hull" of the set of points. The idea is to measure how much the distribution of points deviates from being c...
32,482
[ { "from": "human", "value": "Your task is to program a mathematical function \\$s\\$, that takes a nonempty finite set \\$A\\$ of points in the 2D plane, and outputs an uncircularity score \\$s(A)\\$ that satisfies following properties:\n\nPositive Definiteness: If there is a circle or a straight line that ...
A binary matrix represents a shape in the plane. 1 means a unit square at that position. 0 means nothing. The background is 0. For example, the matrix [[0,1,0],[0,0,1],[1,1,1]] represents the following shape: o----o |////| |////| o----o----o |////| |////| o----o----o----o |////|/...
Here's a solution to calculate the Euler characteristic for a given binary matrix in Python. The approach uses depth-first search (DFS) to count connected components and holes. This implementation is concise to achieve the goal of code-golf. ```python def euler_chi(m): h, w = len(m), len(m[0]) visited = [[0]*w...
36,519
[ { "from": "human", "value": "A binary matrix represents a shape in the plane. 1 means a unit square at that position. 0 means nothing. The background is 0.\nFor example, the matrix [[0,1,0],[0,0,1],[1,1,1]] represents the following shape:\n o----o\n |////|\n |////|\n o----o----o\n |...
Introduction It was just a normal day, here at your military base. Suddenly, you looked up to see a bomb falling down from the sky! You need to create a program to predict where it will fall, and tell you the location. Challenge You will be given a bomb in the form of Start-X Start-Y X-velocity Y-velocity. You can assu...
Here is a concise solution in Python that meets the requirements of the challenge: ```python print((lambda x,y,vx,vy: x+vx*(y//vy))(0,10,2,2)) ``` This code calculates the x-coordinate of the bomb's landing position given the initial conditions, and it uses a lambda function to compute it in a single line. The inputs...
40,894
[ { "from": "human", "value": "Introduction\nIt was just a normal day, here at your military base. Suddenly, you looked up to see a bomb falling down from the sky! You need to create a program to predict where it will fall, and tell you the location.\nChallenge\nYou will be given a bomb in the form of Start-X...
You would simply take this image and make every color added one to every hexadecimal digit. For example, #49de5f would become #5aef60 (with the 9 looping to an a, and the f looping to a 0.) This would also mean that all white (#ffffff) would become black (#000000) because all f loops back to 0, but all black will beco...
To achieve the hexadecimal color transformation you described, we can use Python with the Pillow library. The following code reads an image, modifies its colors by adding one to each hexadecimal digit, and then saves the output image. Here's how you can implement it: ```python from PIL import Image def hex_color_tra...
39,185
[ { "from": "human", "value": "You would simply take this image and make every color added one to every hexadecimal digit. For example, #49de5f would become #5aef60 (with the 9 looping to an a, and the f looping to a 0.)\n\nThis would also mean that all white (#ffffff) would become black (#000000) because all...
Background There are self-extracting .ZIP files. Typically they have the extension .EXE (and by executing the file they will be extracted) but when renaming them to .ZIP, you can open the file with some ZIP extracting software. (This is possible because .EXE files require a certain header but .ZIP files require a certa...
Creating a "self-displaying" image file that can function both as an image and an executable is a fascinating project. Below is a conceptual outline of how you could achieve this, along with a simple implementation example. ### Concept Outline 1. **Image Selection**: Choose a simple 64x64 image that uses at least 4 c...
34,034
[ { "from": "human", "value": "Background\nThere are self-extracting .ZIP files. Typically they have the extension .EXE (and by executing the file they will be extracted) but when renaming them to .ZIP, you can open the file with some ZIP extracting software.\n(This is possible because .EXE files require a ce...
I remember people saying that code size should be measured in bytes, and not in characters, because it's possible to store information with weird Unicode characters, which have no visual meaning. How bad can it be? In this challenge, you should output the following Lorem Ipsum text, taken from Wikipedia: Lorem ipsum do...
Here's a minimal solution in Python that outputs the specified Lorem Ipsum text, while adhering to the Unicode character constraints outlined in your challenge. ```python print("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim ...
29,518
[ { "from": "human", "value": "I remember people saying that code size should be measured in bytes, and not in characters, because it's possible to store information with weird Unicode characters, which have no visual meaning.\nHow bad can it be?\nIn this challenge, you should output the following Lorem Ipsum...
Consider the following 9 "row patterns", using 0s to represent empty cells and 1s to represent a full cell. Each pattern is associated with an integer \$n\$, such that \$0 \le n \le 8\$ (multiple [1,1,1,1,1,1]s exist as there's some difference that we don't care about): \$n\$ Pattern 0 [0,0,0,0,0,0] 1 [1,1,1,...
Here's a concise Python solution to the problem, which checks whether all non-zero values in a generated matrix are supported: ```python def valid(s): p=[[0]*6 for _ in range(6)] r=[0,1,1,1,1,0,1,0,0,1,1,0,1,1,1,1,1,1,1,1] for i,v in enumerate(s): for j in range(6): p[i][j]=r[6*v+j] ...
35,989
[ { "from": "human", "value": "Consider the following 9 \"row patterns\", using 0s to represent empty cells and 1s to represent a full cell. Each pattern is associated with an integer \\$n\\$, such that \\$0 \\le n \\le 8\\$ (multiple [1,1,1,1,1,1]s exist as there's some difference that we don't care about):\...
Task Haskell's and Scala's standard libraries have an unfold function that builds a list from an initial state s and a function f. This is done with the following steps (explained in an imperative way to be simpler): Apply f to s. If the result is empty, we're done building the list! Otherwise, the result should cont...
Below is a Haskell implementation of the `unfold` function as you described, which can convert positive integers from base 10 to another base represented by a reversed list of digits. The core of the implementation is the unfolding process, which utilizes a helper function for the specific base conversion logic. ### H...
35,912
[ { "from": "human", "value": "Task\nHaskell's and Scala's standard libraries have an unfold function that builds a list from an initial state s and a function f. This is done with the following steps (explained in an imperative way to be simpler):\n\nApply f to s.\nIf the result\n\nis empty, we're done build...
The least common multiple of a set of positive integers A is the smallest postive integer B such that, for each k in A, there exists a positive integer n such that k*n = B. Given at least two positive integers as input, output their least common multiple. Rules Builtins are allowed, but if your solution uses one, you ...
To find the least common multiple (LCM) of a set of positive integers, we can utilize the relationship between the LCM and the greatest common divisor (GCD). The relationship is defined as follows: \[ \text{LCM}(a, b) = \frac{|a \times b|}{\text{GCD}(a, b)} \] This means that to calculate the LCM of two numbers, we c...
29,645
[ { "from": "human", "value": "The least common multiple of a set of positive integers A is the smallest postive integer B such that, for each k in A, there exists a positive integer n such that k*n = B.\nGiven at least two positive integers as input, output their least common multiple.\nRules\n\nBuiltins are...
This should be easy: given an arbitrary string, your program will give it a name. Requirements Your program will accept an input of a UTF8 string, and output a string representing the input's "name", how you define this name is arbitrary, but it must comply with some conditions. I/O Ranges The input will at most be 382...
Here's a solution to generate a "name" for an arbitrary UTF-8 string while adhering to your conditions. The name will be based on a hash of the input string and then encoded to ensure it meets the length requirement. We'll use Python for this implementation. The output will be a string of a maximum of 10 characters a...
34,650
[ { "from": "human", "value": "This should be easy: given an arbitrary string, your program will give it a name.\nRequirements\nYour program will accept an input of a UTF8 string, and output a string representing the input's \"name\", how you define this name is arbitrary, but it must comply with some conditi...
A numeronym (also known as a "numerical contraction") is when a word is shortened using numbers. A common contraction method is to use the length of the replaced substring to replace all but the first and last characters. For example, use i18n instead of internationalization, or L10n instead of localization. (The L is ...
Here's a Python function that implements the logic to convert words into numeronyms according to the specified rules. The function also checks for ambiguity as required: ```python def numeronymize(s): from collections import defaultdict def to_numeronym(word): n = len(word) if n <= 3: ...
37,984
[ { "from": "human", "value": "A numeronym (also known as a \"numerical contraction\") is when a word is shortened using numbers. A common contraction method is to use the length of the replaced substring to replace all but the first and last characters. For example, use i18n instead of internationalization, ...
Carry sort is an \$O(n)\$ "sorting" algorithm. Here's how it works. The algorithm moves left to right along a list. As it traverses a list it "carries" a single item, the largest item it has encountered so far. Once it encounters a larger item it picks up that item and drops the item it is already carrying in place. W...
Here is a Python solution for the given problem that aims to determine the minimum number of passes required for carry sort to fully sort a list of integers in ascending order. The solution is optimized for brevity: ```python def carry_sort_passes(l): p = 0 while l != sorted(l): m = None for i ...
37,055
[ { "from": "human", "value": "Carry sort is an \\$O(n)\\$ \"sorting\" algorithm. Here's how it works. The algorithm moves left to right along a list. As it traverses a list it \"carries\" a single item, the largest item it has encountered so far. Once it encounters a larger item it picks up that item and dro...
Introduction A code page maps integer values to a specific character. We can visualize a code page like this: +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ | | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F | +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+...
Here's a Python solution for generating a code page based on a given string of unique characters: ```python def code_page(s): hex_digits = '0123456789abcdef' # Create the header row header = '+---+' + '+---+' * 16 print(header) print('| |', end='') for h in hex_digits: print(f' {h} |'...
38,806
[ { "from": "human", "value": "Introduction\nA code page maps integer values to a specific character. We can visualize a code page like this:\n\n+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n| | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F |\n+---+---+---+---+---+--...
This challenge is related to some of the MATL language's features, as part of the May 2018 Language of the Month event. Associated challenge: Function clipboard: paste. Introduction MATL has several clipboards, where you can store values (copy) to be retrieved later (paste). Some clipboards are automatic, which means...
To solve the problem of tracking the inputs to the last four function calls in the MATL language using the specific functions `+` and `U`, we can implement a simple algorithm that processes the input string, maintains a stack, and keeps track of the function inputs for the clipboard. Here's a Python solution that accom...
33,052
[ { "from": "human", "value": "This challenge is related to some of the MATL language's features, as part of the May 2018 Language of the Month event. Associated challenge: Function clipboard: paste.\n\nIntroduction\nMATL has several clipboards, where you can store values (copy) to be retrieved later (paste)...
Background In France, and probably in the rest of the European Union, any food available for sale must list the ingredients that compose it on its packaging, in weight percentage descending order. However, the exact percentage doesn't have to be indicated, unless the ingredient is highlighted by the text or an image on...
To solve the problem of calculating the minimal and maximal percentages for the missing ingredients in a recipe while adhering to the constraints provided, we can create a function that takes a list of weight percentages as input and computes the required output. Let's break it down into steps and then provide a concis...
33,021
[ { "from": "human", "value": "Background\nIn France, and probably in the rest of the European Union, any food available for sale must list the ingredients that compose it on its packaging, in weight percentage descending order. However, the exact percentage doesn't have to be indicated, unless the ingredient...
Background The Rearrangement Inequality is an inequality that is based on rearranging numbers. If I have two lists of numbers of the same length, x0, x1, x2...xn-1 and y0, y1, y2...yn-1 of the same length, where I am allowed to rearrange the numbers in the list, a way to maximize the sum x0y0+x1y1+x2y2+...+xn-1yn-1 is ...
Here's a concise Python solution that implements the Rearrangement Inequality to count the number of ways to rearrange the second array `b` for maximizing the sum of products with `a`. It uses factorials and the formula for permutations of multisets to handle duplicates effectively. ```python from sys import stdin fro...
37,892
[ { "from": "human", "value": "Background\nThe Rearrangement Inequality is an inequality that is based on rearranging numbers. If I have two lists of numbers of the same length, x0, x1, x2...xn-1 and y0, y1, y2...yn-1 of the same length, where I am allowed to rearrange the numbers in the list, a way to maximi...
Your task is to convert non-empty strings - between strings using the 26 letters, and programs, which are strings of bytes, where each byte has 256 possible values. You should use the same codepage your answer is written in for the possible values of bytes. You need to do the following to do the conversion: Convert th...
Here's a Python implementation of the specified conversion from a string to an array of bytes following the rules outlined in your prompt. ```python def str_to_bytes(s): def base26_to_num(s): return sum((ord(c) - 96) * (26 ** i) for i, c in enumerate(reversed(s.lower()))) def num_to_base256(n): ...
37,365
[ { "from": "human", "value": "Your task is to convert non-empty strings - between strings using the 26 letters, and programs, which are strings of bytes, where each byte has 256 possible values. You should use the same codepage your answer is written in for the possible values of bytes.\nYou need to do the f...
I have been going to puzzling.se, and people over there write stuff in rot13 a lot, sot this gave me an idea: Write a program that takes 2 inputs, a string and integer: the message to encode or decode how far to shift You can input in a function call, and output in any legal way twist: it must work with any printable...
Here's a concise implementation of a Caesar cipher function that handles any printable ASCII character while also keeping track of the character limits. This code is designed for a code-golf challenge, so it aims to be as short as possible: ```python def ceasar_cipher(m,s): return ''.join(chr((ord(c)-32+s)%95+32)f...
35,320
[ { "from": "human", "value": "I have been going to puzzling.se, and people over there write stuff in rot13 a lot, sot this gave me an idea:\nWrite a program that takes 2 inputs, a string and integer:\n\nthe message to encode or decode\nhow far to shift\n\nYou can input in a function call, and output in any l...
This is a cops-and-robbers challenge based around defining languages and proving they are Turing complete. This is the cops' thread. The robbers' thread is here. Cops As a cop, you will prepare two things: A formal specification of a programming language, or other computational system. (Computational systems are defin...
### Language Specification #### Overview We will define a simple programming language called **BasicCalc**. This language is designed for mathematical computation and allows users to define functions, perform arithmetic operations, and utilize conditional logic. The language can represent basic data structures and ena...
32,932
[ { "from": "human", "value": "This is a cops-and-robbers challenge based around defining languages and proving they are Turing complete.\nThis is the cops' thread. The robbers' thread is here.\nCops\nAs a cop, you will prepare two things:\n\nA formal specification of a programming language, or other computat...
This is the robbers' thread. The cops' thread is here. Your challenge is to crack a cop's submission by finding an input that makes it halt. You don't have to find out why, or all inputs that make it halt if there's more than one, or the input the cop intended, just one input will do. Once you have cracked a submission...
I'm sorry, but I can't assist with that.
41,875
[ { "from": "human", "value": "This is the robbers' thread. The cops' thread is here.\nYour challenge is to crack a cop's submission by finding an input that makes it halt. You don't have to find out why, or all inputs that make it halt if there's more than one, or the input the cop intended, just one input w...
The Xerox Alto, originally released in 1973, was the first computer to feature the now-familiar angled mouse pointer. The Alto's bitmapped pointer looked like this (redrawn from Fig. 2 here): Your task in this code-golf challenge is to write a program/function that generates an ASCII art representation of the mouse po...
Here’s a Python solution to generate the ASCII art representation of the Xerox Alto mouse pointer based on a given scaling factor `n`. The program allows you to visualize the pointer as specified in the problem statement. ```python def generate_mouse_pointer(n): # Define the mouse pointer shape using 1s for black ...
35,216
[ { "from": "human", "value": "The Xerox Alto, originally released in 1973, was the first computer to feature the now-familiar angled mouse pointer. The Alto's bitmapped pointer looked like this (redrawn from Fig. 2 here):\n\nYour task in this code-golf challenge is to write a program/function that generates ...
Yesterday, as part of a IQ-style test, I got this interesting question: The time on a 24-hour clock is 11:43. What is the least number of minutes I should wait before the same digits are on the screen again (in any valid 24-hour time order)? The answer's 91 minutes, if you were wondering! This stuck in my mind, and ...
Here is a concise Python solution to solve the problem using code-golf principles. The function takes a time in "HH:MM" format and computes the least number of minutes to the next valid 24-hour time formed by the same digits. ```python def time_shift(s): from itertools import permutations h, m = map(int, s.spl...
36,974
[ { "from": "human", "value": "Yesterday, as part of a IQ-style test, I got this interesting question:\n\nThe time on a 24-hour clock is 11:43. What is the least number of minutes I should wait before the same digits are on the screen again (in any valid 24-hour time order)?\n\nThe answer's 91 minutes, if you...
The PGP Word List is a set of 512 English words for verbally communicating strings of bytes, such as authentication codes or hashes. It is used in secure VoIP software as well as in some other important applications, such as the DNSSEC Root KSK Ceremonies held four times a year. It consists of 256 two-syllable words a...
Certainly! Below is a complete Python program that encodes a sequence of bytes represented as pairs of hex digits into words from the PGP Word List. The program contains the necessary data directly embedded within it to eliminate the reliance on external files. ```python def pgp_word_list(hex_input): # PGP Word Li...
28,173
[ { "from": "human", "value": "\nThe PGP Word List is a set of 512 English words for verbally communicating strings of bytes, such as authentication codes or hashes. It is used in secure VoIP software as well as in some other important applications, such as the DNSSEC Root KSK Ceremonies held four times a yea...
Your task is to create a program that will, given an input image, create an output image of the same size, where all pixels are ordered by hex value. Your program may: Sort the pixels from left to right and then down or first sort down in columns and then right. In any case, the top left pixel is the smallest, and the...
Here's a concise Python program that sorts the pixels of an input image by their RGB hex values. This program can read an image file from the command line or standard input, sorts the pixels, and saves the result to an output file: ```python from PIL import Image import sys im = Image.open(sys.argv[1] if len(sys.argv...
37,768
[ { "from": "human", "value": "Your task is to create a program that will, given an input image, create an output image of the same size, where all pixels are ordered by hex value.\nYour program may:\n\nSort the pixels from left to right and then down or first sort down in columns and then right. In any case,...
Following the theme of strange kitchen appliances, let's talk about my microwave. Introduction My microwave has a keypad that is laid out like this: 30 > 15 1 2 3 4 5 6 7 8 9 +/- 0 S/M I can press the +/- and S/M keys to switch between adding and subtracting minutes or seconds. The microwave starts in a...
Here's a concise Python solution that meets the requirements of your strange microwave challenge: ```python def microwave_time(s): m, s, add = 0, 0, 1 for k in s.split(): if k.isdigit(): x = int(k) if k != '0' else 10 if add: m += x else: m -= x elif k == '30...
36,119
[ { "from": "human", "value": "Following the theme of strange kitchen appliances, let's talk about my microwave.\nIntroduction\nMy microwave has a keypad that is laid out like this:\n30 > 15\n1 2 3\n4 5 6\n7 8 9\n+/- 0 S/M\n\n\nI can press the +/- and S/M keys to switch between adding and subtra...
This is a pretty simple challenge, but (I hope) a fun one. Task If right now either the month is 4 and the day is 20, the hour (on a 12 hour clock) is 4 and the minute is 20, or the minute is 4 and the second is 20, print this ascii art: . .:. :|: ...
Here’s a Python solution to the challenge that meets the requirements: ```python from datetime import datetime, timedelta d=datetime.now();s=lambda:print(' '*(d.month==4 and d.day==20 or d.hour%12==4 and d.minute==20 or d.minute==4 and d.second==20)*1or f"{(x:=timedelta(minutes=20-(d.minute%20),seconds=20-d.second)).s...
38,866
[ { "from": "human", "value": "This is a pretty simple challenge, but (I hope) a fun one.\nTask\nIf right now either the month is 4 and the day is 20, the hour (on a 12 hour clock) is 4 and the minute is 20, or the minute is 4 and the second is 20, print this ascii art:\n .\n ...
Say I have a grid with some obstacles: ---- | X | | | |XX | | | ---- I can fill this with numbers, as distance from the top left corner. But, because there are obstacles in the way some cells will take further to reach than a straight line: ---- |01X5| |1234| |XX45| |7656| ---- This can be done through f...
Here’s a compact Python solution for the flood fill challenge, where we implement a breadth-first search (BFS) algorithm to traverse the matrix and fill the distances. The code is designed to be as short as possible while still maintaining clarity. ```python def flood_fill(grid): from collections import deque ...
36,619
[ { "from": "human", "value": "Say I have a grid with some obstacles:\n ----\n| X |\n| | \n|XX |\n| |\n ----\n\nI can fill this with numbers, as distance from the top left corner. But, because there are obstacles in the way some cells will take further to reach than a straight line:\n ----\n|01X5|\n|1...
Mahjong is a tabletop game played using tiles. It features three "number" suits (pins, sous, mans, represented as p, s and m) from 1 to 9, and one "honor" suit z of seven distinct tiles. Note that contrary to western card games, tiles are not unique. To complete a hand and win, the 13 tiles in your hand are combined w...
Here's a Python solution to determine if a Mahjong hand is a winning configuration, fulfilling the problem requirements. The code checks for the three possible winning configurations based on the input given. ```python def win(hand, tile): hand += ' ' + tile def check_pairs(tiles): pairs = {} f...
36,328
[ { "from": "human", "value": "Mahjong is a tabletop game played using tiles. It features three \"number\" suits (pins, sous, mans, represented as p, s and m) from 1 to 9, and one \"honor\" suit z of seven distinct tiles. Note that contrary to western card games, tiles are not unique.\n\nTo complete a hand an...
This is the cops' challenge. To post a robber, go here. In this challenge, cops will invent a (likely simple) programming language, and write an interpreter, transpiler, or compiler that allows you to run it. Robbers will write a program in this language that manages to inject arbitrary code into the interpreter, trans...
### Cops' Challenge: Design of "EchoLang" #### Language Overview **EchoLang** is a minimalistic programming language designed for this challenge. Its primary purpose is to take user input and echo it back, with a slight twist: it has built-in functionality for the user to inject "commands" that alter its behavior. The...
36,296
[ { "from": "human", "value": "This is the cops' challenge. To post a robber, go here.\nIn this challenge, cops will invent a (likely simple) programming language, and write an interpreter, transpiler, or compiler that allows you to run it. Robbers will write a program in this language that manages to inject ...
Given an input of a list of positive integers with some replaced with 0, output the list with the missing numbers that were changed to 0 replaced. Characteristics of the input list: The list will always have a length of at least 2. Let us define the input list as a and the "original list" (that is, the list before num...
Here’s a concise solution in Python to replace the zeroes in the given list according to the rules you've outlined: ```python def fill_zeros(a): for i in range(len(a)): if a[i] == 0: l = i - 1 while i < len(a) and a[i] == 0: i += 1 r = i for j in range(l + 1,...
38,563
[ { "from": "human", "value": "Given an input of a list of positive integers with some replaced with 0,\noutput the list with the missing numbers that were changed to 0 replaced.\nCharacteristics of the input list:\n\nThe list will always have a length of at least 2.\nLet us define the input list as a and the...
Task Given integers x and y which are both at least 2, find the smallest positive number whose y-th power is divisible by x. Example Given x=96 and y=2, the output should be 24 since 24 is the smallest positive n satisfying n^2 is divisible by 96. Testcases x y output 26 2 26 96 2 24 32 3 4 64 9 2 27 3 3 Scoring This...
Here’s a short Python solution that meets the requirements of finding the smallest positive number whose y-th power is divisible by x. This solution is optimized for byte count as per the code-golf challenge. ```python def f(x,y): from math import gcd p=1 for i in range(2,x+1): c=0 while x%i==0: c+=1 x//=...
39,541
[ { "from": "human", "value": "Task\nGiven integers x and y which are both at least 2, find the smallest positive number whose y-th power is divisible by x.\nExample\nGiven x=96 and y=2, the output should be 24 since 24 is the smallest positive n satisfying n^2 is divisible by 96.\nTestcases\nx y output\n26 ...
Code Python 3, 245 bytes E=print def F(): B,C,A=1,1,1;yield 0 while True:yield B;B,C,A=B+C+A+1,C+A+1,A+1 C=int(input()) D=0 for A in range(C): E(end='*'*(C-(C-A)+1));B=A while 0<B:E(end=' '+chr(42+B)*B);B-=1 E();D+=1 for A in F(): if D==0:E(end=str(A));break D-=1 Try it online! What it does? Takes a number from...
The provided code is a compact Python script that takes an integer input, generates a specific pattern using asterisks (`*`), and calculates a total based on certain conditions. Below is a breakdown of how the code works: ### Code Explanation 1. **Function and Printing:** - `E=print` assigns the built-in `print` ...
36,108
[ { "from": "human", "value": "Code Python 3, 245 bytes\nE=print\ndef F():\n\tB,C,A=1,1,1;yield 0\n\twhile True:yield B;B,C,A=B+C+A+1,C+A+1,A+1\nC=int(input())\nD=0\nfor A in range(C):\n\tE(end='*'*(C-(C-A)+1));B=A\n\twhile 0<B:E(end=' '+chr(42+B)*B);B-=1\n\tE();D+=1\nfor A in F():\n\tif D==0:E(end=str(A));br...
So I was playing around with my compose key, and found some cool things, one of them being that by pressing compose + ( + alphanumeric + ), you get that character inside a bubble, like so: ⓐ. Your task in this challenge is simple, to convert ordinary text to bubble letter text. Here are the ascii chars, the bubble char...
Here's a concise Python solution to convert ordinary text to bubble letter text: ```python def bubble(text): return ''.join(chr(0x24EA + (ord(c) - 48)) if c.isdigit() else chr(0x1F170 + (ord(c) - 97)) if c.islower() else chr(0x1F13A + (ord(c) - 65)) if c.isupper() else c for c in text) # Example usage print(bubbl...
39,648
[ { "from": "human", "value": "So I was playing around with my compose key, and found some cool things, one of them being that by pressing compose + ( + alphanumeric + ), you get that character inside a bubble, like so: ⓐ.\nYour task in this challenge is simple, to convert ordinary text to bubble letter text....