490
\$\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\$

2972 Answers 2972

1
11 12
13
14 15
100
3
\$\begingroup\$

Code Golf Measurer © 2019

Hexdumps used with xxd look something like this:

00000000: 666f 6f20 6261 7220 7370 616d 2065 6767  foo bar spam egg
00000010: 730a                                     s.

Your task is to convert a hexdump in this form in to the number of bytes used.

Rules:

  • Usual loopholes forbidden.
  • This is , so shortest valid answer in bytes wins.
  • You may or may not include the newline at the end of text (0a). This means that if the hexdump ends in a newline (0a), that input may have it's output reduced by one.
  • An empty input must output 0.

Test cases:

00000000: 4865 6c6c 6f2c 2077 6f72 6c64 2120 4865  Hello, world! He
00000010: 6c6c 6f2c 2077 6f72 6c64 210a            llo, world!.

returns 27 or 26

00000000: 0a                                       .

returns 1 or 0

00000000: 6368 616c 6c65 6e67 650a                 challenge.

returns 10 or 9

00000000: 4865 6c6c 6f2c 2077 6f72 6c64 21         Hello, world!

returns 13


returns 0

Sandbox:

  • Is this clear?
  • Is this a duplicate?
  • Other tags?
| |
\$\endgroup\$
  • 1
    \$\begingroup\$ Does the extra rule mean that the input can have an optional trailing newline, or that the results in all of your test cases could be reduced by 1? If you mean the former I recommend adding a test case that doesn't end with a newline. If you mean the latter then I recommend explicitly saying the file will end with a newline character. Also I suppose this is a string challenge. Thanks again for using the sandbox :) \$\endgroup\$ – FryAmTheEggman Oct 3 '19 at 20:55
  • \$\begingroup\$ @FryAmTheEggman It means that all test cases could be reduced by one. This was intended as a code golf byte counter, and the newline most certainly isn't usually included. I'll clarify this and add another test case to highlight it. \$\endgroup\$ – gadzooks02 Oct 4 '19 at 15:17
  • \$\begingroup\$ So: discard all the input except the last line, and parse hex? Or just output the last line and claim that your output is in hex? IMO it would be a more interesting problem with xxd input, where the last line is not present. \$\endgroup\$ – Peter Taylor Oct 5 '19 at 9:00
  • \$\begingroup\$ @PeterTaylor If I were to switch to xxd, would that be a valid edit, or would that be too big a change such that I would have to post another challenge? \$\endgroup\$ – gadzooks02 Oct 5 '19 at 9:45
  • \$\begingroup\$ I'm sure far more significant edits have been made to sandboxed challenges in the past. \$\endgroup\$ – Peter Taylor Oct 5 '19 at 13:10
  • \$\begingroup\$ @PeterTaylor In that case, edited. \$\endgroup\$ – gadzooks02 Oct 5 '19 at 14:52
3
\$\begingroup\$

Java vs C++

Now posted at Time to settle this: Java vs C++

| |
\$\endgroup\$
  • \$\begingroup\$ How vital is the validation to the challenge? \$\endgroup\$ – Unrelated String Aug 27 '19 at 21:01
  • \$\begingroup\$ @UnrelatedString I think it's fairly integral if the story is considered. Gotta inform the user that they're feeding you crap. Also it should add an extra element of challenge. \$\endgroup\$ – Mr Redstoner Aug 27 '19 at 21:07
  • 3
    \$\begingroup\$ @MrRedstoner Validation is generally considered tedious by the users of this site, rather than challenging. I'd recommend reconsidering - clearly the validation code could make use of the submissions as a subroutine. There are also a couple near dupes 1 2 but I haven't found a precise dupe. That said, thanks for using the sandbox! \$\endgroup\$ – FryAmTheEggman Aug 28 '19 at 0:36
  • 1
    \$\begingroup\$ getHTTP would result in... get_h_t_t_p? get_http? Error? Some other thing? \$\endgroup\$ – Chas Brown Aug 28 '19 at 1:42
  • \$\begingroup\$ @ChasBrown should be get_h_t_t_p, I shall add that. @FryAmTheEggman While I considered it part of the story, if those are the standards I figure I'll remove it and say the validation was done by a previous part of code. \$\endgroup\$ – Mr Redstoner Aug 28 '19 at 5:24
  • \$\begingroup\$ "If it is neither, output/return a falsey value." I would change this to something like "If it is neither, any unspecified behavior is fine (return a falsey value; give an error; try to convert it somehow anyway; etc.)." As mentioned by @FryAmTheEggman, validation is usually considered a distraction of the actual challenge (and can sometimes even double the code of the program/function for those answering), so most challenges assume the given input will always be valid. Apart from that the entire challenge looks fine, so +1 from me. Thanks for using the Sandbox! :) \$\endgroup\$ – Kevin Cruijssen Aug 28 '19 at 9:32
  • \$\begingroup\$ @KevinCruijssen Dang it missed that during the edit. Thanks for telling me! \$\endgroup\$ – Mr Redstoner Aug 28 '19 at 10:42
  • \$\begingroup\$ What should be returned from an input of a__b (two underscores)? \$\endgroup\$ – Value Ink Aug 29 '19 at 1:03
  • 1
    \$\begingroup\$ @ValueInk That would be invalid input. 'You may assume all input to be valid'. Therefore I refer you to the ANSI C standard for undefined behaviour. \$\endgroup\$ – Mr Redstoner Aug 29 '19 at 6:00
3
\$\begingroup\$

Can Jimmy escape the ghosts?

Posted: Can Jimmy escape the ghosts?

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ S'all good, no problem \$\endgroup\$ – Veskah Oct 17 '19 at 14:05
3
\$\begingroup\$

Universal Self-correcting Program

The idea here is to make a program that can tolerate errors in its own code, while still functioning correctly.

Since "error" is too broad, we will define it by a single bit flip. Of course, more tolerant versions, that could accept swapping any character with any other character would still be valid.

This program is universal in the sense that you can write any other self-correcting program (with the same tolerance) -- more on that later.

Importantly:

1) This program takes as input a triple-redundancy string of characters, and outputs a corrected string.

2) This program executes correctly with any bit flip in its own code.

(1) Triple redundancy codes

A triple redundancy code consists of simply repeating each bit, character or byte 3 times. In this case we use characters.

Correction is done by taking the majority of the characters, so (A,A,B) is corrected to A, (A,B,B) is corrected to B and so on.

AAA => A
AAB => A
HHHEEELLXLLLXOO => HELLO

This is a very crude an inefficient code for correcting single bit errors, but it is the least complex, which is why I think may be the best choice here. Hamming codes are better but a little more complex.

(2) Error tolerance

Our program will be defined as error tolerant if it performs the desired decoding function for any single bit flip in its own code. It may take longer for some inputs or when some flips occur, but it should always terminate.

Putting it together

The error-tolerant program can receive as input a (possibly faulty) program, and outputs a error-free program. Therefore, if a single-bit error occurs anywhere in the system comprised of (decoder,input program), a corrected program will still be output.

Observation

I don't actually know if this is possible, quite possibly it won't be achievable in every language. If it is too hard, we may relax the tolerable errors.

Scoring

The score will reflect the reliability of your program to errors. Tolerance is simply the number of bit flips you code accepts anywhere. It must be at least 1 (accept 1 bit flip anywhere). Size is the length of your program in bytes.

The score is Score = Size / 2^Tolerance

Lowest score wins.

Note: Several other challenges are possibly solved by solving this one (which would make sense given its universality!) by hardcoding the input.

Detect if your program has been mutated

Write a program that always outputs “2012” - even if it's modified!

This solves the "Who Watches the Watchmen?" problem involved in error correcting programs, like in this challenge:

Meta radiation hardener

since the decoding program itself tolerates errors (what good would be an error correcting program that is itself in error? :p).

| |
\$\endgroup\$
  • 2
    \$\begingroup\$ Check the radiation-hardening tag for duplicates and rules clarifications, too. \$\endgroup\$ – AdmBorkBork Mar 7 '18 at 19:17
  • \$\begingroup\$ @AdmBorkBork Thanks, I wasn't aware of that. It appears no one has proposed a Universal radiation hardener yet (this is universal only in the sense of bit flip errors; those are actually a good model for radiation though!). \$\endgroup\$ – Real Mar 7 '18 at 19:30
  • 1
    \$\begingroup\$ Again Lenguage win lol \$\endgroup\$ – l4m2 Jan 8 '19 at 14:53
  • \$\begingroup\$ Even though your scoring involves code length you should use code-challenge instead of code-golf for challenges that are not solely scored by code length. \$\endgroup\$ – Laikoni Jan 10 '19 at 20:14
3
\$\begingroup\$

Golfing with 2s

It is well-known that all positive integers can be represented via a sum of powers of 2. For example, 13=2^3+2^2+2^0. We can rewrite the 3 and 0, to get 13=2^(2+2/2)+2^2+2^(2-2). A shorter representation might be 13=2^2^2-2-2/2, or a more repetitive one 13=2+2+2+2+2+2+2/2

Challenge

Your task is, given a nonnegative integer as input, output/return a string containing only 2s and elementary operations, which when evaluated will yield that integer. These operations are +, -, *, /, ^, and appropriate parentheses. Use of multiple consecutive 2s (22, 222, etc) is not allowed.

However, the string should tend to be one of the shorter representations of the integer in question. So for the above example with 13, 2^2^2-2-2/2 and 2^2^2-2/2-2 are the shortest representations.

The input can be in any convenient format, but the output must be in the above format, either to a file or STDIO.

Scoring

Short code and efficient representation are both prioritized, so the score is the length in bytes plus the average length of the returned string for 9, 57, 554, 1894, 25993, 113193, 2998225, and 52748566.

Rules

Standard loopholes not allowed

Standard input/output forms apply

Some degree of brute forcing is allowed, but the program must be able to handle each of the test cases in under a minute each.

Example outputs

