507
\$\begingroup\$

What is the Sandbox?

This "Sandbox" is a place where Code Golf users can get feedback on prospective challenges they wish to post to the main page. This is useful because writing a clear and fully specified challenge on the first try can be difficult. There is a much better chance of your challenge being well received if you post it in the Sandbox first.

To post to the Sandbox, scroll to the bottom of this page or click on the "Add Proposal" link below, and click "Answer This Question". Click "OK" when it asks if you really want to add another answer. Write your challenge just as you would when actually posting it. You may also add some notes about specific things you would like to clarify before posting it. Other users will help you improve your challenge by rating and discussing it. When you think your challenge is ready for the public, go ahead and post it, replace the post here with a link to the challenge and delete it.

See the Sandbox FAQ for more information on how to use the Sandbox.

The Sandbox works best if you sort posts by "active".

Add Proposal

Search the Sandbox

Browse your pending proposals

Get the Sandbox Viewer to view the sandbox more easily

To add an inline tag to a proposal use shortcut link syntax with a prefix: [tag:king-of-the-hill]

\$\endgroup\$
0

3134 Answers 3134

1
91 92
93
94 95
105
0
\$\begingroup\$

AOG Day 6: Filtering the Playlist

I promise the next one will be better

You've sent the invitations for the party (and made the postperson do a whole lot more work than they should have, smh), made the decorations as interesting as possible (who doesn't love a painstakingly written quine) and made sure that the event won't kill anyone (at least, not due to COVID). The next thing that needs to be planned is the music.

