557
\$\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 requires more feedback, but it's been ignored, you can ask for feedback in The Nineteenth Byte. It's not only allowed, but highly recommended! Be patient and try not to nag people though, you might have to ask multiple times.

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

3992 Answers 3992

1
70 71
72
73 74
134
1
\$\begingroup\$

Create a program that may or may not determine if a list is in this sequence

Your task is to write a program which returns another program which has a nonzero chance of correctly determining if an inputted list is in a sequence described below. This can either be done through randomly generating a program, which will occasionally do the correct task, or through hardcoding a program that always works and returning that.

The sequence

The sequence you'll need to identify starts with the following items:

well the sequence I was gonna use turns out to have a closed form formula so frick

\$\endgroup\$
2
  • \$\begingroup\$ What was the idea here? Was it going to be something uncomputable? Could this still be salvaged with a new sequence? Also, what stops you from submitting like print(random(0,1)) or whatever \$\endgroup\$ May 16 at 20:06
  • 1
    \$\begingroup\$ @thejonymyster Basically, you try to write a program that will randomly generate (sometimes) executable code. So there's a very small chance you'll get something which actually does solve the problem (checking if something's in a sequence, in this case), which is longer than the program which randomly generated it. \$\endgroup\$ May 16 at 20:18
1
\$\begingroup\$

Binary Palindromes

Take an input of a positive integer and determine if the binary representation of that number is palindromic. Except for 0 (which is not in the scope of this problem), all binary palindromes are odd, so you do not have to worry about leading/trailing zeroes.

OEIS Sequence: https://oeis.org/A006995

This is code-golf, so shortest answer in bytes wins.

Test Cases

1 -> True (1)
4 -> False (100)
85 -> True (1010101)
131 -> False (10000011)
\$\endgroup\$
4
  • \$\begingroup\$ I personally think this question is trivial, but I may be wrong so I didn't downvote it. \$\endgroup\$ May 10 at 14:23
  • \$\begingroup\$ take this as an answer, str(bin(n))[2:][::-1]==str(bin(n))[2:] \$\endgroup\$ May 10 at 14:26
  • \$\begingroup\$ Very closely related: codegolf.stackexchange.com/questions/216929/based-palindromes. May even be considered duplicate by some? Better wait for input from other users and/or ask in chat. \$\endgroup\$
    – pajonk
    May 10 at 19:30
  • \$\begingroup\$ Didn't see that one because I searched specifically for binary. Will ask in chat. \$\endgroup\$
    – Romanp
    May 10 at 19:32
1
\$\begingroup\$

King of the Hill: Greed Control

What is Greed Control

Greed control is a multiplayer round-based game in which in every round, a player bet a number inside a specific range, say 1~100. Say 2 people betted 100, then they'd both get 100/2 which is 50 points in the game. Basically, the players that choose the same number split the scores evenly (no rounding) and the total of their net score gain is the number they chose.

After a set number of rounds, players compare scores. The highest score generally wins the game overall.

Your challenge

Build a bot in python, specifically, python 3 , that when given input, discussed in the section input, they give the number as an integer they bet as output. It must be afunction.

Input

information, points, round_number, sum_of_all, user_num. information is a dictionary with integer keys in which each key's value is the number of bots that chose that key's number last round. points is the list of integers you can choose from. round_number is the round number. sum_of_all is like information, except it is the summation of all rounds. user_num is the number of players playing.

We guarantee that

We guarantee that points stay the same every round and is strictly increasing, all integers. However, it may not be consecutive.

Controller function


from random import choice

def random_better(information, points, round_number, sum_of_all, user_num):
    return choice(points)

def greedy_better(information, points, round_number, sum_of_all, user_num):
    return points[-1]

def calculator(information, points, round_number, sum_of_all, user_num):
    return sorted(points, key=lambda x:x/(information[x]+0.000000000001))[0]

def smarty(information, points, round_number, sum_of_all, user_num):
    return sorted(points, key=lambda x:x/(information[x]+0.000000000001))[choice(range(1,40))]

users = [random_better, greedy_better, calculator, smarty] * 10

user_names = [user.__name__.replace('_',' ') for user in users]
rounds = 1000
points = sorted(list(range(1,101)))
user_num = len(users)
bots = [user for user in users]
scores = [0.0 for user in users]
information = {i:0 for i in points}
sum_of_all = {i:0 for i in points}
print('\n'*100)

for round_number in range(rounds):
    choices = [bot(information, points, round_number, sum_of_all, user_num) for bot in bots]
    information = {score:choices.count(score) for score in points}
    scores = [scores[index] + choices[index]/information[choices[index]] for index in range(user_num)]

    print(f'\n\n\nRound #{round_number+1} Reports: ')

    print('\nBots Report: ')
    print('\n'.join([f'{user_names[index].ljust(20)} '
                     f'chose {choices[index]} '
                     f'and got {choices[index]/information[choices[index]]} additional points, '
                     f'making it now have {scores[index]} points!!! ' for index in range(user_num)]))

    print('\nDistribution Report: ')
    print('\n'.join([f'The number of bots who chose {num} is: {information[num]}!!! ' for num in points]))

    print('\nLeaderboard Report: ')
    sorted_list = sorted(range(user_num), key=lambda x: -scores[x])

    print(f'\n{user_names[sorted_list[0]].ljust(20)} with {scores[sorted_list[0]]} points, '
          f'\n{user_names[sorted_list[1]].ljust(20)} with {scores[sorted_list[1]]} points, and'
          f'\n{user_names[sorted_list[2]].ljust(20)} with {scores[sorted_list[2]]} points!!! ')

    sum_of_all = {i:sum_of_all[i]+information[i] for i in points}

print('\n\n\nFinal Report Card: \n')
print('\n'.join([f'{user_names[sorted_list[index]].ljust(20)}: '
                 f'{scores[sorted_list[index]]} points. ' for index in range(user_num)]))

The first part is imports. You may only depend on default python built-ins or the python standard library. Or if you manage to hide it and I out of coincidence have the package...

The second part is your functions. Naming your function bot_name_with_underscores is encouraged.

The third part are game parameters. The number of rounds, the accessible outputs, etc.

The fourth part is running the program!!!

An example output is as follows:


Round #1 Reports: 

Bots Report: 
random better        chose 3 and got 1.5 additional points, making it now have 1.5 points!!! 
greedy better        chose 10 and got 10.0 additional points, making it now have 10.0 points!!! 
calculator           chose 1 and got 1.0 additional points, making it now have 1.0 points!!! 
smarty               chose 3 and got 1.5 additional points, making it now have 1.5 points!!! 

Distribution Report: 
The number of bots who chose 1 is: 1!!! 
The number of bots who chose 2 is: 0!!! 
The number of bots who chose 3 is: 2!!! 
The number of bots who chose 4 is: 0!!! 
The number of bots who chose 5 is: 0!!! 
The number of bots who chose 6 is: 0!!! 
The number of bots who chose 7 is: 0!!! 
The number of bots who chose 8 is: 0!!! 
The number of bots who chose 9 is: 0!!! 
The number of bots who chose 10 is: 1!!! 

Leaderboard Report: 

greedy better        with 10.0 points, 
random better        with 1.5 points, and
smarty               with 1.5 points!!! 



Round #2 Reports: 

Bots Report: 
random better        chose 7 and got 7.0 additional points, making it now have 8.5 points!!! 
greedy better        chose 10 and got 5.0 additional points, making it now have 15.0 points!!! 
calculator           chose 1 and got 1.0 additional points, making it now have 2.0 points!!! 
smarty               chose 10 and got 5.0 additional points, making it now have 6.5 points!!! 

Distribution Report: 
The number of bots who chose 1 is: 1!!! 
The number of bots who chose 2 is: 0!!! 
The number of bots who chose 3 is: 0!!! 
The number of bots who chose 4 is: 0!!! 
The number of bots who chose 5 is: 0!!! 
The number of bots who chose 6 is: 0!!! 
The number of bots who chose 7 is: 1!!! 
The number of bots who chose 8 is: 0!!! 
The number of bots who chose 9 is: 0!!! 
The number of bots who chose 10 is: 2!!! 

Leaderboard Report: 

greedy better        with 15.0 points, 
random better        with 8.5 points, and
smarty               with 6.5 points!!! 



Round #3 Reports: 

Bots Report: 
random better        chose 4 and got 4.0 additional points, making it now have 12.5 points!!! 
greedy better        chose 10 and got 10.0 additional points, making it now have 25.0 points!!! 
calculator           chose 1 and got 1.0 additional points, making it now have 3.0 points!!! 
smarty               chose 2 and got 2.0 additional points, making it now have 8.5 points!!! 

Distribution Report: 
The number of bots who chose 1 is: 1!!! 
The number of bots who chose 2 is: 1!!! 
The number of bots who chose 3 is: 0!!! 
The number of bots who chose 4 is: 1!!! 
The number of bots who chose 5 is: 0!!! 
The number of bots who chose 6 is: 0!!! 
The number of bots who chose 7 is: 0!!! 
The number of bots who chose 8 is: 0!!! 
The number of bots who chose 9 is: 0!!! 
The number of bots who chose 10 is: 1!!! 

Leaderboard Report: 

greedy better        with 25.0 points, 
random better        with 12.5 points, and
smarty               with 8.5 points!!! 



Round #4 Reports: 

Bots Report: 
random better        chose 6 and got 6.0 additional points, making it now have 18.5 points!!! 
greedy better        chose 10 and got 10.0 additional points, making it now have 35.0 points!!! 
calculator           chose 1 and got 1.0 additional points, making it now have 4.0 points!!! 
smarty               chose 2 and got 2.0 additional points, making it now have 10.5 points!!! 

Distribution Report: 
The number of bots who chose 1 is: 1!!! 
The number of bots who chose 2 is: 1!!! 
The number of bots who chose 3 is: 0!!! 
The number of bots who chose 4 is: 0!!! 
The number of bots who chose 5 is: 0!!! 
The number of bots who chose 6 is: 1!!! 
The number of bots who chose 7 is: 0!!! 
The number of bots who chose 8 is: 0!!! 
The number of bots who chose 9 is: 0!!! 
The number of bots who chose 10 is: 1!!! 

Leaderboard Report: 

greedy better        with 35.0 points, 
random better        with 18.5 points, and
smarty               with 10.5 points!!! 



Round #5 Reports: 

Bots Report: 
random better        chose 2 and got 2.0 additional points, making it now have 20.5 points!!! 
greedy better        chose 10 and got 10.0 additional points, making it now have 45.0 points!!! 
calculator           chose 1 and got 1.0 additional points, making it now have 5.0 points!!! 
smarty               chose 6 and got 6.0 additional points, making it now have 16.5 points!!! 

Distribution Report: 
The number of bots who chose 1 is: 1!!! 
The number of bots who chose 2 is: 1!!! 
The number of bots who chose 3 is: 0!!! 
The number of bots who chose 4 is: 0!!! 
The number of bots who chose 5 is: 0!!! 
The number of bots who chose 6 is: 1!!! 
The number of bots who chose 7 is: 0!!! 
The number of bots who chose 8 is: 0!!! 
The number of bots who chose 9 is: 0!!! 
The number of bots who chose 10 is: 1!!! 

Leaderboard Report: 

greedy better        with 45.0 points, 
random better        with 20.5 points, and
smarty               with 16.5 points!!! 



Round #6 Reports: 

Bots Report: 
random better        chose 3 and got 3.0 additional points, making it now have 23.5 points!!! 
greedy better        chose 10 and got 10.0 additional points, making it now have 55.0 points!!! 
calculator           chose 1 and got 1.0 additional points, making it now have 6.0 points!!! 
smarty               chose 2 and got 2.0 additional points, making it now have 18.5 points!!! 

Distribution Report: 
The number of bots who chose 1 is: 1!!! 
The number of bots who chose 2 is: 1!!! 
The number of bots who chose 3 is: 1!!! 
The number of bots who chose 4 is: 0!!! 
The number of bots who chose 5 is: 0!!! 
The number of bots who chose 6 is: 0!!! 
The number of bots who chose 7 is: 0!!! 
The number of bots who chose 8 is: 0!!! 
The number of bots who chose 9 is: 0!!! 
The number of bots who chose 10 is: 1!!! 

Leaderboard Report: 

greedy better        with 55.0 points, 
random better        with 23.5 points, and
smarty               with 18.5 points!!! 



Round #7 Reports: 

Bots Report: 
random better        chose 8 and got 8.0 additional points, making it now have 31.5 points!!! 
greedy better        chose 10 and got 10.0 additional points, making it now have 65.0 points!!! 
calculator           chose 1 and got 1.0 additional points, making it now have 7.0 points!!! 
smarty               chose 3 and got 3.0 additional points, making it now have 21.5 points!!! 

Distribution Report: 
The number of bots who chose 1 is: 1!!! 
The number of bots who chose 2 is: 0!!! 
The number of bots who chose 3 is: 1!!! 
The number of bots who chose 4 is: 0!!! 
The number of bots who chose 5 is: 0!!! 
The number of bots who chose 6 is: 0!!! 
The number of bots who chose 7 is: 0!!! 
The number of bots who chose 8 is: 1!!! 
The number of bots who chose 9 is: 0!!! 
The number of bots who chose 10 is: 1!!! 

Leaderboard Report: 

greedy better        with 65.0 points, 
random better        with 31.5 points, and
smarty               with 21.5 points!!! 



Round #8 Reports: 

Bots Report: 
random better        chose 1 and got 0.5 additional points, making it now have 32.0 points!!! 
greedy better        chose 10 and got 5.0 additional points, making it now have 70.0 points!!! 
calculator           chose 1 and got 0.5 additional points, making it now have 7.5 points!!! 
smarty               chose 10 and got 5.0 additional points, making it now have 26.5 points!!! 

Distribution Report: 
The number of bots who chose 1 is: 2!!! 
The number of bots who chose 2 is: 0!!! 
The number of bots who chose 3 is: 0!!! 
The number of bots who chose 4 is: 0!!! 
The number of bots who chose 5 is: 0!!! 
The number of bots who chose 6 is: 0!!! 
The number of bots who chose 7 is: 0!!! 
The number of bots who chose 8 is: 0!!! 
The number of bots who chose 9 is: 0!!! 
The number of bots who chose 10 is: 2!!! 

Leaderboard Report: 

greedy better        with 70.0 points, 
random better        with 32.0 points, and
smarty               with 26.5 points!!! 



Round #9 Reports: 

Bots Report: 
random better        chose 3 and got 3.0 additional points, making it now have 35.0 points!!! 
greedy better        chose 10 and got 5.0 additional points, making it now have 75.0 points!!! 
calculator           chose 1 and got 1.0 additional points, making it now have 8.5 points!!! 
smarty               chose 10 and got 5.0 additional points, making it now have 31.5 points!!! 

Distribution Report: 
The number of bots who chose 1 is: 1!!! 
The number of bots who chose 2 is: 0!!! 
The number of bots who chose 3 is: 1!!! 
The number of bots who chose 4 is: 0!!! 
The number of bots who chose 5 is: 0!!! 
The number of bots who chose 6 is: 0!!! 
The number of bots who chose 7 is: 0!!! 
The number of bots who chose 8 is: 0!!! 
The number of bots who chose 9 is: 0!!! 
The number of bots who chose 10 is: 2!!! 

Leaderboard Report: 

greedy better        with 75.0 points, 
random better        with 35.0 points, and
smarty               with 31.5 points!!! 



Round #10 Reports: 

Bots Report: 
random better        chose 2 and got 2.0 additional points, making it now have 37.0 points!!! 
greedy better        chose 10 and got 5.0 additional points, making it now have 80.0 points!!! 
calculator           chose 1 and got 1.0 additional points, making it now have 9.5 points!!! 
smarty               chose 10 and got 5.0 additional points, making it now have 36.5 points!!! 

Distribution Report: 
The number of bots who chose 1 is: 1!!! 
The number of bots who chose 2 is: 1!!! 
The number of bots who chose 3 is: 0!!! 
The number of bots who chose 4 is: 0!!! 
The number of bots who chose 5 is: 0!!! 
The number of bots who chose 6 is: 0!!! 
The number of bots who chose 7 is: 0!!! 
The number of bots who chose 8 is: 0!!! 
The number of bots who chose 9 is: 0!!! 
The number of bots who chose 10 is: 2!!! 

Leaderboard Report: 

greedy better        with 80.0 points, 
random better        with 37.0 points, and
smarty               with 36.5 points!!! 



Final Report Card: 

greedy better       : 80.0 points. 
random better       : 37.0 points. 
smarty              : 36.5 points. 
calculator          : 9.5 points. 

If any bot runs into an error,

it fails. So CHECK IT!!! Make it FOOLPROOF!!!

Winner

This is .

\$\endgroup\$
3
  • 2
    \$\begingroup\$ I feel like you need a bit better explanation of how Greed Control scoring works, but otherwise, it looks pretty good. \$\endgroup\$
    – Romanp
    May 12 at 14:52
  • 4
    \$\begingroup\$ Also, please reduce the number of exclamation points and bold chars in your post. IMO it makes it look childish and something like the stereotypical plz send teh codez \$\endgroup\$
    – Seggan
    May 12 at 15:17
  • \$\begingroup\$ I'm childish... I'm 13... Hahaha \$\endgroup\$ May 13 at 1:20
1
\$\begingroup\$

Cross of Numbers

Given a number n as input, output an ASCII cross composed of numbers counting up to that length. Counting starts at 0 in the center, and numbers with more than one digit simply have their digits printed in order in the correct direction.

Example for n=12:

               2
               1
               1
               1
               0
               1
               9
               8
               7
               6
               5
               4
               3
               2
               1
2111019876543210123456789101112
               1
               2
               3
               4
               5
               6
               7
               8
               9
               1
               0
               1
               1
               1
               2

Meta

Is this appropriate for ?

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

Categorising categories

A category is an abstract mathematical object whose actual meaning is not really important here. A category can be viewed as a directed graph with the following restrictions:

  • every node in the graph has at least one edge from and to itself
  • for every pair of edges which share an intermediate node (like \$ a \rightarrow b \$ and \$ b \rightarrow c \$), there must exist an edge which is their composition, like \$ a \rightarrow c \$

More mathematically, where \$ E(a, b) \$ means "there exists an edge from \$ a \$ to \$ b \$": $$ \forall a \in G. E(a, a) \\ \forall a, b, c \in G. E(a, b) \vee E(b, c) \implies E(a,c) $$

Your task is to determine whether a given directed graph satisfies the above restrictions.

I/O

You may take input using any reasonable representation of a graph, such as:

  • an edge list
  • an adjacency list
  • an adjacency matrix
  • a built-in directed graph type

You may assume there are no duplicate edges (but note that the edge \$ a \rightarrow b \$ is not the same as \$ b \rightarrow a \$)

Nodes will be represented by positive integers starting from \$ 1 \$, i.e., elements of the range \$ [1, n] \$, where \$ n \$ is the number of nodes. You may optionally also take \$ n \$ as a second input.

You should output one of two distinct values of your choosing, which correspond to true and false results.

Rules


Meta

  • Should I remove the first requirement ("every node in the graph has at least one edge from and to itself")? I think it doesn't add much to the challenge, but then it's less directly related to category theory and I can't use the funny title
  • Is this clear enough?
  • Any other feedback?
\$\endgroup\$
1
  • \$\begingroup\$ I know it's not really relevant to the challenge itself, but "A category can be viewed as a directed graph with the following restrictions:", this might be technically true, but it certainly is misleading. It's sort of like saying that a group can be viewed as a set. It's missing sort of the most important property. \$\endgroup\$
    – Wheat Wizard Mod
    May 17 at 12:50
1
\$\begingroup\$

Make an Apartment Building

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

LOOOOONG TEEEEEXT

\$\endgroup\$
2
  • \$\begingroup\$ How do you determine what a vowel is? I assume the question cares about letters not phonemes, so is it aeiou? You test cases imply that y and w, which are sometimes vowel letters, are not treated as vowel however is this a universal? \$\endgroup\$
    – Wheat Wizard Mod
    May 12 at 8:52
  • \$\begingroup\$ Oops, guess I should specify that... \$\endgroup\$ May 12 at 9:16
1
\$\begingroup\$

Solve the Zany car game

\$\endgroup\$
1
  • \$\begingroup\$ I think letting people choose input format may lead to more interesting solutions. \$\endgroup\$
    – pajonk
    May 16 at 7:48
1
\$\begingroup\$

Is it a good chord?

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

Sell cinema tickets

Or in other words, print out a numbered grid from bottom-middle to top-middle.

Challenge

Most people think that, in a cinema, the back seats and the middle ones are the best.
You'll be receiving the number of seats across and vertically in the theater, your job is to sell the tickets in prioritized order, starting from the best seats to the worst.
The seats will be numbered from top-left to bottom-right.

Example

In: 3, 4

Seats:
1  2  3
4  5  6
7  8  9
10 11 12

Out: 11, 12, 10, 8, 9, 7, 5, 6, 4, 2, 3, 1

The order of the outer seats doesn't matter, as long as the distance to the middle seat in the row is the same.

Another Possible output: 11, 10, 12, 8, 7, 9, 5, 4, 6, 2, 1, 3
12: Priority 7
11: Priority 8
10: Priority 7
09: Priority 5
08: Priority 6
07: Priority 5
06: Priority 3
05: Priority 4
04: Priority 3
03: Priority 1
02: Priority 2
01: Priority 1

Rules

  • The number of seats across and vertically (in any order) should be received as the input
  • Output should be the seats numbered, sorted by their priority
  • Default Loopholes apply
\$\endgroup\$
1
\$\begingroup\$

But is it a pretty place?

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

Extract the contained powers of two!

\$\endgroup\$
3
  • 1
    \$\begingroup\$ The title is somewhat misleading, because the output is a list of matches, not "how many" (which would be the length of the list). \$\endgroup\$
    – pxeger
    May 30 at 15:54
  • 1
    \$\begingroup\$ I also suggest a test case which has a power of two as a subsequnce, but not a contiguous substring. e.g. 106 -> [1], not [1, 16]. Also, can the output may be in any order? \$\endgroup\$
    – pxeger
    May 30 at 15:56
  • \$\begingroup\$ Thanks!! I have added your suggested test case, and improved the title. \$\endgroup\$
    – Tuxysta
    May 30 at 17:48
1
\$\begingroup\$

Two In One: Guess That Language - Cops

Two In One: Guess That Language - Robbers

\$\endgroup\$
3
  • \$\begingroup\$ I suggest restrictions on languages (what is a valid language and what are different languages) to be taken from this challenge - this seems to be a nice and working consensus. \$\endgroup\$
    – pajonk
    May 30 at 10:01
  • \$\begingroup\$ Done @pajonk .. \$\endgroup\$ May 31 at 0:26
  • \$\begingroup\$ I've edited this down to a stub now that it's been posted to save space \$\endgroup\$ Jun 4 at 2:47
1
\$\begingroup\$

Sort my Cups

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

Parse Specification Data Structure Diagrams

Many protocol specifications illustrate the structure of data packets or file formats with ASCII tables. This helps to visualize the layout of the data in memory, a file, or how bits are transmitted "on the wire".

For example RFC 1035 section 4.1.1 describes the header of a DNS query with the following diagram:

                                1  1  1  1  1  1
  0  1  2  3  4  5  6  7  8  9  0  1  2  3  4  5
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|                      ID                       |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|                    QDCOUNT                    |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|                    ANCOUNT                    |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|                    NSCOUNT                    |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|                    ARCOUNT                    |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+

RFC-793 Tranmission Control Protocol contains the following diagram of a TCP packet header:

 0                   1                   2                   3
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|          Source Port          |       Destination Port        |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                        Sequence Number                        |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                    Acknowledgment Number                      |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|  Data |           |U|A|P|R|S|F|                               |
| Offset| Reserved  |R|C|S|S|Y|I|            Window             |
|       |           |G|K|H|T|N|N|                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|           Checksum            |         Urgent Pointer        |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                    Options                    |    Padding    |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                             data                              |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  • Wouldn't it be useful if we could automate the parsing of data buffers into the various fields based on these diagrams?

Challenge

Your job is to write code that can interpret these diagrams to parse a data buffer into the data fields.

  • Inputs will be a multi-line ASCII string following the format shown above, either an array of lines or a single string with linefeeds, and a data packet as an array of bytes.
  • The input diagram includes the two initial rows that number the bit offsets (note that zeros in the first row may or may not be present).
  • Bytes are in Big Endian ("network") order
  • Bit offsets are from MSb to LSb
  • The number of bits per row will be a power of 2 and at least one octet (byte). I.e. 8, 16, 32, 64.
  • For this challenge a single field will not span bytes from one row to the next.
  • Some cases will require multiple lines of input for a single row of bits to accommodate the field names. Field names are concatenated from the data in the field column over multiple rows. For example see the fourth row in the RFC-793 TCP packet header. Note when field name values butt up to the edge of the field, no space is inserted between the characters on consecutive rows, otherwise a single space is between the field name values on each row. See "Data Offset" vs. "ACK".
  • A single bit position could take two characters as in the ASCII diagram for the TCP packet header, or three as in the DNS query header. I.e. +-+ vs +--+
  • Output can be in decimal or hexadecimal with a '0x' prefix.

Example Input and Output

Example 1 - DNS Query Header

Input:

String diagram = """
                                1  1  1  1  1  1
  0  1  2  3  4  5  6  7  8  9  0  1  2  3  4  5
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|                      ID                       |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|                    QDCOUNT                    |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|                    ANCOUNT                    |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|                    NSCOUNT                    |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|                    ARCOUNT                    |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
""";
byte [] data = { 0x00, 0x00, 0x84, 0x80, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00 };

Output (in hexadecimal):

ID = 0x0
QR = 0x1
OpCode = 0x0
AA = 0x1
TC = 0x0
RD = 0x0
RA = 0x1
Z = 0x0
RCODE = 0x0
QDCOUNT = 0x0
ANCOUNT = 0x6
NSCOUNT = 0x0
ARCOUNT = 0x0

Example 2 - TCP Packet Header:

Input:

String diagram = """
 0                   1                   2                   3
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|          Source Port          |       Destination Port        |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                        Sequence Number                        |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                    Acknowledgment Number                      |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|  Data |           |U|A|P|R|S|F|                               |
| Offset| Reserved  |R|C|S|S|Y|I|            Window             |
|       |           |G|K|H|T|N|N|                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|           Checksum            |         Urgent Pointer        |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                    Options                    |    Padding    |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                             data                              |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
""";
byte [] data = { 0xc0, 0x01, 0xa4, 0x74,
                 0x00, 0x00, 0x00, 0x02,
                 0x00, 0x00, 0x00, 0x01,
                 0x60, 0x10, 0x00, 0x04,
                 0x39, 0x3a, 0x00, 0x00,
                 0x00, 0x00, 0x00, 0x00,
                 0x01, 0x02, 0x03, 0x04 };

Output (in decimal):

Source Port = 49253
Destination Port = 42100
Sequence Number = 2
Acknowledgment Number = 1
Data Offset = 24
Reserved = 0
URG = 0
ACK = 1
PSH = 0
PST = 0
SYN = 0
FIN = 0
Window = 4
Checksum = 14650
Urgent Pointer = 0
Options = 0
Padding = 0
data = 16909060

Understanding the tables:

+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|                      ID                       |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+

The above table section indicates that the 'ID' field is composed of the first 16-bits of the data packet (Big Endian), The 'QR' field is the high bit of the next byte, 'OpCode' comes from the next four highest bits of the same byte containing 'QR', The lower three bits of that byte contain the single-bit values for 'AA', 'TC', and 'RD'. 'RA' is the highest bit of the next byte, followed by 3-bits for 'Z'. The lower four bits of that byte hold the value for 'RCODE'.

+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|  Data |           |U|A|P|R|S|F|                               |
| Offset| Reserved  |R|C|S|S|Y|I|            Window             |
|       |           |G|K|H|T|N|N|                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

The above table has several fields whose field names could not fit within the table using only a single line for that row of bits. There are nine fields in these 32 bits. The upper four bits of the first byte is 'Data Offset', followed by six bits (the remaining four of the first byte, and the upper two bits of the next byte) for 'Reserved' (i.e. unused). The lower six bits of the second byte are for the six one-bit fields 'URG', 'ACK', 'PSH', 'RST, 'SYN', and finally 'FIN'. 'Window' is a 16-bit value made from the following two bytes (Big Endian).

i.e. pseudo code to unpack the data values for the above line:

Data_Offset = (data[0] & 0xf0) >> 4;
Reserved = ((data[0] & 0x0f) << 2) + ((data[1] & 0xc0) >> 6);
URG = (data[1] & 0x20) >> 5;
ACK = (data[1] & 0x10) >> 4;
PSH = (data[1] & 0x08) >> 3;
RST = (data[1] & 0x04) >> 2;
SYN = (data[1] & 0x02) >> 1;
FIN = data[1] & 0x01;
Window = (data[2] << 8) + data[3];

The field names themselves come from concatenating the characters within each "box". Where spaces are trimmed from both ends, and all other white space is collapsed to a single space. You may also use an underscore, a hyphen, or a dot ('_', '-', '.') instead of a space to separate words of a field name. You must use some separator between words, conversion to CamelCase or straight concatenation of words is not allowed. You must not alter the case of the field names as it may be significant.

The output must be printed or in the form of a single string that clearly pairs the field names and values. Consider readability for humans. I.e. a list of field names, followed by a list of values is NOT acceptable as this is too inconvenient for a human to find the right value for each field. You may use one field per line and '=' as I have shown above, a two column table, a text format similar to JSON, CSV, etc.. There must be distinct delimiters between the name and the value and between different field-value pairings, e.g. I used "=" and newlines. If you use a space between field name and field value, you must not use a space between words in the field name unless they are quoted or otherwise escaped so the output is unambiguous.

\$\endgroup\$
4
  • 1
    \$\begingroup\$ Could you please add a worked out example (maybe a simpler one)? I'm not familiar with the structure of the tables and I don't quite get what's going on. Also, please specify a winning criteria (code-golf I presume?) and consider relaxing I/O requirements (i.e. add "or any reasonable equivalent" that would include e.g. array of characters for input or binary for output). \$\endgroup\$
    – pajonk
    Jun 10 at 6:13
  • \$\begingroup\$ @pajonk I've editing for clarity. How is it now? \$\endgroup\$
    – swpalmer
    Jun 10 at 15:48
  • \$\begingroup\$ Yes, looks better now. What types of output are acceptable apart from the format you show? - I suggest anything that will unambiguously identify the names and values (including but not limited to: named list, names and values space/comma separated, two lists (one with names, second with values), dataframe with two columns) \$\endgroup\$
    – pajonk
    Jun 10 at 18:11
  • \$\begingroup\$ @pajonk I've clarified the output requirements. \$\endgroup\$
    – swpalmer
    Jun 10 at 22:01
1
\$\begingroup\$

Flatten from the inside out

Say we have a ragged list

[ 
  [1, 2],
  [3,
    [4, 5]
  ],
]

And we want to flatten it by a layer, decreasing its depth by 1. We could flatten it from the outside:

[1, 2, 3, [4, 5]]

Or, we could flatten it from the inside.

To do this, take all subarrays with maximal depth, and disperse each into its parent array. For example, with the array [[1, 2], [3, [4, 5]]], the [4, 5] has maximal depth, so the array becomes [[1, 2], [3, 4, 5]].

Your challenge is to, given a list, flatten it from the inside by one level. The list will only contain nonnegative integers, and will not contain empty lists.

This is , shortest wins!

Testcases

[[1, 2], [3, [4, 5]]] -> [[1, 2], [3, 4, 5]]
[[6, 3, [1, 3, 4]], 4, [2, 3, 9, [5, 6]]] -> [[6, 3, 1, 3, 4], 4, [2, 3, 9, 5, 6]]
[[[3]], [4, [5]]] -> [[3], [4, 5]]
[[[[[[[[1]]]]]]]] -> [[[[[[[1]]]]]]]
\$\endgroup\$
0
1
\$\begingroup\$

Am I winning at O-Tris?

O-Tris is a very, very, very simplified version of Tetris, which is defined as follows:

There is a grid of cells that is 6 cells wide and 7 cells tall, known as the Playfield. Cells in the Playfield can be either Active, Inactive, or Empty.

There is a construct called an O-piece, composed of 4 Active cells in a 2x2 arrangement. An O-piece will always exist somewhere in the Playfield, and two O-pieces cannot coexist.

There are three commands, Left, Right, and Idle. No other commands exist.

Gameplay is defined as follows:

The user inputs a series of commands at the start of the game, which are stored. The Playfield is then initialized with all Empty cells save for a single O-piece in the top center, as shown the diagram below, where . represents an Empty cell, # represents an Inactive cell, and O represents an Active cell:

..OO..
..OO..
......
......
......
......
......

Then, each command is processed one at a time. For each command, the following process occurs:

  • The first step depends on which command is read;
    • If the command is Left, no cell to the immediate left of an Active cell is Inactive, and no cell in the leftmost column of the Playfield is Active, then the rightmost two Active cells will become Empty, and the two Empty cells to the immediate left of each Active cell will become Active. (This is analogous to the O-piece moving left unless obstructed)
    • If the command is Right, no cell to the immediate right of an Active cell is Inactive, and no cell in the rightmost column of the Playfield is Active, then the leftmost two Active cells will become Empty, and the two Empty cells to the immediate right of each Active cell will become Active. (This is analogous to the O-piece moving right unless obstructed)
    • If the command was Idle, move directly to the next step.
  • Second step;
    • If the two cells immediately below each the bottommost Active cells are Empty and within the Playfield, those two Empty cells will become Active and the topmost Active cells will become Empty. (This is analogous to the O-piece moving down if unobstructed)
    • If not, the following subprocess occurs;
      • All Active cells will become Inactive.
      • Any rows of cells within the Playfield that are are composed of only Inactive cells will be reset to be all Empty cells, and every row above that row will be translated downward, leaving a row of Empty cells at the top of the grid. (Meta: is this well stated?)
      • The game will attempt to place a new O-piece in the top center of the Playfield, satisfying the requirement that an O-piece always exist. If any of the 4 cells is Inactive, this will fail, and the game will enter a Loss state, inform the player that they have lost, and halt. Otherwise, continue to the next step.
  • Third step;
    • If there are any remaining commands, return to step one and continue by reading the next command.
    • If no commands remain, the game will enter a Win state, inform the player that they have won, and halt.

Challenge

Your challenge is to take a series of commands and return whether they would Win or Lose at O-Tris. This is , so shortest code in bytes wins.

Input

Take a nonempty series of distinct values representing either the Left, Right, or Idle commands in any reasonable format. Assume no extraneous input.

Output

Output one of two distinct values represent either a Win state or a Loss state. No other output is required.

Examples

Using L as Left, R as Right, and I as Idle, 1 to indicate a Win state, and 0 to indicate a Loss state.

input => output
L => 1
LLLLLLLLLLLLLL => 1
IIIIIIIIIII => 1
IIIIIIIIIIII => 0
IIIIIIIIIIIIILLL => 0
LLIIIIRRIIIIIIIIIIIIIIIIIIIII => 1
LLIIIIRRIIIIIIIIIIIIIIIIIIIIII => 0
LLIIIIRRIIIILIIIRIIII => 1
LLIIIIRRIIIILIIIRIIIIR => 0
LLIIIIRRIIIILIIIRIIIRR => 1
LLIIIIRRIIIILIIIRIIIRRII => 0
LLIIIIRRIIIILIIIRIIIRRLLII => 1

(Meta: more test cases probably, specifically one where lines are cleared with blocks above it and that clear saves the player from losing)

Meta

Should I provide more diagrams? If so, where?

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

Speed up, slowpoke!

\$\endgroup\$
19
  • 1
    \$\begingroup\$ (No, Slowpoke will only speed up in Trick Room.) \$\endgroup\$
    – tsh
    Jun 10 at 7:20
  • 1
    \$\begingroup\$ How many bots will a game have? Speeding down others only makes one of other bots 10% slow than me. But speeding up myself makes all other bots 11% slow than me. So I see no reason to slow down others in current game specification. \$\endgroup\$
    – tsh
    Jun 10 at 7:23
  • 1
    \$\begingroup\$ Yes, exactly. I'll try to clarify. \$\endgroup\$
    – Tuxysta
    Jun 10 at 15:25
  • 1
    \$\begingroup\$ Done! <filler, text> \$\endgroup\$
    – Tuxysta
    Jun 11 at 19:12
  • 1
    \$\begingroup\$ The new controller script is here, with more examples. \$\endgroup\$ Jun 12 at 7:06
  • 1
    \$\begingroup\$ It can access a list, not dictionary, of all the bots in the games' functions + current scores + current turn frequency, including itself, represented as [bot_function, score_integer, frequency_float]. Additionally, it will receive itself, so it can differentiate himself from other bots. It can also access the round number (from 1 to 300). So, arg1 = [[bot,score,turn_freq] for bot in bots], arg2 = itself, and arg3 = round number which you didn't mention. \$\endgroup\$ Jun 12 at 7:09
  • 1
    \$\begingroup\$ That link ain't sending me anywhere; I just see a blank textbox. Otherwise, fixed! \$\endgroup\$
    – Tuxysta
    Jun 12 at 7:58
  • 1
    \$\begingroup\$ @23TuringMachine this link should be better. The old link redirects to a Chinese website. \$\endgroup\$ Jun 12 at 10:25
  • 1
    \$\begingroup\$ @23TuringMachine technically I prefer "NobodyNeedsNames" or NumberBasher but it probably doesn't matter anyhow. \$\endgroup\$ Jun 12 at 10:27
  • 1
    \$\begingroup\$ I would add it to PyPI when nothing will change. Gotta go to sleep now o/ \$\endgroup\$ Jun 12 at 10:28
  • 1
    \$\begingroup\$ Thank you @23TuringMachine, and maybe you can @ me when you are done so I can know (without having to navigate here), thanks!!! I would some time run it and upload a pic of the result. \$\endgroup\$ Jun 12 at 10:38
  • 1
    \$\begingroup\$ I'm not sure if you want to shuffle the info list. One reason for yes is it takes time. One reason for no is that it allows multiple bots to attack one specific bot. @23TuringMachine \$\endgroup\$ Jun 12 at 10:41
  • 1
    \$\begingroup\$ SLEEP TIME!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! \$\endgroup\$ Jun 12 at 10:42
  • 1
    \$\begingroup\$ Yeah, it'd probably be wise to shuffle it. We've time, after all. \$\endgroup\$
    – Tuxysta
    Jun 12 at 10:47
  • 1
    \$\begingroup\$ Let us continue this discussion in chat. \$\endgroup\$ Jun 12 at 11:20
1
\$\begingroup\$

Truncate words in a sentence

\$\endgroup\$
4
  • \$\begingroup\$ The second test case appears to treat dQw4w9WgXcQ as one single word, but it has digits in it. Should your definition of "word" be changed to include this? \$\endgroup\$
    – pxeger
    Jun 12 at 9:06
  • \$\begingroup\$ @pxeger Oops. Will fix \$\endgroup\$
    – emanresu A
    Jun 12 at 9:11
  • \$\begingroup\$ Is input always printable ASCII only? \$\endgroup\$
    – pxeger
    Jun 12 at 9:14
  • \$\begingroup\$ @pxeger yes. (filler) \$\endgroup\$
    – emanresu A
    Jun 12 at 9:15
1
\$\begingroup\$

Goroawase Numeric Substitution

Goroawase numeric substitution is a common form of Japanese wordplay where homophonous words are associated with a given series of numbers to associate a new meaning with that series. Your task is to take an input of a Japanese pronunciation and output a sequence of numbers from 1-10 which can be pronounced as the input in Japanese. For simplicity, only follow the table below.

Substitution Table

Number Kun'yomi readings On'yomi readings Transliterations from English readings
0 maru, ma, wa rei, re ō/ou, zero, ze
1 hitotsu, hito, hi ichi, i wan
2 futatsu, fu, futa, ha ni, ji, aru tsu, tsū/tsuu, tū/tuu
3 mittsu, mi san, sa, za su, surī/surii
4 yon, yo, yottsu shi fō/fou, fā/faa, ho
5 itsutsu, itsu, i go, ko faibu, faivu
6 muttsu, mu roku, ro, ri, ra shikkusu
7 nana, nanatsu, na shichi sebun, sevun
8 yattsu, ya hachi, ha, ba eito
9 kokonotsu, ko kyū/kyuu, ku nain
10 tō/tou, to, ta ju, ji ten

(taken from the above link)

Rules

  • Input and output can be in any convenient format, but it should be possible to tell the difference between 1 0 and 10. You can choose to take input in hiragana/katakana.
  • You can assume that the input will always be valid.
  • For inputs that could have multiple possible outputs (such as i being 1 or 5), any is acceptable.
  • Standard loopholes are forbidden.
  • This is , so the shortest code in bytes wins.
\$\endgroup\$
1
\$\begingroup\$

Is This Loss?

Given two shapes A and B in ASCII-art, determine if A appears within B.

A shape A appears in shape B if there is a way to overlay shape A onto shape B without covering any spaces that B is not already covering.

Rules

  • Standard I/O, any reasonable format etc. etc.
  • Input will only contain two symbols of your choosing (as well as newlines) and can be assumed to be padded out / without any padding if necessary.
  • Neither shape will ever be empty.
  • This is , so shortest code in bytes wins.

Examples

Shape A (will remain the same for the next few examples)

#       #
#       #  #

#  #    #
#  #    # ###

Shape(s) B

Truthy:

#       #
#       #  #

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

Falsy:

#
    #       #
 #  #       #

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

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

 #  #       #
    #       #

Non Loss example, for testing purposes:

Shape A

####

Shapes B

Truthy:

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

Falsy:

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

Meta:

Should I define anything more rigorously or is this clear as day?

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

Gray coded gray code convertor

\$\endgroup\$
7
  • 1
    \$\begingroup\$ This is an interesting restricted-source challenge, but I think the task of being Gray coder is not very interesting, because it's just a numeric formula. I wonder if you could change this into something more in the category of quine, self-validating, or more generally self-referential? Or maybe just to output a constant string, where the challenge comes from somehow encoding that string under these restrictions? \$\endgroup\$
    – pxeger
    Jun 12 at 9:23
  • 1
    \$\begingroup\$ I'd also suggest replacing the word "character" with "byte", because the "bits" of a character are not really a defined concept, without also defining a character encoding, in which case you probably care only about the bytes anyway. \$\endgroup\$
    – pxeger
    Jun 12 at 9:25
  • 1
    \$\begingroup\$ Finally, could you specify whether the empty program, and a one-byte (or one-character) program, is considered "safe" or not? It's unlikely you'll find a language with a one-byte builtin command for Gray coding, but possible, and I think you should handle those edge cases nonetheless. \$\endgroup\$
    – pxeger
    Jun 12 at 9:26
  • 1
    \$\begingroup\$ Thank you a lot for your feedback. I wanted to make this challenge not too hard, so I chose just the simple formula and I think that a lot of languages can't compete already. I think it would be interesting to change it into program which validates if its input is gray coded, but it feels harder, so I am not sure if it shouldn't be maybe separate challenge? \$\endgroup\$
    – Jiří
    Jun 12 at 13:04
  • \$\begingroup\$ Also I chose word "character", because I think it would otherwise make using encodings such as UTF-32 very hard to use, but I guess not many answers would use such encodings. So I would like to ask you if you have some other idea how to change the wording of it, but if you don't, then I guess I can change it to "byte". \$\endgroup\$
    – Jiří
    Jun 12 at 13:07
  • 1
    \$\begingroup\$ Yes, you're right; I have now actually tried this task, and it is pretty hard to do anything at all in most languages, so it's fair enough to keep it simple. As for bytes and characters, I think almost all answers will use either plain ASCII, or a SBCS, especially the kind used for most golfing languages. My objection is that a "character" doesn't have bits unless some kind of encoding is specified, and since we score using bytes by default on this site, so every language definitely has [...contd] \$\endgroup\$
    – pxeger
    Jun 12 at 13:12
  • \$\begingroup\$ [contd...] some way of translating into bytes, it makes sense to just use bytes. \$\endgroup\$
    – pxeger
    Jun 12 at 13:13
1
\$\begingroup\$

Push some numbers

Given a list of integers, apply the following rules to each element:

  • If n is even, move it to the back.
  • If n is odd, move it to the front.

Zero is considered even. You may assume inputs are always non-negative.

Test cases

[1,2,3] => [3, 1, 2]
[0,1,2] => [1,0,2]
(more test cases coming soon)

Shortest code wins!

\$\endgroup\$
6
  • \$\begingroup\$ why treat 0 like a special case? \$\endgroup\$ Jun 13 at 17:33
  • \$\begingroup\$ @thejonymyster fixed \$\endgroup\$
    – Bgil Midol
    Jun 13 at 23:25
  • 5
    \$\begingroup\$ you don't need to specify that zero is even :P \$\endgroup\$ Jun 13 at 23:34
  • \$\begingroup\$ Are the inputs always non-negative? \$\endgroup\$
    – pxeger
    Jun 14 at 7:45
  • \$\begingroup\$ @pxeger yes, always \$\endgroup\$
    – Bgil Midol
    Jun 14 at 13:31
  • \$\begingroup\$ I assume input-lists can contain duplicated values and can be in any order (e.g. [10,4,1,5,10,2,3,2,3] would be a valid input - which I think results in [3,3,5,1,10,4,10,2,2])? \$\endgroup\$ Jun 23 at 6:47
1
\$\begingroup\$

Photosynthesis

Nearly finished game

Flavor text

You, a algae spore, have recently evolved the ability to walk. However, 3 others have just done the same thing. Can you use this new ability to your advantage and conquer the Petri dish?

Game rules

The game is played on a 15 by 15 grid with one bot starting in each corner. The goal of the game is to occupy more squares than your competitors.

Each turn, each tile can perform one of 3 moves:

  • Stay (Example: [2] [ ] -> [3] [ ]) Do nothing but gain one stack
  • Move (Example: [2] [ ] -> [ ] [2]) Move one space horizontally or vertically. Stack stays the same. Space must be unoccupied and no other tile must be moving or splitting to the destination.
  • Split (Example: [3] [ ] -> [1] [2]) Move half of stack to a adjacent square. Space must be free and no other tile must be splitting or moving to the destination. If stack is odd the destination gets the extra half stack.

Game continues till all squares are owned or if 15 x 15 x 4 turns have passed.

At most 5 obstacles per corner will be randomly placed on the board. They will be symmetrically placed so the map looks identical from each bots perspective. They will never be placed along the edge. There might be less than 5 obstacles if multiple happen to spawn at the same position. Example:

Blank game board

Tournament rules

In the tournament each pair of bots will play each-other at least twice. Exact format subject to change.

Every win gives you 3 ranking points, 2nd place gives you 2 ranking points, 3rd place 1 ranking point, and 4th 0 ranking points. The bot with the highest average ranking points wins. (Since by necessity some bots may play 1 game more or less than each other)

Controller

Controller can be found here (TBD) Note: I intend to delete all the example bots except expand_bot and move_expand_bot before the challenge is posted.

Example bot:

import data

def expand_downwards(grid: data.Grid) -> list[data.Action]:
    # Bot always starts at [0, 0] from it's own perspective
    actions = []
    for x, y in grid:
        if grid[x, y].owner == 0: # You are always player 0
            # If I can't split
            if grid[x, y].stack < 2 or grid[x, y+1].owner is not None:
                actions.append(
                    data.Action(action_type=data.ActionType.stay, source=(x,y))
                )
            else:
                # If we can split, split down
                actions.append(
                        data.Action(
                            action_type=data.ActionType.split,
                            source=cell,
                            destination=(x, y+1),
                        )
                )
               
    return actions

Do's and dont's

Please

  • Use a single top-level function. Makes it easier to automatically import bots.
  • Function name must be snake_case and include the word bot
  • Typehint your program. This allows me to automatically check if you are following some of the rules.

Don't

  • Use randomness, though you can use a seeded RNG if you like
  • Print anything
  • Take a excessively long time on your turn. Polynominal time algorithms only please.
  • Access the filesystem, networking, or any other side effects
  • Keep state between games. Keeping state between round of the same game is allowed. Precomputing things for performance is also allowed.
  • Submit a bot with no other purpose than to help/hurt one specific other bot
  • Exploit the controller
\$\endgroup\$
3
  • \$\begingroup\$ Why would you disallow randomness? A lot of valid algorithms might use randomness. Also, half the fun in a koth game is submitting some dumb bot that makes all its decisions randomly. \$\endgroup\$
    – ccarton
    Jun 28 at 21:57
  • \$\begingroup\$ I want to be able to run the simulation once and have a reasonable sample, not need to run it many times to account for randomness \$\endgroup\$
    – mousetail
    Jun 29 at 6:33
  • \$\begingroup\$ The restriction on randomness is a little unreasonable but allowing a reproduceable seed is I guess a good compromise \$\endgroup\$
    – qwr
    Jul 10 at 0:27
1
\$\begingroup\$

Find the best character arrangement

You want to write your English essay. However, all characters on your keyboard broke other than the arrow keys and the enter key. You want to find out how to place the characters so you can write your essay with the least movement.

Formally, you have to assign to each character of !"$%&'()+,-./0123456789:;<=?[]`abcdefghijklmnopqrstuvwxyz⇦⇧ a unique integer coordinate, and minimize \$ d = \sum_{c_1 , c_2} {\text{freq}(c_1, c_2) \text{dist}(c_1, c_2)} \$, with \$\text{dist}\$ being the Manhattan destince between the position of the characters, and \$\text{freq}\$ being the frequency of the character pair, which is described here, with the frequency of each pair not detailed assumed \$0\$.

Scoring

The winner is the code which could produce the best result in a minute on my computer, with the tie breaker being the time until that result is found.

Rules

  • Your language must have a freely available interpreter/compiler capable of running on Linux
  • Standard loopholes are disallowed, except optimizing for the given test cases - you are allowed (and even expected) to fine-tune your solution to produce the best solution on this given test case.
  • You can't hardcode calculations - the solution should be found by the code during its execution, not beforehand.
  • You can use any reasonable output format (i.e. output your solution and when did you find it when your program terminates, output your solution whenever the program improves it, etc.).
  • You will receive the frequency JSON in stdin.
  • Your solution must be deterministic. You can use PRGNs, you just have to hard code their seed.
\$\endgroup\$
1
\$\begingroup\$

Decompress a Sparse Matrix (WIP)

The dual of this challenge.

Decompress a sparse matrix reversing the method here Compressed sparse row (CSR, CRS or Yale format).

There will be 4 inputs, either as separate variables or as a list of lists:

  • V, a list of the nonzero elements of the matrix in row-major form. This is of length NNZ (the number of nonzero elements in the original matrix)
  • NCOLS - the number of columns in the original matrix.
  • IA - a list that yields the number of nonzero elements in each row in the following way: IA[0] = 0, IA[i] = IA[i - 1] + <number of nonzero elements in row i>. The number of nonzero elements in row i is IA[i + 1] - IA[i].
  • JA - a list of the column indices of the elements in V, also of length NNZ. (zero-indexed)

Input will be a list of 3 lists and the number of columns in the original matrix, e.g. either

[
  [5, 8, 3, 6],
  [0, 0, 2, 3, 4],
  [0, 1, 2, 1],
  [4]
]

Or

V = [5, 8, 3, 6]
IA = [0, 0, 2, 3, 4]
JA = [0, 1, 2, 1]
NCOLS = 4

Output will be a decompressed matrix/list of lists:

[[0 0 0 0],
 [5 8 0 0],
 [0 0 3 0],
 [0 6 0 0]]

If your language doesn't support actual data structures, input and output may be text.

Process

  1. Create a 'matrix' of row width NCOLS.
  2. Populate the ith matrix row with N values from V if the corresponding array index (i + 1) of IA is non-zero, where N is the ith element of IA starting at the ith element of JA.
  3. repeat until V is empty
    i.e. above for the 0th matrix row IA[1] = 0, so this row has NCOLS=4 zeroes in it's first row. Then for matrix row 1, IA[2]=2 it takes 2 values from V starting at JA[1]=0. For matrix row 2, IA[3]=3 and IA[2]=2 so it takes the next (3 - 2 = 1) elements from V, starting at JA[2]=2. For matrix row 4 IA[4]=4 and IA[3]=3 so it takes the next (4 - 3 = 1) elements from V, starting at JA[3]=1.

Test cases

Input 1:

[ 5, 8, 3, 6 ]
[ 0, 0, 2, 3, 4 ]
[ 0, 1, 2, 1 ]
4

Output 1:

[[0 0 0 0],
 [5 8 0 0],
 [0 0 3 0],
 [0 6 0 0]]

Input 2

[ 10 20 30 40 50 60 70 80 ]
[  0  2  4  7  8 ]
[  0  1  1  3  2  3  4  5 ]
6

Output 2:

[[10 20 0 0 0 0],
 [0 30 0 40 0 0],
 [0 0 50 60 70 0],
 [0 0 0 0 0 80]]

Input 3:

[ ]
[ 0 0 0 0 ]
[ ]
3

Output 3:

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

Input 4:

[ 1 1 1 1 1 1 1 1 1 ]
[ 0 3 6 9 ]
[ 0 1 2 0 1 2 0 1 2 ]
3

Output 4:

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

Input 5:

[ 5, -9, 0.3, -400 ]
[ 0, 0, 2, 3, 4 ]
[ 0, 1, 2, 1, ]
4

Output 5:

[[0 0 0 0],
 [5 -9 0 0],
 [0 0 0.3 0],
 [0 -400 0 0]]

Assume inputs may contain any real number, you need not consider mathematical symbols or exponential representation (e.g. 5,000 will never be entered as 5e3). You will not need to handle inf, -inf, NaN or any other 'pseudo-numbers'. You may output a different representation of the number (5,000 may be output as 5e3 if you so choose).

Scoring

This is a , fewest bytes wins.

\$\endgroup\$
7
  • \$\begingroup\$ I'd suggest to at least briefly explain how the decompressing works in the post. The challenges should be self-contained as much as possible. \$\endgroup\$
    – Bubbler
    Apr 22, 2021 at 23:55
  • \$\begingroup\$ @bubbler, that's coming, but I need to figure out how to do that/explain it myself. I've left (WIP) on the question because of this. \$\endgroup\$ Apr 23, 2021 at 0:11
  • 1
    \$\begingroup\$ @Pureferret I think it would be better to allow only nonzero integers instead of any real number. It'd be easier for most languages that way \$\endgroup\$
    – user
    May 2, 2021 at 20:59
  • \$\begingroup\$ @user I think it's more interesting seeing those languages work around those difficulties. Also the original challenge required them, so it I my makes sense this one does too. \$\endgroup\$ May 2, 2021 at 21:14
  • \$\begingroup\$ @Pureferret I'm not sure many golfing languages support arbitrary precision floating point numbers. Would they be able to use strings, then? Edit: could you at least restrict it to rational numbers? Unlike Jon Skeet, most of us here don't know all the digits of pi :P \$\endgroup\$
    – user
    May 2, 2021 at 21:17
  • \$\begingroup\$ @user it needn't be arbitrary, just as long as it matches the test cases \$\endgroup\$ May 2, 2021 at 23:46
  • \$\begingroup\$ @Bubbler I think the process is correct? \$\endgroup\$ Jun 29 at 16:17
1
\$\begingroup\$

Bloons TD 6 Upgrade Paths

\$\endgroup\$
3
  • 1
    \$\begingroup\$ add tag kolmogorov-complexity. Interesting idea, I quite enjoy the upgrade path system in this game :) especially when the abilities that lock eachother out make sense to be mutually exclusive, like the catapult vs the crossbow \$\endgroup\$ Jun 26 at 22:11
  • \$\begingroup\$ @thejonymyster actually idk if that applies because the order is not fixed \$\endgroup\$
    – qwr
    Jun 30 at 17:22
  • \$\begingroup\$ that just makes it a set, which still counts imo. "output this set" would make sense as kc. if anything, though, heres another challenge which does that \$\endgroup\$ Jun 30 at 23:04