0            2-2
1            2/2
2            2
3            2+2/2
4            2^2
5            2^2+2/2
6            2^2+2
7            2^2+2+2/2
8            2*2*2
9            2*2*2+2/2
10           2*2*2+2
57           2^(2^2+2)-2^2-2-2/2
554          2*2^(2*2*2)+2*2^2^2+2*2*2+2
1894         2*2^(2*2*2+2)-(2^2^2-2)*(2*2*2+2+2/2)
25993        (2*2^(2*2*2+2)-2*2^(2*2*2)-2^2-2-2/2)*(2^2^2+2/2)
113193       2*2^2^2^2-(2^(2*2*2+2)-2^(2^2+2)-2^2^2-2-2/2)*(2^2^2+2+2/2)
2998225      (2*2^2^2^2-(2^(2*2*2+2)-2*2*2-2-2/2)*(2*2*2+2+2/2))*(2^2^2+2*2*2+2/2)
52748566     (2*2^(2^2^2+2^2)-2^2^2^2-2*2^(2*2*2+2)-2*2^(2*2*2)-2^(2*2*2)-2*2*2-2/2)*(2^2^2-2-2/2)*2
| |
\$\endgroup\$
  • \$\begingroup\$ It doesn't have to be optimal. It should tend to be optimal but you can trade it out for a much shorter program if it helps. \$\endgroup\$ – Exalted Toast Dec 8 '19 at 8:10
  • \$\begingroup\$ It might be a good idea to clarify length - do you mean the actual string length or the number of operations and 2s used? \$\endgroup\$ – FryAmTheEggman Dec 8 '19 at 20:19
  • \$\begingroup\$ Added clarification for both. To Fry, I mean the string length, but I'm not entirely sure what the difference is. \$\endgroup\$ – Exalted Toast Dec 9 '19 at 0:39
  • \$\begingroup\$ Can we use the numbers 22, 222, etc. in the output? \$\endgroup\$ – 79037662 Dec 10 '19 at 16:33
  • \$\begingroup\$ No. Will add clarification for that as well. \$\endgroup\$ – Exalted Toast Dec 12 '19 at 0:33
  • 1
    \$\begingroup\$ Can we submit a function that takes a value and returns a string? Typically you should try and avoid restricting input and output, and just rely on the community standards \$\endgroup\$ – Jo King Dec 13 '19 at 3:26
  • 1
    \$\begingroup\$ in reasonable time I know this is hard to specify, but as it stands it is too broad: what is meant by "reasonable time"? Some previous challenges say things like "it should run within a minute on a modern computer for inputs less than..." \$\endgroup\$ – Luis Mendo Dec 16 '19 at 9:47
  • \$\begingroup\$ Yeah, I'm not really sure how to specify it further. I only really added it because when I showed this challenge to my friend, they wrote a brute-force that goes through every string with those 8 characters and finds the shortest one, and it would take a few minutes for inputs > 30. Does being able to run each of the test cases in under a minute sound good? \$\endgroup\$ – Exalted Toast Dec 16 '19 at 19:15
  • \$\begingroup\$ That's the usual tactic, though you should probably specify what computer it is run on, since some will be faster than others. A possible idea could be the answerer has to run the biggest test case to completion, which should eliminate the worst of the brute force scripts \$\endgroup\$ – Jo King Dec 18 '19 at 7:33
  • \$\begingroup\$ Giving the integers you'll be testing with might allow people to optimise those specific inputs sneakily - maybe ask for a TryItOnline link and then give every answer a score yourself? Just a suggestion. \$\endgroup\$ – FlipTack Dec 27 '19 at 19:10
3
\$\begingroup\$

Eats, shoots and leaves

As you know, a panda eats shoots and leaves. Your task today is to write a panda in as few bytes as possible.

       1
      / \
     7   5
    / \   \
   2   6   9
      / \   \
     3   8   4

Here this tree has two branches, 1-7-6 and 1-5-9. The branch 1-7-6 has a shoot 2 and leaves 3 and 8, while the branch 1-5-9 has a leaf 4. After eating the shoots and leaves, your panda should output the following tree:

       1
      / \
     7   5
      \   \
       6   9

If your panda is a program or function, it must output the tree in the same format that you input it. Alternatively it can be a subroutine that modifies the tree in-place.

If it helps, you can assume that the tree has at least two nodes, and/or that each node has at most two child nodes.

No standard loopholes.

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ What is a shoot, and what is a leaf? Is this question asked to remove all leaf nodes (nodes without children) in a tree? \$\endgroup\$ – tsh Jan 13 at 1:30
  • \$\begingroup\$ @tsh For the purposes of the story, a shoot is a node which has no child nodes but whose parent has at least one grandchild node. Otherwise as you notice it has no effect on the outcome. \$\endgroup\$ – Neil Jan 13 at 10:58
3
\$\begingroup\$

Bucket and Minimize

Post here

| |
\$\endgroup\$
  • \$\begingroup\$ @FryAmTheEggman thanks for the info. updated \$\endgroup\$ – scrawl Jan 21 at 9:40
  • \$\begingroup\$ "floor(12%5)+1 into 12 mod 5 buckets, and floor(12%5) in the rest". Shouldn't those floor(12%5) be floor(12/5) based on your \$\left\lfloor\frac{|L|}{N}\right\rfloor+1\$ formula? \$\endgroup\$ – Kevin Cruijssen Jan 22 at 10:40
  • \$\begingroup\$ @KevinCruijssen er, yes. keeping things conventional. in my preferred language (k4) % is float division. i'll update it to avoid confusion. thanks! \$\endgroup\$ – scrawl Jan 22 at 12:27
  • \$\begingroup\$ Ah ok. In most languages I know % is modulo and / is division. :) I thought maybe % was integer-division in your language of choice, making the floor obsolete. But your edit is indeed clearer. \$\endgroup\$ – Kevin Cruijssen Jan 22 at 12:47
  • \$\begingroup\$ I would recommend cleaning the body of this answer and linking to the actual challenge: codegolf.stackexchange.com/q/198406/75323 \$\endgroup\$ – RGS Feb 2 at 21:07
  • \$\begingroup\$ @RGS cleaned up \$\endgroup\$ – scrawl Feb 2 at 23:55
3
\$\begingroup\$

Buildings made from cubes

Posted to main; thanks for input provided!

| |
\$\endgroup\$
  • \$\begingroup\$ this looks perfect for fastest-code. with fastest-algorithm it's difficult to do complexity analysis on the solutions. \$\endgroup\$ – ngn Jan 4 at 23:53
  • \$\begingroup\$ @ngn thanks, I’ve amended the alternative suggestion \$\endgroup\$ – Nick Kennedy Jan 5 at 0:23
  • 3
    \$\begingroup\$ it may be good to mention explicitly that all blocks must form a single connected component, otherwise 2 separate 1x1x2 pieces would technically satisfy rules 1-4 \$\endgroup\$ – ngn Jan 5 at 1:47
  • \$\begingroup\$ Is this basically \$a_n = \sum_{i=1}^n polyminoNumber(i)\cdot i^{n-i}\$? \$\endgroup\$ – the default. Feb 3 at 14:56
  • \$\begingroup\$ @mypronounismonicareinstate no it's not, though it is related to the polyomino numbers. I've posted to main (sorry for not updating Sandbox post), so please see there for two implementations of code. \$\endgroup\$ – Nick Kennedy Feb 3 at 17:35
3
\$\begingroup\$

Parse Iota

Iota is a simple programming language, considered the "sister" of the language Jot. More info can be found here Every Iota program consists of either an i, or a * followed by two Iota programs. In BNF, this is:

iota ::= i | *<iota><iota>

Challenge

Your task is to, given any input, output a truthy or falsy value based on whether or not it is a valid Iota program.

  • Your program may take input in any form agreed upon by the community here. It just has to be able to take input from the user in some form.
  • The same rule goes for output. See the post above for valid output methods. Output may be any truthy or falsy value in your language, including integers, strings, arrays, or objects. If it can be converted to a Boolean, it is OK.

Example I/O

Input: i
Output: 1
Input: hello
Output: 0
Input: *i*i*ii
Output: 1
Input: i*i
Output: 0
Input: ***
Output: 0
Input: *
Output: 0
Input: iiiiiiiii
Output: 0;
Input: i
Output: 1
Input: *ii
Output: 1
| |
\$\endgroup\$
  • \$\begingroup\$ Suggested test cases: *, ***, iiiiiiiiiii \$\endgroup\$ – 79037662 Feb 12 at 23:27
  • \$\begingroup\$ Ok, I added those @79037662 \$\endgroup\$ – sugarfi Feb 13 at 0:37
  • \$\begingroup\$ I don't get how i*i*i*ii is produced. If I understand the grammar right, this is equivalent to checking if parens are matched after removing the final i that must come at the end, using *i as (). \$\endgroup\$ – xnor Feb 13 at 7:12
  • \$\begingroup\$ @xnor - sorry, my bad. i fixed that. \$\endgroup\$ – sugarfi Feb 13 at 12:02
  • 1
    \$\begingroup\$ I think that despite the different presentation, this would be similar enough to checking paren matching to be a duplicate. \$\endgroup\$ – xnor Feb 14 at 11:22
3
\$\begingroup\$

The uniquely solvable sudoku

The task

Given a standard 9x9 sudoku board, output a Truthy value if that sudoku admits one and only one solution. Output a Falsy value if the sudoku has a number of solutions other than one. This means 0 solutions and two or more solutions.

The input