Now, of course, you could go ahead and create a YouTube playlist by hand, but that's way too tedious and, well, predictable. Instead, you've decided to write a program that randomly chooses songs from the music genre (I know...very efficient isn't it).

But of course, there's just one problem with that plan: there's a very small chance that a song selected at random might just ruin the party vibes for everyone (even though people such as myself would consider it a Christmas miracle, others would probably see it as a lame stunt and potentially leave the party).

Thankfully, the magic of code allows us to check the html of the YouTube video before hand to tell if it is indeed a rickroll.

The Challenge

Given a YouTube link as input (not shortened, but a full standard link), retrieve the title and description of the video and output whether or not it is a rickroll. In order for a video to be considered a rickroll, it must have either the unbroken phrase Never Gonna Give You Up or Rickroll in the title or description.

Test Cases

Under construction

\$\endgroup\$
1
  • \$\begingroup\$ How about checking the top 5 comments for the unbroken phrase Never Gonna Give You Up or Rickroll as well? Would that make it inconsistent? \$\endgroup\$ – Razetime Nov 12 '20 at 13:25
0
\$\begingroup\$

Coronavirus Spread

This question is now on the main site here.

\$\endgroup\$
0
\$\begingroup\$

English Stroke Count Alphabet

In a Chinese glossary/index for any given book, to find terms that are contained within the book and because Chinese doesn't have an alphabet like in English, they are sorted by stroke count instead. (一畫 = 1 stroke,二畫 = 2 strokes,三畫 = 3 strokes,四畫 = 4 strokes,and so on)

An English glossary, having an alphabet, is naturally sorted alphabetically. For this challenge, we flip that idea to the Chinese manner. And we'll follow some Chinese writing rules to help determine stroke order for the alphabet below.

Take 口 (kou) for example, a simple square. You'd think it is 4 strokes, but it is actually 3. The 1st being the left vertical line, the 2nd being the top horizontal and right vertical in one fluid stroke, and the 3rd being the lower horizontal line. This pattern, among others, holds relatively true across Chinese characters. For sake of simplicity though, and for some diversity in the English Stroke Count Alphabet, this will be the primary pattern used.

First, I need to define stroke count for each letter. For sake of simplicity, and somewhat subjectively, I'll use the characters as they appear below. If there are any arguments why a letter should have a different stroke count, please make your case, but in order to promote diversity in stroke counts, I made some personal judgment calls. These stroke counts could easily change with different fonts.

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

3 3 1 2 4 3 2 3 3 1 3 2 4 3 1 2 2 3 1 2 1 2 4 2 3 3

a b c d e f g h i j k l m n o p q r s t u v w x y z

2 2 1 2 2 2 2 2 3 2 3 2 3 2 1 2 2 2 1 2 2 2 4 2 2 3

Letters with equal stroke counts should retain the original alphabetic order as before. So the English Stroke Order Alphabet is as follows. (If I made an error, please say as much, there are a lot of examples that I might have to adjust)

C J O S U D G L P Q T V X A B F H I K N R Y Z E M W

c o s a b d e f g h j l n p q r t u v x y i k m z w

The Challenge Given a non-empty string input containing a sentence/series of words, or a list of words, organize all words according to this new English Stroke Count alphabet. Output can be either a string, or a list of properly words is a single string of properly organized words, including duplicates should they exist.

Note 1: If upper and lowercase for the same letter have the same stroke count, uppercase letters take precedence.

  • "Cousin" precedes "cousin"
  • "father" precedes "Father" (because lowercase f is 2 strokes, while the uppercase is 3)
  • "Stop" precedes "soap" (while the o would precede t in stroke count, uppercase S precedes lowercase s)
  • KO precedes kO (K precedes k)
  • kO precedes ko (O precedes o)

Note 2: I've intentionally avoided weird words in input. Inputs such as "WeIrD", "COVID-19". Input will never include any numbers, punctuation, or special characters.

Input / Output

"It was the best of times it was the worst of tImes" / "of of best the the tImes times It it worst was was"

["When", "life", "gives", "you", "lemons", "make", "Lemonade"] / ["gives", "Lemonade", "lemons", "life", "you", "When", "make"]

[The, journey, of, a, thousand, miles, begins, with, one, step,] / [of, one, step, The, a, begins, journey, thousand, miles, with]

"English Stroke Count Alphabet" / "Count Stroke Alphabet English"

"A man a plan a canal panama" / "canal a a panama plan A man"

"Carry on my wayward son" / "Carry on son my wayward"

"Close our store and begin destroying every flower green house just lose no people quietly rather than using vexing xrays yesterday it killed my zoo wombat" / Same as input (If you can write a better sentence than above, I'd be much appreciated.)

["May", "the", "Force", "be", "with", "you"] / ["be", "the", "you", "Force", "May", "with"]

[Im, going, to, make, him, an, offer, he, cant, refuse] / [cant, offer, an, going, he, him, refuse, to, Im, make]

"jello Jello JellO JEllo JELlo JELlO JELLO" / "JellO Jello JELLO JELlO JELlo JEllo jello"

"We suffer more often In imagination than IN reality" / "often suffer reality than In IN imagination more We"

"Code Golf and Coding Challenges" / "Code Coding Challenges Golf and"

["Do", "or", "DO", "not", "there", "is", "no", "try"] / ["or", "DO", "Do", "no", "not", "there", "try", "is"]

"Failure the best teacher is" / "best teacher the Failure is"

"Can you tell that I am a Star Wars fan" / "Can Star a am fan tell that you I Wars"

[enough examples no more words] / [enough examples no more words]

\$\endgroup\$
10
  • \$\begingroup\$ If I is 3, then surely i is 4, no? Similarly for J vs j. \$\endgroup\$ – Adám Nov 2 '20 at 21:32
  • \$\begingroup\$ You should be more lenient about input. E.g. allow a list of words. \$\endgroup\$ – Adám Nov 2 '20 at 21:34
  • \$\begingroup\$ "Uppercase letters take precedence when determining stroke counts, should they be equal." means there's just a single case-sensitive alphabet. It'd be more interesting if uppercase matching lowercase on stroke counts would only be used as a tie breaker. \$\endgroup\$ – Adám Nov 2 '20 at 21:37
  • \$\begingroup\$ @Adám As per point 1, I can see the argument. I can make that change, but it'll likely take a second to get all of the examples in line. Point 2, that input format seems adequate. Point 3, I think I know what you mean. And I'm pretty certain that that's what I was intending, but I had poor wording. \$\endgroup\$ – Sumner18 Nov 2 '20 at 21:49
  • \$\begingroup\$ No rush. I recommend sandboxing for at least one week. \$\endgroup\$ – Adám Nov 2 '20 at 21:52
  • 1
    \$\begingroup\$ You should add KD vs kO and kO vs ko to the examples for Note 1. \$\endgroup\$ – Adám Nov 2 '20 at 21:53
  • \$\begingroup\$ I'm not sure what you mean by "that input format seems adequate", but please familiarise yourself with this. \$\endgroup\$ – Adám Nov 2 '20 at 21:55
  • \$\begingroup\$ @Adám I'd like to add one thing about how stroke count works in Mandarin. 口 (kou) in Mandarin appears to be a square, and you'd think it has 4 strokes, but it actually has 3. The 1st stroke is the left vertical line, the 2nd stroke is the top horizontal and right vertical line, and the 3rd and final stroke is the bottom horizontal line. These patterns hold fairly true across Chinese characters. In the case of the letter i, I actually see 3 strokes instead of your suggested 4. The 1st being the slight horizontal tick and vertical line, the 2nd being the bottom line, and the 3rd for the dot. \$\endgroup\$ – Sumner18 Nov 2 '20 at 21:57
  • 1
    \$\begingroup\$ I see, but then J should be 1, no? 一丿 \$\endgroup\$ – Adám Nov 2 '20 at 21:59
  • \$\begingroup\$ @Adám Correct, I wasn't necessarily thinking of that when I made the challenge, but I'll add the explanation and make the edit. \$\endgroup\$ – Sumner18 Nov 2 '20 at 22:02
0
\$\begingroup\$

Make a die of given number of faces

Objective

Given an integer \$n\$ greater than 3, identify an \$n\$-sided die with the "greatest" symmetry, then decompose \$n\$ to numbers of faces grouped up to the symmetry, and then output the decomposition.

Symmetry

A die can have one of the following symmetries, from the greatest and with descending order:

  • \$I_h\$, icosahedral symmetry

  • \$O_h\$, octahedral symmetry

  • \$T_d\$, tetrahedral symmetry

  • \$D_{ph}\$, \$p\$-fold prismatic symmetry, in ascending order on \$p\$, where \$p\$ is an odd prime number

Note that every other symmetry is redundant.

Faces

A die of each symmetry can have the following faces:

  • For a die of symmetry \$I_h\$:

  • For a die of symmetry \$O_h\$:

  • For a die of symmetry \$T_d\$:

  • For a die of symmetry \$D_{ph}\$:

    • Optionally \$2\$ faces, those from base faces of a \$p\$-gonal prism

    • Optionally \$p\$ faces, those from side faces of a \$p\$-gonal prism

    • Optionally \$2p\$ faces, those from a \$p\$-gonal bipyramid

    • Zero of more sets \$4p\$ faces, those from a \$2p\$-gonal bipyramid

Note that faces from the Catalan solids that are not mentioned here are redundant.

Rules

  • The input and output format doesn't matter. Possible choices of output format include:

    • A list, sorted or unsorted

    • A multiset

  • Invalid inputs fall in don't care situation. Especially, integers that are 3 or less.

Examples

  • For \$n=4\$, the die has \$T_d\$ symmetry, so \$n\$ decomposes to \$(4)\$, with the die being a tetrahedron.

  • For \$n=5\$, the die has \$D_{3h}\$ symmetry, so \$n\$ decomposes to \$(2,3)\$, with the die being a triangular prism.

  • For \$n=6\$, the die has \$O_h\$ symmetry, so \$n\$ decomposes to \$(6)\$, with the die being a cube.

  • For \$n=7\$, the die has \$D_{5h}\$ symmetry, so \$n\$ decomposes to \$(2,5)\$, with the die being a pentagonal prism.

  • For \$n=8\$, the die has \$O_h\$ symmetry, so \$n\$ decomposes to \$(8)\$, with the die being an octahedron.

  • For \$n=9\$, the die has \$D_{3h}\$ symmetry, so \$n\$ decomposes to \$(3,6)\$, with the die being a truncated triangular bipyramid. Note that the die won't have \$D_{7h}\$ symmetry because \$D_{3h}\$ is greater.

  • For \$n=10\$, the die has \$T_d\$ symmetry, so \$n\$ decomposes to \$(4,6)\$, with the die being a chamfered tetrahedron. Note that this is different than the usual d10, which is a pentagonal trapezohedron.

  • For \$n=11\$, the die has \$D_{3h}\$ symmetry, so \$n\$ decomposes to \$(2,3,6)\$.

  • For \$n=12\$, the die has \$I_h\$ symmetry, so \$n\$ decomposes to \$(12)\$, with the die being a dodecahedron. Note that due to the greater symmetry, dodecahedron supersedes rhombic dodecahedron and triakis tetrahedron.

  • For \$n=100\$, the die has \$T_d\$ symmetry, so \$n\$ decomposes to \$(4,24,24,24,24)\$. Note that this is different than usual Zocchihedron, which has prismatic symmtery.

Note that, if \$p\$ and \$p+2\$ are twin primes, \$p+2\$ will always decompose to \$(2,p)\$.

Ungolfed solution

Haskell

This implementation mimics the ReadP parser.

import Control.Monad

type DResult = [([Int], Int)]
type DParser = DResult -> DResult

returnD :: Int -> DResult
returnD n = [([],n)]

pfail :: DParser
pfail _ = []

get :: Int -> DParser
get m results = do
    (ns, n) <- results
    guard (m <= n)
    return (m:ns, n - m)

many :: DParser -> DParser
many p results = let
    results2 = p results
    in case results2 of
        [] -> results
        _  -> results ++ many p results2

optional :: DParser -> DParser
optional p results = p results ++ results

run :: DParser
run = filter ((0==) . snd)

(<++) :: DParser -> DParser -> DParser
(<++) p q results = case p results of
    [] -> q results
    results2 -> results2

decomposeDph :: Int -> DParser
decomposeDph prismFold = run . optional (get 2) . optional (get prismFold) . optional (get (2*prismFold)) . many (get (4*prismFold))

decomposeTd :: DParser
decomposeTd = run . optional (get 4) . optional (get 6) . optional (get 12) . many (get 24)

decomposeOh :: DParser
decomposeOh = run . optional (get 6) . optional (get 8) . optional (get 12) . optional (get 24) . many (get 48)

decomposeIh :: DParser
decomposeIh = run . optional (get 12) . optional (get 20) . optional (get 30) . optional (get 60) . many (get 120)

decomposeDie :: Int -> [Int]
decomposeDie n = fst . head $ foldr (<++) pfail (decomposeIh : decomposeOh : decomposeTd : map decomposeDph [3,5..]) (returnD n)
\$\endgroup\$
0
\$\begingroup\$

Topologies on Rational Numbers (WIP)

Objective

Construct a subset \$P\$ of \$\mathbb{Q}\$ such that:

  • \$P\$ is neither open nor closed in \$\mathbb{Q}\$ as a subspace of \$\mathbb{R}\$, and

  • \$P\$ is open but not closed in \$\mathbb{Q}\$ as a subspace of \$\mathbb{R}_l\$.

Or, in other words, construct a subset \$P\$ of \$\mathbb{Q}\$ such that:

  • There exists \$p \in P\$ such that, there doesn't exist an open interval \$p \in (a,b) \subset \mathbb{R}\$ such that, \$\mathbb{Q} \cap (a,b) \subset P\$.

  • For every \$p \in P\$, there exists a half-open interval \$p \in [a,b) \subset \mathbb{R}\$ such that, \$\mathbb{Q} \cap [a,b) \subset P\$.

  • There exists \$p \in \mathbb{Q} \setminus P\$ such that, there doesn't exist a half-open interval \$p \in [a,b) \subset \mathbb{R}\$ such that, \$\mathbb{Q} \cap [a,b) \subset \mathbb{Q} \setminus P\$.

Notes and Rules

  • Note that \$P\$ is necessarily infinite, and thus cannot be represented as an associative container. One way of representing \$P\$ is to have a function \$f : \mathbb{Q} → \mathbb{Z}_2\$ that halts for every input, where \$\mathbb{Z}_2\$ is the set of the boolean values. Then \$p \in P\$ shall satisfy iff \$f(p)\$ is true.

  • The representation of \$\mathbb{Q}\$ must be exact. Thus you cannot have floating-point values as an input. Though native rational-number arithmetic will be preferred, you may use two arbitrary-length integers as an input. In this case, the fraction is assumed to be irreducible and to have a positive denominator. Otherwise, the fraction falls in don't care situation.

  • Invalid inputs fall in don't care situation.

Example

An example of such \$P\$ is:

$$ \mathbb{Q} \cap ((0,1) \cup [2,3)) $$

Work in progress due to a trivial example.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Is there a way you can frame this question without topology? At the moment I think participation would be very low due to the high background knowledge demanded. \$\endgroup\$ – Sisyphus Nov 10 '20 at 9:58
0
\$\begingroup\$

Write a program that mimics the output of the command env (with no arguments).

The program should print (to standard output, or closest equivalent) a list of all current environment variables, with each variable on it's own line. The name and content of a variable should be separated by an equal sign.

Here's a grammar:

line ::= name "=" contents
output ::= (line "\n")*

No using the env command.

shortest code wins.

\$\endgroup\$
5
  • \$\begingroup\$ Can we use built-ins the get environment variables? \$\endgroup\$ – Adám Nov 15 '20 at 15:50
  • \$\begingroup\$ @Adám If you mean "Can we use built-ins to get the environment variables", yes, I don't see a reason you couldn't, and otherwise it might be impossible to get them in some languages. \$\endgroup\$ – binarycat Nov 15 '20 at 15:54
  • 1
    \$\begingroup\$ And I assume (ba|k|c|…)sh cannot participate? \$\endgroup\$ – Adám Nov 15 '20 at 15:56
  • \$\begingroup\$ @Adám If they can find a way to get a list of environment variables without using env, I guess they could, unless I'm missing some other command that produces the same output. There's a lot of languages that can't complete the challenge (mostly esoteric ones), but they aren't technically banned. \$\endgroup\$ – binarycat Nov 15 '20 at 23:28
  • \$\begingroup\$ How about set on Windows/DOS? \$\endgroup\$ – Adám Nov 16 '20 at 8:07
0
\$\begingroup\$

Find the longest streak of Fibonacci numbers on the Ulam spiral

Fibonacci numbers

Fibonacci numbers are a sequence where each element is the sum of the previous two elements. In the original Fibonacci sequence, the first two number are 1. So the sequence goes: 1, 1, 2, 3, 5, 8, 13, 21, .... For the challenge, we will accept any two numbers as the two starting numbers of the series.

Ulam spiral

The Ulam spiral is an arrangement of natural numbers. The spiral goes counter-clockwise and starts with the numbers 1, 2, where the 2 is right of the 1. For this exercise, only the shape of the spiral is relevant.

Ulam spiral

Task

Find the length of the longest streak of generalised Fibonacci numbers (with any two starting numbers) following the Ulam spiral in a given array of integer numbers.

Example

The following 5x5 array has two generalised Fibonacci sequences: one of length 4 (in blue + yellow: 138, 81, 219, 300) and one of length 8 (in green + blue: 24, 57, 81, 138, 219, 357, 576, 933). The answer is thus 8.

Example

Rules

  • Your program should at least support arrays up to 65535 * 65535 in size and array elements with values up to 4,294,967,295.
  • Invalid input (non-square arrays, float or negative elements, non-arrays, etc.) may lead to unpredicted output, errors or (un)defined behaviour.
  • Default I/O rules apply and default loopholes are forbidden.

on question 1; see comments below

  • This is , so the shortest answer in bytes wins.

on question 2; see comments below

  • This is , so the fastest answer wins.
  • Fastest code is measured in average user time over 5 different, undisclosed input matrices of sizes 100, 1000 and 10,000, each run 3 times on my late 2013 MacBook Pro with 2,3 GHz quadcore Intel i7 CPU and 16 GB of RAM.

Review questions

  • I plan on publishing this question twice: one time as a codegolf and one time as a fastest-code. See the last section of my question. I think this challenge has interesting but very different optimization strategies for speed and size. Is this be something that would be frowned upon by the CGSE community?
  • Is the challenge clear enough as stated?
  • Should I add more/larger test cases? Or a test case generating Python script?
\$\endgroup\$
0
\$\begingroup\$

Isomorphic Modular Arithmetic

For this question, we define \$U(n)\$ as the group consisting of a number below \$n\$ that is coprime to n (1 included but 0 doesn't) and multiplication as group operator.

Your task is to print every integer (so it's an infinite loop, but there should be output during looping) and group it into lines so that:

  1. The line consists of a sequence of sorted number so that the \$U\$ group based on each number is isomorphic
  2. The output itself has to be sorted based on the first number on each line
  3. Every number have to be eventually outputted given enough time.

A pair of groups \$(X,\times_A)\$ and \$(X,\times_B)\$ is called isomorphic if there is a pair of functions \$f : X\to X\$ and \$g:X\to X\$ so that:

\$ f(g(x)) = x = g(f(x)) \text{ (i.e. they are inverses)} \$

\$ f(x) \times_B f(y) = f(x \times_A y) \$

\$ g(x) \times_A g(y) = g(x \times_B y) \$

The shortest code wins.

Example

U(2) consists of only one element 1. U(3) and U(4) is isomorphic because both contains only 2 elements (former 1, 2 and latter 1, 3. 2 is excluded because 2 divides 4) and the table of multiplication is identical aside of replacement of 2 and 3. Less trivially U(8) and U(12) is isomorphic, but not U(5) the elements of U(8) is 1,3,5,7 the elements of U(12) is 1,5,7,11 the elements of U(5) is 1,2,3,4 Look at the table of multiplication:

    U(8)          U(12)          U(5)     
  1 3 5 1       1  5  7 11     1 2 3 4
1 1 3 5 7    1  1  5  7 11   1 1 2 3 4
3 3 1 7 5    5  5  1 11  7   2 2 4 1 3
5 5 7 1 3    7  7 11  1  5   3 3 1 4 2
7 7 5 3 1   11 11  7  5  1   4 4 3 2 1

By replacing 1 <-> 1, 3 <-> 5, 5 <-> 7, 7 <-> 11, the table of multiplication for U(8) and U(12) is identical. U(8) and U(5) is not, as n * n = 1 for any n in U(8), but 22 = 4 and 11 = 1 in U(5). If there is such a pair f : U(8) -> U(5) and g : U(5) -> U(8), then g(22)=g(4) <=> g(2)g(2)=g(4) <=> 1 = g(4) <=> g(1) * g(1) = g(4) <=> g(11) = g(4) <=> f(g(11)) = f(g(4)) <=> 1*1=4 <=> 1=4, which is a contradiction.

Even less obviously U(7) and U(9) are isomorphic, the multiplication table is:

   U(7)           U(9)
1 3 2 5 4 6   1 2 4 5 7 8
3 2 6 1 5 4   2 4 8 1 5 7
2 6 4 3 1 5   4 8 7 2 1 5
5 1 3 4 6 2   5 1 2 7 8 4
4 5 1 6 2 3   7 5 1 8 4 2
6 4 5 2 3 1   8 7 5 4 2 1

Aside of swapping the row and column (has been done) and relabeling, the multiplication table is identical, So, they are symmetric

Output for 2-15

2
3 4 6
5 10
7 9
8 
11
13
14
15
\$\endgroup\$
4
  • \$\begingroup\$ Your opening sentence doesn't quite define a group. Do you mean a group generated by the coprime and multiplication? It seems like the most logical choice. \$\endgroup\$ – Wheat Wizard Nov 24 '20 at 14:55
  • \$\begingroup\$ I am starting to doubt that since the result is always isomorphic to the integers under addition, and completely ignores n. Do you maybe mean the group generated by the coprime and multiplication on the cyclic group of order n? This makes more sense, but not a whole ton of sense. I think if you explained the output requirements more directly it would be easier. As it stands I do not understand them at all. \$\endgroup\$ – Wheat Wizard Nov 24 '20 at 15:19
  • \$\begingroup\$ @WheatWizard I mean group generated by coprime and multiplication on the cyclic group of order n \$\endgroup\$ – Xwtek Nov 25 '20 at 10:43
  • \$\begingroup\$ You still haven't actually changed the problem statement. \$\endgroup\$ – Wheat Wizard Nov 28 '20 at 21:04
0
\$\begingroup\$

Use the wrong paradigm

This is just a general idea, I don't know how you would go about scoring it or what the goal would be, but I think it would be fun to see stuff like oop in haskell.

\$\endgroup\$
1
0
\$\begingroup\$

Golfing on a Budget

The Task

Every answer should take a positive number as input, and print/return every number in reverse down to zero (inclusive), in any reasonable format. For example:

10    -> "10 9 8 7 6 5 4 3 2 1 0"
8     -> [8, 7, 6, 5, 4, 3, 2, 1, 0]
1000  -> [["1", "0", "0", "0"], ["9", "9", "9"], ["9", "9", "8"], ...]

The requirements

Every program has $100 to spend.

The cost of each byte is determined by \$2^{t-1}\$, where \$t\$ is the number of times the byte has appeared in previous programs in addition to the current one.

For example, assuming it's the first program, x->x++ would cost $10. Each - and > are $1, and each x and + are $2.

\$\endgroup\$
3
  • 2
    \$\begingroup\$ In some sense, doesn't this become a contest of speed to solution? The earlier I post, the lower my score. It also severely advantages certain languages that don't use ASCII. \$\endgroup\$ – Xcali Dec 3 '20 at 4:17
  • \$\begingroup\$ Also, what's the criteria for winning? What is the reason for the $100? \$\endgroup\$ – Xcali Dec 3 '20 at 4:25
  • \$\begingroup\$ @Xcali This is currently a very rough idea, so I didn't have any winning criterion decided on yet. What I was trying to do was make it so that it would be harder to come up with valid answers as time went on, but I think the execution ended up really bad here. \$\endgroup\$ – Redwolf Programs Dec 3 '20 at 4:27
0
\$\begingroup\$

Perfect radicals

  • Posted

Perfect radicals

\$\endgroup\$
0
\$\begingroup\$

Posted to the main forum

\$\endgroup\$
4
  • 1
    \$\begingroup\$ We do have occasional fastest code challenges, and many of them get great answers. For objective scoring, (unfortunately) it is necessary to score it on your machine because the specifics of OS/CPU/RAM/storage device/whatever can change the relative run time of two programs. One suggestion is to use smaller test cases (reduce board size and number of ships) so that programs can be tested without waiting for hours. \$\endgroup\$ – Bubbler Dec 1 '20 at 10:01
  • \$\begingroup\$ I can, for instance. set up a Linux virtual machine for the tests. And yes, it is possible to parameterise so as to have a scale of complexity: highest complexity gives authoritative score but lower ones used for weeding. \$\endgroup\$ – user46773 Dec 1 '20 at 15:07
  • 1
    \$\begingroup\$ I'd suggest posting a valid board as the example and then a separate invalid one to illustrate that point. \$\endgroup\$ – Xcali Dec 3 '20 at 4:21
  • \$\begingroup\$ @Xcali - good point. I will do that. \$\endgroup\$ – user46773 Dec 3 '20 at 13:01
0
\$\begingroup\$

Play the percussion for Ravel's Boléro

rhythm

The Boléro by Maurice Ravel is a piece of music characterised by a consistent snare drum pattern, repeated over and over, at unchanging tempo. This task is very challenging for a human performer, who must maintain the beat without rushing the tempo, or increasing the volume too quickly.

That's why you're going to write a program to do it!

I want your program to do something at the tempo and rhythm specified. It can output a key to a console, produce a beep, make a window pop up, have a graphical display flash colour; anything at all is acceptable, as long as it is A) observable to a human, and B) does not need human interaction for the program to continue. So if you make a pop-up, you should not require someone to click it away before the next pop-up can appear.

Using a tempo of 60 bpm (a bit slow but Ravel liked it played slowly), the whole rhythm takes exactly 6 seconds to play through. Here are the timings for when your program must send out some kind of signal, the unit being seconds. I'll tolerate divergences from the ideal of up to 0.02 seconds in either direction.

0.00
0.50
0.67
0.83
1.00
1.50
1.67
1.83
2.00
2.50
3.00
3.50
3.67
3.83
4.00
4.50
4.67
4.83
5.00
5.17
5.33
5.50
5.67
5.83
6.00

Note that here the final beat, at exactly 6 seconds, is the first beat of the next iteration of the rhythm; the next percussion hit occurs at 6.50, then 6.67, and 6.83, etcetera.

So, make your program produce that rhythm indefinitely. Choose whatever output you want. It's , so the shortest code wins!


For the sandboxers; I have considered using either this question as is, or having it be a popularity contest with added the stipulations that it ends after 170 repetitions and that the output somehow gradually gets intenser throughout that time, like the music does. The con is that popularity contests are a bit messier; but I would love to see creative ways to display the rhythm.

\$\endgroup\$
4
  • 1
    \$\begingroup\$ You should add an explanation for people who cannot read music; not everyone knows what a triplet is, or what bpm means. \$\endgroup\$ – Robin Ryder Dec 6 '20 at 13:50
  • \$\begingroup\$ @RobinRyder No knowledge of sheet music is needed; the picture is just illustrative. The list of timings is accurate. \$\endgroup\$ – KeizerHarm Dec 6 '20 at 15:29
  • \$\begingroup\$ The list of timings is accurate at 60 bpm, but not at other tempos. \$\endgroup\$ – Robin Ryder Dec 6 '20 at 16:16
  • 1
    \$\begingroup\$ @RobinRyder Very well, I will make 60 bpm the only accepted tempo and just have the timings be the final specification. \$\endgroup\$ – KeizerHarm Dec 6 '20 at 20:09
0
\$\begingroup\$

Simon says "Make me a game"

Forked from this closed question.

Create a "Simon says" game.

Take an input \$n\$, for number of levels, and \$k\$, for number of buttons and do the following:

  • Create a square area for the buttons.(at least 100x100 pixels in size.)

  • Divide it into k rectangular buttons of equal size. k will always be even.

  • Each button should be of a different color, and none of them should be the same color as the background.

  • The game should proceed as follows:

    • Starting level is 1. Level number should be displayed at the top.

    • Get a random order in which the buttons should "light up". The number of clicks should be level number + 4.

    • In that same sequence, display a visual indicator on each button, so the user knows what order they should click the buttons in.

    • There should be at least a 200ms delay between each visual indication.

    • If the user clicks them in the correct order, move on to the next level, and repeat the above steps. Otherwise, display "Game Over" at the bottom of the screen.

Here is a playable demo for k=4, Courtesy of Gabriele D'Antona.


Meta

  • Is this specification clear?

  • Any thoughts/feedback?

  • Should there be a limit on the values of n and k?

\$\endgroup\$
0
\$\begingroup\$

Animal-Alphabetical Sequence

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Seems like a cool challenge except for the part where you have to start from the googolth element. I'd suggest starting from the beginning instead. \$\endgroup\$ – Beefster Dec 16 '20 at 17:51
  • \$\begingroup\$ Also, JAMBU won't appear anywhere in the output since none of the other animals have Js in them. Same for ZEBRA and maybe others. You might consider choosing different animal names, dropping your 5-letter theme, and ensuring that all 26 letters can possibly exist in the sequence. \$\endgroup\$ – Beefster Dec 19 '20 at 0:12
0
\$\begingroup\$

Answers made up from older answers


In this challenge, your task is to take a number as input, and determine whether it is the number of previous answers. For example, the third answer would print/return a truthy value is given 2, and a falsey value for any other input.

However, all answers must be made up of previous answers. For example, if the existing answers were +1, t()==1, and _=>inpu, some allowed answers would be:

  • t()==1+1
  • _=>input()==1+1
  • +1+1+1+1

Examples of answers that would not be allowed:

  • 1+
  • 1+1
  • _=>+1
  • (newline)

For the output/return format, this is a list of the allowed formats I'll use for this challenge.

Scoring and initial allowed parts of answers coming soon.

Meta

  • What should the title be?
  • Any recommended initial allowed parts?
  • Is this easy to read/understand?
\$\endgroup\$
7
  • \$\begingroup\$ This is understandable, and seems to make a fun challenge. You should probably restrict having the same language twice (although i'm assuming that's implied) because that would make it boring. The title could be like "Answer Recycling" or something, but I'm not very creative with titles. \$\endgroup\$ – Gio D Dec 27 '20 at 6:14
  • \$\begingroup\$ @GioD Oh, I forgot about that, I'll make sure to add that restriction. Thanks for the title suggestion, too! \$\endgroup\$ – Redwolf Programs Dec 27 '20 at 6:16
  • \$\begingroup\$ No problem, I just like the idea of recycling being used in a problem. Are people allowed to submit more than once? because this definitely seems like a fun challenge. My idea of a first program would just be "0" in retina, but that seems like it wouldn't make for a lot of creativity \$\endgroup\$ – Gio D Dec 27 '20 at 6:17
  • \$\begingroup\$ @GioD I'd probably just restrict posting more than one answer in a row. Glad to see there's some interest in this challenge! \$\endgroup\$ – Redwolf Programs Dec 27 '20 at 6:20
  • \$\begingroup\$ My idea for initial characters were "0", "1", " ", newline, and "=" although that might not work as well as I think it would. I'd recommend experimenting, since I'm fairly new to code golfing and i don't know most of the languages out there. \$\endgroup\$ – Gio D Dec 27 '20 at 6:30
  • 2
    \$\begingroup\$ I don't see how the parts list gets expanded with each answer. If it doesn't, how do different answers get created? \$\endgroup\$ – Xcali Dec 29 '20 at 3:07
  • \$\begingroup\$ @Xcali That's an issue I was thinking about, I think my solution will be allowing each answer to add one new part. For example, if the current parts are a, bc, and d, I could answer abcfdabc, so the new parts list would be a, bc, d, abcfdabc \$\endgroup\$ – Redwolf Programs Dec 29 '20 at 3:13
0
\$\begingroup\$

Implement ASCII -> GSM-7 (SMS) text packing

SMS messages can store 160 ASCII characters into 140 characters. It does this by chopping off the top bit from each byte and packing them together.

The simplified steps:

  1. Convert the string to binary little endian ASCII.
  2. Remove the top bit from each byte.
  3. Pack them together so there are no gaps.
  4. If applicable, pad the final byte with zero bits.

So, take the text "Test0123".

First, we convert it to little endian binary.

0x54     0x65     0x73     0x74     0x30     0x31     0x32     0x33
00101010 10100110 11001110 00101110 00001100 10001100 01001100 11001100

Then, we chop off the last (most significant) bit of each octet:

0010101  1010011  1100111  0010111  0000110  1000110  0100110  1100110

Then, we pack them together into a 7 byte array:

0xd4     0xf2     0x9c     0x0e     0x8b     0xc9     0x66
00101011 01001111 00111001 01110000 11010001 10010011 01100110

In the case of bitwise operations, it is a simple funnel shift.

The basic algorithm in C is here for an 8 byte ASCII string. However, your algorithm must accept any length.

void ascii_to_gsm7_8_bytes(uint8_t *buf, const char *str)
{
    buf[0] = (str[0] >> 0) | (str[1] << 7);
    buf[1] = (str[1] >> 1) | (str[2] << 6);
    buf[2] = (str[2] >> 2) | (str[3] << 5);
    buf[3] = (str[3] >> 3) | (str[4] << 4);
    buf[4] = (str[4] >> 4) | (str[5] << 3);
    buf[5] = (str[5] >> 5) | (str[6] << 2);
    buf[6] = (str[6] >> 6) | (str[7] << 1);
}

The input can either be a string (optionally with a provided length) or an input from stdin which is terminated with a newline or EOF.

The string will be a non-empty printable ASCII string that is 160 bytes or less. It is safe to assume that all bytes are 0x20 <= x < 0x80, meaning the last MSB bit is cleared beforehand.

Important: While strings can be null terminated, you are not allowed to use that null terminator for padding the last byte.

Output will be the packed string.

The output can either be printed as a list of values (base 10 or base 16) to stdout or returned in an output array.

Test cases (output is in hex):

Input text -> Output (hex)
"" -> Empty strings do not need to be handled.
"Úñíçódé" -> Unicode does not need to be handled, only ASCII.
"Hi!" -> {0xc8, 0x74, 0x08}
"Test0123" -> {0xd4, 0xf2, 0x9c, 0x0e, 0x8b, 0xc9, 0x66}

More test cases will be added if this is accepted.

This is , so the shortest code in bytes per language wins.

\$\endgroup\$
4
  • 2
    \$\begingroup\$ You should probably provide example input/outputs for so that it's easy for people to test their program and to get a grasp of what the program is asking. \$\endgroup\$ – Gio D Dec 27 '20 at 6:31
  • \$\begingroup\$ I updated the rules to make them more clear, removed the 140 byte requirement, and added an example and a few test cases \$\endgroup\$ – EasyasPi Dec 27 '20 at 22:10
  • \$\begingroup\$ 1. Bonuses to a score are generally frowned upon. 2. I'm confused about the output format. What is needed? 3. Why the null requirement added to the end? I don't see that in the SMS spec. 4. What's the winning criteria? \$\endgroup\$ – Xcali Dec 28 '20 at 17:47
  • \$\begingroup\$ Is this better? \$\endgroup\$ – EasyasPi Dec 28 '20 at 18:45
0
\$\begingroup\$

Isosceles triangle truncations

Most triangles are not isosceles. Here is an example:

A ____ C
 |   /
E|  /
 | /D
 |/
B

However, we can cut this triangle into two smaller triangles, one of which is isosceles. We can do this in a number of ways:

  • By cutting from C to E, we create isosceles triangle BEC. (Due to limitations of ASCII art, you'll just have to imagine that E is in the correct place.)
  • By cutting from A to D, we create isosceles triangle ADB.
  • By cutting from A to D, we create isosceles triangle ADC. (This always happens for right-angled triangles, of course. It's hard to draw ASCII art triangles that are neither right-angled nor isosceles.)

Each triangle can be derived in turn from the original triangle by fixing one of the three sides (which will be the base of the new triangle) and the smaller of the two adjacent angles, adjusting the other base angle as necessary.

Your challenge is, given a triangle of three points A, B and C in any reasonable format, is to output at least one of its isosceles triangle truncations.

It must be possible to obtain all three truncations for a given triangle. This is typically achieved by permuting the parameters of the function, but you can use some other input method if you wish. In any case please indicate how to obtain all truncations.

Example: For an input of (0, 0), (0, 4) and (8, 0), the output might be (0, 0), (4, 2), (8, 0); (0, 0), (0, 4), (4, 2); (3, 0), (0, 4), (8, 0). Alternatively, the output might just be (3, 0), and to obtain (4, 2) you would have to input the triangle in a different order.

You may assume that the input triangle is not isosceles (or equilateral, for those languages that allow parameters that are surds rather than floating-point decimals). For instance, for programs that normally output all truncations, they might simply return a single equilateral triangle unchanged.

Your method should be theoretically exact even if the code suffers from floating-point limitations.

This is , so the shortest program or function that breaks no standard loopholes wins!

\$\endgroup\$
0
\$\begingroup\$

possible chess moves in choice format

the goal is to make a function that takes in a board in choice format and color and outputs all possible moves.

for example: ['pawn',1,1] -> ['pawn',1,2], ['pawn',1,3].

\$\endgroup\$
6
  • \$\begingroup\$ Glad to see you took my advice and posted this here. I don't think fastest code is a good winning criterion - a queen on a central square has a maximum of 27 moves available to her, so even with 16 unrestricted queens (an impossible situation) a player would have 432 moves, which would be solvable instantly in most languages. I would suggest codegolf as a winning criterion \$\endgroup\$ – Level River St Jan 5 at 22:10
  • 1
    \$\begingroup\$ I suggest you develop this with: 1. full definition of input and output format 2. Consideration of the following: do we have to consider castling, double square advance for unmoved pawns, en passant? 3. Do we have to consider pawn promotion, and does promotion to different pieces (a queen or knight for example) count as a different move? 4. What pieces can a player be expected to have? a) the normal 16 at the start of the game, b) the normal 16 after some/all pawns have been promoted c) some more bizarre set of pieces? 5. Should moves leaving king in check be included / excluded from output? \$\endgroup\$ – Level River St Jan 5 at 22:17
  • 2
    \$\begingroup\$ Suggested input format: White pieces RNBKQ and P, black pieces rnbkq and p on an 8x8 grid. By the way welcome to the site. \$\endgroup\$ – Level River St Jan 5 at 22:18
  • \$\begingroup\$ I recommend you look through the existing chess questions and make this one sufficiently different. Here's a couple I've seen before (and answered one of them) but then forgot about codegolf.stackexchange.com/q/45179/15599 and codegolf.stackexchange.com/q/89429/15599 \$\endgroup\$ – Level River St Jan 7 at 16:19
  • \$\begingroup\$ Are chess libraries allowed? \$\endgroup\$ – Razetime Jan 8 at 10:55
  • \$\begingroup\$ @Razetime no, chess libraries are not allowed. \$\endgroup\$ – someone Jan 8 at 20:17
0
\$\begingroup\$

Divisor chains

Definition

A simple path in the divisor graph of {1,...,n} is a sequence of distinct numbers between 1 and n such that if k immediately follows m, then either k divides m or m divides k.

Task

(1) Return a list of integers that represents the lexicographically earliest longest, simple path in the divisor graph of {1,...,n}.

Implement a named function with one argument, f(n), n a positive integer; you can assume n <= 33. The function takes the argument for input.

No print statements (or other I/O-statements) are allowed in the function; the return is a list (or tuple or array). The use of external library functions is not allowed.

(2) A print statement that prints the output of (1): print(f(n)). The function name print is not obligatory and the print function can use standard libraries.

Test

(1) For n = 10 the call f(10) returns [4, 8, 1, 5, 10, 2, 6, 3, 9].

(2) print(f(10)). We do not fix the format of the returned list. The output might also look like 4 8 1 5 10 2 6 3 9 or any other convenient way.

Challenge

This is code-golf with restricted-time, so the shortest code in bytes wins if it can run the test above on TIO https://tio.run/ without timing out. Only the code of the generating function f is counted, without the print statement.

Tags: code-golf, restricted-time, math, sequence

\$\endgroup\$
0
\$\begingroup\$

Lazy Robot Monkey Problem

Question Summary

You have made a robot monkey. The purpose of the robot is to move through the trees and try to reach as many as possible monkeys before running out of battery. You have to follow some rules while moving.

You are give a interlinked tree in the following format :

enter image description here

Here each 1 is a monkey and each 0 is an empty place.

Each note can have multiple parents and Childs but unlike a Graph its direction is downward.

The robot monkey has a initial energy value.

The robot Monkey can move through the nodes following certain rules:

  • Going up to the parent node needs 4 units energy.
  • Going down to the child node needs 2 units energy.
  • There may be some food at some nodes. Each times the monkey eats its energy increases by food value.
  • The monkeys energy can never be negative.
  • The monkey cannot eat more than the initial energy value.

What to do?

You are given the initial node (where your robot monkey is initially sitting).

The node is in the following format :

class Node:
    parents = [] # Will have all the parents
    children = [] # Will have all the children
    isMonkey = 1 # May be 0
    foodValue = 0 # May be anything

You are also given a initial food value and the number of monkeys in the tree.

You now have to find how many monkeys can you maximum meet with before your battery dies.(by going to the same position)

Your answer should be in format:

def monkeyMeet(initialNode, energy, totalMonkeys):
    # write your code here
    pass

Or in any other programming language.

The size of the tree may be huge.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ Is this code golf? You need to have a way to have entries be compared (within a language). \$\endgroup\$ – xnor Jan 12 at 9:10
0
\$\begingroup\$

SimpleHearts KOTH

SimpleHearts

SimpleHearts is a four player trick-taking card game similar to Hearts, with a few simplifications. Hearts has several possible rule variations, and the rules I will use are outlined here.

For each game, each of the four players are dealt 13 of the cards in a standard deck. After that, there will be 13 "tricks", and during each trick the players will take turns playing exactly one of their cards. Each trick will consist of the following:

  • One player leads the trick by playing a card. The suit of this card is the "led suit". On the first trick the player with the 2 of clubs must lead with the 2 of clubs, on the following tricks whoever won the previous trick will lead.

    The leader may not lead a heart until another player has played a heart or the Qs (Queen of Spades). Exception: if the leader only has hearts in their hand, they may lead one of their hearts. The leader may lead the Qs at any time.

  • In a clockwise fashion, each player will take their turn playing one card in their hand of the led suit. If the player has no cards of the led suit, they may play any card. Exception: On the very first trick, no one after the leader may play a heart or the Qs, unless all of their cards are hearts or the Qs (obviously absurdly unlikely).

  • After all four players play a card, whichever player played the highest value card of the led suit wins the trick. Ace is highest value and 2 is lowest. The winner of the trick receives 1 point for every heart played by anyone in the trick, and 13 points if the Qs was played in the trick.

  • Repeat, with the winner leading the next trick.

The objective of the game is to receive as few points as possible. After all 13 tricks are played, the score of each player is the total number of points they took during gameplay. Important exception: if one player takes all possible points, i.e. the 13 hearts and the Qs, they receive 0 points and all other players receive 26 points (this is called "shooting the moon").

Key differences from standard Hearts:

  • There is no passing cards

  • Scores are not cumulative in the standard way (the scoring system of this particular challenge will be explained next).

Gameplay and Scoring

This is a KOTH challenge, meaning the objective is to create a bot (in this case a Python function) which will compete against other submitted bots in the game of SimpleHearts. All subsets of size 4 of the set of submissions will play against each other in N matches of 4 games each. For sandbox: N is tbd, should be as high as reasonably possible.

The dealing of the cards will be identical in each of the 4 games in a match, except rotated. For example, suppose the players are A, B, C, and D. In the second game player B will have the same hand player A had in game 1, C will have B's game 1 hand, etc. This is to reduce the impact of random chance, as one player being dealt a bad hand will affect all players equally in theory.

Each submission's final score will be the sum of their scores in all the games they played. The winner will be the submission with the lowest final score. In the case of a tie, the oldest submission will win.

Technical Requirements

Each submission will be a Python function (for sandbox: this is an arbitrary choice, is there a better one?) which takes as parameters:

  • A list of 2-tuples representing the cards in their hand. Each tuple will be of the form (12, 's') with the number representing the value of the suit and the string representing the suit, being one of s, h, d, c. For simplicity's sake the numbers are from 2 to 14, and we do not care about encoding "Queen" or "Ace". Therefore the Queen of Spades is (12, 's'), Ace of Diamonds is (14, 'd'), and the 2 of clubs is (2, 'c').

  • A list of 4 integers representing the scores of each player so far in the current game. The first element of the list is your score, then the player to your left, then the player across, then the player to your right.

    Note: leading with hearts is allowed if and only if you only have hearts, or someone has a nonzero score.

  • A list of 4 lists of tuples representing which cards have been played and by whom. The first list will be the cards you played, in order. The second list will be the cards played by the player on your left, in order. Etc.

  • A list of 0-3 tuples representing the cards that have been played in the trick, in order.

As output, the submission must return a single tuple representing a card in its hand, which is legal to play according to the rules of SimpleHearts. Of course, the function may choose to ignore any of these inputs but if it makes an illegal output, it is disqualified. In testing, I will force whoever has the 2 of clubs to lead with it on the first hand, ignoring the contents of the function.

The submission must be deterministic, i.e. will always produce the same output on the same input (so pseudorandom numbers with a set seed are allowed).

All submissions must be at most 100 000 characters.

The challenge will end 14 days after this prompt is posted, after which I will test all valid submissions against each other in the manner I described.

For sandbox

This prompt is still WIP, but I appreciate any comments. I intend to create a controller and some example submissions, but only after Sandbox folk deem the challenge to be good enough.

Is there any reasonable way to make the requirements easier or the game simpler? Cause this post is kinda long.

\$\endgroup\$
5
  • \$\begingroup\$ 1. You should probably forbid tampering with the environment/other bots. 2. You probably should clarify what happens if a bot throws an exception, and what happens during a disqualification (do the round with the disqualified bot simply not count or does a dummy bot come into play) 3. There is nothing wrong with a python function but it is worth noting that most koth competitions are either a JS function or a Java abstract class. 4. Also, it might be worth adding some sort of timeout for the bots. \$\endgroup\$ – Aiden4 Jan 20 at 18:25
  • \$\begingroup\$ So you're not playing with the rule that if one player wins all 124 points, then their score changes to 0 and the other players get 124 each instead? The risk there the most fun part of hearts! \$\endgroup\$ – pxeger Jan 21 at 10:06
  • \$\begingroup\$ @pxeger I'm not sure what you mean. I did mention shooting the moon, but what do you mean winning all 124 points? \$\endgroup\$ – 79037662 Jan 21 at 14:52
  • \$\begingroup\$ @79037662 I missed that because I've never heard it described as "shooting the moon". 124 is the sum of the available points in the scoring system I know (2+3+4+5+6+7+8+9+10+10(J)+10(Q)+10(K)+15(A)+25(QS)) \$\endgroup\$ – pxeger Jan 21 at 15:00
  • \$\begingroup\$ @pxeger In the standard ruleset, all hearts are worth 1 each and QS is worth 13 :) \$\endgroup\$ – 79037662 Jan 21 at 15:15