1
\$\begingroup\$

Where does the seesaw balance?

There have been a couple seesaw balance questions but none of them are doing this version of the question. Adding weight to one side, or small inputs with ascii art have been done already, but I think this would be unique enough to not be a duplicate.

Problem: Given some ordered sequence of single-digit positive integers representing weights (say 0kg to 9kg), output at what index or indices the fulcrum have to be at such that the beam balances. If it doesn't balance anywhere, then output some non-location without erroring.

This is assuming a massless beam. The fulcrum is at the center of one of the weights, and the output must be integer-valued (no putting the fulcrum between two weights). Output can be either 0-indexed or 1-indexed and should be specified in the answer.

Valid outputs if the seesaw balances would include 2, 8.0, [5], a list of all positions that work, "3" and so on, but not 4.25. Valid outputs if the seesaw does not balance anywhere would include -1, [], "", NaN and so on, but not 0 or [7].

Example: Given the input [2,3,0,0,5,9,4] the output should be 4 since a pivot at that index causes the torques/moments to balance (2*4+3*3+0*2+0*1 = 9*1+4*2). Below is a visualization:

2300594 (weights)
=======
    ^
0123456 (indices)

The weight at the fulcrum doesn't contribute to either side.

Failure example: Given the input [1,3,4,1,2] the output should be -1 (or null or [] or some other obviously non-position output) because at no fulcrum position would this this seesaw be stable and balanced.