The board can be given in any sensible format. Some come to mind, and I'll exemplify for a 4x4 sudoku.

  • a 2D array with the state of the board, with any placeholder value for non-filled cells (including the digit 0, or no value at all if your language supports it): [[1,2,#,4],[#,4,1,2],[2,1,4,#],[4,#,2,1]]
  • a string of the digits row by row or column by column, so "12#4#412214#4#21" or "1#24241##14242#1"

The output

A Truthy value if the sudoku puzzle has a unique solution, Falsy otherwise.

Test cases

(To add)

Truthy

Falsy

| |
\$\endgroup\$
  • \$\begingroup\$ Hmm, I'm surprised this isn't a duplicate with the amount of Sudoku-related challenges we have. Closest related challenge I could find is perhaps this one. \$\endgroup\$ – Kevin Cruijssen Feb 18 at 16:21
  • \$\begingroup\$ @KevinCruijssen Thanks for your search! I can link this one, but this is still a new challenge, right? :) \$\endgroup\$ – RGS Feb 18 at 17:44
3
\$\begingroup\$

Square Deltas

Given an strictly positive integer n, output all numbers in the sequence up to the index n. For the current test cases of the current challenge numbers are one-indexed. However, other formats are allowed as default.

Base sequence

We start from this sequence:

1, 2, 1, 1, 2, 2, 2, 1, 1, 2, 2, 2, 2, 2, 1, 1, 2, 2, 2, 2, 2, 2, 2, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 2, 2, ...

The sequence is described as follows: 1, 2 (xN), 1 repeated arbitary times. There are 2 more 2's than the previous 2-set, and the 2-sequence starts at 1. i.e.:

1,       2,       1,
1,    2, 2, 2,    1,
1, 2, 2, 2, 2, 2, 1,
and so on ...

However, our point is not to output this sequence. For every item in this sequence, add the item by that item of that sequence.

Adding the sequence

Here's an example of adding the sequence. Here, our sequence starts with 0:

  The sequence
    |
    v
0 + 1 = 1
1 + 2 = 3
3 + 1 = 4
4 + 1 = 5
...

Our generated sequence is therefore

0, 1, 3, 4, ...

Example test cases

Here is a sample program outputting the sequence up to the input.

3 -> [0, 1, 3]
10 -> [0, 1, 3, 4, 5, 7, 9, 11, 12, 13]

Sandbox

  • Can the challenge be clarified?
| |
\$\endgroup\$
  • 5
    \$\begingroup\$ Why is the task asking for infinite output after index n, rather than a standard sequence challenge? A "standard sequence challenge" usually allows several I/O formats in a single challenge, including "input n -> the number at index n", "input n -> first n numbers", "no input -> infinite output of the sequence". \$\endgroup\$ – Bubbler Mar 6 at 4:49
  • 2
    \$\begingroup\$ No, you don't need to make it harder. And even if it is too easy, please don't try to fake up the difficulty by enforcing unnatural I/O requirements. \$\endgroup\$ – Bubbler Mar 6 at 4:56
  • 3
    \$\begingroup\$ Are you sure that you want to override the default sequence IO? Do you actually have a good reason for doing so? \$\endgroup\$ – Jo King Mar 12 at 4:36
3
\$\begingroup\$

Pendulum Encoding

Given an array as an input (which can be any acceptable/convenient format in your language), implement pendulum encoding.

How do I do that?

The current iteration index starts at 0.

  • If the iteration index is even, append the current item onto the output list.
  • If the iteration index is odd, prepend the current item onto the output list.

An example

The input is [a b c d e f g].
Note that the letters a-g are atoms, to prevent confusion from the iteration index.
N: the iteration index

N:0 Out:      [a]
N:1 Out:    [b a]
N:2 Out:    [b a c]
N:3 Out:  [d b a c]
N:4 Out:  [d b a c e]
N:5 Out:[f d b a c e]
N:6 Out:[f d b a c e g]

The output should be [f d b a c e g].

Another example

The input is [u d l n u e m p].

N:0 Out:        [u]
N:1 Out:      [d u]
N:2 Out:      [d u l]
N:3 Out:    [n d u l]
N:4 Out:    [n d u l u]
N:5 Out:  [e n d u l u]
N:6 Out:  [e n d u l u m]
N:7 Out:[p e n d u l u m]

Test cases

Here's a sample program doing this encoding.

Take note that the atoms in the list aren't always unique.

[a,b,c,d,e,f,g]   -> [f,d,b,a,c,e,g]
[]                -> []
[a]               -> [a]
[a,b,c,d]         -> [d,b,a,c]
[a,b]             -> [b,a]
[a,b,d]           -> [b,a,d]
[a,b,a,c,b,c]     -> [c,c,b,a,a,b]
[a,a,b,b,c,c]     -> [c,b,a,a,b,c]
[u,d,l,n,u,e,m,p] -> [p,e,n,d,u,l,u,m]
| |
\$\endgroup\$
  • 1
    \$\begingroup\$ I can't see any issues with this challenge apart from the usual "make sure that you specify that output and input can be taken in any reasonable and convenient format". \$\endgroup\$ – Lyxal Mar 18 at 0:00
  • \$\begingroup\$ The "example" in the first paragraph is confusing. It seems to be example input, but it deson't have clear context. If feels very out of place. \$\endgroup\$ – Wheat Wizard Mar 20 at 15:16
  • \$\begingroup\$ Are the "atoms" unique? If not, you should at least include a test case where they aren't. \$\endgroup\$ – FryAmTheEggman Mar 20 at 20:20
  • \$\begingroup\$ Naming a generic array a, then redefining a as a generic atom and never referring to the original array is not very helpful in an explanation. \$\endgroup\$ – Jonathan Frech Mar 21 at 0:09
3
\$\begingroup\$

Join by intersection

Given a list of strings, output these strings joined by their largest intersecting parts. Your output has to be optimal. Strings have to be joined in the order given.

What is an intersection anyway?

Suppose you have two strings:

"abcbc" "bcbcd"

You extract all suffixes of the first string, as well as all prefixes of the second string:

["abcbc", "bcbc", "cbc", "bc", "c"]
["bcbcd", "bcbc", "bcb", "bc", "b"]

We trunctuate both of these lists to the length of the list of the smaller length (it's an identity in this current case).

Then, we find all items at the same index which are equal to the other item at the same index:

["bcbc", "bc"]
["bcbc", "bc"]

We return the longest string of the output. Therefore, the intersection is:

"bcbc"

How to join two strings by the intersection

To join by the intersection you simply

  1. Append the first string without the intersection to the output string
  2. Append the intersection to the output string
  3. Append the second string without the intersection to the output string

For example, in our example case:

"abcbc" "bcbcd"
(The intersection is "bcbc")

Step 1. Out:"a"
Step 2. Out:"abcbc"
Step 3. Out:"abcbcd"

Reducing a join over a list

If you want to reduce a join over a list

["abc","bcd","rfh","hal"]

You connect them by their longest common substring:

abc
 bcd
    rfh
      hal
=========
abcdrfhal

Therefore the expected output is abcdrfhal.

Further walkdown

You cannot join two strings if their substring can be found in the middle. For example:

["aXc","bXd"]

If you try to match them by the middle substring:

aXc
bXd

You would realize that the other overlapping characters are not equal to each other. That is, a is not equal to b, and c is not equal to d. In that case you simply append the string in the join:

aXc
   bXd
======
aXcbXd

Likewise, if either of these strings contain each other, but isn't equal to the other string, you should simply append the string. E.g.

["abcd","bc"]

would give

abcd
    bc
======
abcdbc

Substrings can overlap past each other. E.g.

["abc","bcd","cde"]

would result in the following join:

abc
 bcd
  cde
=====
abcde

which would evidently make the output abcde.


Strings have to overlap as much as possible. That means, in this example:

["abcbc","bcbcd"]

This is not okay (even if they do overlap):

abcbc
   bcbcd
========
abcbcbcd

Instead, this should be done:

abcbc
 bcbcd
======
abcbcd

The join is consecutive based on the consecutive inputs. For example:

abcde
  cde
     abcde
==========
abcdeabcde

Test cases

A program is worth a thousand words. Here 's a reference implementation that I use to check the test cases.

["abc","bcd","rfh","hal"] -> "abcdrfhal"
["mmm","qqq","rrr"] -> "mmmqqqrrr"
["abcbc","bcbcd"] -> "abcbcd"
["aXc","bXd"]    -> "aXcbXd"
["abc","bcd","cde"] -> "abcde"
["abcd","bc"] -> "abcdbc"
["abcde", "cde", "abcde"] -> "abcdeabcde"
| |
\$\endgroup\$
  • \$\begingroup\$ How would you join aXc and bXd? They have the common substring X in the middle. \$\endgroup\$ – Bubbler Mar 25 at 2:24
  • \$\begingroup\$ Can strings overlap past each other like abc,bcd,cde->abcde? \$\endgroup\$ – xnor Mar 25 at 2:25
  • \$\begingroup\$ Do strings have to overlap as much as possible, or just overlap any amount? For example, for abcbc and bcbcd, is either of abcbcd or abcbcbcd OK? \$\endgroup\$ – xnor Mar 25 at 4:43
  • \$\begingroup\$ Do strings have to be joined in the order given? I feel like the answer is surely "yes", but the text doesn't say outright. Really, I think all these Sandbox questions come from the fact that the task is never actually stated precisely, and doing that would probably head off any further question. \$\endgroup\$ – xnor Mar 25 at 4:49
  • 2
    \$\begingroup\$ Along these lines, what happens if one string contains another? Do we do abcd,bc->abcd? \$\endgroup\$ – xnor Mar 25 at 4:51
  • \$\begingroup\$ Suggested test case: abcde, cde, abcde. \$\endgroup\$ – Jonathan Frech Mar 25 at 4:52
  • \$\begingroup\$ @JonathanFrech Well, what's the expected output? I thought it was abcde in this case. \$\endgroup\$ – user92069 Mar 25 at 6:00
  • \$\begingroup\$ I was not completely sure what the output would be. abcdeabcde does seem reasonable. \$\endgroup\$ – Jonathan Frech Mar 25 at 7:40
  • 2
    \$\begingroup\$ I still don't actually understand how the task works precisely. A reference implementation isn't a replacement for a specification. \$\endgroup\$ – xnor Mar 25 at 23:09
  • \$\begingroup\$ @xnor I've added back the spec, can you understand it now? \$\endgroup\$ – user92069 Mar 26 at 6:24
  • \$\begingroup\$ Not really, sorry. I still wouldn't know what abcd,bc would give. \$\endgroup\$ – xnor Mar 26 at 6:29
  • \$\begingroup\$ @xnor Are there any more test cases you don't understand? \$\endgroup\$ – user92069 Mar 26 at 6:35
  • \$\begingroup\$ This seems to be related to the shortest superstring problem for two strings, but you don't have to handle the case where one of the strings is a substring of another, and the joining order is fixed. Is that correct? Just informing that the specification spans four pages on my laptop, with default browser font size. \$\endgroup\$ – the default. Mar 26 at 6:55
  • \$\begingroup\$ @a'_' en.wikipedia.org/wiki/… \$\endgroup\$ – the default. Mar 26 at 6:58
  • \$\begingroup\$ @mypronounismonicareinstate Ah, it's a duplicate. Thank you for the mention. \$\endgroup\$ – user92069 Mar 26 at 6:58
3
\$\begingroup\$

Sum in 2540 Sums

This is my attempt to pair with .

You need to write a program that sums all codepoints of the input string.

Rules

  • The input will always be in printable ASCII.
  • The sum of the codepoints of your source must be exactly 2540.

    • You are allowed to use your language's own code page to calculate your program's codepoints.
  • Null bytes (which don't contribute to your codepoint sum) are banned.

  • The program must not work with any consecutive substring removed.
  • This is . Your score is the length of your source code, the shorter being better.
| |
\$\endgroup\$
  • \$\begingroup\$ You defined the "base score" only to reference that term exactly once. It seems to be move confusing than helpful. Wouldn't "The sum of the codepoints of your source must be exactly 2540" be clearer and shorter? \$\endgroup\$ – Wheat Wizard Apr 9 at 21:18
  • \$\begingroup\$ Although I am neither suggesting nor recommending against, this could also work as code-bowling if you either outlaw null bytes or sum up the (codepoints+1). \$\endgroup\$ – Wheat Wizard Apr 9 at 21:22
  • \$\begingroup\$ @AdHocGarfHunter The rules are a lot simpler if it were code-golf, and we haven't paired codepoint sum with code golf before. Also I need to fullfill a goal to pair code-bowling with code-golf. This analysis says that there are 11 tags not paired with code-golf, I'm going to make it 10. \$\endgroup\$ – user92069 Apr 9 at 21:24
  • \$\begingroup\$ As far as I know, [pristine-programming] is the tag for programming with the substring removal restriction here. (I think this would work as a [code-bowling] as well as well) \$\endgroup\$ – the default. Apr 10 at 0:12
  • \$\begingroup\$ @mypronounismonicareinstate So which side are you for? Code golf or code bowling? \$\endgroup\$ – user92069 Apr 10 at 0:53
  • \$\begingroup\$ Probably code-golf. \$\endgroup\$ – the default. Apr 10 at 1:07
3
\$\begingroup\$

Will this simplified befunge-93 program terminate?

The challenge today is to solve the halting problem for simplified befunge-93.

Simplified befunge-93 has exactly four instructions - > v < ^ @. The program is restricted to a 80x24 grid. Each of the commands modifies the instruction pointer (so that, for instance > makes the instruction pointer start executing commands to the right), except of the @ instruction, which terminates the program.

When the instruction pointer reaches the end, it wraps around (imagine the snake game).

You may read input in form of a string or a two-dimensional array using any reasonable device. The output may be either a truthy value if the program terminates, or a falsy value if the program doesn't terminate.

Example data

Input:
>v
^<

Output: Doesn't terminate.
----------------------------------------
Input:
> v
 @
^ <

Output: Doesn't terminate.
----------------------------------------
Input:
v@
[23 newlines]
>v

Output: Terminates.
----------------------------------------
Input:
v @
[23 newlines]
>v

Output: Doesn't terminate.
----------------------------------------
Input:

Output: Doesn't terminate.
| |
\$\endgroup\$
  • 3
    \$\begingroup\$ Possibly dupe? \$\endgroup\$ – null Apr 27 at 8:47
  • \$\begingroup\$ is the instruction ptr initially at 0 0 and moving to the right? \$\endgroup\$ – ngn Apr 27 at 8:55
  • \$\begingroup\$ yes, I maybe forgot to state that. But it's most probably a dupe right now, so I don't think I should push it forward anymore :P \$\endgroup\$ – Kamila Szewczyk Apr 27 at 8:56
3
\$\begingroup\$

Posted.

| |
\$\endgroup\$
  • \$\begingroup\$ For the sake of completion: can I give my output as a list of strings? \$\endgroup\$ – Lyxal Apr 29 at 23:02
  • \$\begingroup\$ @Lyxal Seeing as that's a generally accepted I/O method, yes. \$\endgroup\$ – sporeball Apr 30 at 0:09
3
\$\begingroup\$

Complete a sequence using its distances

Given \$A = (a_1,\dots,a_k)\ k\ge2 \$ a nonrepetitive sequence of positive integers.
Starting from \$i=2\$, while \$a_i\in A:\$

  • If \$d=|a_i-a_{i-1}|\$ is not already in \$A\$, append \$d\$ to \$A\$
  • Increase \$i\$

Output the completed sequence.

Example

In:  16 20 13 3

     16 20 13 3 4
      --^
     16 20 13 3 4 7
         --^
     16 20 13 3 4 7 10
            --^
     16 20 13 3 4 7 10 1
              --^
     16 20 13 3 4 7 10 1
                --^
     16 20 13 3 4 7 10 1
                  --^
     16 20 13 3 4 7 10 1 9
                     --^
     16 20 13 3 4 7 10 1 9 8
                         --^
Out: 16 20 13 3 4 7 10 1 9 8

This is

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ You could define the self-distances completion for a sequence of positive integers instead of a k-permutation. I believe it would be clearer that way. Also, is the input guaranteed to be duplicate-free? \$\endgroup\$ – Zgarb Jun 1 at 20:15
  • \$\begingroup\$ @Zgarb Yes, you're right, for the purpose of this challenge refer to a sequence would be totally ok, I've copied this def from the linked challenge where since it's fundamental to consider the max in the input sequence, this number in the context of k-permutation of n - containing n - will naturally be n... But that's not a problem, a k permutation is also a sequence of positive integer. And yes, I forgot to require the input to be duplicate-free \$\endgroup\$ – Domenico Modica Jun 1 at 20:44
  • \$\begingroup\$ @Zgarb what do you think about the name? Does it make sense? It's a bit too bulky? \$\endgroup\$ – Domenico Modica Jun 1 at 20:53
  • 1
    \$\begingroup\$ "append d to (the end of) A" could be clearer to programmers than "prolong A with d". Using "the end of" is optional. \$\endgroup\$ – Hiatsu Jun 2 at 3:05
  • 1
    \$\begingroup\$ The name could be "Complete a sequence using its distances" if you want to go for maximum clarity. \$\endgroup\$ – Zgarb Jun 2 at 8:08
3
\$\begingroup\$

_

| |
\$\endgroup\$
  • \$\begingroup\$ @mathjunkie then the codepoints given are incorrect. \$\endgroup\$ – Lyxal May 24 at 22:43
  • \$\begingroup\$ @Lyxal Why are they incorrect? I wrote a program to generate the codepoints. \$\endgroup\$ – user92069 May 25 at 8:15
  • \$\begingroup\$ Oh wait. I thought they were in binary. \$\endgroup\$ – Lyxal May 25 at 8:18
  • \$\begingroup\$ As in, you were using the binary representation of each ordinal value. \$\endgroup\$ – Lyxal May 25 at 8:19
  • \$\begingroup\$ @Lyxal No. I was using the decimal expansion of the ord codes. I am going to clarify that. \$\endgroup\$ – user92069 May 25 at 8:19
  • \$\begingroup\$ I cam see that now. I just assumed those numbers were base 2,rather than base 10 \$\endgroup\$ – Lyxal May 25 at 8:20
  • \$\begingroup\$ Seems pretty clear, but would benefit from test cases with odd-length strings. For example, 'rim' (false) and 'rum' (true) illustrate the 'first half longer' splitting rule. (Truthiness for these two words would be swapped if the rule were second half longer.) \$\endgroup\$ – Dingus May 29 at 7:24
3
\$\begingroup\$

Bot Duels KOTH

Obligatory blurb adding story fluff. Or, maybe a self-referential paragraph about meta-self-referential blurbs? Or: <announcer voice> Will your bot survive... The Arena? </announcer voice>. Yes, I think a good non-self-referential (such as this) short paragraph full of short sentences without run-ons or many, many, many, many commas will suffice.

Overview

This is a King-of-the-Hill challenge. Bot with the most wins wins. You may submit multiple bots as long as they differ in strategy. Bots will play against every other bot. The bot who is currently playing against every other bot goes first, and goes second when their opponent is playing against every other bot. Bots will face off in an arena with x boundaries of 10 and -10 and y boundaries of 10 and -10. Bots will either start at (-5, 0) or (5, 0). Your goal is to defeat the other bot by reducing it's HP to 0 or less. Bots start with 20+armor modifier HP and do not regenerate health. Your bot defeats the other bots using weapons, which have damage, range, and cooldown. Armor has speed.

Submissions

Submissions should be a JS function that takes the following parameters:

  • curr_x - the current x coordinate of your bot
  • curr_y - the current y coordinate of your bot
  • enemy_x - the current x coordinate of your opponent's bot
  • enemy_y - the current y coordinate of your opponent's bot
  • enemy_armor - the armor that your enemy is wearing
  • storage - a storage object you can use to store data between function calls

The function should return an array with 3 items (in the following order):

  • desired x - the x coordinate you want to move to
  • desired y - the y coord you want to move to
  • use weapon? - if true, and desired x and desired y are Infinity, then you use your weapon

Submissions should be structured as

Weapon: your weapon here
Armor: your armor here

function definition
block

Explanation underneath, if any.

Armor

(currently designing new weapons and armor) The types of armor available are:

  • Light - increases HP by 3, has a speed of 3
  • Medium - increases HP by 5, has a speed of 2
  • Heavy - increases HP by 7, has a speed of 1

Weapons

The types of weapons are:

  • Laser - High-range, high-damage, low ROF. 5 points of damage, 5 rounds to cool down, and a range of 6 units
  • Rifle - General-purpose weapon. 5 damage, range of 4, 3 rounds to cool down.
  • Sword - High-ROF, high-damage spiky thing. 5 points of damage, really low range of 1, and a rather quick 2 rounds to cool down.

Turns

On your turn, you can either move or use weapon (or do nothing, if that's what you really want to do).

  • If you move, you can move a distance (computed using the Euclidean Distance formula) less-than or equal-to (<=) your armor's speed.
  • If you choose to use weapon, and if the enemy is in range of your weapon, then you deal damage equal to your weapon's damage and the weapon goes into cooldown. A weapon in cooldown can't be used. Weapons can be used after a number of turns equal to their cooldown property has passed after being used.
  • To do nothing, simply return your current x and y coordinates, like so: return [curr_x, curr_y, false].

Rules

  • If you try to use a weapon during cooldown, nothing happens and your turn ends
  • If you try to use a weapon and your opponent is out of range, nothing happens and your turn ends.
  • If you try to move more than your armor's speed, nothing happens and your turn ends
  • If you try to move out-of-bounds, same thing
  • If you move into another bot's space, then the bot with the lowest HP loses and the bot with the highest HP wins, making this a viable strategy.
  • All standard loopholes (accessing controller, duplicate bots, suicide bots, etc.) are, of course, disallowed.

Examples

TowerDefense Weapon: Laser
Armor: Heavy

function(curr_x, curr_y, enemy_x, enemy_y, enemy_armor, storage) {
    let actions = [Infinity, Infinity, true];
    return actions;
}

Just sits and shoots, lol. A perfectly viable strategy (and a rather strong one, too, while weapons are still being reworked). Takes the highest-hp armor available because it doesn't need to move at all.


DumbBot

Weapon: Rifle
Armor: Medium

function(curr_x, curr_y, enemy_x, enemy_y, enemy_armor, storage) {
      let actions = [curr_x, curr_y, false];
      // if storage is empty
      if (!storage.data) {
        // then write our starting loc
        storage.data = curr_x.toString() + " " + curr_y.toString();
      }

      // if we're starting at x = -5
      if (storage.data.includes("-5")) {
        if (curr_x < 3) {
          // move right
          actions[0] += 2;
          actions[1] = curr_y;
        }
        // otherwise we must be close enough
        else {storage.data = "shoot";}
      }

Assumes enemy doesn't move (such as TowerDefense). Moves to the enemy's starting location, then shoots. As such, takes the Medium armor and the Rifle. Kind of a generic all-purpose bot, like the weapons and armor it uses.

Controller

The controller can be found here. Run all current submissions here.

Best of luck, and, may the odds be ever in your favor (even though this is a 1v1 and not a FFA)

Sandbox

  • Are the rules explained thoroughly? Is anything unclear?
  • Is the game (armor, weapons, punishment for breaking rules, etc.) balanced well? Are there any strategies that dominate?
  • Would this KOTH be fun?
  • Would you participate in the competition?
  • Any obvious bugs in the (horribly messy) controller code?
  • Create a simple submission similar to something that you would actually submit and test it against the example bots. Is the code still working?
| |
\$\endgroup\$
  • \$\begingroup\$ An arena that contains the points (-5, 0) and (5, 0) would be larger than 10x10. Isn't the heavy armor creating more health that can be removed in a turn? \$\endgroup\$ – the default. Jun 15 at 17:07
  • \$\begingroup\$ Armor adds health at beginning of game. It’s a one-time buff. And yes, I messed up the field size. It’s 20x20 \$\endgroup\$ – nope Jun 15 at 21:32
  • \$\begingroup\$ If armor is one-time, then the Light armor is strictly better than Medium because both last only for one shot, leading to various weirdness. \$\endgroup\$ – the default. Jun 16 at 1:41
  • \$\begingroup\$ a) How much health does each bot start with? b) Are you sure the arena is supposed to be 20x20? Not 21x21 or 19x19? As it is one of the bots will have to start closer to the edge (and which one it is isn't specified as far as I can tell). c) Is there a reason why some disallowed actions cause an immediate forfeit while others only make the offending bot skip a turn? d) The "Stuff Not Allowed" and "Other viable strategies" are confusing. Namely, under the first one you list a viable strategy, and under the second - something that's disallowed. \$\endgroup\$ – Alion Jun 16 at 12:02
  • \$\begingroup\$ b.2) On further inspection, is this game grid-based or played on a continuous arena? As in, can you move in fractions? In the second case, (b) becomes irrelevant. \$\endgroup\$ – Alion Jun 16 at 12:40
  • \$\begingroup\$ e) What's the mysterious "Distance formula"? Plain old euclidean distance? Taxicab? Chebyshev? f.1) How do you "include [what weapon and armor your bot is using] in your submission"? f.2) More generally, is there a specific submission format? Or will anything human-readable do? g) Are bots allowed to act randomly with the help of Math.random, for example? h) Is it really necessary to override this loophole? \$\endgroup\$ – Alion Jun 16 at 13:06
  • \$\begingroup\$ i) Have you considered adding more weapon types or modifying the current set? Currently the choice is pretty one-dimensional, since you avoid varying the damage property. \$\endgroup\$ – Alion Jun 16 at 13:07
  • \$\begingroup\$ As for whether this KotH is fun or not - it seems okay, but I think it lacks variety. Addressing (i) would probably help with that. I would definitely give this challenge a try regardless if it hit main (perhaps as a result of me being a JS KotH junkie). \$\endgroup\$ – Alion Jun 16 at 13:18
3
\$\begingroup\$

Posted.

| |
\$\endgroup\$
  • 2
    \$\begingroup\$ Just an observation: the table is almost antisymmetric reading top-down vs bottom-up. That is, if you split the table in half based on the value of A, then the X value in any row in the top half of the table is mostly the opposite of the X value in the same row (reading upwards from the bottom) in the bottom half. Whether that simplifies the problem at all, I'm not sure. \$\endgroup\$ – Dingus Jun 15 at 0:23
  • \$\begingroup\$ I think the [kolmogorov-complexity] tag should apply here, and the [number] tag doesn't seem very helpful. \$\endgroup\$ – the default. Jun 16 at 5:58
3
\$\begingroup\$

Polyglot: Convert Case


Your task is to write a program that performs case conversion from plain text, and other case formats, into one of the specified formats below. Inputs will be either plain lowercase text, or one of the detailed cases below. You must remove non-alphabetic characters, except (space), _ and -, split on these, or differences in case (e.g. bA), and either join on the desired chars or join on the empty string and capitalise the first char of each word (or not the first of doing camel case). Your program must be a polyglot in at least two different languages. For example, running your code in Python 2 transforms input to snake_case, running it in JavaScript transforms to kebab-case, Ruby transforms to PascalCase and 05AB1E transforms to camelCase.

Tasks

The following case conversions must be completed:

camelCase

this is a test         thisIsATest
camelCaseTest          camelCaseTest
PascalCaseTest         pascalCaseTest
snake_case_test        snakeCaseTest
kebab-case-test        kebabCaseTest
Testing!!one!!!1!!!    testingOne1
aBCDef                 aBCDef
ABCDef                 aBCDef
a_b_c_def              aBCDef
a-b-c-def              aBCDef

Try it online!

PascalCase

this is a test         ThisIsATest
camelCaseTest          CamelCaseTest
PascalCaseTest         PascalCaseTest
snake_case_test        SnakeCaseTest
kebab-case-test        KebabCaseTest
Testing!!one!!!1!!!    TestingOne1
aBCDef                 ABCDef
ABCDef                 ABCDef
a_b_c_def              ABCDef
a-b-c-def              ABCDef

Try it online!

snake_case

this is a test         this_is_a_test
camelCaseTest          camel_case_test
PascalCaseTest         pascal_case_test
snake_case_test        snake_case_test
kebab-case-test        kebab_case_test
Testing!!one!!!1!!!    testing_one_1
aBCDef                 a_b_c_def
ABCDef                 a_b_c_def
a_b_c_def              a_b_c_def
a-b-c-def              a_b_c_def

Try it online!

UPPER_SNAKE_CASE

this is a test        THIS_IS_A_TEST
camelCaseTest         CAMEL_CASE_TEST
PascalCaseTest        PASCAL_CASE_TEST
snake_case_test       SNAKE_CASE_TEST
kebab-case-test       KEBAB_CASE_TEST
Testing!!one!!!1!!!   TESTING_ONE_1
aBCDef                A_B_C_DEF
ABCDef                A_B_C_DEF
a_b_c_def             A_B_C_DEF
a-b-c-def             A_B_C_DEF

Try it online!

kebab-case

this is a test         this-is-a-test
camelCaseTest          camel-case-test
PascalCaseTest         pascal-case-test
snake_case_test        snake-case-test
kebab-case-test        kebab-case-test
Testing!!one!!!1!!!    testing-one-1
aBCDef                 a-b-c-def
ABCDef                 a-b-c-def
a_b_c_def              a-b-c-def
a-b-c-def              a-b-c-def

Try it online!

Rules

  • Your code should produce the same output as the linked examples.
  • Entries with the most conversions win, with code length being a tie-breaker.

Questions for sandbox

  • Have I missed any other major naming schemes?
| |
\$\endgroup\$
  • \$\begingroup\$ in the example, at the start, you said python 2 and javascript, while below there are 4 conversions. Must you do all of them in a different language each? Also, do language versions (python 2 / python 3) count as different languages? \$\endgroup\$ – Command Master Jul 3 at 3:27
  • \$\begingroup\$ @CommandMaster It was just a cut down example to explain the concept of a polyglot. I'm still unsure whether it makes sense to allow two or more languages or require all four. I feel like allowing two or more would enable more elegant solutions as snake Vs kebab is the same bar the delimiter and Pascal Vs camel is the same bar leading capitalisation. What're your thoughts? \$\endgroup\$ – Dom Hastings Jul 3 at 6:28
  • \$\begingroup\$ Different language versions count as different languages (not sure of there's a relevant meta post. I'll try and look for it when I'm not on mobile.) \$\endgroup\$ – Dom Hastings Jul 3 at 6:29
  • \$\begingroup\$ If the usual 'different command-line flags count as different languages' rule applies, then is there a risk that the snake vs kebab cases could be trivially solved using the command-line flag to specify the delimiter...? \$\endgroup\$ – Dominic van Essen Jul 6 at 11:23
  • \$\begingroup\$ Yeah, I guess so. Something like Perl's -i flag could enable using $^I to be either - or _. Although then doing the same would probably be tricky and potentially still at least a little ingenious. \$\endgroup\$ – Dom Hastings Jul 6 at 12:46
  • \$\begingroup\$ "Have I missed any other major naming schemes?" Yes: Ada_Ninety_Five_Case, Title Case, and (jokingly) StRaNgEcAsE. What's wrong with UPPER_SNAKE_CASE? \$\endgroup\$ – fireflame241 Jul 9 at 5:55
  • \$\begingroup\$ @fireflame241 I think that converting back from upper snake case might be slightly more tricky than just snake case, as checking for an underscore might not be enough to see if there's more transformation necessary, if for example there was already an underscore in normal text... I could state that isn't a problem though I guess? Adding more cases might make me lean towards mandating only a minimum of two transformations required as well and changing the scoring to number of transformations with code length as a tie-breaker... Thanks again, will think on this a bit. \$\endgroup\$ – Dom Hastings Jul 9 at 6:16
  • \$\begingroup\$ If you restrict words to be composed only of letters, then you could avoid that issue, and a few others. For example, how would aB_Cd be handled? It could be snake case, where the _ separates the words, or camel case, where the _ is the start of the second word. I think right now there's too many test cases, too little explanation. \$\endgroup\$ – fireflame241 Jul 9 at 6:32
  • \$\begingroup\$ @fireflame241 Yeah, I think you're right. Ok. I'll work on this. Thanks! \$\endgroup\$ – Dom Hastings Jul 9 at 6:45
  • \$\begingroup\$ Re: flags as languages again. I was more thinking of a program 'checking' to see what flags had been used (even if they have no direct effect), and modifying its behaviour accordingly. For instance, perl -m foo + then checking whether foo is loaded. This would also be similar to language+library = different language. Worst cheat of all would be awk -v mode=1... \$\endgroup\$ – Dominic van Essen Jul 9 at 16:03
  • \$\begingroup\$ Along the same lines, it would be important to specify that it isn't Ok to just run different versions of a language (which currently 'count' as different languages), and for the program to determine the version & modify its behaviour. \$\endgroup\$ – Dominic van Essen Jul 9 at 16:10
  • \$\begingroup\$ I don't think it's possible to rule out different language versions for polyglot challenges, and using flags to classify as different languages might be questionable too. I guess if the answers aren't in the spirit of the task or are a little boring they'll be voted on accordingly. I'm open to more input on this though! Thank you for the feedback! \$\endgroup\$ – Dom Hastings Jul 9 at 21:13
  • \$\begingroup\$ "polygot in at least two different languages" so we must write 4 programs, how can there be fewer than 4 languages? \$\endgroup\$ – qwr Jul 9 at 22:46
  • \$\begingroup\$ @qwr I just amended the rules to allow 2 or more languages, you don't have to have all 5. I'm hoping this will allow some creative solutions. If I missed a reference to that I'm struggling to see it, but morning eyes... \$\endgroup\$ – Dom Hastings Jul 10 at 6:07
  • \$\begingroup\$ For some reason I thought there were 4 programs. So to clarify, the minimum is two languages / two conversions? \$\endgroup\$ – qwr Jul 10 at 6:11
3
\$\begingroup\$

Posted: Find the Block on the Extended Periodic Table Using the Diagonal Rule

| |
\$\endgroup\$
  • \$\begingroup\$ I would be more inclined to compete if all the elements were classified into the correct blocks. I know it's only a code-golf challenge, but somehow it seems annoying to deliberately give the wrong answer! I don't know whether there's a precedent for it, but is there any way to say, for instance "additional code to adjust the positions of elements (currently only 4: La, Ac, Lu & L4) that are exceptions to the diagonal rule will not be included in the byte-count"...? \$\endgroup\$ – Dominic van Essen Jul 10 at 6:22
  • \$\begingroup\$ the real reason I made it require the wrong answer was because I do not quite know the behavior of the extended periodic table (are all group 3 elements in the d-block?) I will likely put the exceptions back, especially if I find the answer to that question @DominicvanEssen \$\endgroup\$ – golf69 Jul 10 at 6:33
  • \$\begingroup\$ I think my guess about group 3 was correct. The best way to phrase the exceptions might be to say "all elements directly adjacent to an s-block element are in the d-block, and those directly adjacent to that block are also in that block" (phrasing tbd, as is that is way too ambiguous) @DominicvanEssen \$\endgroup\$ – golf69 Jul 10 at 6:56
  • \$\begingroup\$ I like it if all the elements can be assigned in a rule-based way (rather than expermentally) to their correct positions. But, from the way you describe it, I get the impression that the 'diagonal rule' is more of a rule-of-thumb that breaks-down at tht 6th row... or have I misunderstood? \$\endgroup\$ – Dominic van Essen Jul 10 at 7:07
  • \$\begingroup\$ A purely-cosmetic change could be to change the title to "Find the predicted block on the periodic table" and subtext as "as predicted by the Madelung_energy_ordering_rule". Then there'd be no exceptions (by definition), and nerds like me would be fooled into thinking that we're calculating 'correct' answers... \$\endgroup\$ – Dominic van Essen Jul 10 at 7:16
  • \$\begingroup\$ The diagonal rule specifically breaks for the 3rd column (group 3). I like your idea of just changing the title, I will do that @DominicvanEssen \$\endgroup\$ – golf69 Jul 10 at 7:34
  • \$\begingroup\$ I think it's still important to mention/highlight somewhere that the experimentally-measured periodic table deviates from that predicted by the diagonal rule at higher atomic numbers, and that this challenge is only to find the blocks predicted by the diagonal rule. Otherwise it could be confusing to understand what the intended output should be. \$\endgroup\$ – Dominic van Essen Jul 10 at 8:02
3
\$\begingroup\$

posted

| |
\$\endgroup\$
  • \$\begingroup\$ Suggested testcase: 23:59 \$\endgroup\$ – fireflame241 Jul 13 at 17:11
  • \$\begingroup\$ Can we take input base 60? \$\endgroup\$ – fireflame241 Jul 13 at 17:12
  • \$\begingroup\$ 'in which you start both at exactly hh:mm:00' - should this rather say something like 'you start the timer when the clock shows exactly hh:mm:00'? \$\endgroup\$ – Dingus Jul 14 at 15:12
  • \$\begingroup\$ @Third-party'Chef' Could you specify that handling unsolvable inputs is unnecessary? \$\endgroup\$ – fireflame241 Jul 14 at 15:57
  • \$\begingroup\$ @fireflame241 Done. \$\endgroup\$ – user92069 Jul 15 at 13:24
3
\$\begingroup\$
| |
\$\endgroup\$
  • \$\begingroup\$ What's the upper limit of the output string Y? \$\endgroup\$ – user92069 Jul 25 at 5:24
  • \$\begingroup\$ @Third-party'Chef' Y is a programming language not a string. \$\endgroup\$ – Wheat Wizard Jul 25 at 12:31
  • \$\begingroup\$ Sorry, I meant X. \$\endgroup\$ – user92069 Jul 25 at 12:32
  • \$\begingroup\$ @Third-party'Chef' I didn't put an upper limit, but its length is your score so longer means worse score. Is there some issue I am not seeing that means an upper limit is needed. \$\endgroup\$ – Wheat Wizard Jul 25 at 12:36
3
\$\begingroup\$

Is this Chessboard Reachable?

The goal of this challenge is to determine, given the state of a chessboard, whether or not that chessboard can actually be reached in the course of standard play. Of course, doing this in general is a rather hard problem, so we'll be simplifying the problem to a set of a few rules which should approximate the "reachability" constraint.

Your input will be a chessboard, specifying what pieces are at what positions on the 8x8 board. At each position, there can be either nothing or a piece. If there is a piece, it is either a pawn, bishop, knight, rook, queen, or king, and it is either white or black. Input can be taken in any reasonable form. Your output should be truthy or falsy, indicating whether all of the below rules are satisfied.

For the below rules, I'll be using standard chess notation to refer to the squares on the board. That is, I'll be referring to squares on the board by their rank (1-8) and their file (a-h), as such

 8........
 7........
 6........
 5........
 4........
 3........
 2........
 1........
  abcdefgh

where the white player starts on ranks 1-2 and the black player starts on ranks 7-8. Obviously, you don't have to use the same notation, and if it's easier for you to take the board input flipped or rotated, that's fine too as long as you specify it in your answer.

For one of the rules, you have to distinguish between white and black squares on the board. The board is layered with a checkerboard pattern, so white squares are always immediately surrounded by black on all four sides, and vice versa. In typical chess, the a1 square is black, but that doesn't really matter for the below criteria.

The Rules

In order for a board to be considered reachable, it must satisfy all of the following rules. This is , so you don't have to tell me which rule an unreachable board violated; all I expect of your output is a "yes" or a "no".

  1. White and black each have exactly one king on the board: no more, no less.

  2. Pawns cannot appear on rank 1 or rank 8.

  3. Each player has a maximum of 16 pieces on the board total. These pieces must be a subset of the following: 2 bishops, 2 rooks, 2 knights, 1 queen, 1 king, and 8 wildcards. The "wildcard" pieces can be any piece they please (since we assume pawns could have been promoted).

  4. For either player, if that player has at least two bishops, and those two bishops cannot have been promoted from pawns (i.e. they must be the "bishops" in rule 3, not the "wildcards"), then that player must have at least one bishop on a white square and at least one bishop on a black square.

  5. All of a player's pawns must be able to reach the square they're occupying. More formally, for each player, there must be an assignment (an injective function) from the set of that player's surviving pawns to the files (a-h) they started on, such that each pawn can reach its current position from its starting position with only forward and forward-diagonal movements.

Pawn Movements

Rule 5 may require some elaboration. Suppose a white pawn is on d5. Then it could have come from the following places (indicated by X)

 8........
 7........
 6........
 5...♙....
 4..XXX...
 3.XXXXX..
 2XXXXXXX.
 1........
  abcdefgh

So it could have started on a2, b2, c2, d2, e2, f2, or g2, but not h2. There must be an assignment of pawns to starting positions such that no two pawns started at the same position and every pawn can reach its current position from where it began. A black pawn follows the same rules but started on rank 7 and moves down rather than up. So a black pawn at the same position could have come from b7, c7, d7, e7, or f7, as follows.

 8........
 7.XXXXX..
 6..XXX...
 5...♟....
 4........
 3........
 2........
 1........
  abcdefgh

Notes

  • Only the rules above apply. Other complexities of a standard game of chess (in particular, castling or en passant) are not part of this problem and should not be considered.
  • This is , so the shortest solution wins.
  • Input can be taken in whatever form is most convenient. Output follows the usual rules, so any two distinct outputs for truthy/falsy are acceptable.
  • This is an oversimplification of the reachability problem in chess. As such, an answer which provably enumerates every chessboard and tests for membership is not correct.

Examples

Reachable chessboards (true):

 8♜♞♝♛♚♝♞♜
 7♟♟♟♟♟♟♟♟
 6........
 5........
 4........
 3........
 2♙♙♙♙♙♙♙♙
 1♖♘♗♕♔♗♘♖
  abcdefgh

 8........
 7........
 6........
 5........
 4........
 3........
 2..♚.....
 1.....♔..
  abcdefgh

 8........
 7.....♚..
 6.♛......
 5...♟....
 4........
 3.....♕..
 2........
 1...♔....
  abcdefgh

 8.....♚..
 7♟♟♟♟♟♟♟♟
 6........
 5........
 4........
 3........
 2♙♙♙♙♙♙♙♙
 1....♔...
  abcdefgh

 8.....♚...
 7♟♟♟♟♟♟♟♟
 6........
 5........
 4........
 3........
 2♙♙♙♙♙♙♙♙
 1....♔...
  abcdefgh

 8........
 7.♚......
 6...♕♕♕♕.
 5..♕....♕
 4..♕..♔.♕
 3.......♕
 2........
 1........
  abcdefgh

 8........
 7...♚.♟.♙
 6.♙.♙..♙.
 5.....♘..
 4.♕..♕♘♗♖
 3.....♘♗♖
 2..♕....♖
 1......♔.
  abcdefgh

 8♜..♛♚♜♜♜
 7♟♟♟♟♟♟..
 6........
 5........
 4........
 3........
 2♙♙♙♙♙♙♙♙
 1♖♘♗♕♔♗♘♖
  abcdefgh

 8♜♞♝♛♚♝♞♜
 7♟♟♟♟♟♟♟♟
 6........
 5........
 4........
 3........
 2♙♙♙♙♙♙♙.
 1♖♗♘♕♔♗♘♖
  abcdefgh

 8♛♛♛♛♛♛.♛
 7........
 6......♚.
 5.♝.♝....
 4.....♟..
 3........
 2..♖♖♖.♔.
 1........
  abcdefgh

 8.....♚..
 7........
 6........
 5........
 4........
 3.♙♙.....
 2..♙♙♙♙♙♙
 1.....♔..
  abcdefgh

 8.....♚..
 7........
 6........
 5........
 4........
 3.....♙..
 2...♙♙♙.♙
 1.....♔..
  abcdefgh

 8.....♚..
 7........
 6.♟♟♟♟...
 5.♟♟.....
 4........
 3........
 2........
 1.....♔..
  abcdefgh

Unreachable chessboards (false):

(Rule 1: Not enough kings)

 8........
 7........
 6........
 5........
 4........
 3........
 2........
 1........
  abcdefgh

(Rule 1: Too many kings)

 8♚♚♚♚♚♚♚♚
 7♚♚♚♚♚♚♚♚
 6♚♚♚♚♚♚♚♚
 5♚♚♚♚♚♚♚♚
 4♚♚♚♚♚♚♚♚
 3........
 2........
 1...♔....
  abcdefgh

(Rule 2: Bad white pawn placement)

 8.....♚..
 7♟♟♟♟♟♟♟♟
 6........
 5........
 4........
 3........
 2.♙♙♙♙♙♙♙
 1♙...♔...
  abcdefgh

(Rule 2: Bad black pawn placement)

 8.♟...♚..
 7♟.♟♟♟♟♟♟
 6........
 5........
 4........
 3........
 2♙♙♙♙♙♙♙♙
 1....♔...
  abcdefgh

(Rule 3: Too many white queens)

 8........
 7.♚......
 6...♕♕♕♕.
 5..♕....♕
 4..♕..♔.♕
 3..♕....♕
 2........
 1........
  abcdefgh

(Rule 3: Too many black pieces)

 8♜♞♝♛♚♝♞♜
 7♟♟♟♟♟♟♟♟
 6......♟.
 5........
 4........
 3........
 2♙♙♙♙♙♙♙♙
 1♖♘♗♕♔♗♘♖
  abcdefgh

(Rule 3: Too many white pieces)

 8........
 7...♚.♙.♙
 6.♙.♙..♙.
 5.....♘..
 4.♕..♕♘♗♖
 3.....♘♗♖
 2..♕....♖
 1......♔.
  abcdefgh

(Rule 3: Too many black rooks)

 8♜..♛♚♜♜♜
 7♟♟♟♟♟♟♟.
 6........
 5........
 4........
 3........
 2♙♙♙♙♙♙♙♙
 1♖♘♗♕♔♗♘♖
  abcdefgh

(Rule 4: White bishops are the same color)

 8♜♞♝♛♚♝♞♜
 7♟♟♟♟♟♟♟♟
 6........
 5........
 4........
 3........
 2♙♙♙♙♙♙♙♙
 1♖♗♘♕♔♗♘♖
  abcdefgh

(Rule 4: Black bishops are the same color)

 8♛♛♛♛♛♛♛♛
 7........
 6......♚.
 5.♝.♝....
 4.....♟..
 3........
 2..♖♖♖.♔.
 1........
  abcdefgh

(Rule 5: White pawn placement is impossible)

 8.....♚..
 7........
 6........
 5........
 4........
 3..♙.....
 2.♙♙♙♙♙♙♙
 1.....♔..
  abcdefgh

(Rule 5: White pawn placement is impossible)

 8.....♚..
 7........
 6........
 5........
 4........
 3.....♙.♙
 2...♙♙♙.♙
 1.....♔..
  abcdefgh

(Rule 5: Black pawn placement is impossible)

 8.....♚..
 7.♟♟♟♟...
 6........
 5.♟♟.....
 4.♟♟.....
 3........
 2........
 1.....♔..
  abcdefgh

Example Implementation (Python 3)

# Takes input from stdin in the form shown above (a grid of Unicode
# chess characters and dots). Prints True if reachable. Prints False
# and the first rule number which is violated if unreachable.

import sys
from collections import defaultdict, namedtuple

Piece = namedtuple('Piece', ['color', 'type'])

# Read in the data from stdin.
data = []
for line in sys.stdin:
    chars = list(filter(lambda x: x in ".♟♙♝♗♞♘♜♖♛♕♚♔", line))
    if chars:
        data.append(chars)
    if len(data) == 8:
        break
assert len(data) == 8
for line in data:
    assert len(line) == 8

# Parse it into a more convenient format.
translation = {
    ".": None,
    "♟": Piece('black', 'pawn'),
    "♙": Piece('white', 'pawn'),
    "♝": Piece('black', 'bishop'),
    "♗": Piece('white', 'bishop'),
    "♞": Piece('black', 'knight'),
    "♘": Piece('white', 'knight'),
    "♜": Piece('black', 'rook'),
    "♖": Piece('white', 'rook'),
    "♛": Piece('black', 'queen'),
    "♕": Piece('white', 'queen'),
    "♚": Piece('black', 'king'),
    "♔": Piece('white', 'king'),
}
for rank in data:
    for i in range(8):
        rank[i] = translation[rank[i]]

# Count the number of each piece that each player has, slotting
# necessary pawn promotions into their own category.
allowed = { 'bishop': 2, 'rook': 2, 'knight': 2, 'king': 999, 'queen': 1, 'pawn': 0 }
pieces = defaultdict(lambda: 0)
for rank in data:
    for piece in rank:
        if piece is None:
            continue
        if pieces[piece] >= allowed[piece.type]:
            # Already have too many; it's a promoted pawn
            pieces[Piece(piece.color, 'pawn')] += 1
        else:
            # Count it normally
            pieces[piece] += 1

# Rule 1: Each color should have exactly one king.
if pieces[Piece('white', 'king')] != 1 or pieces[Piece('black', 'king')] != 1:
    print(False, 1)
    exit(0)

# Rule 2: Pawns cannot appear on rank 1 or rank 8.
for piece in data[0] + data[7]:
    if piece is not None and piece.type == 'pawn':
        print(False, 2)
        exit(0)

# Rule 3: Since we already put any "overflow" pieces at the pawn key,
# we just need to make sure we have at most eight pawns.
for color in ['white', 'black']:
    if pieces[Piece(color, 'pawn')] > 8:
        print(False, 3)
        exit(0)

# Rule 4: If we have both bishops and our pawns are all accounted for,
# then we have to have a bishop in each color.
for color in ['white', 'black']:
    if pieces[Piece(color, 'bishop')] >= 2 and pieces[Piece(color, 'pawn')] >= 8:
        squares = { 'white': False, 'black': False }
        for y, rank in enumerate(data):
            for x, piece in enumerate(rank):
                square_color = 'white' if (x + y) % 2 == 0 else 'black'
                if piece == Piece(color, 'bishop'):
                    squares[square_color] = True
        if not (squares['white'] and squares['black']):
            print(False, 4)
            exit(0)

# Rule 5: All pawns must be able to get to where they are. I solve
# this here by brute force (simply trying every possible permutation),
# which is exponentially inefficient, but it'll do for this example.
def recursive_assign(taken, choices, i):
    if i >= len(choices):
        return True
    current = choices[i]
    for x in current:
        if x not in taken:
            if recursive_assign(taken + [x], choices, i + 1):
                return True
    return False

for color in ['white', 'black']:
    starting_file = 6 if color == 'white' else 1
    choices = []
    for y, rank in enumerate(data):
        for x, piece in enumerate(rank):
            if piece == Piece(color, 'pawn'):
                possibilities = range(8)
                possibilities = filter(lambda i: abs(i - x) <= abs(y - starting_file), possibilities)
                choices.append(list(possibilities))
    if not recursive_assign([], choices, 0):
        print(False, 5)
        exit(0)

print(True)

Proposed Tags

Sandbox Concerns

  • I worry Rules 4 and 5 are still not clear enough. I tried to write them in a way that was as clear as possible while still being mathematically unambiguous.
| |
\$\endgroup\$
  • \$\begingroup\$ too long. try to combine rules or at least don't draw so many of them in a column \$\endgroup\$ – Noone AtAll Aug 4 at 9:06
  • 2
    \$\begingroup\$ If you're going to use unicode chess symbols, use a double-wide filler character instead of .. The alignment in your examples is off, making it very distracting. I'd recommend switching them to ASCII letters using the typical KQRBNP convention. \$\endgroup\$ – Beefster Aug 4 at 16:40
  • 2
    \$\begingroup\$ To add to Beefster's comment, in some fonts the chess symbols are not even double wide, they're somewhere in between. So double-wide fillers won't work either. +1 for ASCII notation. \$\endgroup\$ – Bubbler Aug 4 at 23:43
  • \$\begingroup\$ if I recall correctly, you can have two bishops of the same color. Up to nine. By promoting pawns to bishops. Very rare indeed, but legal. I want this to main page, though. \$\endgroup\$ – V. Courtois Aug 14 at 15:19
3
\$\begingroup\$

Road Sort Order

In Britain, road identifiers use a scheme of a letter, followed by a 1-4 digit number.

From Most-Important to Least-Important, the letters are:

M
A
B
C
D
U

The numbers also represent further assumptions around the importance of the road, such that a 1-digit number is more important than a 4-digit number.

Thus, the M898 is less important than the M8, but more important than the A8.

interesting but not relevant for the challenge - Roads are also sorted into nine Zones, of equal importance. The first number in each road identifier gives the Zone that the road starts in (e.g. A8 starts in Zone 8 - although there are exceptions where one Motorway spurs off of another, e.g. M48 is so named because it is a spur of the M4 even though it is officially in Zone 5).

The challenge

Given a pair of road identifiers, identify and output which is the most important road. Where there is no difference in importance by the above rules (e.g "B4063" and "B1234") then either output is acceptable.

Usual I/O rules apply, this is so lowest bytes wins. There will be two inputs, and no invalid inputs (i.e. they will follow the rules, although they may not be actual real-life roads).

If you say so in your answer, you may instead output the least significant road (i.e. as long as I know which it is, you can do either).

You may take the input as a string, array of strings, or array of strings and integers as follows:

"M123M223"
["M123","M223"]
["M",123,"M",223]

#SANDBOX# If there are input formats that you think should/n't be allowed, let me know.

Examples

  • A11,M2 -> M2(Motorways come before A roads)
  • M823,M89 -> M89 (two-digit roads are more important than 3-digit roads, even though 89 alphabetically comes after 823)
  • A1262,A150 -> A150
  • U6340,D6340 -> D6340
  • M1,M2 -> Either
  • B100,C99 -> B100
| |
\$\endgroup\$
  • 1
    \$\begingroup\$ I'd suggest simplifying sorting to just comparing two distinct values. Or even, mapping a value to a number so that the comparisons are right. \$\endgroup\$ – xnor Aug 4 at 19:56
  • \$\begingroup\$ @xnor sorry I'm not sure what you mean. Do you mean only ever have two inputs? \$\endgroup\$ – simonalexander2005 Aug 5 at 7:25
  • \$\begingroup\$ Yes, like have a possible input be like f("A11","M2") with it being a decision problem to tell if the first or second one is more important. Or, just have us write a function g producing a number so that, say, g("A11")>g("M2"). \$\endgroup\$ – xnor Aug 5 at 21:11
  • \$\begingroup\$ @xnor how's that? I've made it return the most (or least) significant road of a pair \$\endgroup\$ – simonalexander2005 Aug 6 at 7:34
  • \$\begingroup\$ Looks good! I'm a bit worried about the "any sensible format" since counting digits is important. Like, would a length-four array padded with nulls for missing digits count as acceptable? I think this would be you compare the number parts as a direct list comparison in some languages. \$\endgroup\$ – xnor Aug 7 at 3:15
3
\$\begingroup\$

Generalized Game Theory KOTH

Game Theory is a field of mathematics that is concerned with strategic interactions among 'rational decision-makers'. The main focus of game theory is the payoff-matrix.

A payoff matrix represents an interaction between two parties, and shows how many points a party can get if they choose different strategies. Here is an example of a payoff matrix:

             Player 1
             A  |   B
Player 2 +------+-------
       A | 3, 3 | 5, 1
         +------+-------
       B | 1, 5 | 2, 2

In this example, if player 1 chooses A and player 2 also chooses A, they would both get 3 points. If player 1 chooses B but player 2 chooses A, player would get 5 points but player 2 would only get 1.

The above payoff matrix is an example of the prisoners dilemma

The challenge

Programs will face off in a round-robin tournament. Each round will consist of a randomly generated payoff matrix, with both programs choosing either strategy A or strategy B. Programs will earn points accordingly. The winner will be the program with the most points, with ties broken by source code length.

Questions for meta:

  • best practices for creating KOTH challenges?
    • language considerations? I'm most comfortable with javascript but am also capable of writing in python
    • is it better to limit a KOTH to one language? it's easier to manage but limits who can submit
    • or allow multiple languages? It allows more people to compete but is more difficult to judge
  • Any comments about the overall problem?
    • Has this been done before?
| |
\$\endgroup\$
  • 1
    \$\begingroup\$ 1-1) Either JS or Python should be fine. Both are popular here and you can share the controller's code on TIO so that others can easily run it. Some other KOTH writers tend to provide a visual interface, but it's completely optional. 1-2) KOTH is usually limited to one language since they have to compete through the controller. 2) I don't think it's done before. But tie-breaking by code golf is not a good idea (in fact, tie breaking is not necessary at all). \$\endgroup\$ – Bubbler Aug 19 at 0:29
  • \$\begingroup\$ Also, if you're planning to run through hundreds of payoff matrices, it will be more interesting to allow the programs to remember previous matches, so the whole competition looks like a generalized repeated game. \$\endgroup\$ – Bubbler Aug 19 at 0:32
  • \$\begingroup\$ @Bubbler In that case I will probably make the controller in javascript. And yes, the game will definitely be repeated and programs will be able to access the past history. thank you for your feedback :) \$\endgroup\$ – thesilican Aug 19 at 0:40