0
\$\begingroup\$

The UTM theorem

Let denote the set of natural numbers. Let A × B denote the Cartesian product of A and B. Let A ⇀ B denote the set of partial functions from A to B.

The UTM theorem says that there exists a computable function u : ℕ × ℕ ⇀ ℕ such that, for every computable function f : ℕ ⇀ ℕ, there exists a p : ℕ such that, for every x : ℕ, u(p, x) ≃ f(x). That is, there exists a universal computable function (analogous to the universal Turing machine).

Implement such a function in your language. Shorter is better.

Example: Python (57 chars)

lambda p,x:eval(p.to_bytes(p.bit_length()//8+1,'big'))(x)
\$\endgroup\$
3
  • \$\begingroup\$ Are you sure you can emulate a while loop in Python eval? \$\endgroup\$ – Bubbler Jan 19 at 6:33
  • 2
    \$\begingroup\$ Also, this has the same problem as your other sandboxed challenge in that eval does the job in many languages. \$\endgroup\$ – Bubbler Jan 19 at 6:41
  • \$\begingroup\$ @Bubbler It should be able to emulate (some variant of) the lambda calculus, which requires only pure functions. \$\endgroup\$ – user76284 Jan 19 at 7:05
0
\$\begingroup\$

Radical of an integer

The radical of an integer (written as \$\mathrm{rad}(n)\$) is defined as the product of all prime numbers that divide it. This it A007947.

For example, since \$ 504 = 2^3 \cdot 3^2 \cdot 7 \$, \$ \mathrm{rad}(504) = 2 \cdot 3 \cdot 7 = 42 \$.

Challenge

Your task is to write a function or a program which takes a number as the input, and output its radical.

You don't have to handle any cases where the input isn't an integer or isn't positive (you don't have to handle 0).

Test cases:

504 -> 42
6 -> 6
57 -> 57
1024 -> 2
9 -> 3
1 -> 1

This is code-golf, so the shortest answer in bytes wins. Good Luck!

\$\endgroup\$
9
  • \$\begingroup\$ I think you can omit the "input/output in any base" part ("the output base must match the input base" is especially unnecessary) and let the answers use any sensible, consistent integer I/O as allowed in our defaults. Other than that, nice challenge. \$\endgroup\$ – Bubbler Jan 19 at 7:02
  • \$\begingroup\$ Suggested test case: 1 -> 1. \$\endgroup\$ – Bubbler Jan 19 at 7:03
  • \$\begingroup\$ What is the behaviour for negative numbers and zero? \$\endgroup\$ – pxeger Jan 19 at 11:15
  • \$\begingroup\$ @pxeger You don't have to handle any cases where the input isn't an integer or isn't positive (you don't have to handle 0). \$\endgroup\$ – Command Master Jan 19 at 12:16
  • \$\begingroup\$ @CommandMaster whoops, missed that \$\endgroup\$ – pxeger Jan 19 at 13:49
  • \$\begingroup\$ This is A007947, which describes it as "Largest squarefree number dividing n". \$\endgroup\$ – xnor Jan 20 at 10:27
  • 2
    \$\begingroup\$ Duplicate \$\endgroup\$ – ChartZ Belatedly Jan 20 at 20:55
  • 1
    \$\begingroup\$ Dang, I should stop using built-in SE search for finding duplicates. \$\endgroup\$ – Bubbler Jan 21 at 0:24
  • \$\begingroup\$ @Bubbler I was pretty sure I recognized the challenge, it was xnor's comment that lead me to it (searched "squarefree number is:q") \$\endgroup\$ – ChartZ Belatedly Jan 21 at 9:07