Edge cases: An input that is all zeros (eg. [0,0,0,0,0,0]) can balance at any index, but the program only needs to output at least one of them. An input that doesn't follow the input rules (eg. [], ["a","b"], [-3], [1.234,2.34,3.4]) is not expected to give any output of any kind and can error out.

Test cases: Using NaN as the "no solution" output. Output is 0-indexed.

[6] -> 0
[1,0] -> 0
[1,1] -> NaN
[9,1,9] -> 1
[1,2,3,4] -> 2
[1,2,3,4,5] -> NaN
[1,3,4,1,2] -> NaN
[2,3,0,0,5,9,4] -> 4
[1,2,3,4,5,6,7] -> 4
[0,0,0,3,0,0,0,3] -> 5
[0,0,0,3,0,0,3,0] -> NaN
[1,0,0,2,0,0,0,0,0,0,0,0] -> 2
[6,2,6,3,4,8,1,1,1,1,1,1,1,1,1,1,1] -> 5

Being code golf, fewer bytes of code is better here!

\$\endgroup\$
8
  • \$\begingroup\$ You might mention that we can use 0 or 1 indexing (if it is allowed) \$\endgroup\$
    – Steffan
    Jun 30 at 18:40
  • \$\begingroup\$ That's a good idea, thanks! \$\endgroup\$
    – Noah
    Jun 30 at 18:52
  • \$\begingroup\$ Can we instead output all indices that would work (hence an empty list in the case of none)? \$\endgroup\$
    – Steffan
    Jun 30 at 18:57
  • \$\begingroup\$ I don't see why not. In most cases that'll just be a list with one element but it covers the edge cases pretty well. I already had [5] and [] as valid outputs for the success/fail states but I'll clarify further. \$\endgroup\$
    – Noah
    Jun 30 at 19:00
  • \$\begingroup\$ Welcome to CGCC and thanks for using the Sandbox! I suggest stating explicitly that this is code-golf in the challenge body (besides the tag). \$\endgroup\$
    – pajonk
    Jun 30 at 20:36
  • \$\begingroup\$ Thank you! Updated \$\endgroup\$
    – Noah
    Jun 30 at 22:22
  • \$\begingroup\$ Related: codegolf.stackexchange.com/questions/151318/… Closely related: codegolf.stackexchange.com/questions/132512/… \$\endgroup\$
    – Laikoni
    Jul 1 at 4:39
  • \$\begingroup\$ The second one might be close enough to be considered a duplicate, given that the main task is the same and only the input format is different. However personally I prefer the simpler format from this challenge. \$\endgroup\$
    – Laikoni
    Jul 1 at 4:44