3
\$\begingroup\$

Is my triangle on the lattice?

Write a program or function which takes three positive integers \$a^2, b^2, c^2\$ and returns/outputs one value if there is, and a different value if there isn't, a triangle on the square lattice, whose sides' lengths are \$a, b, c\$. (Note that the side lengths are the square roots of the numbers read.). By "on the square lattice" I mean that its vertices are in the \$xy\$ plane, and their \$x\$ and \$y\$-coordinates are all integers.

Test cases:

  • 16 9 25: true (3-4-5 triangle)
  • 8 1 5: true (e.g. (0,0), (1,0), (2,2))
  • 5 10 13: true (e.g. (0,1), (1,3), (3,0); sides needn't be on grid lines)
  • 10 2 1: false (not a triangle: long side is too long for short sides to meet)
  • 4 1 9: false (not a triangle: three points in a straight line)
  • 3 2 1: false (triangle is on the cubic lattice but not the square lattice)
  • 3 7 1: false (triangle is on the hex lattice but not the square lattice)
  • 25 25 25: false (no such triangle on this lattice)
  • 5 5 4: true (isosceles is OK)
  • 15 15 12: false (OK shape, wrong size)
  • 25 25 20: true (OK shape and size; common prime factor 5 is OK)
| |
\$\endgroup\$
3
\$\begingroup\$

Posted

| |
\$\endgroup\$
  • \$\begingroup\$ I think that it will never. Assumes that it's easy to see whether the program is "two step away from being complete", the next user is never going to move it "one step away from being complete", since they can't win in that case. \$\endgroup\$ – user202729 Jul 24 at 16:36
  • \$\begingroup\$ I agree with @user202729 that it will never terminate in its current state. It would be more likely to terminate if: languages could be changed every answer; answers could not remove 3 characters (or weaken to maybe remove 1 character; presently it allows loops); maybe allow for more characters added per answer \$\endgroup\$ – fireflame241 Jul 24 at 19:24
  • \$\begingroup\$ @user202729 I've updated the rules to potentially avoid such loops \$\endgroup\$ – Lyxal Jul 25 at 7:14
  • \$\begingroup\$ @fireflame241 I've updated the rules to potentially avoid such loops \$\endgroup\$ – Lyxal Jul 25 at 7:14
  • \$\begingroup\$ Bonus for the first answer in Mornington Crescent? :-) \$\endgroup\$ – Luis Mendo Jul 25 at 10:07
  • \$\begingroup\$ @LuisMendo sure, imaginary brownie points it is \$\endgroup\$ – Lyxal Jul 25 at 10:29
  • \$\begingroup\$ All hail Lyxal, +1 \$\endgroup\$ – null Jul 25 at 11:04
  • 1
    \$\begingroup\$ I think it will not complete until an Unary answer is produced because you can simply replace all characters that are not as with a. A long string of as is seldom a useful program. (that is, extending user202729's comment: you don't have to see the "two step away from being complete" state, it's sufficient to find a large class of programs that are definitely not "one step from being complete") \$\endgroup\$ – the default. Jul 25 at 11:41
  • \$\begingroup\$ @mypronounismonicareinstate I've completely changed the rules of the challenge to make it model a more plausible game. \$\endgroup\$ – Lyxal Jul 28 at 4:35
3
\$\begingroup\$

Number size

Given a whole number \$< 100,\$ extend(or shorten) the number to have as many characters as it's value.

Inspired by this meme. Please tell me if there is anything I left out or failed to consider.

Rules

Take the whole number \$n\$, and write it in words(without spaces). i.e. 53 → fiftythree, not fivethree.

Then, do the following with the string:

  • If the string's length is lower than the number, repeat some of its characters in place until the length matches the number.
  • The first and last characters should not be repeated, and the numbers of repetitions of the other characters should differ by at most one (so you can repeat some of them 5 times and others 6 times, for example; it doesn't matter which ones exactly).
  • If the string's length is greater than the number, remove any of its characters except the first and last to make the length match the number.
  • The order of the letters in the string must be maintained.
  • Example:
50 → f[ift]y → 3 letters must be duplicated 16 times
61 → s[ixtyon]e → 5 letters must be duplicated 10 times, 1 character must be duplicated 9 times

Step by step run-through

Taking 11 as an example,

(formatted as word → length)

eleven → 6
 ^
elleven → 7
   ^
elleeven → 8
     ^
elleevven → 9
       ^
elleevveen → 10
  ^
ellleevveen → 11 (end)

Examples

2 → to
3 → the or tre or tee
4 → four
5 → fiive or fivve
7 → seevven or sevveen or seeveen 
10 → teeeeeeeen

Special cases:
0 → (Any null value/no output)
1 → o

Winning Criteria

This is . Shortest code in each language wins.

| |
\$\endgroup\$
  • \$\begingroup\$ Why isn't 3 "tre"? (also, I don't understand the "remove each of the characters uniformly" part) \$\endgroup\$ – the default. Aug 31 at 16:27
  • \$\begingroup\$ I shuld keep that separate. three can be the or tre. \$\endgroup\$ – Razetime Aug 31 at 16:28
  • 2
    \$\begingroup\$ Is fivie a valid output for 5? \$\endgroup\$ – Bubbler Sep 1 at 2:40
  • \$\begingroup\$ "so long as the order of the letters in the string remains the same." so no. @Bubbler \$\endgroup\$ – Razetime Sep 1 at 3:22
  • \$\begingroup\$ What do you mean by "duplicate uniformly"? Should all letters be repeated by the same amount (±1)? \$\endgroup\$ – Zgarb Sep 1 at 7:43
  • \$\begingroup\$ yes, that is pretty close to what I mean, @Zgarb. I'll make it clearer. \$\endgroup\$ – Razetime Sep 1 at 7:44
  • 2
    \$\begingroup\$ It's still not clear what is meant: the text says "uniformly" but also "in whatever way you like", and the example does it in a cyclic order. \$\endgroup\$ – Zgarb Sep 1 at 13:51
  • \$\begingroup\$ I hope it makes more sense now. @Zgarb \$\endgroup\$ – Razetime Sep 1 at 15:36
  • \$\begingroup\$ I suggest something like this: "If the string's length is lower than the number, repeat some of its characters in place until the length matches the number. The first and last characters should not be repeated, and the numbers of repetitions of the other characters should differ by at most one (so you can repeat some of them 5 times and others 6 times, for example; it doesn't matter which ones exactly). If the string's length is greater, remove any of its characters except the first and last to make the length match the number." \$\endgroup\$ – Zgarb Sep 2 at 10:25
  • \$\begingroup\$ Thanks for the modification. I've put it in bullet points. \$\endgroup\$ – Razetime Sep 2 at 10:40
  • \$\begingroup\$ sorry about that, fixed it, \$\endgroup\$ – Razetime Sep 3 at 11:13
  • \$\begingroup\$ Do we really have to support the edge case 100? \$\endgroup\$ – Arnauld Sep 3 at 11:25
  • \$\begingroup\$ It doesn't make too much of a change from the challenge, I'll keep it till 99. \$\endgroup\$ – Razetime Sep 3 at 11:26
  • \$\begingroup\$ Looks pretty good. A few small things: (1) 'write it in words(without spaces)' do you mean with or without spaces? You have both 'fifty three' and (later) 'sixtyone'. (2) 'Taking 20 as an example' -> 'Taking 11 as an example'. (3) For the 61 example, 5 letters must be duplicated 10 times and 1 character must be duplicated 9 times. \$\endgroup\$ – Dingus Sep 4 at 1:24
  • 1
    \$\begingroup\$ It's unfortunate that answers will probably spend most of their bytes getting the word for the input number, rather than the actual stretching. I'd consider having the word being stretched be a separate input or something. \$\endgroup\$ – xnor Sep 6 at 8:33
1
11 12
13
14 15
100

You must log in to answer this question.

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