0
\$\begingroup\$

Cosmic ray hacking

Cosmic background radiation can cause random bit flips in electronics. For this reason, some mission-critical computers undergo radiation hardening. Your task is to use your magic bit flip gun to hack in to a program and make it print something different.

Cops' challenge

  • Write a program or function that outputs a determinate, non-empty string of your choice (which you should specify).
  • Choose a different, determinate string of your choice (which you should specify).
  • Also specify a number n which is the number of bit flips the robbers should perform on your answer in order to get it to output the second string.

Rules

Robbers' challenge

Choose an uncracked cop submission written by another user. Find a program that differs by exactly n bit flips from the original cop's program, and outputs the string s (where n and s are specified by the cop). First valid crack for each cop answer wins.

Rules

  • Your program must be written in the same language and version as the cop's
  • Your program must use the same I/O method as the cop's, unless they specify otherwise
  • Flipping the same bit twice (which does nothing to the whole string) is allowed, but it takes up 2 of your available bit flips.

Example

Cops - Python 3, 8 bytes

Prints 5.

print(5)

Using 1 bit flip, change this program to print 4.

Robbers - Cracks example answer

print(4)

Because the ASCII digit 5 is 00110101, and 4 is 00110100 (the last bit has been flipped)


Meta

  • Should I change the scoring system?
  • This is related to , but I don't think it actually is. Is this right? Or maybe or would be better? (?)
  • refers to the limit that the cop imposes on the robber, rather than the scoring system - is this an acceptable use of the tag?
  • Is this clear enough?
  • Is this a duplicate of an existing challenge?
  • Any other feedback?