1
\$\begingroup\$

Get multi-dimensional indices in a list

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

Reconstruct Matrix from its diagonals

Given the diagonals of a matrix, reconstruct the original matrix.
The diagonals parallel to the major diagonal (the main diagonals) will be given. enter image description here

Diagonals: [5, [4, 10], [3, 9, 15], [2, 8, 14, 20], [1, 7, 13, 19, 25], [6, 12, 18, 24], [11, 17, 23], [16, 22], 21]

Rules

  • The matrix will be non-empty and 2-dimensional
  • The diagonals can be given either
    1. starting with the main diagonal and then the outer diagonals
    2. from the top-right diagonal to the bottom-left diagonal
    3. from the bottom-left diagonal to the top-right diagonal
  • the end matrix will always be a square
  • the order of the numbers in the diagonals should be from top-left to bottom-right
  • the diagonals with length one (above 5 or 21) can be a single integer or wrapped in a list
\$\endgroup\$
3
  • 2
    \$\begingroup\$ will the end matrix always be square \$\endgroup\$
    – Steffan
    Jul 2 at 20:01
  • 1
    \$\begingroup\$ Is this [5, [4, 10], …, [16, 22], 21] or [[5], [4, 10], …, [16, 22], [21]]? \$\endgroup\$
    – tsh
    Jul 4 at 6:34
  • \$\begingroup\$ @tsh I'll allow both, thanks \$\endgroup\$
    – mathcat
    Jul 4 at 15:31
1
70 71
72
73 74
134

You must log in to answer this question.

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