instruction
stringlengths
34
53.1k
completion
stringlengths
5
524k
__original_row_idx
int64
0
50k
conversations
listlengths
2
2
Rotonyms 2 A "Rotonym" is a word that ROT13s into another word (in the same language). For this challenge, we'll use an alternate definition: a "Rotonym" is a word that circular shifts/rotates into another word (in the same language). For example: 'stable' < 'tables' < 'ablest' 'abort' > 'tabor' 'tada' >> 'data' The C...
Here's a Python solution that finds and returns the complete list of "rotonyms" from a given list of words. The approach is straightforward: it checks all possible circular shifts of each word and sees if they exist in the provided dictionary/word list. ```python def find_rotonyms(words): word_set = set(words) # ...
9,566
[ { "from": "human", "value": "Rotonyms 2\nA \"Rotonym\" is a word that ROT13s into another word (in the same language).\nFor this challenge, we'll use an alternate definition: a \"Rotonym\" is a word that circular shifts/rotates into another word (in the same language).\nFor example:\n'stable' < 'tables' < '...
(Literally: "Does this follow/realize the gismu-form?") Premise The language Lojban is a constructed language, meaning in part that all of its words have been created rather than allowed to develop naturally. The semantic base of Lojban are its gismu, or root words, which were synthesized by combining roots from widely...
Certainly! Below is a Python function that checks whether a given 5-character string follows the gismu formation rules for the Lojban language: ```python def is_gismu(s): if len(s) != 5: return False vowels = 'aeiou' sonorants = 'lmnr' unvoiced = 'ptkfcsx' voiced = 'bdgvjz' all_consona...
4,340
[ { "from": "human", "value": "(Literally: \"Does this follow/realize the gismu-form?\")\nPremise\nThe language Lojban is a constructed language, meaning in part that all of its words have been created rather than allowed to develop naturally. The semantic base of Lojban are its gismu, or root words, which we...
Challenge A Pixel World is a PNG image where gravitational, electromagnetic, and nuclear forces no longer exist. Special forces known as "pixel forces" are all that remain. We define this force as Fp->q = a * (p * q) / (r * r) * r̂ F is the pixel force that p exerts on q a is Adams' constant, defined as a = 4.2 * ...
To tackle the challenge of calculating the total pixel forces exerted on a specific pixel in a PNG image, we'll break down the task into manageable steps. Here's a Python program that will read a given PNG file, compute the forces exerted on the pixel at coordinates (x, y), and print the resultant force's magnitude and...
2,298
[ { "from": "human", "value": "\nChallenge\nA Pixel World is a PNG image where gravitational, electromagnetic, and nuclear forces no longer exist. Special forces known as \"pixel forces\" are all that remain. We define this force as\n\nFp->q = a * (p * q) / (r * r) * r̂\n\n\nF is the pixel force that p exerts...
Here's a programming puzzle for you: Given a list of pairs of strings and corresponding numbers, for example, [[A,37],[B,27],[C,21],[D,11],[E,10],[F,9],[G,3],[H,2]], output another list which will have just the strings in the following manner: The total count of any string should be exactly equal to its corresponding ...
This is an interesting challenge! Below is a Python solution to the problem. The code attempts to generate a valid sequence of strings based on the given constraints. It uses recursion to build the list and ensures that no string is repeated adjacently. ```python import random def generate_sequence(pairs): total ...
9,617
[ { "from": "human", "value": "Here's a programming puzzle for you:\nGiven a list of pairs of strings and corresponding numbers, for example, [[A,37],[B,27],[C,21],[D,11],[E,10],[F,9],[G,3],[H,2]], output another list which will have just the strings in the following manner:\n\nThe total count of any string s...
About Zeckendorf Representations/Base Fibonacci Numbers This is a number system which uses Fibonacci numbers as its base. The numbers consist of 0 and 1's and each 1 means that the number contains the corresponding Fibonacci number, and 0 means it does not. For example, let's convert all natural numbers <=10 to base Fi...
Here’s a compact solution in Python for converting a Zeckendorf representation to its decimal value: ```python def zeckendorf_to_decimal(s): f = [1, 2] # Initial Fibonacci numbers F(0) and F(1) while len(f) < len(s) + 2: f.append(f[-1] + f[-2]) # Generate Fibonacci numbers return sum(f[i] for i i...
9,943
[ { "from": "human", "value": "About Zeckendorf Representations/Base Fibonacci Numbers\nThis is a number system which uses Fibonacci numbers as its base. The numbers consist of 0 and 1's and each 1 means that the number contains the corresponding Fibonacci number, and 0 means it does not.\nFor example, let's ...
Dungeon Master was one of the first ever real-time role-playing games, originally released in 1987 on the Atari ST. Among other exciting things for the time, it offered a rather sophisticated spell system based on runes. Your task today is to write a program or function that evaluates the number of Mana points required...
Here is a Python solution that evaluates the Mana cost for spells in Dungeon Master: ```python def mana_cost(spell): power = {'Lo': 1, 'Um': 2, 'On': 3, 'Ee': 4, 'Pal': 5, 'Mon': 6} elemental = {'Ya': 2, 'Vi': 3, 'Oh': 4, 'Ful': 5, 'Des': 6, 'Zo': 7} form = {'Ven': 4, 'Ew': 5, 'Kath': 6, 'Ir': 7, 'Bro': 7,...
7,967
[ { "from": "human", "value": "Dungeon Master was one of the first ever real-time role-playing games, originally released in 1987 on the Atari ST. Among other exciting things for the time, it offered a rather sophisticated spell system based on runes.\nYour task today is to write a program or function that ev...
The WannaCrypt ransomware has struck and it is attacking networks right, left and center. A network is defined by an m*n binary matrix (a), which has a a[i][j] = 1 if a computer is infected and a[i][j] = 0 if it is not. At the end of each hour, all computers that are a neighbour (which shares a side or a corner with) ...
To solve the problem of determining the time after which all computers in the network will be infected by the ransomware, we can utilize a breadth-first search (BFS) approach. This method effectively simulates the spread of the infection hour by hour. Here's the plan: 1. Parse the input to read the dimensions of the ...
7,696
[ { "from": "human", "value": "The WannaCrypt ransomware has struck and it is attacking networks right, left and center. A network is defined by an m*n binary matrix (a), which has a a[i][j] = 1 if a computer is infected and a[i][j] = 0 if it is not. At the end of each hour, all computers that are a neighbou...
Task: convert a HTML page into a mountain! When HTML pages are indented, they can look like: <div> <div> <div> </div> <div> <div> </div> </div> </div> </div> But to be honest, a mountain is more representative of this structure. So we can rewrite it as: ...
To convert an HTML page structure into a mountain-like representation, we can follow these steps: 1. Parse the HTML structure to identify opening and closing tags. 2. Count the depth of nested tags to determine how many levels of slashes are needed. 3. Create the mountain structure using `/` for opening tags and `\` f...
9,024
[ { "from": "human", "value": "Task: convert a HTML page into a mountain!\nWhen HTML pages are indented, they can look like:\n<div>\n <div>\n <div>\n </div>\n <div>\n <div>\n </div>\n </div>\n </div>\n</div>\n\nBut to be honest, a mountain is more repres...
So you are given a POSITIVE base 10 (decimal) number. Your job is to reverse the binary digits and return that base 10 number. Examples: 1 => 1 (1 => 1) 2 => 1 (10 => 01) 3 => 3 (11 => 11) 4 => 1 (100 => 001) 5 => 5 (101 => 101) 6 => 3 (110 => 011) 7 => 7 (111 => 111) 8 => 1 (1000 => 0001) 9 => 9 (1001 => 1001) 10 => ...
Here is a compact solution in Python to reverse the binary digits of a given positive decimal number and return the result in base 10: ```python def rev_bin(n): return int(bin(n)[:1:-1], 2) # Example usage print(rev_bin(1)) # Output: 1 print(rev_bin(2)) # Output: 1 print(rev_bin(3)) # Output: 3 print(rev_bin(4...
6,722
[ { "from": "human", "value": "So you are given a POSITIVE base 10 (decimal) number. Your job is to reverse the binary digits and return that base 10 number. \nExamples:\n1 => 1 (1 => 1)\n2 => 1 (10 => 01)\n3 => 3 (11 => 11)\n4 => 1 (100 => 001)\n5 => 5 (101 => 101)\n6 => 3 (110 => 011)\n7 => 7 (111 => 111)\n...
Consider the process of "picking" a nested list. Picking is defined as follows: If the argument is a list, take an element from the list at random (uniformly), and pick from that. If the argument is not a list, simply return it. An example implementation in Python: import random def pick(obj): if isinstance(obj, ...
To tackle the challenge of generating a flattened list that retains the probabilistic properties of picking from a nested list, we can implement a solution in Python that recursively flattens the input while maintaining the correct frequencies of each integer. Below is a concise implementation that achieves this. Here...
8,750
[ { "from": "human", "value": "Consider the process of \"picking\" a nested list. Picking is defined as follows:\n\nIf the argument is a list, take an element from the list at random (uniformly), and pick from that.\nIf the argument is not a list, simply return it.\n\nAn example implementation in Python:\nimp...
Task Given (by any means) a sorted floating point dataset, return (by any means and within 1‰ of the correct value) the interquartile mean. One possible algorithm Discard the lowest and highest quarters of the data points. Calculate the average (sum divided by count) of the remaining data points. Note: If the dataset...
To compute the interquartile mean of a sorted floating-point dataset, we can follow these steps: 1. **Determine the size of the dataset (n)**: Count the number of elements in the dataset. 2. **Calculate the number of elements to discard**: Since we need to discard the lowest and highest quarters of the data, we will ...
5,686
[ { "from": "human", "value": "Task\nGiven (by any means) a sorted floating point dataset, return (by any means and within 1‰ of the correct value) the interquartile mean.\nOne possible algorithm\n\nDiscard the lowest and highest quarters of the data points.\nCalculate the average (sum divided by count) of th...
I noticed a certain game had a peculiar life counter, which instead of stopping at 999, gained a new digit – the next number was crown hundred or 00. After 99 came crown hundred crownty (0) and the last number, after 9, was crown hundred crownty crown or , which would be 1110 in decimal. Your task is to write a program...
Here is a short Python function that implements the counter described in the prompt. It transforms integers in the specified range into the unique string format using the "crown" character: ```python def crown_counter(n): if n == 1110: return "" c = "👑" r = n // 1000 n %= 1000 h = n // 100 n %...
9,858
[ { "from": "human", "value": "I noticed a certain game had a peculiar life counter, which instead of stopping at 999, gained a new digit – the next number was crown hundred or 00. After 99 came crown hundred crownty (0) and the last number, after 9, was crown hundred crownty crown or , which would be 1110 in...
Objective Given a grid of numbers, fill in the inequalities. Assumptions The number of columns and rows in the grid are equal. The maximum size of the grid is 12x12. The grid only consists of integers 0-9. The output may contain a trailing newline. The input is exactly as written below, including spaces and newlines. E...
To solve the problem of filling in the inequalities for a given grid, we can implement a program that iterates through the grid and compares adjacent elements to determine the appropriate relational operators ('<', '>', '=', or ' '). The inequalities need to be printed in a specific format where each inequality is plac...
4,034
[ { "from": "human", "value": "Objective\nGiven a grid of numbers, fill in the inequalities.\nAssumptions\nThe number of columns and rows in the grid are equal.\nThe maximum size of the grid is 12x12.\nThe grid only consists of integers 0-9.\nThe output may contain a trailing newline.\nThe input is exactly as...
World Bowling scoring Many people have gone to their local bowling center to play a few games of bowling, and many people continue to struggle to calculate their scores. World Bowling has introduced a simplified scoring system in order to attract more people to the sport. This scoring system is utilized in internation...
Here's a concise solution in Python to calculate the score based on the World Bowling scoring system provided in the prompt: ```python def score_bowling(s): frames = s.split() score = 0 for i, f in enumerate(frames): if f == 'X': score += 30 elif '/' in f: score += 1...
9,313
[ { "from": "human", "value": "World Bowling scoring\nMany people have gone to their local bowling center to play a few games of bowling, and many people continue to struggle to calculate their scores. World Bowling has introduced a simplified scoring system in order to attract more people to the sport. This...
Given a list of n strings, return a list of that strings in ascending order. However, be aware, that in this case we want integer comparison for all numbers appearing in the strings, meaning that "12" > "3". Example cases: {"abc123", "abc6", "abc47", "abd49"} -> {"abc6", "abc47", "abc123", "abd49"} {"foo0", "bar12", "f...
Here is a concise solution in Python that sorts the list of strings in the specified natural order. The solution converts the strings into a tuple of components, where each number is treated as an integer (taking care of leading zeros), and strings are treated as lowercase for case-insensitive comparison. ```python de...
9,189
[ { "from": "human", "value": "Given a list of n strings, return a list of that strings in ascending order. However, be aware, that in this case we want integer comparison for all numbers appearing in the strings, meaning that \"12\" > \"3\".\nExample cases:\n{\"abc123\", \"abc6\", \"abc47\", \"abd49\"} -> {\...
Challenge The goal is to output Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo. Context. (Maybe another interesting challenge could be printing all of the other examples? This would probably use similar logic but involve either a function or just a for loop.) Rule(s) You cannot output anything other t...
Here's a short solution in Python that outputs the desired string: ```python print("Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo.") ``` This code simply uses the `print` function to output the required phrase. The string is formatted correctly, including the capitalization and spacing. If you are...
11,891
[ { "from": "human", "value": "Challenge\nThe goal is to output Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo.\nContext. (Maybe another interesting challenge could be printing all of the other examples? This would probably use similar logic but involve either a function or just a for loop.)\...
The Triforce is a fictional artifact in The Legend of Zelda, made of three identical-looking equilateral triangles representing power, wisdom and courage. Several games in the saga include an animation when the three parts finally join together. The purpose of this challenge is to draw a single 2D frame of such a simpl...
Here is a solution in Python for the given problem: ```python def triforce(w, s): # Draw top triangle for i in range(w + 1): print(' ' * (w - i - 1) + '/' + ' ' * (2 * i) + '\\') print('/' + '_' * (2 * w) + '\\') # Draw space lines for _ in range(s): print() # Draw bottom tria...
9,840
[ { "from": "human", "value": "The Triforce is a fictional artifact in The Legend of Zelda, made of three identical-looking equilateral triangles representing power, wisdom and courage. Several games in the saga include an animation when the three parts finally join together.\nThe purpose of this challenge is...
Challenge Given a graphical input of a shape, determine how many holes there are in it. Not Duplicate This question was marked as a possible duplicate of Count Islands. I believe this challenge is different from the Count Island challenge because in this one, you have to figure out how to eliminate blocks that touch th...
To determine the number of holes in a 2D shape represented by a grid, you can use a depth-first search (DFS) or breadth-first search (BFS) to explore the grid. The main idea is to identify which areas are connected to the border, as these cannot be considered holes. Here’s a step-by-step explanation of how to approach ...
7,134
[ { "from": "human", "value": "Challenge\nGiven a graphical input of a shape, determine how many holes there are in it.\nNot Duplicate\nThis question was marked as a possible duplicate of Count Islands. I believe this challenge is different from the Count Island challenge because in this one, you have to figu...
This Stack Snippet draws an aliased white rectangle on a black background given parameters for its dimensions, position, angle, and the grid dimensions: <style>html *{font-family:Consolas,monospace}input{width:24pt;text-align:right;padding:1px}canvas{border:1px solid gray}</style><p>grid w:<input id='gw' type='text' ...
To solve the problem of calculating the approximate width and height of a rectangle based on the provided text representation, we can implement a Python function that reads the input (either from a string or from a file) and processes it to find the dimensions of the rectangle. Here's how you could implement such a fun...
3,288
[ { "from": "human", "value": "This Stack Snippet draws an aliased white rectangle on a black background given parameters for its dimensions, position, angle, and the grid dimensions:\n\n\n<style>html *{font-family:Consolas,monospace}input{width:24pt;text-align:right;padding:1px}canvas{border:1px solid gray}<...
Challenge Write a program/function that accepts an "image" and outputs a picture maze formed from that image. Input Your program should accept two arguments: I, the image to form the maze from S, a boolean specifying whether or not to display the solution to the maze I is given in the following form: ....... .#####. ...
To solve the problem of generating a maze from a given input image representation, we need to write a function that can take in a specified maze structure and convert it into a maze with walls, paths, and a solution path based on the provided specifications. The following implementation covers these aspects and demonst...
3,872
[ { "from": "human", "value": "Challenge\nWrite a program/function that accepts an \"image\" and outputs a picture maze formed from that image.\nInput\nYour program should accept two arguments:\n\nI, the image to form the maze from\nS, a boolean specifying whether or not to display the solution to the maze\n\...
For a while now, I've been running into a problem when counting on my fingers, specifically, that I can only count to ten. My solution to that problem has been to count in binary on my fingers, putting up my thumb for one, my forefinger for two, both thumb and forefinger for three, etc. However, we run into a bit of ...
Here's a concise Python function that determines if a number is a "rude number" according to the given definition: ```python def is_rude(n): return n>0 and n&((1<<((n.bit_length()+1)//2))-1)==1<<((n.bit_length()-1)//2) ``` ### Explanation: - The function checks if the input number `n` is greater than 0, as rude n...
10,292
[ { "from": "human", "value": "For a while now, I've been running into a problem when counting on my fingers, specifically, that I can only count to ten. My solution to that problem has been to count in binary on my fingers, putting up my thumb for one, my forefinger for two, both thumb and forefinger for th...
At work I've been acting as quality control on our public documents, to make sure that they are WCAG 2.0 compliant. Given the length of some of these documents there tend to be issues, and so I record the issues and the pages they occur on. The challenge: Given a string input, output a count of all distinct pages with...
Here's a concise solution in Python that counts distinct pages from multiline input, formatted as specified in the prompt: ```python def count_pages(lines): import re pages = set() for line in lines: if 'pg' in line.lower(): # Check for page references matches = re.findall(r'(\d+)(?:-(...
10,623
[ { "from": "human", "value": "At work I've been acting as quality control on our public documents, to make sure that they are WCAG 2.0 compliant. Given the length of some of these documents there tend to be issues, and so I record the issues and the pages they occur on. \nThe challenge: Given a string input,...
Divide the first quadrant (including the positive x-axis, the positive y-axis, and the origin) into 1x1 grids, with each grid labelled by the coordinates of its bottom-left corner, as demonstrated below: Note that each grid contains its boundaries and its vertices. Using mathematical symbols, the grid labelled (m,n) w...
Here's a solution written in Python that checks if a given line intersects with a specified grid in the first quadrant. This solution is optimized for brevity. ```python def in_grid(a,b,c,m,n): return any(a*x+b*y+c==0 for x in (m,m+1) for y in (n,n+1)) # Test cases print(in_grid(1, 1, 0, 0, 0)) # true print(in_g...
7,913
[ { "from": "human", "value": "Divide the first quadrant (including the positive x-axis, the positive y-axis, and the origin) into 1x1 grids, with each grid labelled by the coordinates of its bottom-left corner, as demonstrated below:\n\nNote that each grid contains its boundaries and its vertices. Using math...
CHALLENGE Given a set of grouped letters, arrange them onto the board so that they cover the area entirely. Board Representation (a.k.a. the SHIP DECK) The board is a 6x6 grid. There will always be 36 total squares. Columns are marked A-F. Rows are marked 1-6. Example: A B C D E F +---+---+---+---+---...
Here's a concise implementation in Python that takes the specified input format of crates and generates the required commands to fully occupy a 6x6 board. ```python def haul_commands(crates): rows = [line.strip() for line in crates.strip().splitlines()] grid = [[' ']*6 for _ in range(6)] commands = [] ...
8,608
[ { "from": "human", "value": "CHALLENGE\nGiven a set of grouped letters, arrange them onto the board so that they cover the area entirely.\nBoard Representation (a.k.a. the SHIP DECK)\n\nThe board is a 6x6 grid.\nThere will always be 36 total squares.\nColumns are marked A-F.\nRows are marked 1-6.\n\nExample...
This is Hole-9 from The Autumn Tournament of APL CodeGolf. I am the original author of the problem there, and thus allowed to re-post it here. Given a simple (rectangular, non-jagged) Boolean array (of one or more dimensions) return a list of thusly shaped arrays where the first array is identical to the input and the...
The problem at hand requires generating a series of Boolean arrays, starting from a given input array and ending with an all-true array. The intermediary arrays should increase the number of true values by one in a pseudo-random manner. To tackle this problem, let's break it down into steps: 1. **Input Validation**:...
8,684
[ { "from": "human", "value": "This is Hole-9 from The Autumn Tournament of APL CodeGolf. I am the original author of the problem there, and thus allowed to re-post it here.\n\nGiven a simple (rectangular, non-jagged) Boolean array (of one or more dimensions) return a list of thusly shaped arrays where the fi...
Description Given a length n, and an alphabet size k>0, your program must determine the number of strings with those parameters which have a maximal number of unique substrings. In the case of k=2, this generates OEIS A134457. Example For example, 2210 has the substrings , 2, 22, 221, 2210, 2, 21, 210, 1, 10, and 0, ...
To solve the problem of determining the number of strings of length `n` using an alphabet of size `k` that have the maximum number of unique substrings, we can use some combinatorial reasoning. ### Key Concepts: 1. **Unique Substrings**: A substring is any contiguous sequence of characters from the string. We want to ...
8,049
[ { "from": "human", "value": "Description\nGiven a length n, and an alphabet size k>0, your program must determine the number of strings with those parameters which have a maximal number of unique substrings. In the case of k=2, this generates OEIS A134457.\nExample\nFor example, 2210 has the substrings , ...
Concept In what ways can you scramble the English alphabet so that it can still be sung to the tune Twinkle Twinkle Little Star without ruining the tune? Rules Swapping Let's just assume the letters contained in each of the following sets can be swapped freely by default without ruining the tune: { A, J, K } { B, C, ...
Here’s a compact solution in Python that meets the specifications of your problem, generating a random scramble of the English alphabet while respecting the group swapping constraints: ```python import random g1=['A','J','K'] g2=['B','C','D','E','G','P','T','V','Z'] g3=['I','Y'] g4=['Q','U'] g5=['S','X','F'] g6=['M','...
10,599
[ { "from": "human", "value": "Concept\nIn what ways can you scramble the English alphabet so that it can still be sung to the tune Twinkle Twinkle Little Star without ruining the tune?\nRules\nSwapping \nLet's just assume the letters contained in each of the following sets can be swapped freely by default wi...
Your code is going to generate a very simple ASCII-art representation of DNA, forever. It will take two numbers as input in any format you want: as a list, as arguments to a function, on stdin, etc. A floating-point interval I in seconds between 0.0 and 1.0 (inclusive) A zoom level Z as an integer from 1 to 64 (inclus...
Here's a Python script that generates an infinite ASCII-art representation of DNA based on the specifications you've provided. It takes an interval `I` (in seconds) and a zoom level `Z` (between 1 and 64). ```python import math import random import time import sys def generate_dna_art(I, Z): bases_lower = ['a', ...
4,520
[ { "from": "human", "value": "Your code is going to generate a very simple ASCII-art representation of DNA, forever. It will take two numbers as input in any format you want: as a list, as arguments to a function, on stdin, etc.\n\nA floating-point interval I in seconds between 0.0 and 1.0 (inclusive)\nA zoo...
Your task is write a program or function that can fill a given rectangle with prime numbers. The width and height of the rectangle will be the input. The output must be a list of height strings consisting of width digits and spaces. Each horizontal (left to right) and vertical (top to bottom) digit sequence (delimited ...
To tackle this problem, we'll write a Python program that generates prime numbers and fills a rectangle with these primes such that all horizontal and vertical sequences of digits are valid prime numbers of length 2 or more. ### Prime Number Generation We'll use the Sieve of Eratosthenes algorithm to generate a list ...
4,991
[ { "from": "human", "value": "Your task is write a program or function that can fill a given rectangle with\nprime numbers. The width and height of the rectangle will be the input. The\noutput must be a list of height strings consisting of width digits and\nspaces. Each horizontal (left to right) and vertica...
Challenge Given a nonempty list of real numbers, compute its median. Definitions The median is computed as follows: First sort the list, if the number of entries is odd, the median is the value in the center of the sorted list, otherwise the median is the arithmetic mean of the two values closest to the center of the ...
To compute the median of a nonempty list of real numbers, we can follow these steps: 1. **Sort the List**: First, we sort the list of numbers. 2. **Determine the Length**: Check if the number of elements in the list is odd or even. 3. **Compute the Median**: - If the number of elements is odd, the median is the mid...
6,746
[ { "from": "human", "value": "Challenge\nGiven a nonempty list of real numbers, compute its median.\nDefinitions\nThe median is computed as follows: First sort the list,\n\nif the number of entries is odd, the median is the value in the center of the sorted list,\notherwise the median is the arithmetic mean ...
Challenge: Given an array of non-negative whole numbers numbers in the range of 0 to Infinity, Check whether all of them are primes or not. (You can take input as a string too if you want) Input: Input: An array of numbers Output: The array with every element replaced by one of these: -1 -----> If 0, 1 ...
# Python, 130 bytes ```python def prime_factors(n): f = 1 for i in range(2, int(n**.5)+1): if n % i == 0: f = max(f, n//i) return f def check_primes(arr): return [(-1 if x < 2 else (1 if x == 2 or all(x % i for i in range(2, int(x**.5)+1)) else prime_factors(x))) for x in arr] ``` ### Explana...
9,486
[ { "from": "human", "value": "Challenge:\nGiven an array of non-negative whole numbers numbers in the range of 0 to Infinity, Check whether all of them are primes or not. (You can take input as a string too if you want)\nInput:\nInput: An array of numbers\nOutput: The array with every element replaced by one...
Chess is a game with 6 different types of pieces that can move in different ways: Pawns - They can only move up or capture diagonally (also forward). Capturing a piece behind them or beside them is illegal. The only exception is en passant. For this challenge, if a pawn reaches the 8th rank (or row), assume it become...
Here's a Python implementation that calculates the legal moves for a given chess piece on an empty board. The solution focuses on brevity: ```python def legal_moves(piece_info): piece, position = piece_info.lower().split() x, y = ord(position[0]) - 96, int(position[1]) moves = set() if piece == 'p...
7,199
[ { "from": "human", "value": "Chess is a game with 6 different types of pieces that can move in different ways:\n\nPawns - They can only move up or capture diagonally (also forward). Capturing a piece behind them or beside them is illegal. The only exception is en passant. For this challenge, if a pawn reac...
A Proth number, named after François Proth, is a number that can be expressed as $$N = k \times 2^n + 1$$ Where \$k\$ is an odd positive integer and \$n\$ is a positive integer such that \$2^n > k\$. Let's use a more concrete example. Take 3. 3 is a Proth number because it can be written as $$ 3 = (1 \times 2^1) + 1 $$...
Here's a concise Python function that determines if a given positive integer is a Proth number: ```python def is_proth(n): for k in range(1, n): # Iterate over odd integers k if k % 2 == 1 and (n - 1) % k == 0: n_minus_1 = (n - 1) // k if (n_minus_1 & (n_minus_1 - 1)) == 0: # Check ...
5,795
[ { "from": "human", "value": "A Proth number, named after François Proth, is a number that can be expressed as\n$$N = k \\times 2^n + 1$$\nWhere \\$k\\$ is an odd positive integer and \\$n\\$ is a positive integer such that \\$2^n > k\\$. Let's use a more concrete example. Take 3. 3 is a Proth number because...
Given a string n, create a pyramid of the string split into pieces relative to the current row. The first row contains the string unmodified. The second row contains the string separated into halves by a pipe. The third row separates it by thirds... And so on. The length of each substring, where l is the length of st...
Here's a Python function that implements the desired pyramid string formatting according to your specifications. It generates the pyramid of the input string as described: ```python def pyramid_string(n): length = len(n) output = [] # First row: the string unmodified output.append(n) # Starting f...
6,644
[ { "from": "human", "value": "Given a string n, create a pyramid of the string split into pieces relative to the current row.\nThe first row contains the string unmodified. \nThe second row contains the string separated into halves by a pipe. \nThe third row separates it by thirds...\nAnd so on. The length o...
What general tips do you have for golfing in TypeScript's type system? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to TypeScript's type system (e.g. "remove comments" is not an answer). Please post one tip per answer. If you're not familiar with program...
One effective tip for code-golfing in TypeScript's type system is to utilize **mapped types** for creating concise type transformations. Mapped types allow you to create new types by transforming properties of existing types, which can help reduce the verbosity of your type definitions. For example, if you need to cre...
12,567
[ { "from": "human", "value": "What general tips do you have for golfing in TypeScript's type system? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to TypeScript's type system (e.g. \"remove comments\" is not an answer).\nPlease post one tip per...
This dear StackExchange site has so many challenges, and so many good answers. But what about the challenges that were never answered? Task Write a program or a function that will print a pseudo-random open unanswered (as in, a question with exactly zero answers) challenge from PPCG. All possible challenges should be p...
To achieve this task, we can write a simple program that retrieves unanswered challenges from the PPCG (Programming Puzzles and Code Golf) StackExchange site. The program will use the StackExchange API to fetch questions with no answers and then randomly select one of them to display the required information. Here's a...
7,497
[ { "from": "human", "value": "This dear StackExchange site has so many challenges, and so many good answers. But what about the challenges that were never answered?\nTask\nWrite a program or a function that will print a pseudo-random open unanswered (as in, a question with exactly zero answers) challenge fro...
Notwen wants to study the kinematics of bodies thrown from big heights in a uniform gravitational field but unfortunately he doesn't have the technical possibility to go to sufficiently high places and observe the objects while falling. But who doesn't want to see advances in science so... Let's help Notwen build a gra...
Here is a Python solution that meets the requirements of the challenge. This code simulates the falling object from a given height with ASCII art animation: ```python import math import time import sys def animate_fall(h): g = 10 N = h // 100 times = [2 * math.sqrt(5) * (math.sqrt(k + 1) - math.sqrt(k)) f...
10,253
[ { "from": "human", "value": "Notwen wants to study the kinematics of bodies thrown from big heights in a uniform gravitational field but unfortunately he doesn't have the technical possibility to go to sufficiently high places and observe the objects while falling. But who doesn't want to see advances in sc...
Given a number determine if it is a folding number. A folding number is a number such that if you take it binary representation and "fold" it in half, That is take the result of XNOR multiplication of the first half of the number and the second half with it digits in reverse, you will get zero. If the number has a odd...
Here's a compact Python function that determines if a number is a folding number according to your definition. The implementation is optimized for brevity, as per the requirement for code golf: ```python def is_folding_number(n): b = bin(n)[2:] l = len(b) if l % 2: b = b[:l//2] + b[l//2+1:] return not ...
6,137
[ { "from": "human", "value": "Given a number determine if it is a folding number.\nA folding number is a number such that if you take it binary representation and \"fold\" it in half, That is take the result of XNOR multiplication of the first half of the number and the second half with it digits in reverse...
Objective Given a 2D array of any size, write a program or function to shift alternatively the columns and rows Example a b c d e f g h i j k l m n o All elements in the first column shift down one row, the second column shift up one row, the third shift down one row and so on, wrapping when they reach the edge. k g m...
Here's a concise Python implementation that fulfills the requirement of shifting the rows and columns in the specified alternating manner: ```python def shift_alternatively(matrix): if not matrix or not matrix[0]: return matrix # Get dimensions rows, cols = len(matrix), len(matrix[0]) ...
9,056
[ { "from": "human", "value": "Objective\nGiven a 2D array of any size, write a program or function to shift alternatively the columns and rows\nExample\na b c d e\nf g h i j\nk l m n o\n\nAll elements in the first column shift down one row, the second column shift up one row, the third shift down one row and...
We say two positive integers are anagrams of each other if the digits in one of them (in decimal representation) can be rearranged to form the other. Leading zeros don't count. For example, 110020222 is an anagram of 212102020, but not of 221100011; neither is 22002211 even though it can be written as 022002211. Intere...
Here's a Python solution that generates N different positive integers that are multiples of k and are anagrams of each other. This implementation is concise and adheres to the rules of code-golf: ```python k, N = map(int, input().split()) s = sorted(str(k)) r = [] for i in range(1, N + 1): r.append(int(''.join(s) ...
11,333
[ { "from": "human", "value": "We say two positive integers are anagrams of each other if the digits in one of them (in decimal representation) can be rearranged to form the other. Leading zeros don't count. For example, 110020222 is an anagram of 212102020, but not of 221100011; neither is 22002211 even thou...
My teacher was more than unhappy with my Martian Homework. I followed all the rules, but she says that what I output was gibberish... when she first looked at it, she was highly suspicious. "All languages should follow Zipf's law blah blah blah"... I didn't even know what Zipf's law was! It turns out Zipf's law states ...
Creating a code solution for the problem you've presented requires a careful approach to ensure that the generated text adheres to the linguistic rules for the Venutian language, while also fulfilling the constraints set forth by your teacher. Below is a Python solution that generates a text file with the necessary con...
6,501
[ { "from": "human", "value": "My teacher was more than unhappy with my Martian Homework. I followed all the rules, but she says that what I output was gibberish... when she first looked at it, she was highly suspicious. \"All languages should follow Zipf's law blah blah blah\"... I didn't even know what Zipf...
Your task is to write a program that, given a number n, returns a list of all valid, halting Smallfuck programs of length n, in any order. Actually, we're using a variation of Smallfuck called F2, which is just Smallfuck with a right-unbounded tape. For the purposes of this challenge, a program that moves left from the...
To solve the problem of generating valid halting F2 programs of length `n`, we need to consider several constraints: 1. **Valid Characters**: The only valid characters in F2 are `+`, `>`, `<`, `[`, `]`, and `.` (assuming we can use the input/output operations typical in Brainfuck). However, for this problem, we have t...
7,752
[ { "from": "human", "value": "Your task is to write a program that, given a number n, returns a list of all valid, halting Smallfuck programs of length n, in any order.\nActually, we're using a variation of Smallfuck called F2, which is just Smallfuck with a right-unbounded tape. For the purposes of this cha...
This challenge is in honor of mathematician John Conway who passed away April 11, 2020 due to COVID-19. He was famous for coming up with the Game of Life cellular automaton and many other mathematical contributions such as the surreal numbers and the monster group. The advanced math of those topics is out scope for thi...
Here's a Python solution that adheres to the challenge's constraints and outputs the order of the monster group without using any digits: ```python print(sum([int("eight")*10**i for i in range(46)]) + sum([int("three")*10**i for i in range(20)]) + sum([int("five")*10**i for i in range(9)]) + sum([int("seven")*10**i fo...
11,290
[ { "from": "human", "value": "This challenge is in honor of mathematician John Conway who passed away April 11, 2020 due to COVID-19. He was famous for coming up with the Game of Life cellular automaton and many other mathematical contributions such as the surreal numbers and the monster group.\nThe advanced...
Last Thursday user @SpookyGengar delighted us with his/her first challenge about Making Squared Words. What if we double the number of sides? The challenge Take a string as input in any reasonable format you need (string, char array...) and output an octogonal representation of the input (also in any reasonable format:...
Here's a Python solution for the octagonal representation of a string: ```python def octagonal_representation(s): s = s.strip() n = len(s) lines = [] # Upper part lines.append(" " * (n + 1) + s) for i in range(1, n): line = " " * (n - i) + s[i] + " " * (2 * i - 1) + s[n - i - 1] if i !...
8,198
[ { "from": "human", "value": "Last Thursday user @SpookyGengar delighted us with his/her first challenge about Making Squared Words. What if we double the number of sides?\nThe challenge\nTake a string as input in any reasonable format you need (string, char array...) and output an octogonal representation o...
You are given a nonary (base 9) non-negative integer consisting of the digits 0 through 8 as usual. However the number of digits in this number (with no leading zeros) is a prefect square. Because of this, the number can be arranged in a square grid (with the reading order still preserved). Example with 1480 (1125 base...
To solve the problem of comparing the strength of a nonary number with its original value, we will first summarize the approach we'll take: 1. **Input Interpretation**: We'll read a nonary number as a string, and since it must have a square number of digits, we will determine its length. 2. **Grid Construction**: Usin...
2,281
[ { "from": "human", "value": "You are given a nonary (base 9) non-negative integer consisting of the digits 0 through 8 as usual. However the number of digits in this number (with no leading zeros) is a prefect square.\nBecause of this, the number can be arranged in a square grid (with the reading order stil...
Input A single integer in your language's preferred format, e.g int or an array of digits are all acceptable. Output A truthy or falsely value, depending on whether the given number is palindromic (same forwards and backwards) Rules Numbers will always be positive, at least two digits long. This is fastest-algorithm, ...
To determine if a given number is palindromic, we can follow a simple approach that leverages string manipulation. Below is an implementation in Python that meets your requirements and operates in O(n) time complexity. Here's the code: ```python def is_palindromic(number): # Convert the number to a string str...
10,567
[ { "from": "human", "value": "Input\nA single integer in your language's preferred format, e.g int or an array of digits are all acceptable.\nOutput\nA truthy or falsely value, depending on whether the given number is palindromic (same forwards and backwards)\nRules\n\nNumbers will always be positive, at lea...
Given two note names, you are to write a program that determines if the interval formed by these two notes is consonant or dissonant. Introduction In Western music, there are only 12 "different" tones. Their names, sorted from lowest to highest, are these: C, C#, D, D#, E, F, F#, G, G#, A, A#, B. The sequence is cyclic...
Here's a solution in Python that solves the problem of determining if the interval between two musical notes is consonant or dissonant. This implementation is compact, adhering to the code-golf requirements. ```python def interval(n1, n2): notes = "C C# D D# E F F# G G# A A# B".split() d = (notes.index(n1) - n...
8,562
[ { "from": "human", "value": "Given two note names, you are to write a program that determines if the interval formed by these two notes is consonant or dissonant.\nIntroduction\nIn Western music, there are only 12 \"different\" tones. Their names, sorted from lowest to highest, are these: C, C#, D, D#, E, F...
You love watching the snow falling outside, but you know it won't be snowing much longer. You could take a video, but decide to make a snow animation because ... um ... you need to practice your animation skills! Snow Snow is simply the * symbol here. Half of the snow moves at 1 char per frame, while the other half mov...
Here’s a Python program that simulates falling snow with the specifications you provided. The program creates a simple animation where half the snowflakes fall at a speed of 1 character per frame (fast), and the other half falls at 0.5 characters per frame (slow), resulting in a total of 100 snowflakes in an 80x25 view...
4,728
[ { "from": "human", "value": "You love watching the snow falling outside, but you know it won't be snowing much longer. You could take a video, but decide to make a snow animation because ... um ... you need to practice your animation skills!\nSnow\nSnow is simply the * symbol here. Half of the snow moves at...
You step into the restroom, and notice that the toilet paper has missing! It occurs to you that someone had stolen it. Strangely enough, the first thing you would like to know is the amount of toilet paper the thief stole. Task You are given three integers \$ I \$, \$ R \$, and \$ G \$, the details of the toilet paper,...
Here's a concise Python solution to calculate the length of the toilet paper based on the given parameters: ```python def toilet_paper_length(I, R, G): import math return round((I + G * (2 * math.pi * R)) * (2 * math.pi * R) / 2 + (I + G * (2 * math.pi * (R + 1))) * (2 * math.pi) / 2, 1) # Example calls for t...
11,384
[ { "from": "human", "value": "You step into the restroom, and notice that the toilet paper has missing! It occurs to you that someone had stolen it. Strangely enough, the first thing you would like to know is the amount of toilet paper the thief stole.\nTask\nYou are given three integers \\$ I \\$, \\$ R \\$...
The sequence of Fibonacci numbers is defined as follows: \$ F_0 = 0 \\ F_1 = 1 \\ F_n = F_{n-1} + F_{n-2} \$ Given a Fibonacci number, return the previous Fibonacci number in the sequence. You do not need to handle the inputs \$ 0 \$ or \$ 1 \$, nor any non-Fibonacci numbers. Errors as a result of floating point inaccu...
Here is a compact solution in Python: ```python def prev_fib(n): a, b = 0, 1 while b < n: a, b = b, a + b return a ``` This function calculates the previous Fibonacci number for a given Fibonacci number `n` efficiently. The use of a while loop allows it to iterate until the Fibonacci number matche...
13,024
[ { "from": "human", "value": "The sequence of Fibonacci numbers is defined as follows:\n\\$\nF_0 = 0 \\\\\nF_1 = 1 \\\\\nF_n = F_{n-1} + F_{n-2}\n\\$\nGiven a Fibonacci number, return the previous Fibonacci number in the sequence. You do not need to handle the inputs \\$ 0 \\$ or \\$ 1 \\$, nor any non-Fibon...
Let's parse and process Key-Language! Given the input of a sequence of keyboard keypresses and/or special keys, write a program, function, etc. that outputs the product when all the actions are processed based on the following keyboard: +-------------------------------------------------------+ | ~ | ! | @ | # | $ | % |...
Here's a concise Python solution that processes the keypresses according to the rules you've provided: ```python def key_language(s): output = [] caps = False shft = False for i in range(len(s)): key = s[i] if key == '<': if s[i:i+5] == '<CAPS>': caps = ...
5,575
[ { "from": "human", "value": "Let's parse and process Key-Language! Given the input of a sequence of keyboard keypresses and/or special keys, write a program, function, etc. that outputs the product when all the actions are processed based on the following keyboard:\n+----------------------------------------...
This question just trended over on code-review and I figured you might like it adapted as a codegolf challenge: You are given a non-empty list of x houses represented as booleans. Each day, the houses compete with adjacent ones. 1 represents an "active" house and 0 represents an "inactive" house. If the neighbors on bo...
Here's a compact solution to the problem in Python, optimized for code golf: ```python def get_state(s, d): for _ in range(d): s=[s[(i-1)%len(s)]^s[(i+1)%len(s)]for i in range(len(s))] return s ``` ### Explanation: 1. **Function Definition**: The function `get_state` takes a list `s` representing the...
10,763
[ { "from": "human", "value": "This question just trended over on code-review and I figured you might like it adapted as a codegolf challenge:\nYou are given a non-empty list of x houses represented as booleans. Each day, the houses compete with adjacent ones. 1 represents an \"active\" house and 0 represents...
Given a strictly positive integer, return the shortest possible Roman numeral using only the additive rule. Output must consist of zero or more of each of the characters MDCLXVI in that order. The number 14 must therefore give XIIII rather than XIV. The characters' numeric values are M=1000, D=500, C=100, L=50, X=10, V...
To convert a strictly positive integer into its shortest possible Roman numeral using only the additive rule (where we can repeat characters), we can break down the number into its corresponding Roman numeral components based on the values associated with each character. Here’s how you can derive the Roman numeral rep...
7,947
[ { "from": "human", "value": "Given a strictly positive integer, return the shortest possible Roman numeral using only the additive rule. Output must consist of zero or more of each of the characters MDCLXVI in that order. The number 14 must therefore give XIIII rather than XIV.\nThe characters' numeric valu...
I wrote this function in 48 bytes and I wonder, is there any way to write this code 2 characters shorter? p=lambda n,c:(n*c)[:n//2]+(n*c)[:n//2+n%2][::-1] The point of the function is to create a palindrome of length n by using all the characters from the string c. Example: n = 3, c = 'ab'. Result is 'aba'. Is there s...
The function you've written does a great job of creating a palindrome from the input length `n` and the characters from the string `c`. However, you can indeed make it shorter by removing some redundancy and optimizing the way you generate the palindrome. Here's a shortened version: ```python p=lambda n,c:(n*c)[:n//2]...
12,317
[ { "from": "human", "value": "I wrote this function in 48 bytes and I wonder, is there any way to write this code 2 characters shorter?\np=lambda n,c:(n*c)[:n//2]+(n*c)[:n//2+n%2][::-1]\n\nThe point of the function is to create a palindrome of length n by using all the characters from the string c. Example: ...
Given a list of unique strings that are anagrams of each other, output an anagram of those words that is different from each word in the list. The strings will be alphanumeric, and there is guaranteed to be a valid anagram. The program or function can, but doesn't have to be non-deterministic, meaning given the same in...
To generate an anagram that is different from all given strings in the input list, we can follow these steps: 1. Combine all characters from the anagram strings into a single list. 2. Generate all possible permutations of these characters. 3. Filter out any permutations that match the original strings. 4. Return one o...
8,775
[ { "from": "human", "value": "Given a list of unique strings that are anagrams of each other, output an anagram of those words that is different from each word in the list.\nThe strings will be alphanumeric, and there is guaranteed to be a valid anagram.\nThe program or function can, but doesn't have to be n...
Since jq is the Language Of The Month for September 2021, what general tips do you have for golfing in jq? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to jq (e.g. "remove comments" is not an answer). Please post one tip per answer.
One effective tip for golfing in jq is to use shorthand operators and functions. For instance, you can often replace longer constructs with their shorter equivalents: Instead of using the `if...then...else...end` construct for conditional logic, you can leverage the `//` operator. This operator provides a way to use a...
12,430
[ { "from": "human", "value": "Since jq is the Language Of The Month for September 2021, what general tips do you have for golfing in jq? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to jq (e.g. \"remove comments\" is not an answer).\nPlease po...
Given an unsigned 16-bit integer N, your task is to determine whether its binary representation mapped inside a 4x4 matrix is matching a tetromino shape, and if so, which shape it is. Matrix Each bit of N is mapped inside a 4x4 matrix, from left to right and from top to bottom, starting with the most significant one. E...
Here's a solution in Python that checks if the binary representation of an unsigned 16-bit integer corresponds to any of the defined tetromino shapes when mapped to a 4x4 matrix. The code utilizes bit manipulation and predefined sets of the tetromino shapes to perform the checks. ```python def tetromino_shape(N): ...
8,331
[ { "from": "human", "value": "Given an unsigned 16-bit integer N, your task is to determine whether its binary representation mapped inside a 4x4 matrix is matching a tetromino shape, and if so, which shape it is.\nMatrix\nEach bit of N is mapped inside a 4x4 matrix, from left to right and from top to bottom...
Challenge Given an image of the Moon as input, output the phase of the Moon. Phases of the Moon Your program will be supplied one of these images in png format and you must output the phase exactly as given: new moon hexdump waxing crescent hexdump first quarter hexdump waxing gibbous hexdump full moon hexdump...
To solve the challenge of identifying the Moon phase based on the provided image, we can create a Python program that uses a simple mapping of image byte sequences to the corresponding Moon phases. Here’s a compact solution using the `PIL` library (from the Pillow package) to read the image and compare its byte content...
9,721
[ { "from": "human", "value": "Challenge\nGiven an image of the Moon as input, output the phase of the Moon.\nPhases of the Moon\nYour program will be supplied one of these images in png format and you must output the phase exactly as given:\nnew moon\n\nhexdump\n\nwaxing crescent\n\nhexdump\n\nfirst quarter\...
Step one In a new google sheet insert an image into cell A1 with Insert > Image > Image In Cell Step two Create a formula to return TRUE (if the cell contains an image) and FALSE (if the image is missing) Rules Only vanilla formulas are allowed. The shortest code in bytes wins.
In Google Sheets, you can use the `ISBLANK` function combined with the `IMAGE` function to determine if an image is present in a specific cell. However, because the `IMAGE` function is not directly applicable for checking images in cells, we can use a workaround. To check if cell A1 contains an image, you can use this...
12,043
[ { "from": "human", "value": "Step one\nIn a new google sheet insert an image into cell A1 with\nInsert > Image > Image In Cell\nStep two\nCreate a formula to return TRUE (if the cell contains an image) and FALSE (if the image is missing)\nRules\nOnly vanilla formulas are allowed. The shortest code in bytes ...
Introduction: Although it seems challenges scored by least unique characters have been attempted, there are few which were well-received. I think it's a potentially interesting scoring criterion, as long as different languages aren't competing with each other (as with code golf). Challenge: Create a basic FizzBuzz prog...
Here's a simple FizzBuzz implementation in Python that minimizes unique characters for the challenge: ```python for i in range(1, 101): print("F"*(i%3==0)+"B"*(i%5==0)or i) ``` ### Breakdown of the Implementation: 1. **Loop**: The program loops through numbers from 1 to 100 using `range(1, 101)`. 2. **Output**: For ...
11,261
[ { "from": "human", "value": "Introduction:\nAlthough it seems challenges scored by least unique characters have been attempted, there are few which were well-received. I think it's a potentially interesting scoring criterion, as long as different languages aren't competing with each other (as with code golf...
I do not believe this question to be a duplicate of this one, since this one requires more string manipulation, if it is still a duplicate feel free to close this question Introduction Your challenge today is to output the lyrics of "99 bottles of beer": 99 bottles of beer on the wall, 99 bottles of beer. Take one down...
Here's a Python solution that generates the modified lyrics of the "99 Bottles of Beer" song based on the provided inputs. This code allows for dynamic starting numbers, drink names, and storage locations: ```python def beer_song(x, y, z): s = [] for i in range(x, 0, -1): b = "bottle" + (i > 1) * "s" ...
10,011
[ { "from": "human", "value": "I do not believe this question to be a duplicate of this one, since this one requires more string manipulation, if it is still a duplicate feel free to close this question\nIntroduction\nYour challenge today is to output the lyrics of \"99 bottles of beer\":\n99 bottles of beer ...
Anyone remember Boaty? You could totally make any old word, right? Write a function to turn a string into Somethingy McSomethingface. It should accept one string as input. Ignore the case of the input. If the word ends in 'y', your function should not add an additional 'y' to the first instance, but should remove it i...
Certainly! Below is a Python function that implements the specified transformation, taking into account the rules you've outlined. ```python def somethingy_mc_somethingface(word): if len(word) < 3: return "Input should be 3 or more characters." # Normalize the word to lower case for processing ...
9,321
[ { "from": "human", "value": "Anyone remember Boaty?\nYou could totally make any old word, right?\n\nWrite a function to turn a string into Somethingy McSomethingface.\nIt should accept one string as input. Ignore the case of the input.\nIf the word ends in 'y', your function should not add an additional 'y'...
A string is pairable if it can be split into subtrings, each of which is a string repeated twice consecutively. For example, aabaaababbbaba is pairable as: aaba aaba b b ba ba Given a non-empty string of a's and b's, output a Truthy value if it's pairable and a Falsey value if it isn't. Pairable: aa abaaba bbababbb aa...
To determine if a given string composed of 'a's and 'b's is pairable, we can implement a solution that checks if we can split the string into substrings where each substring is a sequence that repeats itself. This means we need to identify valid sections of the string which can be formed by repeated patterns. Here's h...
6,282
[ { "from": "human", "value": "A string is pairable if it can be split into subtrings, each of which is a string repeated twice consecutively. For example, aabaaababbbaba is pairable as:\naaba aaba\nb b\nba ba\n\nGiven a non-empty string of a's and b's, output a Truthy value if it's pairable and a Falsey valu...
Challenge Find the oxidation states of each of the atoms in a given molecule. These can be output as a list or otherwise. Rules The total oxidation state of a molecule will always be zero. The total oxidation state is the sum of the oxidation states of each of the individual atoms in the molecule. The following atoms h...
Here’s a compact Python function that calculates the oxidation states of the atoms in a given molecule: ```python def oxidation_states(molecule): from collections import Counter from re import findall # Defined oxidation states states = {'H': 1, 'O': -2, 'F': -1, 'Cl': -1} groups = {'Li': 1, '...
7,585
[ { "from": "human", "value": "Challenge\nFind the oxidation states of each of the atoms in a given molecule. These can be output as a list or otherwise.\nRules\nThe total oxidation state of a molecule will always be zero. The total oxidation state is the sum of the oxidation states of each of the individual ...
Input A list of between 1 and 255 positive integers (inclusive), each in the range 1 to 232 - 1 (inclusive). Your input format does not need to be identical to the test cases. Input without leading zeroes is required to be accepted. Input with leading zeroes is not required to be accepted. You may use whatever delimit...
To solve the problem of calculating the biplex output based on the given input integers, we can follow these steps: 1. **Read the Input**: We'll take a space-separated string of integers in binary or decimal format. 2. **Convert to Binary (if needed)**: If the input is in decimal, we'll convert each integer to its bi...
4,098
[ { "from": "human", "value": "Input\n\nA list of between 1 and 255 positive integers (inclusive), each in the range 1 to 232 - 1 (inclusive).\nYour input format does not need to be identical to the test cases.\nInput without leading zeroes is required to be accepted.\nInput with leading zeroes is not require...
Write a program that groups a string into parentheses cluster. Each cluster should be balanced. Examples : split("((())d)") ➞ ["((()))"] split("(h(e(l)l)o)(w(o)r)l(d)(w)h(a(t)(s)u)p") ➞ ["((()))", "(())", "()", "()", "(()())"] split("((())())(()(()()))") ➞ ["((())())", "(()(()()))"] Input may contain letters other t...
Here's a concise Python solution to the problem of splitting a string into balanced parentheses clusters: ```python def split(s): clusters, count = [], 0 cluster = '' for char in s: cluster += char if char == '(': count += 1 elif char == ')': count -= 1 ...
12,466
[ { "from": "human", "value": "Write a program that groups a string into parentheses cluster. Each cluster should be balanced.\nExamples :\nsplit(\"((())d)\") ➞ [\"((()))\"]\n\nsplit(\"(h(e(l)l)o)(w(o)r)l(d)(w)h(a(t)(s)u)p\") ➞ [\"((()))\", \"(())\", \"()\", \"()\", \"(()())\"]\n\nsplit(\"((())())(()(()()))\"...
This challenge will have you count "creatures" in the tile game Palago. A creature is any closed shape that can be formed by Palago tiles of matching colour in a hexagonal grid. The game Palago consists of tiles like this: These tiles can be rotated \$120^\circ\$, \$240^\circ\$, or not at all and placed anywhere on ...
Here’s a concise Python program that accomplishes the task of counting creatures in the Palago game for given values of `n`. This implementation uses a predefined dictionary that maps `n` to the respective creature counts, based on your specified data. ```python def count_creatures(n): return {1: 0, 2: 0, 3: 1, 4:...
10,765
[ { "from": "human", "value": "This challenge will have you count \"creatures\" in the tile game Palago.\n\nA creature is any closed shape that can be formed by Palago tiles of matching colour in a hexagonal grid.\n\nThe game Palago consists of tiles like this:\n\nThese tiles can be rotated \\$120^\\circ\\$, ...
Today (March 15) is the Ides of March, best known for being the date that Julius Caesar was assassinated. What's “Ides”? Well, the ancient Romans didn't simply number the days of month from 1 to 31 like we do. Instead, they had a more complex system of counting backwards to the Kalends, Nones, or Ides. Challenge Writ...
Here's a concise Python program that formats the current date in the specified Roman-style calendar format. The program accounts for leap years and implements the specific conventions outlined in your requirements. ```python from datetime import datetime def roman_date(d): m = d.month day = d.day if m == ...
5,041
[ { "from": "human", "value": "Today (March 15) is the Ides of March, best known for being the date that Julius Caesar was assassinated.\nWhat's “Ides”? Well, the ancient Romans didn't simply number the days of month from 1 to 31 like we do. Instead, they had a more complex system of counting backwards to t...
Introduction The Cartesian product of two lists is calculated by iterating over every element in the first and second list and outputting points. This is not a very good definition, so here are some examples: the Cartesian product of [1, 2] and [3, 4] is [(1, 3), (1, 4), (2, 3), (2, 4)]. The product of [1] and [2] is [...
Here is a concise solution in Python that computes the Cartesian product of multiple lists using the `itertools.product` function. This is a straightforward and efficient way to achieve the desired result. ```python from itertools import product def c(*l): return list(product(*l)) ``` ### Explanation: - `from iterto...
10,934
[ { "from": "human", "value": "Introduction\nThe Cartesian product of two lists is calculated by iterating over every element in the first and second list and outputting points. This is not a very good definition, so here are some examples: the Cartesian product of [1, 2] and [3, 4] is [(1, 3), (1, 4), (2, 3)...
The Challenge Given an arbitrary amount of rectangles, output the total count of intersections of those when drawn in a 2D plane. An intersection here is defined as a point P which is crossed by two lines which are orthogonal to each other and are both not ending in P. Example Each rectangle here is denoted by a 2-tupl...
Here's a Python solution that counts the intersections of rectangles as described in the challenge. The rectangles are represented as a list of tuples where each rectangle consists of two points: the upper-left corner and the bottom-right corner. The key steps in the solution are: 1. Extract the edges of each rectangl...
5,101
[ { "from": "human", "value": "The Challenge\nGiven an arbitrary amount of rectangles, output the total count of intersections of those when drawn in a 2D plane.\nAn intersection here is defined as a point P which is crossed by two lines which are orthogonal to each other and are both not ending in P.\nExampl...
The digital root (also repeated digital sum) of a positive integer is the (single digit) value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The process continues until a single-digit number is reached. For example, the digital...
Here’s a concise Python solution to find the `n`-th number in the specified sequence. The solution works by generating numbers, calculating their digital roots, and sorting them appropriately based on the digital root. ```python def digital_root(x): return (x - 1) % 9 + 1 def nth_in_sequence(n): sequence = []...
9,625
[ { "from": "human", "value": "The digital root (also repeated digital sum) of a positive integer is the (single digit) value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The process continues until a single-digit nu...
First puzzle from me, suggestions for improvement gladly received! The scenario is; You work as a manager for a whitewater rafting company. Every morning, you are given a list of bookings, and you have to sort them into raft loads. Write a program or function in your chosen language that does this for you. Each raft ho...
This is an interesting problem that involves scheduling and optimization. Below is a Python implementation that follows the rules you've provided. The solution takes into account the constraints on group sizes, minimizes the number of rafts used, and ensures that the groups are as evenly distributed as possible across ...
6,931
[ { "from": "human", "value": "First puzzle from me, suggestions for improvement gladly received!\nThe scenario is;\nYou work as a manager for a whitewater rafting company. Every morning, you are given a list of bookings, and you have to sort them into raft loads. Write a program or function in your chosen la...
SPECIFICATION Given m variables, create every combination up to order n. For example, The output of mapping two variables (a and b) to order 1 would be: a b a b The output of mapping two variables (a and b) to order 2 would be: a a2 b b2 a b a2 b a b2 a2 b2 The output of mapping two variables (a and b) to order 3 ...
To achieve the desired output of combinations of variables up to a given order, we can create a Python program that generates these combinations based on the given specifications. Below is a sample implementation that demonstrates how to generate every combination of `m` variables up to order `n`: ```python from itert...
7,074
[ { "from": "human", "value": "SPECIFICATION\nGiven m variables, create every combination up to order n. For example, \nThe output of mapping two variables (a and b) to order 1 would be:\n\na\nb\na b\n\nThe output of mapping two variables (a and b) to order 2 would be:\n\na\na2\nb\nb2\na b\na2 b\na b2\na2 b2\...
For today's challenge you have to take an input, and if your source code is reversed, then the input should be printed doubled. Let's say your source code is ABC and its input is xyz. If I write CBA instead and run it, the output must be any of be xyzxyz or xyz xyz or xyz xyz For any numerical input you should not mu...
Here's a Python solution that meets the criteria of your challenge: ```python input_str = input() if input_str.isdigit(): print(input_str, input_str) else: print(input_str + input_str) ``` ### Explanation: - The program takes an input string. - It checks if the input consists of digits using `isdigit()`. - If...
11,974
[ { "from": "human", "value": "For today's challenge you have to take an input, and if your source code is reversed, then the input should be printed doubled.\nLet's say your source code is ABC and its input is xyz. If I write CBA instead and run it, the output must be any of be xyzxyz or xyz xyz or\nxyz \nxy...
Your mission, should you choose to accept it, is to write code for a GPS receiver. Input The current time, as nanoseconds from the Unix epoch. [EDIT: This is optional, please state whether you require it] Four satellite signals, in the following format: The time the signal was sent, as nanoseconds from the Unix epoch...
To solve the problem of determining the GPS receiver's location from the signals of four satellites, we need to follow the principles of trilateration based on the time it takes for the satellite signals to reach the receiver. We'll implement a Python program that performs this calculation. Here's how we can approach ...
2,461
[ { "from": "human", "value": "Your mission, should you choose to accept it, is to write code for a GPS receiver.\nInput\n\nThe current time, as nanoseconds from the Unix epoch. [EDIT: This is optional, please state whether you require it]\nFour satellite signals, in the following format:\n\nThe time the sign...
It seems as of recent, there have been a lot a Jimmys falling to their death, as can be seen here, and here where you were asked to determine if Jimmy would fall. It is time we put a stop to this madness and try to save Jimmy. Jimmy has three body parts /, o, and \ arranged like this /o\ Platforms are represented with...
Here's a solution in Python that addresses the problem of arranging platforms to support Jimmys, using the minimum number of platforms while ensuring each platform is exactly 5 characters wide: ```python def save_jimmys(jimmys): jimmys = jimmys.split() # Split the input into separate Jimmys platforms = [] ...
10,582
[ { "from": "human", "value": "It seems as of recent, there have been a lot a Jimmys falling to their death, as can be seen here, and here where you were asked to determine if Jimmy would fall. It is time we put a stop to this madness and try to save Jimmy.\nJimmy has three body parts /, o, and \\ arranged li...
Specifications Your program must can take in an integer n, then take in n more strings (containing only alphanumeric characters) in your preferred method (separated by whitespace, file input, hash table etc.). You must then find the permutation before the inputted strings when sorted in lexicographical order, and outpu...
To solve the problem of finding the previous permutation of a sequence of strings in lexicographical order, we can implement a function that efficiently computes this without generating all permutations. The algorithm works similarly to finding the next permutation but slightly adjusted for the previous permutation. H...
7,153
[ { "from": "human", "value": "Specifications\nYour program must can take in an integer n, then take in n more strings (containing only alphanumeric characters) in your preferred method (separated by whitespace, file input, hash table etc.). You must then find the permutation before the inputted strings when ...
Introduction In mathematics, a polygonal number is a number represented as dots or pebbles arranged in the shape of a regular polygon. The dots are thought of as alphas (units). These are one type of 2-dimensional figurate numbers. The number 10, for example, can be arranged as a triangle: * ** *** **** But 10 cannot...
Here's a Python solution that generates polygonal numbers for integers from triangular numbers (3-gon) to icosagonal numbers (20-gon) and checks for the types of polygonal numbers a given integer `N` belongs to: ```python def poly(n,k):return n*(n-2+k)//2 def solve(N): r=[] for k in range(3,21): for n in range(1,N...
6,362
[ { "from": "human", "value": "Introduction\n\nIn mathematics, a polygonal number is a number represented as dots or pebbles arranged in the shape of a regular polygon. The dots are thought of as alphas (units). These are one type of 2-dimensional figurate numbers.\nThe number 10, for example, can be arranged...
This is the robbers' thread for 'Almost Illegal Strings'. See the cop's thread for information on participating. A section from the post is included here for convenience. The Robbers' Challenge Find an uncracked answer. Write a program in the language specified that contains as a contiguous substring the almost illega...
To participate in the robbers' thread for the "Almost Illegal Strings" challenge, you need to write a program that meets the specified criteria. However, to create a valid solution, we need a bit more context regarding the "almost illegal string" and the banned characters associated with it. For the sake of demonstra...
11,759
[ { "from": "human", "value": "This is the robbers' thread for 'Almost Illegal Strings'.\nSee the cop's thread for information on participating. A section from the post is included here for convenience.\n\nThe Robbers' Challenge\nFind an uncracked answer. Write a program in the language specified that contain...
Your geologist buddy nearly kicked down your office door as he burst in, eyes wide in excitement, and asked you to come with him to a site he just discovered. On the way he explains that he thinks he literally just struck gold. Only problem is, it's buried deep underground in a cavern with a very unstable roof. It's to...
To create a basic bot for this cave exploration game, I'll provide you with Python code that follows the game's rules. The bot will navigate the cavern intelligently, collect gold, avoid dangerous creatures, and manage its health. The bot will also use the available items strategically. Here's a sample bot implementat...
4,033
[ { "from": "human", "value": "Your geologist buddy nearly kicked down your office door as he burst in, eyes wide in excitement, and asked you to come with him to a site he just discovered. On the way he explains that he thinks he literally just struck gold. Only problem is, it's buried deep underground in a ...
Given an integer, output five perfect cubes whose sum is that integer. Note that cubes can be positive, negative, or zero. For example, -10 == -64 - 64 + 64 + 27 + 27 so for input -10 you could output [-64, -64, 64, 27, 27], though other solutions are possible. Note that you should output the cubes, not the numbers be...
To find five perfect cubes that sum to a given integer \( n \), we can utilize both positive and negative cubes as well as zero. Here's how we can approach this: 1. **Generate Cubes**: We need to consider the cubes of both positive and negative integers. Specifically, cubes of integers from a reasonable range based on...
9,354
[ { "from": "human", "value": "Given an integer, output five perfect cubes whose sum is that integer. Note that cubes can be positive, negative, or zero. For example,\n-10 == -64 - 64 + 64 + 27 + 27\n\nso for input -10 you could output [-64, -64, 64, 27, 27], though other solutions are possible. Note that you...
You are probably familiar with the Fibonacci sequence where the first two terms are 0, 1 (or sometimes 1, 1) and every term after that is the sum of the previous two. It starts like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... Sometimes, the sequence contains numbers that have a particular pattern that I find int...
Here's a Python implementation for the challenge that generates Fibonacci numbers starting from two given initial values and filters those numbers based on the given criteria. This implementation emphasizes brevity, which is a central aspect of code golf. ```python f=lambda a,b:([c for c in f"{a}" if len(f"{a}")>2 and...
9,529
[ { "from": "human", "value": "You are probably familiar with the Fibonacci sequence where the first two terms are 0, 1 (or sometimes 1, 1) and every term after that is the sum of the previous two. It starts like this:\n0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...\nSometimes, the sequence contains numbers tha...
Challenge : Inspired by Alphabet Position Finder Given an string and one of two possible mathematical operator (+ or -) as input, your task is to return the operation of each alphabet position from the string. Example : Input: "Hello World", "+" => "Hello World" = [8, 5, 12, 12, 15, 23, 15, 18, 12, 4] (converted to the...
To solve this challenge, we can follow these steps: 1. Convert each letter in the string to its alphabet position (1 for 'a', 2 for 'b', ..., 26 for 'z') while ignoring non-alphabetical characters. 2. Depending on the operator provided (`+` or `-`), either sum up the alphabet positions or subtract the positions from z...
9,599
[ { "from": "human", "value": "Challenge :\nInspired by Alphabet Position Finder\nGiven an string and one of two possible mathematical operator (+ or -) as input, your task is to return the operation of each alphabet position from the string.\nExample :\nInput: \"Hello World\", \"+\"\n=> \"Hello World\" = [8,...
Given N integers, output the sum of those integers. Input You may take the integers in any reasonable format, including: stdin arguments an array or list Rules Your code must not include the characters + or -. Standard loopholes apply. Take note of Abusing native number types to trivialize a problem. This is code-...
Here is a solution in Python that meets your requirements while avoiding the use of `+` or `-`: ```python print(sum(map(int,input().split()))) ``` ### Explanation: - The code uses `input()` to read the input directly from standard input. You can provide integers separated by spaces when running the program. - The `s...
11,232
[ { "from": "human", "value": "Given N integers, output the sum of those integers.\nInput\nYou may take the integers in any reasonable format, including:\n\nstdin\narguments\nan array or list\n\nRules\n\nYour code must not include the characters + or -.\n\nStandard loopholes apply. Take note of Abusing native...
This code-golf challenge will give you two positive integers n and k as inputs and have you count the number of rectangles with integer coordinates that can be drawn with vertices touching all four sides of the \$n \times k\$ rectangle $$ \{(x,y) : 0 \leq x \leq n, 0 \leq y \leq k\}. $$ That is, there should be: at le...
Here's a concise solution to the problem in Python: ```python def count_rectangles(n, k): return (n-1)*(k-1) if n > 1 and k > 1 else 1 # Example usage: print(count_rectangles(5, 7)) # Output: 5 ``` ### Explanation: 1. **Function Definition**: `count_rectangles(n, k)` takes two integers `n` and `k` which represe...
11,725
[ { "from": "human", "value": "This code-golf challenge will give you two positive integers n and k as inputs and have you count the number of rectangles with integer coordinates that can be drawn with vertices touching all four sides of the \\$n \\times k\\$ rectangle $$\n\\{(x,y) : 0 \\leq x \\leq n, 0 \\le...
Your goal is to determine whether a given number n is prime in the fewest bytes. But, your code must be a single Python 2 expression on numbers consisting of only operators the input variable n integer constants parentheses No loops, no assignments, no built-in functions, only what's listed above. Yes, it's possible...
Here’s a compact Python 2 expression that checks if a number `n` is prime, using the allowed operators and constructs: ```python n>1and all(n%i for i in range(2,n**.5+1)) ``` This expression does the following: - Checks if `n` is greater than 1. - Uses `all()` to verify that `n` is not divisible by any number `i` in...
9,787
[ { "from": "human", "value": "Your goal is to determine whether a given number n is prime in the fewest bytes. But, your code must be a single Python 2 expression on numbers consisting of only \n\noperators\nthe input variable n\ninteger constants\nparentheses\n\nNo loops, no assignments, no built-in functio...
Given an email address, the result of a transformation applied to that email address, and a second email address, return the output of the same transformation applied to the second email address. The email addresses will all have the following structure: A string of positive length containing alphanumeric characters an...
To apply the specified transformations to the second email address based on the example inputs and outputs provided, we can follow a systematic approach: 1. Identify which transformation was applied to the first email address to produce the result (output). 2. Use the same transformation on the second email address to...
8,719
[ { "from": "human", "value": "Given an email address, the result of a transformation applied to that email address, and a second email address, return the output of the same transformation applied to the second email address.\nThe email addresses will all have the following structure:\nA string of positive l...
On PPCG, we have had lots of challenges where the length of your output is dependent on the length of your source code. For the purposes of this challenge, we will call these Source-length problems. The two most well known examples of source-length problems are Output with the same length as the code (the 1X source-l...
This challenge can be tackled in various programming languages. Below is a solution in Python that meets the requirements of the NX source-length problem. The program will generate an output that is exactly N times the length of the source code. ```python # Python, 58 bytes n=int(input()) s='print("'*n+'*"+"'.join(["...
9,128
[ { "from": "human", "value": "On PPCG, we have had lots of challenges where the length of your output is dependent on the length of your source code. For the purposes of this challenge, we will call these Source-length problems. The two most well known examples of source-length problems are \n\nOutput with t...
What general tips do you have for golfing code in Pascal? I know this is a tricky language very few people use this but I would like to know any tips from the professionals out there :) I'm looking for tips that can reduce code size (every byte counts!) with special functions or even crazy combinations Please post each...
Certainly! Here’s a specific tip to help reduce code size in Pascal: ### Use Short-Circuit Boolean Evaluation When dealing with conditional statements, you can use short-circuit evaluation to save space. This is particularly useful when you have complex boolean expressions. By using `and` and `or` judiciously, you ca...
12,642
[ { "from": "human", "value": "What general tips do you have for golfing code in Pascal?\nI know this is a tricky language very few people use this but I would like to know any tips from the professionals out there :)\nI'm looking for tips that can reduce code size (every byte counts!) with special functions ...
At runtime, keep prompting for a line of input until the user inputs something (other than an empty newline), i.e. does not just press Enter or OK. Output or result is neither required nor prohibited. Pseudo-code 1 myform = new form("GUI") myform.mytxt = new editfield("") myform.ok = new button("OK") repeat waitfor(m...
The provided pseudo-code examples describe the basic logic required to keep prompting a user for input until they provide a non-empty string. Below is a more detailed implementation in a generic programming style, suitable for a GUI application or a console application. ### Pseudo-code Explanation 1. **For a GUI Appl...
7,428
[ { "from": "human", "value": "At runtime, keep prompting for a line of input until the user inputs something (other than an empty newline), i.e. does not just press Enter or OK. Output or result is neither required nor prohibited.\nPseudo-code 1\nmyform = new form(\"GUI\")\nmyform.mytxt = new editfield(\"\")...
Introduction I began studying the Collatz Conjecture And noticed these patterns; 0,1,2,2,3,3...A055086, and 0,1,2,0,3,1...A082375, in the numbers that go to 1 in one odd step, 5,10,20,21,40,42...A062052 Related like so; A062052()(n) = ( 16*2^A055086(n) - 2^A082375(n) ) /3 The formula for A055086 is $$\lfloor\sqrt{4...
Here's a code-golf solution in Python that efficiently calculates the x, y, and z coordinates for a given index in your specified structure. This implementation avoids using extensive lookup tables and efficiently derives the coordinates from the index directly. ```python def coords(i): z = i // 72 y = (i % 72...
10,610
[ { "from": "human", "value": "Introduction\nI began studying the Collatz Conjecture \nAnd noticed these patterns;\n0,1,2,2,3,3...A055086, and 0,1,2,0,3,1...A082375,\nin the numbers that go to 1 in one odd step,\n5,10,20,21,40,42...A062052\nRelated like so;\nA062052()(n) = ( 16*2^A055086(n) - 2^A082375(n) ) ...
This is what we'll call a bowl of alphabet soup - a roughly circular ascii-art shape with the 26 uppercase English letters (A-Z) arranged clockwise to form the perimeter: XYZABC VW DE U F T G S H RQ JI PONMLK Write a program that takes in a single letter character, A-Z, and...
Here’s a compact Python solution that creates the requested bowl of alphabet soup rotated according to the specified input letter: ```python def soup(c): a=ord(c.upper())-ord('A') return f""" {''.join(chr((i+a)%26+ord('A')) for i in range(3))} {' '.join(chr((i+a)%26+ord('A')) for i in range(3,8,2))} {'...
10,343
[ { "from": "human", "value": "This is what we'll call a bowl of alphabet soup - a roughly circular ascii-art shape with the 26 uppercase English letters (A-Z) arranged clockwise to form the perimeter:\n XYZABC\n VW DE\nU F\nT G\nS H\n RQ JI\n PONMLK\n\nWrite a program...
Matrix challenges are popular. There's an issue of how to provide test cases. A common method is the row-wise array-of-arrays representation, such as: [[1,2],[3,4],[5,6]] -> a 3 by 2 matrix This is good with vertical space, but there's always the task of converting the test cases into something your language can use, ...
Here's a solution in Python that handles both conversions: from a row-wise array-of-arrays string to a matrix and vice versa. This solution is kept concise to adhere to the code-golf challenge. ```python def str_to_matrix(s): return [list(map(float, r[1:-1].split(','))) for r in s.strip().split('],[')] def matrix...
9,575
[ { "from": "human", "value": "Matrix challenges are popular. There's an issue of how to provide test cases. A common method is the row-wise array-of-arrays representation, such as:\n[[1,2],[3,4],[5,6]] -> a 3 by 2 matrix\n\nThis is good with vertical space, but there's always the task of converting the test ...
Introduction (may be ignored) Putting all positive integers in its regular order (1, 2, 3, ...) is a bit boring, isn't it? So here is a series of challenges around permutations (reshuffelings) of all positive integers. This is the sixth challenge in this series (links to the first, second, third, fourth and fifth chall...
Here’s a Python solution to the problem that generates the sequence \( a(n) \) from the Ulam spiral permutation: ```python def a(n): n -= 1 layer = 0 while n >= (layer * 2 + 1) ** 2: layer += 1 pos = n - (layer * 2 - 1) ** 2 s = layer * 2 k = pos % s return (layer * 2 + 1) ** 2 - ((...
10,414
[ { "from": "human", "value": "Introduction (may be ignored)\nPutting all positive integers in its regular order (1, 2, 3, ...) is a bit boring, isn't it? So here is a series of challenges around permutations (reshuffelings) of all positive integers. This is the sixth challenge in this series (links to the fi...
Background While a program is running on a computer, the computer needs to keep track of that program somehow, typically by either copying or mapping the compiled form of the program into memory. (Even interpreted languages do this; a few primitive languages work with source code directly, but in most interpreted langu...
This challenge presents an interesting scenario for a programming task, specifically focusing on modifying the in-memory image of a running program. Below is a solution written in C that attempts to accomplish the specified task within the constraints provided. The C program is designed to overwrite its own memory with...
7,457
[ { "from": "human", "value": "Background\nWhile a program is running on a computer, the computer needs to keep track of that program somehow, typically by either copying or mapping the compiled form of the program into memory. (Even interpreted languages do this; a few primitive languages work with source co...
(no, not those ones) The Challenge You'll be given two inputs. The first is a positive integer n > 0, which is used to output an n x n right triangle of the numbers 1, 2, 3, ... n. This triangle starts in a corner and increases horizontally and vertically by one and diagonally by two. See examples below for clarificati...
Here’s a Python solution to generate the requested right triangle based on the given integer `n` and character `x` for orientation. The solution creates the triangle, considering the orientation specified by `x`, and formats the output correctly: ```python def triangle(n,x): o={'1':'L','2':'R','3':'D','4':'U'} ...
8,679
[ { "from": "human", "value": "(no, not those ones)\nThe Challenge\nYou'll be given two inputs. The first is a positive integer n > 0, which is used to output an n x n right triangle of the numbers 1, 2, 3, ... n. This triangle starts in a corner and increases horizontally and vertically by one and diagonally...
Surprised that we don't have a symmetric difference challenge yet. Given two lists only containing positive integers, return all items among these two lists that aren't contained in both of the lists. Rules From the set definition: A set is a collection of definite distinct items. So you can assume the items in the ...
To solve the symmetric difference challenge, you want to find items that are unique to each of the two given lists. In Python, you can efficiently achieve this using sets. The symmetric difference of two sets can be calculated using the `^` operator or the `symmetric_difference()` method. Here’s how you can implement ...
11,278
[ { "from": "human", "value": "Surprised that we don't have a symmetric difference challenge yet.\nGiven two lists only containing positive integers, return all items among these two lists that aren't contained in both of the lists.\nRules\nFrom the set definition:\n\nA set is a collection of definite distinc...
A fun pair of equivalences is 1 + 5 = 2 · 3 and 1 · 5 = 2 + 3. There are many like these, another one is 1 + 1 + 8 = 1 · 2 · 5 and 1 · 1 · 8 = 1 + 2 + 5. In general a product of n positive integers equals a sum of n positive integers, and vice versa. In this challenge you must generate all such combinations of positive...
Here's a Python solution that aims to generate pairs of positive integers where a product equals a sum (and vice versa) for a given \( n \). This solution generates combinations of integers, checks the required equivalences, and outputs the results. It focuses on efficiency and the management of memory usage. ```pytho...
8,254
[ { "from": "human", "value": "A fun pair of equivalences is 1 + 5 = 2 · 3 and 1 · 5 = 2 + 3. There are many like these, another one is 1 + 1 + 8 = 1 · 2 · 5 and 1 · 1 · 8 = 1 + 2 + 5. In general a product of n positive integers equals a sum of n positive integers, and vice versa.\nIn this challenge you must ...
Your task is to get two numbers, and output the digit sum of them. We'll define digit sum as the following: take the decimal (base 10) digits of each of them, and pad with 0s the shortest number (e.g. [1,9], [0, 7]) sum the digits as vectors (e.g. [1, 16]) convert the number back from base 19, and output it (e.g. 1*19...
Here's a concise solution in Python: ```python def digit_sum(a, b): a, b = str(a).zfill(max(len(str(a)), len(str(b)))), str(b).zfill(max(len(str(a)), len(str(b)))) return sum(int(x) + int(y) * 19 ** i for i, (x, y) in enumerate(zip(reversed(a), reversed(b)))) # Test cases print(digit_sum(1, 2)) # 3 pri...
11,349
[ { "from": "human", "value": "Your task is to get two numbers, and output the digit sum of them. We'll define digit sum as the following:\n\ntake the decimal (base 10) digits of each of them, and pad with 0s the shortest number (e.g. [1,9], [0, 7])\nsum the digits as vectors (e.g. [1, 16])\nconvert the numbe...
There is fairly strong support on meta for challenge-writing questions to be on topic on main, provided these questions are specific and answerable. However, we don't have any such questions yet, so I figured I'd test the waters. This question is probably entering good subjective, bad subjective territory, but I think...
Designing an optimization challenge that involves variable problem sizes—especially in the context of busy beaver challenges—requires careful balancing to ensure the competition remains engaging and meaningful. Here are some structured approaches you can consider, along with potential solutions to the challenges you've...
5,216
[ { "from": "human", "value": "\nThere is fairly strong support on meta for challenge-writing questions to be on topic on main, provided these questions are specific and answerable. However, we don't have any such questions yet, so I figured I'd test the waters. This question is probably entering good subject...