\$\endgroup\$
2
  • \$\begingroup\$ How are cops' answers scored? \$\endgroup\$ – the default. Jan 21 at 14:11
  • \$\begingroup\$ @thedefault. code-golf; it's in the cops' rules section \$\endgroup\$ – pxeger Jan 21 at 14:45
0
\$\begingroup\$

Write a Brainfuck compiler + decompiler!

Many Brainfuck compilers will convert to a different language instead of compiling directly.

Your job is to write not only a compiler in language X which compiles Brainfuck to the same language as the compiler, but also a decompiler which takes code compiled with said compiler and outputs equivalent Brainfuck.

Rules

  • No embedding the original/stripped source code or similar loopholes. You know what I mean.
    • Additionally, no outputting an interpreter with the original source code.
  • The compiler must accept whitespace and comments
  • Optimizations are allowed and encouraged, as long as you can convert these back to Brainfuck.
  • The input will always be a valid Brainfuck program
  • You are not required to print comments in the decompiler, however, excess comments and whitespace are allowed in the output as long as the program is valid. However, these lower your score. 🙂
  • You do not need to handle excess whitespace or comments in the decompiler, you can assume it was code directly generated by your compiler.
    • Therefore, it is also guaranteed to be valid code.
  • No executing the compiled code.
  • The compiler must generate correct code and run without any helpers.
    • You are allowed to be flexible with the cell size as long as it is at least 8 bits.
    • You are allowed to be flexible with the tape size as long as it is at least 30,000 elements. A wrapping tape is not required.
    • EOF can store either 0, -1, or leave unchanged

