541
\$\begingroup\$

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

Sandbox FAQ

Posting

To post to the sandbox, scroll to the bottom of this page 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, though you can optionally add a title at the top. 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, and replace the post here with a link to the challenge and delete the sandbox post.

Discussion

The purpose of the sandbox is to give and receive feedback on posts. If you want to, feel free to give feedback to any posts you see here. Important things to comment about can include:

  • Parts of the challenge you found unclear
  • Comments addressing specific points mentioned in the proposal
  • Problems that could make the challenge uninteresting or unfit for the site

You don't need any qualifications to review sandbox posts. The target audience of most of these challenges is code golfers like you, so anything you find unclear will probably be unclear to others.

If you think one of your posts needs more feedback, but it's been ignored, you can ask for feedback in The Nineteenth Byte. It's not only allowed, but highly recommended!

It is recommended to leave your posts in the sandbox for at least several days, and until it receives upvotes and any feedback has been addressed.

Other

Search the sandbox / Browse your pending proposals

The sandbox works best if you sort posts by active.

To add an inline tag to a proposal use shortcut link syntax with a prefix: [tag:king-of-the-hill]. To search for posts with a certain tag, include the name in quotes: "king-of-the-hill".

Get the Sandbox Viewer to view the sandbox more easily!

\$\endgroup\$
0

3616 Answers 3616

1
62 63
64
65 66
121
1
\$\begingroup\$

Fully matched numbers

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

Convert superscript numbers to normal numbers

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Maybe specify exactly what characters will be included in the input? \$\endgroup\$
    – emanresu A
    Dec 11 '21 at 22:02
  • \$\begingroup\$ @emanresuA Done \$\endgroup\$ Dec 12 '21 at 0:05
1
\$\begingroup\$

Posted here

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

Rotate two differently cased subwords independently

You have one string made of two subwords in different cases, the upper case first, then the lowercase:

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz

And you must return each subword cycled by a given increment. (N.b. the letters aren't rotated through the alphabet, but each character is shifted in the word)

The subwords are not always the same length as each other, and are part of the same 'data' structure. If your language cannot store strings, you're permitted to store the 'string' in a single array, e.g. ['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', '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']

Here are the test cases:

Input Output
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", 13 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm'
"ABCDEFGHIJKLMNOPQRSTUVWXYZnopqrstuvwxyzabcdefghijklm", 13 'NOPQRSTUVWXYZABCDEFGHIJKLMabcdefghijklmnopqrstuvwxyz'
"ABCDEFGHIJKLMNOPQRSTUVWXYZnopqrstuvwxyz", 26 'ABCDEFGHIJKLMNOPQRSTUVWXYZopqrstuvwxyzn'
"ABCDEFGHIJKLMNOPQRSTUVWXYZnopqrstuvwxyz", 13 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyz'
"ABCnopqrstuvwxyz", 2 'BCAyznopqrstuvwx'
"AAABBBcccddd", 2 "BBAAABddcccd"
"AAABBBcccddd", 6 "AAABBBcccddd"
"HELLOworld", 5 'LLOHErldwo'
"CODEgolf", 0 'CODEgolf'

Here is an ungolfed example program:

const subWordRotate = (original, rot) => [...original.split(/([A-Z]+)(?![A-Z][a-z]+)/)].map(list => [, ...list].reduce((memo, char, index, input) => {
  memo = memo.slice(0, input.length);
  memo.splice((index + rot) % (input.length), 1, char);
  return memo
}, Array(original.length).fill('')).join('')).join('')


const testCases = [
  ["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", 13],
  ["ABCDEFGHIJKLMNOPQRSTUVWXYZnopqrstuvwxyzabcdefghijklm", 13],
  ["ABCDEFGHIJKLMNOPQRSTUVWXYZnopqrstuvwxyz", 26],
  ["ABCDEFGHIJKLMNOPQRSTUVWXYZnopqrstuvwxyz", 13],
  ["ABCnopqrstuvwxyz", 2],
  ["AAABBBcccddd", 2],
  ["AAABBBcccddd", 3],
  ["AAABBBcccddd", 4],
  ["AAABBBcccddd", 5],
  ["AAABBBcccddd", 6],
  ["AAABBBcccddd", 7],
  ["AAABBBcccddd", 8],
  ["AAABBBcccddd", 9],
  ["AAABBBcccddd", 10],
  ["HELLOworld", 69],
  ["CODEgolf", 0]
]
testCases.forEach(
    testCase => console.log(`original: ${testCase[0]}, rotated by ${testCase[1]}: ${subWordRotate(...testCase)}`)
  );


Sandbox note: I think there is a bug in my code, such that ["AAABBBcccddd", 6],["AAABBBcccddd", 7], return the same values. I think this is the same bug that is preventing me specifying how negative numbers work. Any help fixing the code would be much appreciated

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

The Most Wanted Prime Numbers

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

Can we patch the corona certificate validation code (part 1/3)?

The new chancellor of Germany, Mr. Olaf Scholz, is in deep trouble: the Covid app does not show the vaccination status correctly beginning with booster vaccinations. He was not involved in the development of the app, since that was under chancellor Angela Merkel. He is now hiring you, Secret Agent 0x007, in order to understand the problem and later apply a strategy to fix the problem.

In step 1, Mr. Scholz wants to understand how the app has worked correctly when booster vaccinations were not even thought of. Mr. Scholz is an important person, so he has no time to read lengthy source code. Your code has to be .

These are the rules of valid vaccinations:

  • There are 4 vaccination types in Germany: BioNTech (B), Moderna (M), Astra Zeneca (A) and Johnson&Johnson (J).
  • A person is considered vaccinated 14 days after the necessary amount of injections.
  • Biontech, Moderna and Astra Zeneca need 2 injections, Johnson needs 1 injection only.
  • If 2 injections are needed, the second injection may occur earliest 28 days after the first injection.
  • If 2 injections are needed, the second injection may only be with the same vaccination type.
  • You get an entry in your vaccination pass which has the date in the format YYMMDD. COVID-19 is all post 2000, so we never need a 4 digit year.
  • A full entry is in the form YYMMDD X followed by a newline, where X is the vaccination type.

How the application works:

You get the input in a reasonable form, e.g.

  • from stdin, separated by newlines of your platform
  • an array of strings (like argv)
  • a function with variable number of arguments (like ...)

The first line/entry is today's date, which you check the validity against. This comes from a time server, so it's always valid. Each following line/entry is for one injection. There may be many of them, mainly limited by your platform (254 is certainly enough, also for part 2 and 3).

The application gives the following output:

  • injected after a successful injection with the 14 days period not over
  • vaccinated 14 days after the necessary amount of injections
  • manipulated in case things do not match

manipulated takes precedence over vaccinated over injected. The output may contain arbitrary leading or trailing whitespace. A newline is not needed (it will be displayed in a mobile phone app textbox anyway).

The output can be

  • on stdout
  • the return value of the function

As there are quite some anti-vaxxers, the application checks for manipulations.

  • Totally invalid vaccination types (like Y)
  • Mix of vaccination types for the first and second injection
  • More injections than needed
  • Invalid date (like 200231 - there is no February 31st)
  • Date too early (earlier than 200101, the beginning of the pandemic)
  • Injection date later than today
  • Injections in wrong order (second date before first date)

You don't need to consider:

  • dates other than 6 digits
  • characters in the date other than 0-9
  • other character than space as the separator
  • more than 1 character as vaccination type

Test cases:

<any date>
200231 X
= manipulated (invalid vaccination type)

<any date>
210301 B
210329 A
= manipulated (different vaccination types)

<any date>
210301 B
210329 B
210426 B
= manipulated (too many injections)

210814
210301 J
210814 J
= manipulated (too many injections)

<any date>
200231 B 
= manipulated (invalid date February 31st)

<any date>
191231 B 
= manipulated (date earlier than the pandemic)

210301
210302 J
= manipulated (date of the injection is tomorrow)
 
210301
210301 J
= injected (14 days not over)

210315
210301 J
= vaccinated (14 days over, only 1 injection needed)

210315
210301 B
= injected (14 days over, but 2 injections needed)

<any date>
210301 B
210302 B
= manipulated (28 days between 2 injections required)

210331
210301 B
210329 B
= injected (28 days between 2 injections, but not 14 days after the last one)

210412
210301 B
210329 B
= vaccinated (28 days between 2 injections, 14 days after the last one)

210412
210329 B
210301 B
= manipulated (injections in wrong order)

About realism: while this challenge has a realistic background, not all vaccination of rules in Germany are considered. Do not claim that your program can calculate the validity of a COVID-19 vaccination certificate.

Coming up:

  • part 2, in which you need to consider booster vaccinations the wrong way
  • part 3, in which you check whether you can patch the wrong code of part 2 to make it work correctly

I would appreciate if you participate in all 3 parts.

\$\endgroup\$
5
  • \$\begingroup\$ Regarding the process: I will start writing part 2 when I have received feedback on part 1. I will start writing part 3 when I received feedback on part 2. I want to release part 1 not before all 3 parts were reviewed. Would that be fine? \$\endgroup\$ Dec 18 '21 at 21:06
  • \$\begingroup\$ Interesting question, and I like it. The only thing that really sticks out to me is the input format, you should probably clarify before anybody asks - can you take input as an array/list of strings, rather than a newline delimited string? i.e. ["a", "b"] instead of "a\nb". It really doesn't matter much which you pick but since newline delimited strings would take more bytes for most langs, it's probably going to get asked immediately. \$\endgroup\$
    – Riker
    Dec 18 '21 at 21:24
  • \$\begingroup\$ @Riker: thank you for the feedback. Yes, if that's a common thing to have for input, that's totally fine. Is there an example for a formulation considering all the common inputs? \$\endgroup\$ Dec 18 '21 at 21:26
  • 1
    \$\begingroup\$ I'm unsure if it counts as common, but yeah - it's just that indexing an array is probably shorter than calling .split("\n") for many languages, lol. Regarding posting 3 challenges, I think it's worthwhile to sandbox all 3 before posting any of course, but then posting maybe each one on sunday or something for 3 weeks would be fun. Somebody in chat compared it to a mini advent of code (golf) :) \$\endgroup\$
    – Riker
    Dec 18 '21 at 21:29
  • \$\begingroup\$ I implemented this challenge (non-golfed) and all test cases work. I'll start working on the next one now. \$\endgroup\$ Dec 27 '21 at 15:22
1
\$\begingroup\$

Fuzzy friends

Introduction

Congratulations! You've been selected to do research a a newly discovered animal called a fuzzy, a docile, simple creature that strongly resembles a cotton ball. Fuzzies love to be near other fuzzies, but not all fuzzies want to be near each other.

There are 6 types of fuzzies, 1a, 1b, 2a, 2b, 3a, and 3b. Each obeys different rules.

  • Type 1a fuzzies want to be near any type b fuzzy. (vice versa for 1b)

  • Type 3a fuzzies want to be near any type a fuzzy. (vice versa for 3b)

  • Finally, type 2 fuzzies want to be near any fuzzy type, a or b.

  • Perfect pairings are matches in which both fuzzies want to be near each other (ex. 1a and 1b)

  • Semiperfect pairings are matches in which only one fuzzy wants to be near the other (ex 3a and 1b)

  • Imperfect pairings are matches in which neither fuzzy wants to be with the other (ex. 3a and 3b)

Your Challenge

Given a list of fuzzies:

  1. Output the total number of perfect pairings. If there are any left:
  2. Output the number of semiperfect pairings. If there are any left:
  3. Output how many leftover bachelors there are.

Output and input format don't matter as long as you state them both.

Test cases

1a, 1b:
1a and 1b are a perfect match
> 1 perfect, 0 semiperfect, 0 bachelors
1a, 2b, 2a, 3b:
1a and 2b are a perfect match
2a and 3b are a semiperfect match
> 1 perfect, 1 semiperfect, 0 bachelors
1a, 1b, 2a, 3a, 3b, 3b:
1a and 1b are a perfect match
2a and 3a are a perfect match
3b and 3b are an imperfect match
> 2 perfect, 0 semiperfect, 1 bachelor
1b, 2a, 3a
1b and 2a are a perfect match
3a is left over
(note: could also be:
2a and 3a are a perfect match
1b is left over
for the same result)
> 1 perfect, 0 semiperfect, 1 bachelor

Scoring

This is , so shortest in bytes wins.

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

Make a negative afterimage

We've all seen the strange, inverted-color images of the American Flag or similar that look correct after you stare at them for a minute and look at a white object. These are called negative afterimages.

Your Challenge

Given an image as input, your program should return that same image, recolored to create a negative afterimage. To do this, simply invert each color in the image. Your program may take either raw image data or a path to an image file as input, and either create a new image file or display the inverted image as output.

Scoring

This is code-golf, so shortest answer wins.

\$\endgroup\$
2
  • \$\begingroup\$ What does inverted-color mean? For example, if input color is pink, should I output darkred, darkgreen or lightgreen? \$\endgroup\$
    – tsh
    Dec 23 '21 at 8:23
  • \$\begingroup\$ How many colors should I support at least. Is a program only support black-white image acceptable? Or what about 16 color image? \$\endgroup\$
    – tsh
    Dec 23 '21 at 8:24
1
\$\begingroup\$

Loading Circle Animation

\$\endgroup\$
3
  • 1
    \$\begingroup\$ I think it would be simpler if a program was just required to output eight frames, then stop. The infinite looping is unnecessary. (I think it's fine how it is) \$\endgroup\$ Oct 28 '21 at 1:45
  • \$\begingroup\$ For example, someone submit a progrom like this: while True: print(".#\n#\n#..#\n.##);clearScreen();print(.##\n#\n#\n.##);clearScreen()... The program try to print a frame, and then clear the screen immediately. It in theory output each frame one by one. But user would be hard to distinguish each frames. Also, if you try to take a screenshot, most time you will got an empty screen (suppose clearScreen would be much slower than print). Is this still a valid answer? \$\endgroup\$
    – tsh
    Nov 4 '21 at 8:03
  • \$\begingroup\$ @tsh Yes, as long as the user can tell what the animation is. \$\endgroup\$
    – Yousername
    Nov 12 '21 at 22:59
1
\$\begingroup\$

Sides of a polygon

Given an ASCII-art shape made of the characters /\|_, your challenge is to return the number of sides it has.

A side is a straight line of one of those, for example:

\
 \
  \

 /
/

|
|
|
|

_____

Are all sides.

For example, this shape:

  ___
 /   \
/_____\

Has four sides. You can assume the input will be a single valid, closed shape - that is, things like this:

/
 _
/ \

 \
/

/_\
\_/
 _   _
/_\ /_\

Will not occur, and the shape will never touch itself, so this is invalid:

  /\/\
 / /\ \
/ /__\ \
|______|

Testcases:

 /\
/__\ -> 3

 ________
/        \
|_________\  -> 5

___
|_| -> 4

/\/\/\/\/\
|________| -> 13

 _   _
| |_| |
|  _  | -> 12
|_| |_|
          
         /\
        /  \
   /\  /    \    /\
  /  \/      \  /  \
 /            \/    \
/____________________\ -> 7

   _
  / |
 _| |
/___/ -> 8
\$\endgroup\$
5
  • \$\begingroup\$ Will the shape touch itself? Say, like this or this ? \$\endgroup\$
    – tsh
    Dec 27 '21 at 5:40
  • \$\begingroup\$ @tsh No,it won't. \$\endgroup\$
    – emanresu A
    Dec 27 '21 at 5:56
  • \$\begingroup\$ By your current examples, this is a valid shape although it looks very strange. \$\endgroup\$
    – tsh
    Dec 29 '21 at 7:15
  • \$\begingroup\$ @tsh Yeah, I’ll just leave that since allowing those shapes doesn’t car assist any problems or ambiguousities. \$\endgroup\$
    – emanresu A
    Dec 29 '21 at 8:18
  • \$\begingroup\$ I would like for the valid inputs to be more clearly defined. How many sides does @ths's "very strange" looking shape have? \$\endgroup\$ Jan 10 at 12:52
1
\$\begingroup\$

Shuffle a subsequence

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

Recursive Pi


Given an integer \$n\$ with \$0 \leq n \leq 9\$, return all the digit \$d's\$ as the program goes through this process:

  • Find the digit \$d\$ in the decimals of \$\pi\$ with the index \$n\$, \$0\$-indexed
  • Run the same process with \$n\$ being the digit \$d\$

After at least \$10\$ steps, the program will always get stuck in a loop. That is when the program should terminate and output all the \$d's\$ / stop outputting \$d's\$.

All Cases

$$ 0 \to [1, 4, 9, 5, 2] \\ 1 \to [4, 9, 5, 2, 1] \\ 2 \to [1, 4, 9, 5, 2] \\ 3 \to [5, 2, 1, 4, 9] \\ 4 \to [9, 5, 2, 1, 4] \\ 5 \to [2, 1, 4, 9, 5] \\ 6 \to [6, 6] \\ 7 \to [5, 2, 1, 4, 9, 5] \\ 8 \to [3, 5, 2, 1, 4, 9] \\ 9 \to [5, 2, 1, 4, 9] \\ $$

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

Is this word in standard order?

Let \$ A \$ represent the alphabet, such that \$ A_1 = \$ a and \$ A_{26} = \$ z.

Let's define that a word \$ W = w_1 w_2 ... w_n \$ (where \$ w_c \in A\$) is in standard order if and only if:

  • \$ w_1 = A_1 \$, and
  • for \$ 2 \le i \le n \$, if \$ w_i = A_x \$ then \$ w_j = A_{x-1} \$ for some \$ j < i \$.

In other words, the word must start with a and each other letter can only appear in a word if the preceding letter in the alphabet has already appeared.

For example, ac is not in standard order, because there is no b before the c.

The following relationships exist between the property of standard order and some others:

Task

Given a string of letters, determine if it is in standard order according to the Latin alphabet.

Test cases

Truthy:

a
aaa
abab
abacabadabacaba
abcdefghijklmnopqrstuvwxyz

Falsey:

b
ac
bac
abbdc
bcdefghijklmnopqrstuvwxyza
abracadabra

Rules

  • You should represent true and false outputs using any two distinct values of your choice
  • You may assume the input is non-empty and only contains lowercase ASCII letters
  • You may use any standard I/O method
  • Standard loopholes are forbidden
  • This is , so the shortest code in bytes wins

Meta

  • "standard order" doesn't seem to be a well-used term in the literature. I can find it only in a tightly-knit web of sources all referencing each other
  • Is this a duplicate? Because of the lack of nomenclature, my searches were ineffectual
  • Is this clear enough?
\$\endgroup\$
3
  • \$\begingroup\$ IMO this would be better as an array challenge with arrays of [1,2,3] etc. \$\endgroup\$
    – emanresu A
    Dec 31 '21 at 22:07
  • \$\begingroup\$ @emanresuA I considered that, but I thought using letters might create some interesting solutions using regular expressions and what-not. Do you think I should allow working over any set (e.g. the natural numbers), not just the alphabet? Or would that be too complex? \$\endgroup\$
    – pxeger
    Dec 31 '21 at 22:14
  • \$\begingroup\$ And "some \$x\$"? \$\endgroup\$ Jan 10 at 12:35
1
\$\begingroup\$

Pluralize a Noun List

Currently Closed

\$\endgroup\$
7
  • \$\begingroup\$ Can you change dropbox to github? \$\endgroup\$
    – Fmbalbuena
    Jan 3 at 3:17
  • \$\begingroup\$ I can see if I can do that. Got some other big changes this thing probably needs though. \$\endgroup\$
    – Romanp
    Jan 4 at 4:02
  • \$\begingroup\$ most users use Github \$\endgroup\$
    – Fmbalbuena
    Jan 4 at 4:03
  • \$\begingroup\$ Got it. I realized that my lists of words were not particularly accurate, so as soon as I get better ones, I will switch to Github. \$\endgroup\$
    – Romanp
    Jan 5 at 12:58
  • \$\begingroup\$ The link example fakehtpps://python.org can be [link](fakehtpps://python.org) \$\endgroup\$
    – Fmbalbuena
    Jan 5 at 15:03
  • \$\begingroup\$ test-battery would be a good tag for this, I think \$\endgroup\$
    – user
    Jan 12 at 1:45
  • \$\begingroup\$ Now that this is posted, could you edit it down to a stub and delete it? \$\endgroup\$ Jan 12 at 3:05
1
\$\begingroup\$

Short programs for fixed outputs

Inspired by Lynn's Jelly puzzles. Check them out if you're interested in practicing your Jelly skills

Cops

The cops should choose three things:

  • A freely available programming language,
  • a byte count \$B\$, and
  • a number of programs to write, \$n\$ (minimum 5)

They should then write \$n\$ programs, each of which:

  • is exactly \$B\$ bytes long, and

  • outputs a fixed, non-empty, non-whitespace output. That is, the output should contain at least one non-whitespace character. "Fixed" can mean that either:

    • it outputs the same thing no matter what input is provided, or
    • that it always outputs the same thing and takes no input.

    You may choose which of these meanings to take, but it must be the same for all \$n\$ programs. Please mention which of these options your programs use.

The cops should then reveal the following bits of information:

  • The programming language used,
  • the byte count \$B\$,
  • any command line flags used for specific outputs,
  • the \$n\$ outputs for each of the \$n\$ programs. If the outputs use any non-printable ASCII characters, please include a hexdump of the output.

The Robbers will be attempting to find \$B\$ byte long programs that output the same outputs, so you should keep your programs secret.

For example, if you choose to write 7 programs in Python, each of them 10 bytes, that output

4, True, 2 3 , 1, 72, ! and [0]

then you may have these 7 programs (one per line).

Robbers will crack one of your \$n\$ outputs if they can find any \$B\$ byte program in your language that has the same output. Note that the program does not have to be the same as the cop's program.

Any outputs that go a week without being cracked can be marked safe, and the programs for each output should be revealed. Until the program is revealed for a specific output, it can still be cracked.

You may post multiple answers, but each answer should be independent from all others. Your score is equal to the total number of safe outputs across all your answers. The user with the highest score wins.

Robbers

You should find a Cops answer with at least one uncracked, unsafe output, and attempt to crack any of the outputs. That is, find a program that is exactly \$B\$ bytes long that outputs the same fixed output. Note that your program does not have to be the same as the Cop's original answer, just that the output has to be equal.

If you crack an answer, please do the following:

  • Leave a comment on the Cop's answer, linking to either your answer or a TIO (or similar) link demonstrating the crack
  • If this is your first crack, post an answer to the Robbers thread with your crack, linking to the relevant Cop answer
  • For further cracks, edit them in to your existing answer, linking to the relevant Cop answer

A Robber's score is equal to the total number of cracks they make. The Robber with the highest score wins.


Meta

\$\endgroup\$
1
  • \$\begingroup\$ Other than the original inspiration, is there any reason to have multiple tasks in one cop submission? Since they're not related to each other and each one can be cracked individually, it seems like they should each be separate answers. \$\endgroup\$
    – DLosc
    2 days ago
1
\$\begingroup\$

Number of arrangements of half a Rubik's cube

From a corner-on view of a Rubik's cube calculate the number of arrangements of stickers that are out of view.

Your input will provide the state of a Rubik's cube when viewed like the below image:

enter image description here

This input will be an array, in any defined order†, grouping†, and nesting† that you choose, containing the colours‡ of the \$27\$stickers (A.K.A. facelets or tiles) on three sides of a 3x3 Rubik's cube that join at one corner, like you can see above.

The input may be assumed to be that of a solvable state where only face turns can return the cube to having six sides with a single colour on each (if it isn't then your code may do anything, short of summoning Cthulhu).

† The input may be a flat list of colour-labels or you may specify that these labels will already be grouped in any way you wish (it may be a ragged, nested list for example), but the content thereof should only consist of the sticker colour-labels.

‡ Since the centres of the cube are actually fixed relative to each other, and hence the hidden centres' colours are known, you may choose to leave any or all of the central stickers out of the expected input (it could be as short as \$24\$ sticker colour-labels) while using a labeling that identifes the colours as the top-centre, left-centre, right-centre, and their three opposite colours. For the record, the standard colour theme, as in the image above, has orange opposite red, white opposite yellow, and green opposite blue (hence orange is the hidden centre sticker on the bottom etc.).

You should output the number of possible arrangements of sticker colours of the \$27\$ stickers which are not in the input (i.e. those stickers which are out of view). Note that swapping two of those stickers of the same colour is considered to be the same arrangement.


Sandbox questions

  1. Does this need test cases? (I'm not even 100% sure what the output should be if the input looked like a solved cube from that perspective although I may be able to work it out without writing a program it's certainly more than one - e.g. U' L R2 D' M D2 M' D' L' R2 U or R2 U R2 F2 R2 U2 F2 R2 F2 U R2)

  2. Is the spec clear?

\$\endgroup\$
1
  • \$\begingroup\$ You should probably make it more explicit that the center colors of the opposite faces are known. (Also, I'm fairly sure that a "solved cube" input would have an output of 192, but that's just me doing quick math in my head, so I could be wrong.) \$\endgroup\$
    – Nitrodon
    Jan 14 at 15:18
1
\$\begingroup\$

Implement an argwhere function

The \$argwhere\$ function takes a list of values and a predicate/boolean function as arguments and returns a list of indices where the predicate function returns true in the input list. For example,

argwhere([1, 2, 3, -5, 5], x -> x > 2)

would produce an output of [2, 4] because those are the (0-indexed) indices whose values are greater than two.

Challenge

Implement the \$argwhere\$ function in your language of choice.

Format

For the purposes of this challenge, we will deal with lists of integers. You must accept a list of integers and a black box function and return a list of integers in any reasonable format. You may assume the input list will never be empty. Your output may be either 0-indexed or 1-indexed — please specify which.

Rules

  • Builtins are allowed, but please consider adding a less trivial answer so we can see how \$argwhere\$ might be implemented in your language.
  • Explaining your answer(s) is encouraged!
  • Standard loopholes are forbidden.
  • This is , so the code with the fewest bytes (in each language) wins.

Why argwhere?

argfoo is a naming convention where you don't want the elements themselves — you want their indices or some other quality. \$argmax\$, \$argmin\$, and \$argsort\$ are examples of this. Read more about it here. (Also, because my favorite programming language comes with this function and it's called arg-where. 🤫)

Test cases

0-indexed

Input Output
[1, 2, 0, 0, 3, 0, 0, 0, 4], x -> x == 0
[4, 3, 5, 7, 11, 13, 17], x -> x % 2 == 0
[8, 9, 10, 11, 12, 13], x -> x + 10 > 20
[5, -5, 2, -2, 0], x -> x < 0
[5, 2, 0], x -> x < 0
[2, 3, 5, 6, 7]
[0]
[3, 4, 5]
[1, 3]
[]

1-indexed

Input Output
[1, 2, 0, 0, 3, 0, 0, 0, 4], x -> x == 0
[4, 3, 5, 7, 11, 13, 17], x -> x % 2 == 0
[8, 9, 10, 11, 12, 13], x -> x + 10 > 20
[5, -5, 2, -2, 0], x -> x < 0
[5, 2, 0], x -> x < 0
[3, 4, 6, 7, 8]
[1]
[4, 5, 6]
[2, 4]
[]
\$\endgroup\$
2
  • \$\begingroup\$ Interesting. I'm guessing "no", but are langs without function definition allowed to participate? \$\endgroup\$ 2 days ago
  • \$\begingroup\$ @thejonymyster I'm not too interested in making restrictions. If your language can accept code as input and run it to make decisions, I'd say that's good enough. But as with all functional-programming questions, some languages will inevitably be excluded. \$\endgroup\$
    – chunes
    2 days ago
1
\$\begingroup\$

Highlight a Wordle guess

In Wordle, you try to guess a secret word, and some letters in your guess are highlighted to give you hints.

If you guess a letter which matches the letter in the same position in the secret word, the letter will be highlighted green. For example, if the secret word is LEMON and you guess BEACH, then the E will be highlighted green.

If you guess a letter If you guess a letter which is present in the secret word, but not in the correct corresponding position, it will be highlighted yellow.

If a letter appears more times in the guess than it does in the secret word, only upto as many occur in the secret may be highlighted. If any of the occurrences are in the same place, they should be preferentially highlighted green, leaving earlier letters unhighlighted if necessary.

For example, with the secret LEMON and the guess SCOOP, the second O will be green, because it is in the right place, but the first O will be unhighlighted, because there is only one O in the secret, and one O has already been highlighted.

Any of the remaining letters in the secret may be highlighted yellow if they match, as long as the right number are highlighted in total. For example, with the secret LEMON and the guess GOOSE, only one of the Os should be highlighted; it does not matter which.

Task

Given two five-letter strings, a secret and a guess, highlight the letters in the guess according to the rules above.

You can "highlight" the letters using any reasonable output format. For example:

  • a length-5 list of highlight values
  • a list of 5 pairs of (letter, highlight value)
  • a mapping from indices 0-4 or 1-5 to the highlight at that position

You can choose any three distinct values to represent unhighlighted, yellow, and green. (For example, 0/1/-1, or ""/"Y"/"G"...)

If in doubt about the "reasonable"ness of your output format, please ask. It must be unambiguous about the ordering of highlighting in case of double letters.

Rules

  • You may assume the inputs are both of length 5 and contain only ASCII letters
  • You may choose whether to accept input in uppercase or lowercase
  • You may use any standard I/O method
  • Standard loopholes are forbidden
  • This is , so the shortest code in bytes wins

Test cases \$ \require{color} \newcommand{\qG}[1]{\colorbox{##0f0}{$ \mathtt #1 $}} \newcommand{\qY}[1]{\colorbox{##ff0}{$ \mathtt #1 $}} \newcommand{\qW}[1]{\colorbox{ ##eee}{$ \mathtt #1 $}} \$

All using the secret word HELLO:

  • SCRAP -> \$ \qW S \qW C \qW R \qW A \qW P \$
  • HELLO -> \$ \qG H \qG E \qG L \qG L \qG O \$
  • EPOCH -> \$ \qY E \qW P \qY O \qW C \qY H \$
  • CIVIL -> \$ \qW C \qW I \qW V \qW I \qY L \$
  • BELCH -> \$ \qW B \qG E \qG L \qW C \qY H \$
  • ZOOMS -> \$ \qW Z \qY O \qW O \qW M \qW S \$ or \$ \qW Z \qW O \qY O \qW M \qW S \$
  • EERIE -> \$ \qW E \qG E \qW R \qW I \qW E \$
  • LILAC -> \$ \qY L \qW I \qG L \qW A \qW C \$
  • LLLLL -> \$ \qW L \qW L \qG L \qG L \qW L \$

Copy and paste friendly format


Meta

  • Is this clear enough?
  • Is this a duplicate?
  • Test-case suggestions?
  • Tag suggestions?
  • Any other feedback?
\$\endgroup\$
7
  • \$\begingroup\$ confused to be honest . maybeeee abit too hard? \$\endgroup\$
    – DialFrost
    6 hours ago
  • \$\begingroup\$ @DialFrost Can you be more specific? What part are you confused about? \$\endgroup\$
    – pxeger
    6 hours ago
  • \$\begingroup\$ er mostly about the highlighting value \$\endgroup\$
    – DialFrost
    6 hours ago
  • \$\begingroup\$ @DialFrost do you mean: 1) you don't understand when to highlight the letters in which colour; or 2) you don't understand how the output values used for highlighting can be chosen? Or something else? \$\endgroup\$
    – pxeger
    6 hours ago
  • \$\begingroup\$ both i dont understand \$\endgroup\$
    – DialFrost
    6 hours ago
  • \$\begingroup\$ @DialFrost without some more details on what you're missing, I can't help you to understand or clarify the description. What bits you do you understand? \$\endgroup\$
    – pxeger
    6 hours ago
  • \$\begingroup\$ pretty much none i just meant i dont understand the hilighting value and how it works the most \$\endgroup\$
    – DialFrost
    5 hours ago
1
\$\begingroup\$

Climb a ragged list


Your task is to represent a ragged list as ASCII art that looks like a mountain.
You are given a list of lists, either having other lists inside them or being empty.

Here is somewhat a description:

Looping through every list:
    If entering a list, print (current_depth - max_depth - 1) newlines with a "/"
    If exiting a list, print (current_depth - max_depth - 1) newlines with a "\"

The printing in the description is from left to right, top to bottom.
So [[[[]], [[]]]] would output (max depth = 3):

  /\  /\
 /  \/  \
/        \

Rules

Test Cases:

In: [] # empty list
Out: 

In: [[]]
Out:
/\

In: [[], [[]], [[[]]]]
Out:
        /\  
   /\  /  \
/\/  \/    \

In: [[[[]], []]]
Out:
  /\    
 /  \/\
/      \

In: [[], [[]], [[], []], [[[]], []]]
Out:
              /\    
   /\  /\/\  /  \/\
/\/  \/    \/      \

In: [[[[], []], [[]]], [[[]], [[], [[], [], []]]], [[[], [], []]]]
Out:
                     /\/\/\
  /\/\  /\    /\  /\/      \    /\/\/\
 /    \/  \  /  \/          \  /      \
/          \/                \/        \

Good Luck!

Example Python script with a different approach

\$\endgroup\$
1
  • \$\begingroup\$ Seems like a dupe of this treating the array as a string... \$\endgroup\$
    – emanresu A
    13 hours ago
1
\$\begingroup\$

Will the tower balance?

You are given as input a tower made of bars of unit height, and your task is to decide if the tower is stable. Here is an ascii art drawing of a tower:

 #
####
# ####
#####

For extra clarity here is the same tower but with the different bars in different characters:

 A
BBBB
C DDDD
EEEEE

The bars are rigid, but they are not connected to each other. Even though the bars are not connected, they stay still under the influence of gravity. Here however is a tower that is not stable:

      B
CCCCCCCC
   D
  EEE
FFFFFFFF

In this tower, under the influence of gravity, the top bar will fall to the right.

The following tower is metastable:

AA
B

The center of mass of the A-bar lies on top of the edge of the B-bar. In this kind of situation the tower is considered unstable, since even a small perturbation will cause it to fall eventually.

Input/output format

The input format is an ascii drawing of the tower like so:

 ###
  #
### #

In this picture there are 4 bars. It is guranteed that all bars are on top of another bar or on top of the ground and that every row has at least one bar. You can use a different printable ascii character instead of #. You can also take a 2d array instead of a string and use two distinct values for # and . In that case please use simple values, that don't encode extra information (standard loopholes prohibited).

Output two distinct values for STABLE and UNSTABLE.

Test cases

#

STABLE

###
 #
 ##
  #

UNSTABLE

  ###
 ###
###

UNSTABLE (metastable)

#
#     ######
####    ##
 #      ##

STABLE

###
 #
#####
 #

STABLE

 #
#####
 #

UNSTABLE

######  #
 #  #   #
### #####
 #   #
 #####
   #

STABLE

\$\endgroup\$
1
  • \$\begingroup\$ The rules do not actually specify what makes a tower stable. The stable test cases use balancing methods not stated anywhere, and the rules themselves just seem to be more examples. As a non physicist, "use gravity" isn't enough information IMO. This is a cool idea though and +1 once that's fixed \$\endgroup\$ 2 hours ago
1
\$\begingroup\$

Remove odd indices and double the even indices

Your task is simple, just remove the odd indices and double the even indices

Example

the input is Hello, World! and we get indices

H e l l o , _ W o r  l  d  !
1 2 3 4 5 6 7 8 9 10 11 12 13

and remove the even indices

el,Wrd

Double!

eell,,WWrrdd

and you are done

1-Indexing

Test cases

abcdef => bbddff
umbrella => mmrrllaa
looooooooong text => ooooooooooggttxx
abc => bb
xkcd => xxcc
Hello, World! => eell,,WWrrdd
D => DD
KK => KK
Hi => ii

The input can be list of integers if you want.

Meta

  • Any feedback?
\$\endgroup\$
3
  • 1
    \$\begingroup\$ The test cases are now consistent with the example explanation, but not with the "remove odd, double even" description. You could fix this by either changing this to "remove even, double odd", or switching to 0-indexing \$\endgroup\$
    – pxeger
    3 hours ago
  • \$\begingroup\$ @Adám sorry, test case fixed \$\endgroup\$
    – Fmbalbuena
    6 mins ago
  • \$\begingroup\$ @Adám Also, fixed \$\endgroup\$
    – Fmbalbuena
    5 mins ago
0
\$\begingroup\$

Find Maximum number of 4+ letter words from Scabble Tiles

The challenge is to find the most words with 4 or more letters you can make with one set of scrabble tiles.

The tile distribution is as follows:

2 Blank Tiles
A 9  N 6    +====+===========+
B 2  O 8    | 01 | K J X Q Z |
C 2  P 2    | 02 | B C M P F |
D 4  Q 1    | 02 | H V W Y * |
E 12 R 6    | 03 | G         |
F 2  S 4    | 04 | L S U D   |
G 3  T 6    | 06 | N R T     |
H 2  U 4    | 08 | O         |
I 9  V 2    | 09 | A I       |
J 1  W 2    | 12 | E         |
K 1  X 1    +====+===========+
L 4  Y 2
M 2  Z 1

Valid words are any words that are 4+ that are available in this file, the official scrabble dictionary.

Tiles cannot be used twice. This means you can only have 1 word with a K, J, X, Q, and/or Z unless you use a blank tile to represent one of these letters.

I'm not sure how I'd do scoring on this. I want shorter code to score better, but I don't want a short piece of code that finds a lot less words to score better than a longer piece that finds many more words.

\$\endgroup\$
11
  • \$\begingroup\$ Meh. I don't like dependency on external files; are we allowed to load it, or even embed it into the source code? \$\endgroup\$ Dec 17 '13 at 20:00
  • \$\begingroup\$ as for finding more vs. shorter code, you could demand all words be found \$\endgroup\$ Dec 17 '13 at 20:19
  • \$\begingroup\$ @JanDvorak Any way to use it. It's a text version of the official scrabble dictionary, it seemed to be the most fitting word list for the task. "All words being found" might be hard, considering there are probably many combinations of words that would deplete all the tiles. It's a maximum of 25 words, (25 words, 4 letters each, 100 tiles), but I don't know if it's possible to use all tiles with just 4 letter words. After so many words, you might not have enough tiles to make an actual word, which means you'd either have to go back or accept that you're not using all the tiles. \$\endgroup\$
    – Rob
    Dec 17 '13 at 20:23
  • 5
    \$\begingroup\$ As currently described, this is a no-input task, which means that the answer can be precomputed and then the program only needs to decompress it. Consider rewriting it to take input (either of the word list or of the tiles available). \$\endgroup\$ Dec 18 '13 at 8:01
  • \$\begingroup\$ I suggest taking a list of tiles as input, loading the list of words from a predefined file and requiring all combinations / best combination to be found. Of course, if the input is the full list of tiles, the computation is going to take ages. I might allow preprocessing the word list outside the program itself (up to a certain point; a linearithmic growth?) \$\endgroup\$ Dec 18 '13 at 8:32
  • 1
    \$\begingroup\$ I suggest modifying this so that input is a list of tiles, limited to a full rack or less (therefore 4-7 tiles, since our minimum word length is 4). Input should be assumed to be valid based on the standard set of tiles (e.g.: it wont' have something like 3 J's or 4 G's). This would have some practical use for a player in a scrabble game to figure out their next move (though it does not take into account tiles available to them which are already on the board). \$\endgroup\$
    – Iszi
    Dec 18 '13 at 21:14
  • \$\begingroup\$ Alternative mode: Input is a list of tiles, maximum 96 (so that at least 4 are remaining in the set). Output only includes words (minimum 4 letters) which can be created without those tiles. This would be interesting as it provides words that may yet be created (though, again, not taking into account usable tiles on the board) at a given point in the game. \$\endgroup\$
    – Iszi
    Dec 18 '13 at 21:15
  • \$\begingroup\$ Output needs to be decided as either a list of all possible words, or only the highest-scoring word(s). Another enhancement may be to require that the list be sorted descending in order of score (if output is all words), then ascending alphabetically. There's no reason to take each program's output into account for scoring. Since everyone is expected to use the same dictionary, all programs' outputs should be identical (except perhaps in sorting, if that's left out of the spec). So, this should be Code Golf. \$\endgroup\$
    – Iszi
    Dec 18 '13 at 21:15
  • \$\begingroup\$ It's also worth noting that, as currently written, the task could just be to filter the given dictionary down to words which have 4 or more letters. By its very nature, the Scrabble dictionary should already exclude any words that cannot be made with a Scrabble set. \$\endgroup\$
    – Iszi
    Dec 18 '13 at 21:18
  • \$\begingroup\$ @Iszi it's not "what are all the words you can make", it's "what are all the words you can make, where every letter used depletes a tile". There's a max of 25 words if you can use all 100 tiles. \$\endgroup\$
    – Rob
    Dec 19 '13 at 16:40
  • \$\begingroup\$ I think I misunderstood the problem, then. I thought it was "all the words possible using a set of tiles" not "all the words possible, using only one set of tiles". Still, my point about code golf remains. There is an absolute maximum to the number of words (each with 4 or more letters) you can make with a single Scrabble set, and a finite number of permutations which can be used to hit that maximum. Every program written with this goal should end up with the same (or nominally similar) output. \$\endgroup\$
    – Iszi
    Dec 19 '13 at 16:56
0
\$\begingroup\$

Since this question is closed, I figured I'd post it here so further issues can be hammered out in Meta instead of the main site.

Known Issues:

  • Some rules seem a bit unclear to some users.
  • Clarification may be needed on what is needed to qualify for the "win percentage" bonus.
  • Win percentage bonus may not be enough to be a real incentive. (This may just depend on the language or implementation.)
  • Perhaps the win percentage bonus should be eliminated entirely, or maybe it should just be made a mandatory part of the spec.
  • It's been suggested to use a simple 1-9 numbering system for the board positions, instead of any sort of X,Y coordinates.
  • May want to allow some flexibility on the input format. (i.e.: Input must still specify the sequence of moves thus far, using whatever addressing scheme is specified in the spec, but leave the delimiters - or lack thereof - up to the developer.)
  • Exactly what is expected of the program, such as how it can figure out whose turn it is or what the output should be, seems to need some clarification.
  • Some test cases should probably be added.
  • Clarification may be needed on the matter of what parts of the game we can assume have followed the guide already.
  • Some flaws exist in the chart. (Two already mentioned in comments on the original post.) These should be identified and addressed so that proper expectations for those conditions are clearly set.
  • Original post said we would not have to account for null input (i.e.: X asking what their first move should be) but this might be a good enhancement to add.

I personally think this is a great challenge. So far, I've had a very hard time finding a lot of room for optimization and got up to probably 400 characters in PowerShell before I gave up (not even half-way through the chart yet) due to some of the above issues. I'd really like to see what some more serious golfers could do with this, once the spec is properly hammered out.


Overview

This is the XKCD tic-tac-toe cheetsheet:

enter image description here

It's rather big, I know. But it's also your most valuable resource in your challenge.

The challenge

Create a program (in your language of choice) that uses the Optimal Move Cheatsheet (henceforth OMC) to output the optimal move when given a sequence of moves.

The input

Your program will be fed a series of moves in the following fashion:

A3 A2 B2 C2 ...

Where the first combination is always X, the second O, and so on. The letter is the Y coordinate (A-C, A at the top) and the number is the X coordinate (1-3, 1 at the left).

You may assume that the given combination is following the OMC's suggestion for each move at least for the player asking for a recommendation. You can also assume that the input will never be null (at least one move has been made). You must:

  1. Figure out whether the next move is for X or O (you don't need to output this)
  2. Use the OMC to decide the next move
  3. Print the next move in the standard format A3

Optional:

You may also include the player's chance of winning (as a percentage) for 50 character discount on your score.

\$\endgroup\$
4
  • 1
    \$\begingroup\$ I think a 1-9 system would be easier than any XY system, but not by too much. The biggest issue I think is that if you go by the chart (rather than formulating your own algorithm that plays the same way) you have a ton of data to enter (there are several hundred squares in the two charts). Perhaps limit the input to only sequences starting A1 B2 (or 1 5 if you use telephone keypad numbering)? That's the center square in the X chart and the top left square in the O chart. \$\endgroup\$
    – Blckknght
    Dec 23 '13 at 5:14
  • \$\begingroup\$ @Blckknght Limiting the scope of the challenge makes it less interesting. Part of the challenge (if not the entire challenge) here is to find ways to shortcut the flow while still putting out accurate results. As for the 1-9 system, the simplification may be relatively trivial but it does help clear out some otherwise unneeded bloat since everyone will probably build in some conversion to a 1-9 system anyway to shorten the code. It also enables some other shortcuts where the same move suggestion applies to multiple situations which are mathematically related. \$\endgroup\$
    – Iszi
    Dec 23 '13 at 19:47
  • 1
    \$\begingroup\$ My point is that the chart data so dominates the code size that winning answers will pretty much have to ignore the data in the chart and use an AI. So the challenge becomes "write a Tic-Tac-Toe AI that plays exactly like this chart", which seems less interesting to me than "use (part of) this chart to make an AI with trivial code". I already have working code for the problem and bonus in about 200 non-golfed characters of Python, but it will require many 1000s of characters of data, even if I exploit some symmetries. Even if I was willing to type all that data, an AI will beat it, I'm sure. \$\endgroup\$
    – Blckknght
    Dec 23 '13 at 20:55
  • 1
    \$\begingroup\$ @Blckknght I'm pretty sure even a fairly straightforward implementation of the chart can be fit within about 5,000 characters - especially in a proper golfing language. IRRC, I'd finished the X portion of the chart in about 400 characters with PowerShell before I gave up on my first go at it. Even then, there was still plenty of room for optimization, and that's in a language which is far from optimal for golfing. Certainly, it's nice when you can bang out a quick answer in 15 minutes. But not every challenge has to fit in 500 characters or less. \$\endgroup\$
    – Iszi
    Dec 23 '13 at 21:12
0
\$\begingroup\$

Test for Irreducible Complexity (Check for Redundant Characters)

I may need some additional help coming up with the full spec for this competition. As of right now, this is just a concept.

Many interesting questions, such as the "42" question in this sandbox, involve finding the longest program which is not reducible. This means that no set of characters can be removed and still allow the program to function as desired.

The basic idea is that your program will test a Base Program to make sure that it contains no redundant characters. The input will consist of:

  • Base Program (in the same language as your answer)
  • Expected Output

Your program will simply evaluate all possible subsequences of the Base Program and verify that none of them give the Expected Output.

This challenge actually has a utility value to several other challenges. For example, it verifies the results of a "longest non-reducible"-type challenge. In addition, it could make sure that a golfed solution cannot be golfed further.

I assume that the winning criteria will be fastest program, as cycling through all the possibilities takes a long time.

Problems

A sequence of length N has 2^N subsequences. Even if each evaluation is done very quickly, it might be unfeasible to test any program with more than 20 or so characters in a reasonable amount of time.

\$\endgroup\$
8
  • \$\begingroup\$ Problem: some subsequences of legitimate answers may be pretty dangerous to the environment. You don't want to eval just everything. \$\endgroup\$ Dec 23 '13 at 16:59
  • \$\begingroup\$ @JanDvorak Yes that actually is a serious problem. To what extent is it possible to fix that? \$\endgroup\$
    – PhiNotPi
    Dec 23 '13 at 17:04
  • 1
    \$\begingroup\$ Forbidding any program with dangerous subsequences? :-) \$\endgroup\$ Dec 23 '13 at 17:05
  • 1
    \$\begingroup\$ A more reasonable (but very difficult) solution would be the requirement to implement a sandbox. \$\endgroup\$ Dec 23 '13 at 17:07
  • 1
    \$\begingroup\$ Even without dangerous behavior, the halting problem will be an issue: it's hard to tell whether a shortened program will terminate at all, especially for every conceivable input. \$\endgroup\$
    – MvG
    Jan 7 '14 at 23:49
  • \$\begingroup\$ Are you sure this is possible? The problem of testing if two functions/programs/turing-complete things are equivalent is undecidable - I'm fairly sure it's reasonable easy to constract a brainfuck program that you can't tell if you can remove even a single character. \$\endgroup\$ May 16 '21 at 4:44
  • \$\begingroup\$ Extending on my previous comment - Let's assume you have a solution to this. Take a brainfuck program you want to test if halts. Let it reduce it, now you have an equivalent irreducible program. Add +. in the end of it, and then try to reduce it again. If the code never halts, that +. is reducible and when you'll run it again it will be removed. Otherwise it's important, so it will be kept. The halting problem is undecidable, therefor this is undecidable. \$\endgroup\$ May 16 '21 at 4:54
  • \$\begingroup\$ You can also get its undecidablility from that in Unary it will tell you if a given program is minimal, which is known to be undecidable as well \$\endgroup\$ May 16 '21 at 5:25
0
\$\begingroup\$

Wordlist detector

You are to write a program which, given a list of words, constructs a regular expression to match all these words but nothing else. Both your program and the constructed regular expressions are to be as short as possible.

Input and Output

Input comes on standard input and consists of one line giving n, the total number of words, followed by n lines with one word each. The number of words will be less than 1000, the length of each word less than 30. Words will consist only of lower case ASCII letters, i.e. a-z. You may choose to ignore the first line and use EOF instead to end the list.

Output shall be written to standard output. It consists of a single line, giving a POSIX extended regular expression to match these words and no others. Since input for this regex is not restricted to letters only, elements like . or [^…] won't make too much sense, which limits the language in a natural way. You may choose whether you want to terminate the line with a newline or not. Programs may choose to print multiple lines of output, in which case only the last one will be used for scoring. So you might print intermediate results and continue searching for improvements.

Test cases

Each submission may be accompanied by one regular expression. When scoring the submissions, I'll use this regular expression to reconstruct a word list from it. The code to do this reconstruction can be found at the end of this post. The reconstructed word list must fit the input specification above in terms of word count and length. It would be nice if your own program would be able to regenerate that regular expression from the word list, but that is not a strict requirement. But please don't paste bogus programs just to submit a challenging regular expression, though.

These test cases will be collected and fed to all programs for scoring.

Scoring

The final score of each program will be the program size plus the size of all its generated regular expressions for the inputs collected from submitted answers, including the example from this question. So short code which produces too long results might get beaten by longer code which generates shorter expressions.

Does this still qualify as ?

Submissions which generate an incorrect regular expression for one of the test cases will be disqualified, as will those which don't terminate in the allotted time. You can use the input reconstruction program below to check whether a produced regular expression does encode the correct word list.

Requirements

All submissions are welcome, but in order to include your submission in the tournament, it must be executable with reasonable effort on my Linux machine. It shouldn't depend on any exotic libraries, or any specialized ones which take too much work away from your own program. It must operate in reasonable time, say no more than five minutes per input. Your output must be reproducible, so if you use randomization at some point, please seed the randomizer, and please don't terminate an improove loop by a timer measuring execution time or some such.

Tournament times

I'll run the first major tournament two weeks after posting this question. I'll include a table of the results in this question. I'll try to run tournaments repeatedly as late submissions arrive, but I'll not promise any regular schedule.

Example

An very simple example application would be in Python 3 (53 chars):

print('|'.join(input() for i in range(int(input()))))

And here is a test case which could be posted along with the program, although this program obviously doesn't generate exactly this concise output:

bann?ana|ap(fel|ple)|s[ou]n|[hs](a|ou)nd

The expansion of that expression could be turned into the following example input, which need not be posted as part of an answer since it can be deduced from the regular expression:

10
banana
bannana
apfel
apple
son
sun
hand
hound
sand
sound

Regex expander program

And here is a program to turn regular expressions into word lists, again written in Python 3.

#!/bin/env python3
concat = set(('',))
altin = set(('',))
altout = set()
prev = None
stack = []
regex = iter(input())
for ch in regex:
    if ch == '(':
        stack.append((concat, altin, altout))
        altin = concat
        altout = set()
        prev = None
    elif ch == ')':
        concat.update(altout)
        prev, altin, altout = stack.pop()
    elif ch == '|':
        altout.update(concat)
        concat = altin
    elif ch == '[':
        ch = regex.__next__()
        cls = []
        while ch != ']':
            if ch == '-':
                crange = range(ord(cls[-1]), ord(regex.__next__()) + 1)
                cls.extend(map(chr, crange))
            else:
                cls.append(ch)
            ch = regex.__next__()
        prev = concat
        concat = set(w + c for w in prev for c in cls)
    elif ch == '?':
        concat.update(prev)
        prev = None
    elif ch >= 'a' and ch <= 'z':
        prev = concat
        concat = set(w + ch for w in prev)
    else:
        raise Exception("Illegal input")
if stack:
    raise Exception("Unclosed group")
concat.update(altout)
words = sorted(concat)
print(len(words))
print('\n'.join(words))

This is restricted to the part of regular expression syntax which I expect for this answer. If you have good reason to use something I did not consider, feel free to do so although I will likely have to update this code to cope with it. If you find a bug, please let me know.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ This is just Meta regex golf under the constraint that the two lists between them cover all possible words. Given that some people are tackling that existing question on that basis, this would qualify for closing as a duplicate. \$\endgroup\$ Jan 8 '14 at 8:45
0
\$\begingroup\$

Rhymalator

(at the point, it's just something that came to me before i wake up, so it may need some adjusting, and i'd like some feedback as to if this could be fun)


The code challenge is to write a program that takes as input a calculation in Reverse Polish Notation and outputs the result. It must at least implement + - * /. It So far so easy, but to make it fun and "artistic", the following restriction applies:

  • The source code must rhyme when read. Example in PHP

    $iterator = str_split($a);
    foreach ($iterator as $key=>$value){
        if ($key > 3){
            ++$virtue;
        }
    }
    

    (the rhyme is on value-virtue)

  • Lines whitout readable characters count as whitespace (the two lines with } in the example)

\$\endgroup\$
2
  • \$\begingroup\$ How does that example rhyme...? \$\endgroup\$
    – Doorknob Mod
    Jan 25 '14 at 12:54
  • \$\begingroup\$ @DoorknobofSnow well, i'm not really a poet, that's why i propose it as a challenge for others :p. if you have a better example i'll replace it \$\endgroup\$
    – Einacio
    Jan 27 '14 at 15:58
0
\$\begingroup\$

Implement Kalah

The game of Kalah is a two-player board game in the Mancala family. Your implementation must:

  • Identify the active player ("Player 1" or "Player 2")
  • Display board state (in format specified below)
  • Accept input to allow that player to move (using index system below)
  • Announce a winner ("Player N wins")

Overview

Each player has a line of six spaces, called houses, and one additional space called a store. Each space holds seeds, which move from house to house in a counter-clockwise direction. The objective is to fill your store with seeds.

You must represent the board in the following two-row format with stores offset, where HH is a house and SS is a store:

SS HH HH HH HH HH HH
   HH HH HH HH HH HH SS

The top row represents the number of seeds in player #1's spaces, and the bottom row represents the seeds in player #2's spaces. The S in each row is the respective player's store (player #1's is top-left, #2's is bottom right). Single-digit values should include a leading space.

In this challenge, user-input will identify each house numerically. Use a left-to-right, indexed-from-one scheme for both sides:

S 1 2 3 4 5 6
  1 2 3 4 5 6 S

Note that the players' stores are not numbered, because seeds placed in the store never move out.

Rules

Wikipedia has a good summary of the game and its rules:

  1. At the beginning of the game, three seeds are placed in each house.

  2. Each player controls the six houses and their seeds on his/her side of the board. His/her score is the number of seeds in the store to his/her right. [Clarification: from our perspective, player 1's store is to the left, player 2's store is to the right.]

  3. Players take turns sowing their seeds. On a turn, the player removes all seeds from one of the houses under his/her control. Moving counter-clockwise, the player drops one seed in each house in turn, including the player's own store but not his/her opponent's.

  4. If the last sown seed lands in the player's store, the player gets an additional move. There is no limit on the number of moves a player can make in his/her turn.

  5. If the last sown seed lands in an empty house owned by the player, and the opposite house contains seeds, both the last seed and the opposite seeds are captured and placed into the player's store. [Clarification: moves that end on an opponent's empty house end normally without a capture.]

  6. When one player no longer has any seeds in any of his/her houses, the game ends. The other player moves all remaining seeds to his/her store, and the player with the most seeds in his/her store wins.

Example

(Parenthetical text should not appear in actual output.)

Player 1
 0  3  3  3  3  3  3
    3  3  3  3  3  3  0
> 2                      (prompt arrow and line break
                          are purely optional)
 Player 2
 1  1  0  3  3  3  3
    4  3  3  3  3  3  0
> 4

Player 2  (P2 gets a bonus turn from rule #4)
 1  0  3  3  3  3  3
    4  3  3  0  4  4  1
> 5

Player 1  
 1  0  3  3  3  4  4
    4  3  3  0  0  5  2
> 4

Player 1  (P1 captures P2's seeds in space 1)
 6  0  4  4  0  4  4
    0  3  3  0  0  5  2
...

Player 2
12  0  0 10  0  1  0
    0  0  0  0  0  1 13
 > 6

Player 1 wins            (because the non-finishing players gets
                          all remaining seeds on their side, it's 23-14)

Meta question: Would this be improved by removing some of the rules?

\$\endgroup\$
1
  • \$\begingroup\$ Do the players run the game once and then take it in turns to take moves, with the process ending only when the game ends? Or do they run the program once per move? \$\endgroup\$ Jan 30 '14 at 10:06
0
\$\begingroup\$

[This is the first time I'm using the sandbox. I want to get feedback/suggestions before posting the question.]

Make a spider web (standard, orb type) that fills frame in the ratio of n:m, where n, m are input integers. You may use the example below as a model (but you don't need to use labels).

spider web

Your web should have multiple radii, at least 4 of which attach directly to the frame. The remaining radii should attach to the outer outline (perimeter) of the web. The web should have at least 15 radii. The mesh spacing should be more or less uniform spacing (although occasional weaving mistakes" or crossings are encouraged and will receive a bonus).

This is code-golf, so the shortest code (minus bonuses) wins.


Bonuses (to be removed from the number of characters in your code). Bonuses are awarded for the following features that reflect the architecture of an actual web (as opposed to a perfectly symmetric rendering). They are somewhat greater than usual as an incentive for attention to detail and realism.

-mesh spiral instead of concentric circles: 40 pts

-assymmetric web: 31 pts. (e.g. height of capture area greater than width)

-irregularly spaced radii: 42 pts

-distinct segments between radii (straight or crooked, but not the arc of a circle): 32 pts

-outer and inner outline clearly distinct from the spiral: 41 pts

-irregular outer outline: 20 pts

-2 or more easily observable reverses in spiral: 40

The accept will be awarded on Feb. 20, 2014.

\$\endgroup\$
2
  • \$\begingroup\$ If there are bonuses then it isn't code-golf, by definition. It's not clear what output formats are acceptable. I'm not sure what you mean by "distinct segments between radii". "2 or more easily observable reverses" seems problematic: the ease of observing reverses is subjective, and might in addition depend on input and/or on the random numbers obtained. The weighting for the bonuses seems very arbitrary: is there any justification for it? \$\endgroup\$ Feb 3 '14 at 11:49
  • \$\begingroup\$ Re: bonuses, I should probably decide on the features I want included in the web, thereby eliminating bonuses altogether. Distinct segments means that there should be 2 straight mesh segments between radius n and radius n+2 (not sure whether this should be required in instructions to be updated.) Will give reverses more thought. \$\endgroup\$
    – DavidC
    Feb 3 '14 at 12:02
0
\$\begingroup\$

Write a PHP Code Golfer

Since my currently daily programming is in PHP, I tend to try the challenges on the site using that language, but frequently I large program because of the verbosity of the language. And then I have to strip it for presentation...

But this is not a tips question, it's an eviscerating challenge.

The objective is to write a program in the language of your choice that takes a PHP file and outputs a golfed valid PHP file with the same functionality.

The scoring will be the average reduction in percent of the result of running the program with 3 selected files (not yet selected, I was thinking of some open source library)

The output file should run on at least 5.4 (so shorthand arrays, function dereference, traits are available)

Since the score is the difference between the ungolfed and golfed files, techniques beyond minifying are encouraged, such as using code subtitution, eval, compression, $$ (variable variables), dereferencing...


Scoring example: The 3 sources have 450, 1200 and 3500 chars respectively

Answer 1
results lenghts: 250, 1000, 3300
reduction: 200, 200, 200 (44%, 17%, 6%) average: 22%

Answer 2
results lenghts: 350, 1050, 3150
reduction: 100, 150, 350 (22%, 13%, 10%) average: 15%

In this case Answer 1 would win, even tough both answers got the same total reduction (-600 chars)

\$\endgroup\$
8
  • \$\begingroup\$ It's a specialisation of codegolf.stackexchange.com/q/3652/194 , so would likely be closed as a duplicate. \$\endgroup\$ Feb 4 '14 at 22:44
  • \$\begingroup\$ @PeterTaylor I saw it. is similar, but I include an objetive goal and score. have any idea on how to make it more unique? \$\endgroup\$
    – Einacio
    Feb 5 '14 at 2:43
  • \$\begingroup\$ "Making it shorter" is too broad, can I just delete some comments? If not, can I only shorten one variable and it's ok. It's not very interesting like this... \$\endgroup\$
    – Fabinout
    Feb 5 '14 at 9:56
  • \$\begingroup\$ @Fabinout the objective is golfing the code. If you only remove some characters, I doubt you'll get a good score \$\endgroup\$
    – Einacio
    Feb 5 '14 at 15:27
  • \$\begingroup\$ Alright, the criterion is the size of the output source code. good clarification. \$\endgroup\$
    – Fabinout
    Feb 5 '14 at 15:55
  • \$\begingroup\$ Sum the bytes with the percents or separately? Also, no matter what sources you choose, make sure to paste the code into your questions; who knows when the code in the library will change? \$\endgroup\$
    – Justin
    Feb 6 '14 at 19:11
  • \$\begingroup\$ i'll edit the bit about scoring (with examples) tomorrow (when i come back to work). I'll post the test sources as a pastebin, but I'll wait to choose them until the question is polished enough and someone consider it interesting enough \$\endgroup\$
    – Einacio
    Feb 6 '14 at 19:34
  • \$\begingroup\$ Is there anyone more with questions? is still possible that it will be marked as a duplicate? or can i choose the sources and publish it? \$\endgroup\$
    – Einacio
    Feb 13 '14 at 19:22
0
\$\begingroup\$

Create diagonal code

Your task is to create a program that outputs d=s*sqrt(2).

Specs:

  • Your program must be at least 4 lines long;

  • d=s*sqrt(2) cannot be hardcoded as is (so using ascii, compression, encoding, etc. is allowed and encouraged);

  • For each line of code n, pick up the nth character. The string obtained this way must be a valid program in a programming language of your choice, that must be different from the one you used for the main program. The obtained program must compile successfully, but it can throw errors, exceptions, etc.;

  • If at the nth line there is no nth character, you can consider that character as a whitespace or a newline. This cannot be done for the first 4 lines, which must be long at least n non-whitespace characters.

  • Your main program must end successfully (no errors, exceptions, etc.);

  • Internet access is forbidden;

  • Most upvoted answer in 2 weeks wins.

Happy coding!


I was unsure about making this a with several bonuses (polyglot answer, secondary program still valid, etc...).


Some bonuses for the code-challenge version:

Your valid answer starts with 0 points. You gain:

+10 if the secondary answer hides a third answer in it;
+15 for any other hidden answer;
+5 for every hidden answer that runs and ends successfully, without any problem;
+10 if your main answer is a polyglot;
+15 for every hidden answer that is a polyglot;


Which version would you prefer? Is there something you would change/improve in this question?

I personally like the one, but the KISS principle (Keep it simple, stupid!) reminds me that I may be wrong.

\$\endgroup\$
5
  • \$\begingroup\$ It's trivial to make the diagonal program be just whitespace (many scripting languages will accept this as a program) or H (valid program in H9Q+). \$\endgroup\$ Feb 26 '14 at 9:26
  • \$\begingroup\$ Nowhere does it say that the diagonal program must output your magic string: it doesn't even have to execute correctly. Your amendment doesn't really fix things: I can now have the second line be #H, the third be #HH, etc. \$\endgroup\$ Feb 26 '14 at 9:37
  • \$\begingroup\$ You're right; Don't know why, on a second read I messed up the meaning of your comment. Anyway, I suppose this excludes code-challenge unless I/we don't find a way to avoid such trivial solutions. I guess popularity-contest would still be ok, since more interesting solutions could be found, right? \$\endgroup\$
    – Vereos
    Feb 26 '14 at 9:41
  • \$\begingroup\$ I think my views on popularity-contest in general are well known. On further reflection, there are enough languages in which any string of bytes is a valid program that I don't think this question can work as is. If you want to save it, I think you need to look at doing something like a very difficult double-quine. \$\endgroup\$ Feb 26 '14 at 9:49
  • \$\begingroup\$ Thinking about quines and diagonals (which was the "spirit" of the question), what about a sort of mini-quine? The main program would have to display d=s*sqrt(2) only, and its diagonal must reproduce the code used to display the magic string (no comments allowed). It could be tagged code-golf or code-challenge. \$\endgroup\$
    – Vereos
    Feb 26 '14 at 11:04
1
62 63
64
65 66
121

You must log in to answer this question.

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