Your score will be the following:

(compiler size in bytes + decompiler size in bytes) × (compiled size of factor.bf in bytes ÷ size of factor.bf in bytes)

This is , so the most votes wins. This is because there can be some creative and boring solutions. Golfing is still encouraged.

\$\endgroup\$
15
  • \$\begingroup\$ Couldn't there be multiple BF programs that compile to the same "byte code" due to optimisations? \$\endgroup\$ – Adám Jan 20 at 14:38
  • \$\begingroup\$ Good catch. I added a note about that. I emphasized that you are decompiling YOUR code, and optimizations are not required, and if you do add optimizations, they must decompile to the same code (so basically, don't optimize if you want to win 😏) \$\endgroup\$ – EasyasPi Jan 20 at 14:41
  • 1
    \$\begingroup\$ Am I allowed to add hints in my code that identify what the original BF was? \$\endgroup\$ – Adám Jan 20 at 15:13
  • \$\begingroup\$ Hmm..yeah that is kind of difficult to rule out. I am going to change it to include the size of the code output in the score to discourage it. \$\endgroup\$ – EasyasPi Jan 20 at 15:18
  • \$\begingroup\$ So is the total score the size of the compiler plus the size of the decompiler? Can they be a single program doing both? \$\endgroup\$ – Adám Jan 20 at 15:21
  • \$\begingroup\$ Any restrictions on what target languages are allowed? \$\endgroup\$ – Adám Jan 20 at 15:22
  • 1
    \$\begingroup\$ So am I understanding it right that the compiler and the target language must be identical? \$\endgroup\$ – Adám Jan 20 at 15:22
  • 1
    \$\begingroup\$ Can the decompiler be a macro? Also, I know it's not recommended often, but this wouldn't be too bad as a popularity challenge. \$\endgroup\$ – user Jan 20 at 16:22
  • 1
    \$\begingroup\$ Should the cells be wrapping or not? \$\endgroup\$ – Aiden4 Jan 20 at 16:28
  • \$\begingroup\$ I don't think it's possible to support comments without embedding them into the code. \$\endgroup\$ – the default. Jan 21 at 4:31
  • \$\begingroup\$ I mean that your compiler must accept comments, but it is not required to preserve them. I also made some of the changes suggested in the comments \$\endgroup\$ – EasyasPi Jan 21 at 12:39
  • \$\begingroup\$ Can we have EOF as no change? That's a somewhat common way of handling EOF \$\endgroup\$ – Jo King Jan 23 at 5:03
  • \$\begingroup\$ Note that if it's too hard then it won't be popular anyway. (writing an optimizing compiler alone is a very difficult task, and who would read that?) \$\endgroup\$ – user202729 Jan 28 at 9:30
  • \$\begingroup\$ Still not quite understand about what "embedding" means here. The program translated / synthesized is required to include what the source code do. So it will always embedding the source code by some how. Is it valid if I simply replace +-<>[],. by 01234567 and then convert it back? May I simply submit a brainf**k (or bf variance) program say ,[.,]? \$\endgroup\$ – tsh Feb 5 at 2:32
  • \$\begingroup\$ Yeah I should try to clarify that. \$\endgroup\$ – EasyasPi Feb 5 at 2:36
0
\$\begingroup\$

Introduction

This challenge was originally the "Among Us" challenge in the "Misc" category of YASCON CTF 2020. (The link includes an answer to that challenge. Click at your own risk.)

You're given a lot of files, only 1 of which is different from every other files. Your job is to find that 1 different file.

Challenge

  • Input: the file names of all the files to be searched through.
  • Output: the name of the 1 different file.

Avoid burying the important details of your challenge in a mound of unimportant details. Be concise. Include what needs to be included.

It is guaranteed to have $n+1$ files, of which $n \ge 2$ files are the exact same, and 1 different file.

This is a . Least bytes wins.

Example Input and Output

Input:

1.txt 2.jpg 3.png 4.mp3

Output:

(3.png is different)

3.png

\$\endgroup\$
3
  • \$\begingroup\$ 'Answer the following questions for your readers . . . Avoid burying the important details of your challenge in a mound of unimportant details. Be concise. Include what needs to be included.' This is what you are supposed to do as the challenge writer, not part of the spec. \$\endgroup\$ – Dingus Jan 26 at 22:30
  • 1
    \$\begingroup\$ Do you have permission to repost this challenge here? \$\endgroup\$ – Dingus Jan 26 at 22:30
  • \$\begingroup\$ Well I got permission to upload the challenge and its files anywhere from that CTF, so yes. \$\endgroup\$ – John Zhau Jan 27 at 3:10
0
\$\begingroup\$

Create a playable, unbeatable Tic Tac Toe game

The challenge is to write the smallest possible Tic Tac Toe game where the opponent is an unbeatable AI. The requirements are as follows:

  • The opponent should be an unbeatable AI (self-playing opponent that can't lose)
  • The game should be able to detect win/draw/loss and end if this happens (without crashing)
  • The input should be the player move (square index or something like that)
  • The game should be able to handle invalid input and act appropriate if this happens (ask for input again)
  • The game must be displayed graphically on a classic 3x3 format with X:s, O:s and empty squares. The display should be in line vertically and horizontally, se below examples. The display needs to happen after at least every human move to be able to follow the progress.

As long as these conditions are fulfilled you are free to solve it in any way you'd like.

Rules of Tic Tac Toe: Each player (X and O) takes turn placing their marker on the 3x3 board. The game ends in a win if the player gets 3 in a row, loss if opponent gets 3 in a row, and draws if the board gets full.

Challenge winning criterion: Smallest code in bytes.

Example view of a valid input/output gameplay:

[' ', ' ', ' ']
[' ', ' ', ' ']
[' ', ' ', ' ']

Your move: 3
[' ', ' ', 'X']
[' ', ' ', ' ']
[' ', ' ', ' ']

[' ', ' ', 'X']
[' ', 'O', ' ']
[' ', ' ', ' ']

Your move: 6
[' ', ' ', 'X']
[' ', 'O', 'X']
[' ', ' ', ' ']

[' ', ' ', 'X']
[' ', 'O', 'X']
[' ', ' ', 'O']

Your move: 8
[' ', ' ', 'X']
[' ', 'O', 'X']
[' ', 'X', 'O']

['O', ' ', 'X']
[' ', 'O', 'X']
[' ', 'X', 'O']

Example of invalid gameplay (not horizontally or vertically in line and not using X and O as markers, which makes it hard to see what is going on):

Your move: 4
[, , ]
[0, , ]
[, , ]

[1, , ]
[0, , ]
[, , ]

Your move: 9
[1, , ]
[0, , ]
[, , 0]

Suggested tags: tic-tac-toe, code-golf

\$\endgroup\$
12
  • \$\begingroup\$ Good draft. Now you're well on the way to a properly specified challenge. Thank you for using the sandbox! \$\endgroup\$ – Adám Feb 2 at 7:45
  • \$\begingroup\$ I assume that by "graphically" you include e.g. text-based in a console. You might want to make that clear. \$\endgroup\$ – Adám Feb 2 at 7:45
  • \$\begingroup\$ Who makes the first move? \$\endgroup\$ – Adám Feb 2 at 7:46
  • \$\begingroup\$ Thanks, updated. I don't udnerstand what you mean with the text based comment though. I feel like this thing is getting worse than writing for some government, really killing the joy to be honest. \$\endgroup\$ – eligolf Feb 2 at 7:53
  • 2
    \$\begingroup\$ It is stricter than government writings; the latter can be vague and instead rely on the courts to disambiguate later. We don't have that luxury here. But while painful for the challenge writer, it is exactly what makes it enjoyable for the challenge answerer. I highly recommend that you answer a few existing challenges before attempting the, frankly monumental, task of writing your own. This will give you an appreciation for well-specified challenges. I've been here for years, and have an order of magnitude more answers than challenges, and yes, my early challenges were problematic too. \$\endgroup\$ – Adám Feb 2 at 8:00
  • \$\begingroup\$ Updated with tags and winning criterion \$\endgroup\$ – eligolf Feb 2 at 8:05
  • \$\begingroup\$ Suggested tags (remember that the max is 5): interactive, game, board-game, grid, ai-player. \$\endgroup\$ – Adám Feb 2 at 8:09
  • 2
    \$\begingroup\$ I'd suggest paring down this challenge to what I think is the most interesting part, making the unbeatable AI. That is, just require writing a function/program that takes in a single game state and outputs an optimal move, without needing to handle the game flow. \$\endgroup\$ – xnor Feb 2 at 20:28
  • \$\begingroup\$ @xnor, that could also be an idea! \$\endgroup\$ – eligolf Feb 3 at 5:00
  • \$\begingroup\$ @Adám, could I try that or xnors idea in the real questions thread now? \$\endgroup\$ – eligolf Feb 3 at 5:40
  • 1
    \$\begingroup\$ @eligolf I like xnor's idea, as game flow as already been done before, e.g. here. However, I generally recommend allowing at least a week in the sandbox (wait for a couple of upvotes here) since some people visit the site on a weekly schedule (e.g. only on weekends, or only during work). It's code golf ― what's the rush? If, after a week, you've not gotten enough feedback here, consider asking for more feedback in the chat room. \$\endgroup\$ – Adám Feb 3 at 6:57
  • \$\begingroup\$ I found a similar challenge: codegolf.stackexchange.com/q/152064/20260 \$\endgroup\$ – xnor Feb 3 at 7:26
0
\$\begingroup\$

Ratios to Ben Johnston's Notation

Given a just intonation ratio, express it as a note name in Ben Johnston's notation relative to C.

You can take your input as a rational number (if your language has a rational type) or as a pair of integers. You have to handle ratios with a prime limit of 19, or in other words, ratios whose prime factorizations don't contain any primes above 19.

Use the following characters for the accidentals:

+ - 81/80
# b 25/24
7 L 35/36
^ v 33/32
13 _13 65/64
17 _17 51/50
19 _19 95/96

Output them in the following order:

  • 7, ^, 13, 17, 19
  • #, b
  • L, v, _13, _17, _19
  • +, -

7, 13, 17, and 19 should be separated by commas when they occur adjacently in order to avoid ambiguity.

Test cases:

1/1 -> C
2/1 -> C
3/2 -> G
4/3 -> F
5/4 -> E
5/3 -> A
6/5 -> Eb
7/4 -> B7b
7/5 -> G7b
9/5 -> Bb
9/8 -> D
10/9 -> D-
11/8 -> F^
16/9 -> Bb+
17/16 -> C17#
21/16 -> F7+
25/24 -> C#
32/27 -> Eb-
34/19 -> A17_19#
78/77 -> C13Lv
81/64 -> E+
160/147 -> C#LL-
323/280 -> D17,19L-
416/405 -> D13bb-
441/440 -> Db7v+
1029/1024 -> Db777+
6144/6125 -> CbLL-
531441/524288 -> B#+++
4194304/4117715 -> A#LLLLLLL---
\$\endgroup\$
1
  • \$\begingroup\$ Same issue as the other challenge, I didn't read the link and the question is not self-contained. \$\endgroup\$ – user202729 Feb 8 at 2:42
0
\$\begingroup\$

Find all enharmonic equivalences of an arbitrary EDO

Given integers n and s, print all pairs of enharmonically equivalent pitch classes in n-EDO, such that each note of a pair has at most s sharps and flats.

Note names are assigned such that F, C, G, D, A, E, and B form a chain of n-EDO's best approximation to 3/2 (that is, \$n \log_2(3/2)\$ steps, rounded to the nearest integer, or the "fifth"). "#" adds seven fifths, and "b" subtracts seven fifths; you can have as many of one as you want or none at all. (Note that in some EDOs, such as 24, there are some pitches that can't be written with only sharp and flat accidentals.)

Note that C# = Db means the same thing as Db = C#. Your code should output only one of these, but which one you output is up to you.

Be prepared to handle these situations:

  • # and b might not raise or lower the pitch
  • # might lower the pitch
  • E and F might be the same note
  • F might be lower than E

Your code should work for at least all integers n in [1, 200] and all integers s in [0, 50].

Test output

(12, 1)

F# = Gb
Fb = E
F = E#
C# = Db
Cb = B
C = B#
G# = Ab
D# = Eb
A# = Bb

(19, 1)

Fb = E#
Cb = B#

(19, 2)

F# = Gbb
F## = Gb
Fbb = E
Fb = E#
F = E##
C# = Dbb
C## = Db
Cbb = B
Cb = B#
C = B##
G# = Abb
G## = Ab
D# = Ebb
D## = Eb
A# = Bbb
A## = Bb

(22, 2)

Fbb = C#
Fb = C##
F## = Bbb
Cbb = G#
Cb = G##
Gbb = D#
Gb = D##
Dbb = A#
Db = A##
Abb = E#
Ab = E##
Ebb = B#
Eb = B##

(31, 3)

Fbbb = D#
Fbb = D##
Fb = D###
F## = Abbb
F### = Abb
Cbbb = A#
Cbb = A##
Cb = A###
C## = Ebbb
C### = Ebb
Gbbb = E#
Gbb = E##
Gb = E###
G## = Bbbb
G### = Bbb
Dbbb = B#
Dbb = B##
Db = B###

(32, 3)

F## = Dbbb
F### = Dbb
Fbbb = A#
Fbb = A##
Fb = A###
C## = Abbb
C### = Abb
Cbbb = E#
Cbb = E##
Cb = E###
G## = Ebbb
G### = Ebb
Gbbb = B#
Gbb = B##
Gb = B###
D## = Bbbb
D### = Bbb

(53, 4)

F#### = Dbbbb
Fbbbb = A###
Fbbb = A####
C#### = Abbbb
Cbbbb = E###
Cbbb = E####
G#### = Ebbbb
Gbbbb = B###
Gbbb = B####
D#### = Bbbbb

(5, 0)

F = E
C = B

(7, 1)

Fb = F
Fb = F#
F = F#
Cb = C
Cb = C#
C = C#
Gb = G
Gb = G#
G = G#
Db = D
Db = D#
D = D#
Ab = A
Ab = A#
A = A#
Eb = E
Eb = E#
E = E#
Bb = B
Bb = B#
B = B#

(9, 1)

Fb = G
F = G#
Fb = A#
F# = Eb
Cb = D
C = D#
Cb = E#
C# = Bb
Gb = A
G = A#
Gb = B#
Db = E
D = E#
Ab = B
A = B#

(11, 1)

F# = Db
Fb = A
F = A#
C# = Ab
Cb = E
C = E#
G# = Eb
Gb = B
G = B#
D# = Bb

(13, 1)

F# = Cb
Fb = B
F = B#
C# = Gb
G# = Db
D# = Ab
A# = Eb
E# = Bb
\$\endgroup\$
3
  • \$\begingroup\$ I think most people prefer that questions should not include background knowledge that not most people know without explanation. \$\endgroup\$ – user202729 Feb 3 at 0:58
  • \$\begingroup\$ Do you have any ideas about reducing the amount of background knowledge required and making the question more accessible? \$\endgroup\$ – bb94 Feb 3 at 1:49
  • \$\begingroup\$ I didn't read it... \$\endgroup\$ – user202729 Feb 3 at 1:51
1
91 92
93
94 95
105

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .