537
\$\begingroup\$

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

Sandbox FAQ

Posting

To post to the sandbox, scroll to the bottom of this page and click "Answer This Question". Click "OK" when it asks if you really want to add another answer.

Write your challenge just as you would when actually posting it, though you can optionally add a title at the top. You may also add some notes about specific things you would like to clarify before posting it. Other users will help you improve your challenge by rating and discussing it.

When you think your challenge is ready for the public, go ahead and post it, and replace the post here with a link to the challenge and delete the sandbox post.

Discussion

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

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

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

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

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

Other

Search the sandbox / Browse your pending proposals

The sandbox works best if you sort posts by active.

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

Get the Sandbox Viewer to view the sandbox more easily!

\$\endgroup\$
0

3508 Answers 3508

1
29 30
31
32 33
117
2
\$\begingroup\$

Is there a left-right connection?

Task

Given a square array of 0s and 1s, determine whether or not there exists a path of 1s connecting the leftmost and rightmost columns. A path can take steps of one unit up, down, left or right, but not diagonally. Every symbol on the path must be a 1, and it must start somewhere in the first column and end somewhere in the last column.

Shortest code in each language wins.

Examples

000
111   ->  True
111

110
110   ->  False
110

101
010   ->  False
101

0     ->  False

1     ->  True

11110
00010
01110 ->  True
01000
01111

11110
00010
01100 ->  False
01000
01111

Notes

The array may be represented in any reasonable form, such as a list of lists [[0,0,0],[1,1,1],[1,1,1]] or a string '000 111 111'. It can optionally be in transposed form (so that the roles of rows and columns are exchanged; equivalently the code can instead determine whether there is a top-bottom connection). Any two distinct symbols can be used in place of 0 and 1. The output can be in any truthy/falsy form.

\$\endgroup\$
2
\$\begingroup\$

Consecutive Distance Rating

Posted

\$\endgroup\$
1
  • \$\begingroup\$ This is really neat! Simple, elegant, but nontrivial. It'd be interesting to look at the sum and its growth given an (OEIS) sequence. \$\endgroup\$
    – AviFS
    Jun 12 at 1:25
2
\$\begingroup\$

Title: Make a WebCrawler dictionary writer.

Notice: for any text within <> tags, please ignore any .'s. These are simply added so that they are treated as plain text, and not code.

Your goal is to make a program that acts as a regular WebCrawler, but also writes a dictionary using the websites.

You should have a list that is used to store words that have been added called Dictionary, and another list to store website urls called NextSites. You should also have a variable called sites, and a variable called input2. Any other variables or lists are optional.

It should ask for input upon running the program, allowing you to input a website url, from where it will start web crawling. How it asks for input does not matter, so long as you are able to use any website as input. It should then ask for input again, allowing you to chose how many sites it should continue for. The variable much should be set to this input.

Next, it should check the website for any text contained within <.p> tags. It should separate the text contained within the tag at any space contained in it. Next, it will compare each part that has been separated against the current text in the list used to store words. Any part that is not already in the list should be added to it.

After it has checked all of the text within the <.p> tags on the site, it should check for any <.a> tags on the site. Any urls that it finds in the 'href' part of the <.a> tag should be added to the website url list, so long as the url list is not larger than 99 urls. (This means that the maximum amount of urls that can be in the url list at any one time is 100).

When all of the <.a> tags on the site have been checked for urls, it should change the current site it is on to the first site in the list of urls. It should remove this url from the list, and move all other urls to the spot one less than them on the list, so that there is no empty space at the beginning. (eg: If you had 3 urls: 1. google.com , 2. wikipedia.com , 3.stackexchange.com, then after switching to google.com, the list would now be 1. wikipedia.com , 2.stackexchange.com .)

It should then repeat the above steps, and continue to do so until the variables sites and much are the same.

Next, it should should output the entire list of words that it found. The method used to output it does not matter, so long as all words in the list are outputted, with a new line for each word. E.g.: You may have found the words cat, mouse, and food. The output would look as follows:

cat

mouse

food

Scoring: The scoring follows regular code golf rules. The person with the smallest program in bytes wins. However, in the case of a tie between two programs, the program that can webcrawl and write the dictionary starting on wikipedia.com for 100 sites fastest will win.

\$\endgroup\$
1
  • \$\begingroup\$ running this type of program even once would probably ends up throttling the sites and blocking access to the crawler. Is there a good way to prevent that? \$\endgroup\$
    – Razetime
    Jun 17 at 2:32
2
\$\begingroup\$

Largest Number with No Repeating Digit Pairs

Inspired by the problem with the same name on Puzzling SE.

You are to find the largest number that only uses every digit pair once, in a given base. For example, in ternary we have 2212011002. We can do this greedily by simply starting with the largest number, and then adding the next largest number we can without repeating a pair, until we’ve gotten them all.

Challenge: Given a base from 1-10, output the largest number in that base with no repeating digit pairs.

As long as the digits make the number, you may output with anything, or nothing, in between. Whether regularly delimited, or irregularly gibberished.

You may also take input in any reasonable way. For example, you might take the base, the max digit, or an ordered list representing the digits available. For octal, this would mean 8, 7 or 76543210. If you feel like a challenge, you can take octal as input. I won't complain!

Note that it need only work for bases from 1-10. Invisible points for doing alphanumeric bases like hex, but not at all required.

This is , so least bytes per language wins.

Test Cases

Decimal: 10
99897969594939291908878685848382818077675747372717066564636261605545352515044342414033231302212011009


Octal: 8
77675747372717066564636261605545352515044342414033231302212011007


Quaternary: 4
33231302212011003


Ternary: 3
2212011002


Binary: 2
11001


Unary: 1
00
\$\endgroup\$
2
  • 1
    \$\begingroup\$ I was gonna suggest this be able to support even higher bases, up to 36 maybe. Though that might give some languages that have built-in support for higher number bases an unfair advantage? Because other languages might have to add special support for A = 9 + 1 rather than just using the ASCII values. Maybe just base 26, and use only letters, no numbers? Not sure if it's worth bothering... (Ah, I see you added that note after I posted this comment) \$\endgroup\$ Jun 16 at 19:27
  • \$\begingroup\$ @DarrelHoffman I did add the edit to make the question as is clearer, but whether or not to include higher bases is precisely my one hang-up! That's what we're discussing in TNB. Come join us! \$\endgroup\$
    – AviFS
    Jun 16 at 19:37
2
\$\begingroup\$

Draw an Ascii Grid

\$\endgroup\$
2
  • \$\begingroup\$ You can use this to visualise a tictactoe game -- might just do that. \$\endgroup\$ Jun 16 at 7:32
  • \$\begingroup\$ Looks great, just leave it for another 2 days before posting! \$\endgroup\$
    – user100690
    Jun 16 at 15:56
2
\$\begingroup\$

Implement a cleave function

\$\endgroup\$
13
  • \$\begingroup\$ @Adám You're right. Thanks! \$\endgroup\$
    – chunes
    Jun 16 at 7:27
  • \$\begingroup\$ If my language can directly apply a list of functions to a number, giving me a list of results, does that mean a 0-byte answer, or do I have to wrap the application in no-op code? \$\endgroup\$
    – Adám
    Jun 16 at 7:30
  • \$\begingroup\$ @Adám I have no idea if there's a precedent for 0-byte answers, but if the mere act of writing a list of functions immediately applies them to some object in your programming language, that's interesting and I would want to see it. Would writing a blurb about builtins/builtin behavior being allowed help? Something like "Builtin functionality is allowed but consider adding a less trivial answer as well."? \$\endgroup\$
    – chunes
    Jun 16 at 7:37
  • \$\begingroup\$ Yes, that would help, and asking for non-trivial things is nice. You might also want to ask for people to explain. \$\endgroup\$
    – Adám
    Jun 16 at 7:38
  • \$\begingroup\$ @Adám Added, thanks. \$\endgroup\$
    – chunes
    Jun 16 at 7:43
  • \$\begingroup\$ While tagged functional-programming, are we still allowed to submit a full program that prompts for \$L\$ and \$n\$? \$\endgroup\$
    – Adám
    Jun 16 at 7:44
  • \$\begingroup\$ @Adám I'm not sure. I took a look at some other higher-order function questions for inspiration, for example https://codegolf.stackexchange.com/questions/223881/implement-an-over-function and it uses the language "You may input and output in the most convenient format for your language, and in any convenient method,..." and that seemed to suffice there. \$\endgroup\$
    – chunes
    Jun 16 at 7:56
  • \$\begingroup\$ Funny thing is that while you call it a conceptual inverse of map, it is just a map, right? E.g. in JS: (L,n)=>L.map(f=>f(n)) \$\endgroup\$
    – Adám
    Jun 16 at 8:03
  • \$\begingroup\$ Indeed, it can be written in terms of map. Does it seem too trivial, you think? Does it need spicing up? \$\endgroup\$
    – chunes
    Jun 16 at 8:07
  • \$\begingroup\$ No, I think it is great. \$\endgroup\$
    – Adám
    Jun 16 at 8:07
  • \$\begingroup\$ How would one apply a list of functions to a number in something like Python, which is not a functional-programming language \$\endgroup\$ Jun 16 at 11:07
  • \$\begingroup\$ @StackMeter lambda l,n:map(lambda f:f(n),l) \$\endgroup\$
    – user100690
    Jun 17 at 5:31
  • \$\begingroup\$ I see now, thanks @RecursiveCo. \$\endgroup\$ Jun 17 at 6:06
2
\$\begingroup\$

On a Collapsing Platform

Rules

In this KoTH, your task is to not die. It seems simple, right? Well, no.

You're on a platform. A giant platform, of size 100 * (entries) ^ 1.1 units across (this may change if we get a lot of entries). And every few turns, a random tile is removed. As well as this, you, not a small mass in the scale of things, can cause a tile to fall down. Let me explain how this works.

You (the entrant to this KoTH) control a certain number of bots. You (the bots) can then move around on the platform and try not to die. You (still the bots) can move up to 10 units away at base, and can see up to 100 units away (units will be called u from now). However, jumping over a hole costs 2u more, meaning that the largest gap you can clear is three units (3 * 3 for the gap and 1 to land). Do not try and clear 4u+ gaps; you will die. Going off the edge of the platform also is an unwise choice - you will die.

By "you - not a small mass in the scale of things", I mean to say that every step you take takes you closer to your inevitable death - each tile you step on has a hidden durability stat, that will not be revealed to you during the course of the round. When it hits 0, the unlucky bot (hopefully not you (the bot)) on it will be removed with the tile. Do not do this; you will die.

Your weight is a random stat that is decided at the start of your game, and is subtracted from a tile's durability each time you step on it (weights are 150 at base, and durability values in the range of 15000 - 45000 * (entrants) ^ 1/2, or 15000 * 1-3 * entrants ^ 1/2, so it only becomes an issue in the long term, or when a lot of players exist.) Do not forget about this and start camping on the same 10 tiles on the end; you will die.

Everything takes place on a tick system - every 10 ticks, you can do an action (subject to change to 20ish if this is exploitable) and this may well be the most important part of the game - reduce it at all costs - the fewer ticks you waste, the less durability you take off, and the longer you can thread the needle between life and death. Do NOT, and I mean NOT in caps, forget about this - you will die.

There are a few items that you can get that will improve your chances and delay your inevitable death represented by these characters:

-: Removes 1-7% of your weight (or 1-7, whichever is lesser)

=: Increases your speed by 1 (at 13, this will in fact, prove me wrong and let you clear 4u jumps - still not got the + though).

? Increases vision by 5 (allowing you to see 5 more blocks in either direction.

> Reduces your tick delay by 0.1 or 1% of your tick rate, should it drop below 5 (however, before that, you will die most likely.)

+ Duplicates the bot - you start with 10 bots, and each bot left over at the end is worth 10 000 points (1 per tick survived), so this can, effectively, give you 10 000 points free.

Every 10-25 turns, a random platform is removed - unless necessary, this will not drop any bots - the platform chosen will always be empty (just so people don't get unlucky and die at turn 85) unless it is forced not to be - for example, in the endgame, where there is only 10 tiles left. Do not forget this; you will die

Input and Output

To begin with, you will get a string such as this

0, 111, 132, 122, 133, 211, 201, 212, 233, 310, 323, where:

The first number represents your unique player id, known as PID in the it gang. Then, you get 10 numbers, representing your bots' start positions.

Then, for each turn, for each bot that did not die, you (the player) get a string such as this (shortened to save space):

.___.+>-__u__...+>+-_._

representing the bot's vision.

You must then return an integer, representing how many units you wish to move forward (negative is backwards) (and do not forget that spaces take 2u more, or you will die.); do not try and move more than your speed, or it will be modulo-ed. Errors and invalid input return 0. Note, spaces are represented with ., in the examples and in game.

Helper functions (to delay your death, hopefully until the end):

info(): gives you a chunk of info, in this format:

PID: 0
Bots: 11
Score: 10000
[
BID: 1
Weight: 97
Speed: 12
Tick Delay: 8.8
Vision: 110
Pos: -932
Score: 830
]

[
BID: 3
...
]

The string is format as such:

  • First, your unique PID.

  • Then, the number of bots you still have.

  • Then, your total score.

  • Then, for each bot:

    • Its bot ID (or BID for the it gang). (Note, BID are cannot be reassigned, so if Bot 2 dies, and then Bot 1 duplicates, it will have a BID of 10, not 2 (also we count from 0) as it would be if they were.)

    • Its weight, speed, tick delay and vision, in that order.

    • Its position on the platform, in that order.

    • Its score.

position(): gives a position of every bot, ordered by their bot ID, or BID (again, only for the it gang).

position(ID): gives the x position for a bot with a specific ID. If that ID has died already, it will return "Dead" - plus the space where it died. If that bot never existed, it will return None.

tickdelay(), weight(), speed(), vision(), tickdelay(ID), weight(ID), speed(ID), vision(ID):

Does exactly what it says on the tin, returns that specific stat for all bots if no ID is given, or the one with that ID should it be given (again, if the bot is dead, it just returns its stats on the turn it died, and if it never existed, it returns None. Make of it what you will).

vision(ID) Gives a specific bot's vision - this is useful for sketching a map of the world in conjunction with position(ID). Note that other bots are represented as s, so if you're lucky enough to get your bot (u) in between two opposing bots (s), feel free to laugh.

You are allowed access to ALL the random functions (apart from random.seed(), however I will use a set of predetermined seeds in a random order to facilitate retesting. There will be a large number of trials done - this is just to aid improvements if you so desire to make them.

Bots can store variables and write to files, but ONLY in their directory. I will find any bot who does this and ban them.

Scoring

Bots gain 1 point for each turn they survive, increasing by 1 every 100-200 turns. This will be notified with the string Score/turn increased by 1. Every powerup gives +500, except for +, which duplicates the bot, including its score, thus adding its score to your total. At the end, when there is three or fewer tiles left, you gain 10000 + the bot's current score for each bot left alive. This is done for every bot that lives, so people getting 2 or more bots through gain more than those getting 1, and two opposing bots can both get points for their team.

At least 10000 games will be run per round (subject to change), each time resetting all the stats to the base, rerolling RNG and restarting from the beginning.

After as many rounds as I can get through on my PC, the scores will be added up, and the winner gets an accept.

Meta

Help with a Python controller would be appreciated.

Any specifications need to be made?

Should I edit any formulae?

\$\endgroup\$
2
\$\begingroup\$

When's my weekend finally here?

\$\endgroup\$
2
\$\begingroup\$

Reverse RegEx

Take a regex a as input, output a regex b such that, for each string x, x matches a iff x.reverse matches b.

Here, regex need to support such symbols:

  • .(any character expect \n)
  • [abc](any character in abc)
  • [^abc](any character not in abc)
  • x?(appears 0-1 times), x*(appears any amount of times), x+(appears any positive amount of times)
  • x{n,m}(appears n to m times, m can be omitted to mean infinite)
  • (abc) (?:abc)(group block, () can be referred while (?:) can't)
  • \n(refer to the latest match of n-th group)
  • ^(begin of string), $(end of string) (or begin/end of line, see flags/m)
  • |(or, choose one in some choices)
  • Letters, \n(this n is char rather than variable, line-feed)

You need to handle flags i(ignore upper/lower case) and m(multiline, ^ and $ match begin/end of lines rather than string). You can also just pipe the flags and make the containment of regex work for all possible flags, aka. you can treat pipe free. (They refuse to allow or disallow)

Sample Input    Sample Output
/abcd/          /dcba/
/[abc]/         /a|c|b/
/[^abc]/        /[^abc]/
/(.)abc\1$/     /^(.)cba\1/
/$1/            /10% of $10/

Shortest code win

\$\endgroup\$
13
  • 2
    \$\begingroup\$ What's the regex flavor/set of allowed features/inputs? Is it for a full or partial match? \$\endgroup\$
    – feersum
    May 10 '19 at 9:07
  • \$\begingroup\$ @feersum Allowed features need discuss. To be a full match ^ and $ can be added \$\endgroup\$
    – l4m2
    May 10 '19 at 9:21
  • \$\begingroup\$ Why is test case /[^abc]/ there twice? Or is it to give two different example outputs? Since just outputting /[^abc]/ for input /[^abc]/ would be fine. Also, I'm not too familiar with this Regex syntax, but how does /$1/ work, since $ is the end of the match? And why is it /10% of $10/ reversed? \$\endgroup\$ May 10 '19 at 9:27
  • \$\begingroup\$ @KevinCruijssen twice to show that same input may lead to different output. /$1/ and /10% of $10/ both match nothing \$\endgroup\$
    – l4m2
    May 10 '19 at 9:32
  • \$\begingroup\$ "both match nothing" Ah ok.. I falsely assumed the regex would match something. So incorrect (but still valid) regexes are also allowed as input. Maybe it's a good idea to add some comments to the sample outputs, like /10% of $10/ can be anything as long as it doesn't match anything (and maybe put the /(?!a)[^bc]/ or /[^abc]/ for the same input on one line. \$\endgroup\$ May 10 '19 at 9:37
  • 2
    \$\begingroup\$ You should more rigorously explain what x.reverse means, from the examples it looks like you mean the order of letters is reversed, but some people might be confused. \$\endgroup\$ May 11 '19 at 21:28
  • \$\begingroup\$ 1) I think x|y is missing in the list of symbols. 2) The behavior of each symbol is underspecified in so many ways. What does [a-z], [[\]], (ab+)*\1, or (((((((((((x)))))))))))\11 do? Do we need to handle any backslash escapes other than newline? 3) Are you sure this is possible? Can you reverse (a(bx*){0,2}c)*\2\1? \$\endgroup\$
    – Bubbler
    Jun 22 at 23:38
  • \$\begingroup\$ 4) Using such a complex flavor of regex is a parsing hell, which I don't recommend with the same reasons as parsing arithmetic. Good challenges about manipulating regexes include this and this. \$\endgroup\$
    – Bubbler
    Jun 22 at 23:41
  • \$\begingroup\$ @Bubbler I'll just don't care [[\]] and assume input only contain letters and \n. (a(bx*){2}c)+\2\1 reverses into (c(x*b)(?:x*b)a)\2\1(c(x*b)(?:x*b)a)*(Handcode, maybe wrong; need some OR to fit your original one) \$\endgroup\$
    – l4m2
    Jun 23 at 0:53
  • \$\begingroup\$ I'll ask differently: 1) Should we support range notation [a-z] or not? I assume it's not a set of three chars a-z since - is not a letter. 2) I think you have the knowledge that (x)* only captures the last iteration and \1 fails if it is not actually captured. You need to include it in the post. 3) Should we support multi-digit backreference (like \11 being the eleventh)? \$\endgroup\$
    – Bubbler
    Jun 23 at 2:06
  • \$\begingroup\$ A note for the future: a regex with backreferences is no longer a regular expression in the CS sense, and any kind of manipulation on it can easily fall into an uncomputable problem. \$\endgroup\$
    – Bubbler
    Jun 23 at 2:20
  • \$\begingroup\$ Also, about the "pipe free" thing: you didn't define the term "pipe" anywhere, so it only makes the challenge more unclear. "They refuse to allow or disallow" seems like a misunderstanding on your side; see Jo King's comment there. Basically an I/O method is allowed only when the language or the answer format (function or full program) supports it. And regardless of what site policy says, you can allow anything you want as long as you make it explicit (you already did here, so no need to mention the meta post). \$\endgroup\$
    – Bubbler
    Jun 23 at 3:41
  • \$\begingroup\$ I'm pretty sure that the algorithm you have in mind does not handle ((x)|(y))+\2\3 (though it is reversible). I suspect it can be made irreversible if I replace x and y with something more dynamic. \$\endgroup\$
    – Bubbler
    Jun 23 at 4:09
2
\$\begingroup\$

The Great Betting Game

\$\endgroup\$
2
\$\begingroup\$

Play Thud

Thud is a game described by Terry Pratchett in his novel, Thud!.

The game simulates a battle between the Dwarfs (in blue) and the Trolls (in green) on an octagonal board with the Thudstone (an impassable space) in the centre of the board.

Thud board

I have created an environment to play the game and develop game playing code at: https://ajfaraday.github.io/Thud/dist/index.html

The challenge is to write the most successful dwarf or troll player of this game (these will be two separate challenges).

Rules

Starting with the Dwarfs, players take it in turns to move.

Dwarf Movement

On the Dwarf player's turn, they can move one dwarf piece either as a walk or a hurl.

Walk: Dwarfs can move as far as they like in any direction until they hit an obstacle (another dwarf, the edge of the board, or a troll). They can only kill a troll by walking if they are only one space away.

Hurl: If two or more dwarfs are in a line (horizontal, vertical or diagonal), they can hurl the dwarf on the end of the line, by the length of the line (e.g. in a line of 3, the dwarf on the end can be hurled 3 spaces). If a dwarf is hurled into a troll, the troll is killed, reducing the trolls score by 4 points.

Troll Movement

On the Troll player's turn they can move one troll piece, either as a walk or a shove.

Walk: Trolls can move one space in any direction, unless a troll, dwarf or the edge of the board is in the way. Whenever a troll moves, it kills all dwarfs adjacent to it's destination space.

Shove: If two or more trolls are in a line (horizontal, vertical or diagonal) they can shove the troll at the end of the line that number of spaces away, but only if any of the target space's immediate
neighbours contain a dwarf. When a troll is shoved, it kills all dwarfs on or adjacent to it's destination space.

It is not permitted for a troll to land directly on a dwarf by either walk or shove moves.

Each dwarf killed reduces the dwarfs score by 1 point.

Scores

The score is calculated thus:

  • The dwarf player has one point for every dwarf remaining on the board.
  • The troll player has four points for every troll remaining on the board.
  • The key figure is the difference between these two. This will be used to calculate players' scores in the tournament.

Ending the game

The game ends when any of these conditions is met:

  • There are no dwarfs on the board.
  • There are no trolls on the board.
  • Both players have declared the game over.
  • The game has reached it's cut-off length of 500 moves.

How to manually play a game

  • Go to https://ajfaraday.github.io/Thud/dist/index.html
  • Hover the mouse over a piece to see it's available moves.
    • Safe moves are outlined in green.
    • Dangerous moves (which can be killed the next turn) are outlined in orange.
    • Killing moves are highlighted in red when the mouse hovers over them.
  • Click a piece to select it for the current move.
  • Click one of the available moves to move the piece.
  • (You can click the relevant 'Make Peace' button to declare the game over according to that player, during their turn)

How to set up a local instance of the game

You don't have to clone the repository and use it locally to to create an entry, but it helps.

  • git clone git@github.com:AJFaraday/Thud.git
  • cd Thud
  • npm install
  • You can then run ./get_answers.sh to get the latest entries from Stack Exchange

If you prefer, you can use the github pages instance at https://ajfaraday.github.io/Thud/dist/index.html

How to customize a game

  • Open /dist/index.html in your browser
  • Click 'Customize'
  • Select troll and dwarf clients (manual allows direct control)
  • Select a turn time in milliseconds (only relevant to non-manual players)
  • Click 'Run Game' to see or play the game.
  • (Clicking 'Close' will not enact any changes)

Clients

The game is played by clients, which represent either a troll or a dwarf player. Each is a JavaScript class which must have these three functions:

  • constructor(controller) - controller is an object which acts as your interface with the game (see below).
  • turn() - This is called whenever it is your players turn to move.
  • end_turn() - This is called after your player's turn is over. It can not move pieces, but can make decisions on whether or not to declare the game over.

Controller

The controller object is your client's interface with the game itself. You can find full documentation for the controller class here: https://github.com/AJFaraday/Thud/blob/main/docs/controller_interface.md

It provides these methods to interrogate the state of the game:

  • turn() - Current turn of the game

  • scores() - The current score

  • spaces() - Every space, and what's in it

  • space_info(x, y) - Detailed information on any space on the board.

  • dwarves() - The location of every dwarf

  • trolls() - The location of every troll

  • pieces() - All pieces belonging to the current player (equivalent of dwarves() or trolls())

  • indexed_dwarves() - The location of every dwarf with a fixed index

  • indexed_trolls() - The location of every troll with a fixed index

  • previous_move() - What got moved to where last turn

  • killing_moves() - All moves which can kill one or more opponent

  • current_space - Currently selected space (not a function)

  • clear_space() - Empties currently selected space These methods are used to actually make your move:

  • check_space(x, y)- Find out what moves are available from a given space

  • select_space(x, y) - The player decides to move a piece at space.

  • check_move(x, y) - Find out what will happen if you move to a place

  • move(x, y) - The player moves the current piece to the selected space.

These are concerned with ending the game:

  • declare(game_over) - Say whether or not your player thinks the game is over.
  • opponent_declared() - Has the opponent declared the game over?

How to write a client

Warning: There is an issue with the project on Firefox (https://github.com/AJFaraday/Thud/issues/3) which prevents editing the code in the browser. This has been confirmed to work in Chrome.

  • Open 'dist/index.html' in your browser.
  • Click 'Customize'.
  • Select 'dwarf/template' as the Dwarf player (or use another client as a starting point).
  • Click 'Edit' beside the Dwarf player select.
  • Write your client code in the text box provided.
  • The Validate button will change colour based on whether or not the client is passes validations (see below).
  • When you're happy with it, click 'Apply' (This can be done before it passes validation, but it may not actually work).
  • Select a worthy opponent and click 'Run Game' to see the game.

Validations

In order for a client to work, and therefore be enterable in the challenge, it has to pass these validations:

  • It must evaluate as Javascript code.
  • The code must return a class, with a constructor which accepts one argument.
  • Instances of this class should have functions named turn() and end_turn()
  • The client must play a game until it is over (i.e. it must call a valid move during every turn call). The validator will run games against default opponents to determine if this happens.
  • Does not have any forbidden terms ** game. - Only interact with the game via controller ** Math.random - Please keep it deterministic ** setTimeout or setInterval - Keep it sequential
    ** eval, require or import - Just don't

You can open the developer console (F12) to see more detailed information on your client's validation process.

How to save a client

If you have cloned the git repository, you can save your entry for future tinkering. This step is not required for entry in the challenge, but it may be helpful.

  • Edit a client, as above.
  • When you're happy with it (preferably if it's passing validation, too), click 'Copy' from the edit interface.
  • Create a .js file in /src/clients/dwarf/entry with the name of your entry e.g. /src/clients/dwarf/entrygreat_dwarf_player.js. (This folder will not be wiped by get_clients.js)
  • Run node script/get_clients.js from the Thud directory to make your entry available from the Dwarf player select. You only need to do this once to make it avilable.
  • npm run build - this will keep watching for changes in your entry and updating the package.

How to enter your client in the competition

  • Decide on the name of your client, your client_name must only have alpha characters and underscores.
  • Answer this question with your entry
    • The first line of your answer should be your client's name as a title (with = characters under it on the second line)
    • There should be a code block containing the class for your entry (with or without the preceeding module.exports =)
    • After that please include a brief explanation of your client's behaviour, and any other information you'd like to include.

Once this is in place, anyone running ./get_answers.sh will see your client available under your username.

The GitHub Pages instance will also be updated periodically. So by making an entry, your code will be added to the repo.

Tournament rules

The tournament will pit every available dwarf client (in /src/clients/dwarf/) against every available troll client (in /src/clients/troll/), and each pairing will play exactly one game.

The difference between the two players' scores will then update a running total for each client. The winner will gain the difference, and the loser will lose the difference.

There are two winners in the tournament, the most successful troll player and the most successful dwarf player.

According to the rules, after playing a game, the players swap sides, so please also write an entry on the Troll challenge.


This is now nearly complete (apart from some UI improvments and presenting the tournament results a bit more nicely). There's a working example of the code importer working against these two meta questions:

I could really use someone to attempt an end-to-end run at creating a client and adding it to one of these to check that my instructions are clear and everything works.

\$\endgroup\$
4
  • \$\begingroup\$ Very well described challenge. Seems nice! \$\endgroup\$
    – user100752
    Jun 20 at 14:17
  • \$\begingroup\$ @EliteDaMyth Thank you for taking a look. Glad it looks complete. \$\endgroup\$
    – AJFaraday
    Jun 20 at 22:43
  • \$\begingroup\$ Two rule questions: 1. in which direction can be hurled/shoved? 2. It is not permitted for a troll to land directly on a dwarf by either walk or shove moves. but both troll moves have lines like kills dwarfs on … destination/…only if the target space … contains a dwarf. \$\endgroup\$
    – xash
    Jul 2 at 14:17
  • 1
    \$\begingroup\$ @xash Good questions, I'll update to be clear. The answer is always 8 directions vertical, horizontal and diagonal. Also, I learned about the rule that trolls can't land on anything after writing the rules. I should have updated the steps too \$\endgroup\$
    – AJFaraday
    Jul 2 at 14:31
2
\$\begingroup\$

Print this sequence I just made up

\$\endgroup\$
5
  • \$\begingroup\$ Your test cases are correct. (Confirmed with an ungolfed integer implementation.) \$\endgroup\$
    – Arnauld
    Jun 27 at 0:05
  • \$\begingroup\$ Your code must not fail due to floating point errors. If the language used doesn't have arbitrary-precision integers, an integer implementation may fail because of integer overflow before a floating point implementation fails. :-/ \$\endgroup\$
    – Arnauld
    Jun 27 at 0:13
  • \$\begingroup\$ @Arnauld Thanks for confirming my testcases. Would saying that you cannot use floats work? \$\endgroup\$
    – emanresu A
    Jun 27 at 0:34
  • \$\begingroup\$ I think the current wording is fine. It's just weird that prohibiting floating point errors is likely to lead to integer implementations that are actually worse. \$\endgroup\$
    – Arnauld
    Jun 27 at 0:41
  • \$\begingroup\$ @Arnauld Oh well. \$\endgroup\$
    – emanresu A
    Jun 27 at 0:44
2
\$\begingroup\$

Generate off-by-one regex for a string

Given an alphanumeric string as input, generate JS-flavored regex in order to match any off-by-one errors for that string. In stricter terms, your resulting regex must match any single deletions, single replacements, or single additions like in the below examples.

Examples:

"hi" -> "(h|i|.i|h.|.hi|h.i|hi.)"
"golf" -> "(olf|glf|gof|gol|.olf|g.lf|go.f|gol.|.golf|g.olf|go.lf|gol.f|golf.)"

Here is a program for generating the results.

Note: The order of the regex does not need to matter (ie, "hi" could be "(h|h.|hi.| . . .")) so long as all patterns are in the regex.

This is , so shortest program in bytes wins.

\$\endgroup\$
5
  • \$\begingroup\$ Which flavor of regex will be used? \$\endgroup\$
    – user
    Jul 4 at 16:13
  • 1
    \$\begingroup\$ @user Lets go with JS to make it consistent, it shouldn't really matter though as the regex will share the exact same format as the example cases, with only the order possibly changed. However, i've now updated the post for clarity. \$\endgroup\$
    – Underslash
    Jul 4 at 17:23
  • \$\begingroup\$ May string contains special characters like `.[]$^(?!)\`? \$\endgroup\$
    – tsh
    Jul 5 at 1:36
  • 1
    \$\begingroup\$ Your regexp for input hi also match hi itself, which is not off-by-one. Is this designed behavior? \$\endgroup\$
    – tsh
    Jul 5 at 1:37
  • \$\begingroup\$ @tsh for question 1, ill specify alphanumeric, and for question 2, ill keep it as intended just so it doesn't needlessly complicate the question, but if you have a simple way to implement it, be my guest \$\endgroup\$
    – Underslash
    Jul 5 at 9:18
2
\$\begingroup\$

Are you a probabilist or a physicist?

\$\endgroup\$
4
  • \$\begingroup\$ Is it fine to be a function in one language and a full program in another? \$\endgroup\$
    – Bubbler
    Jul 23 at 2:13
  • \$\begingroup\$ "Your programs should be true polynomials" - did you mean polyglots? \$\endgroup\$
    – pxeger
    Jul 23 at 7:50
  • \$\begingroup\$ @Bubbler Yep, that's fine \$\endgroup\$ Jul 23 at 11:35
  • 1
    \$\begingroup\$ @pxeger No, clearly you should code mathematical functions involving powers, multiplications and additions to solve this ;) Typo fixed \$\endgroup\$ Jul 23 at 11:36
2
\$\begingroup\$

Calculate the integer square root of a matrix

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Should really be "Calculate the integer square root of a matrix", because there acan be multiple square roots. E.g. [[18, 63], [14, 67]] also has as square root, the given solution divided by 11. \$\endgroup\$
    – Adám
    Jul 31 at 23:16
  • \$\begingroup\$ I think it should be "Calculate an integer square root of a matrix", since "the integer square root" is the language you would use if there were only one. If you find combining "Calculate" with "an" a bit awkward, you could substitute "Determine" or "Find". \$\endgroup\$
    – theorist
    Aug 4 at 2:22
2
\$\begingroup\$

Pinpoint the typo!

Task

Write a program that finds the location of an error in its own code!

The program itself must output either nothing or an empty string (or an appropriate equivalent in your language).

Let n be the length of the program in bytes, which must be at least 2. For an integer k with 1<=k<=n, if the kth byte of the source code is deleted, then the resulting program should output the integer k (and nothing else), in as many cases as possible.

Outputs may be 0-indexed if preferred, so that omitting the kth byte outputs k-1, but the choice of indexing must be consistent across all k.

Error messages do not count as valid output unless they are of exactly the required form.

Your score is the number of integers k for which the above condition is satisfied, divided by n. Highest score wins, with ties broken by smallest n.

Example

Consider the program blob() in a fictitious language. Suppose that:

blob() outputs nothing (this is a requirement)

lob() outputs 1 (right)

bob() outputs 2 (right)

blb() outputs 3 (right)

blo() outputs 4 (right)

blob) outputs nothing (wrong)

blob( outputs 6: Syntax error (wrong)

Then the score would be 4/6 = 0.66666667

\$\endgroup\$
7
  • 1
    \$\begingroup\$ This might be abused by simply making a very long answer. \$\endgroup\$
    – user
    Aug 5 at 20:06
  • 1
    \$\begingroup\$ Related. Related. Related \$\endgroup\$ Aug 5 at 20:11
  • \$\begingroup\$ @user Yes, I did wonder about that, although such answers might still be interesting. Ideas for a better scoring system? Number of 'wrong' answers is not great, because of very short answers.... \$\endgroup\$
    – aeh5040
    Aug 5 at 20:12
  • 1
    \$\begingroup\$ What I did with my 'Quantum quine' question, which is similar, is for the scoring system count the number of chars that it doesn't work for. \$\endgroup\$
    – emanresu A
    Aug 6 at 11:23
  • \$\begingroup\$ @emanresu A The problem I see with that is that very short programs would get an unreasonable advantage. E.g. any 4-byte program that does nothing gets 4 without even trying to accomplish the task... \$\endgroup\$
    – aeh5040
    Aug 6 at 13:24
  • \$\begingroup\$ Perhaps it would be better if the unaltered program must output Hello World or something... \$\endgroup\$
    – aeh5040
    Aug 6 at 13:27
  • \$\begingroup\$ @aeh5040 I also ruled that each answer had to have at least one functional result... Then again, quines do have to be at least a certain size. Your choice. \$\endgroup\$
    – emanresu A
    Aug 7 at 10:45
2
\$\begingroup\$

IATA Airport Codes

Out of 17576 alphabetical triplets, to this day, 9144 are used as IATA airport codes.

Given a 3-letter string, tell whether it appears in the list.

  • The input string is mixed-case by default, but you can restrict it to non-mixed-case or lower-case or upper-case

  • To output the affirmative/negative outcome you should use:

    • truthy/falsy according to your language's convention (swapping is allowed), or
    • one consistent value as either affirmative or negative, and any other value as the other
  • This is

The list was scraped from iata.org on 2021-08-07

Meta

  • Is there something that needs to be specified/clarified?
\$\endgroup\$
3
  • 1
    \$\begingroup\$ What is uniform case? Add the kolmogorov-complexity tag since there's a limited input domain? GitHub Gist is an alternative that's well-trusted by this community, I'd say \$\endgroup\$
    – pxeger
    Aug 8 at 17:05
  • \$\begingroup\$ @pxeger I want to say a string where all the letters are uppercase or lowercase, contrary to mixed-case \$\endgroup\$
    – Domenico
    Aug 8 at 17:07
  • \$\begingroup\$ @pxeger maybe non-mixed-case would be more direct? \$\endgroup\$
    – Domenico
    Aug 8 at 17:25
2
\$\begingroup\$

Radiation hardening up to order \$n\$

We'll call a program radiation-hardened of order \$n\$ if the output remains unchanged when any \$k\$ characters are removed from the program, for all \$1 \le k \le n\$. For example, a radiation hardened program of order \$2\$ would produce the same output when run as when run with any single character removed, or with any pair of characters removed.

As an example, consider the program abcde which outputs 123 in some language. This would be radiation-hardened of order \$2\$ if:

  • All of bcde, acde, abde, abce and abcd output 123, and
  • All of abc, abd, abe, acd, ace, ade, bcd, bce, bde and cde output 123

If any of the second bullet point didn't output 123 (but all of the first still did), this would only be of order \$1\$.

Your task is to write a radiation hardened program of order \$n \ge 2\$ that outputs Greetings, Earth! exactly, with an optional trailing newline.

Your score is equal to \$n\$, with a higher score winning, with code golf being the tie breaker.


Meta

\$\endgroup\$
6
  • \$\begingroup\$ If you find a language that outputs something no matter the program's contents, then you can get infinite score. I'd suggest requiring some specific output. Also infinite score is likely possible in a whole host of other cases so maybe also make the score the ratio of k to code length? \$\endgroup\$
    – pxeger
    Aug 6 at 16:54
  • \$\begingroup\$ @pxeger The point about output is a good one, I'll need to think about that. I doubt that an infinitely large score is possible (assuming I add in a specific output), as it'd require a language where either one character outputs the required string exactly once no matter how often it is repeated, or that every program in that language is equivalent to a one byte program, and that all one byte programs are the same that output the specific string \$\endgroup\$ Aug 6 at 17:01
  • \$\begingroup\$ I would add a tie breaker, since answers beyond n=1 are brutally difficult, so at least you can improve your score without having to jump up to n=3. \$\endgroup\$
    – Grain Ghost Mod
    Aug 6 at 18:08
  • \$\begingroup\$ Also source-layout is a good tag. (And it's not just that I am working towards that tag badge or something) \$\endgroup\$
    – Grain Ghost Mod
    Aug 6 at 18:13
  • \$\begingroup\$ DeadPig, order ∞. \$\endgroup\$
    – emanresu A
    Aug 7 at 2:16
  • \$\begingroup\$ I believe Backhand can make an infinite score. \$\endgroup\$
    – Bubbler
    Aug 11 at 23:37
2
\$\begingroup\$

Sum of 3 Vectors

Question

Given 3 vectors a, b, c

Find integer (n, m, r) where a*n+b*m+c*r = 0 and n,m,r are all not equal to 0.

your answer group (n, m, r) must be the closest valid group to 0, calculate by adding abs value together: |n|+|m|+|r|

You can assume that 3 vectors do not parallel

Test case

work in progress

Rules

  • no Standard loopholes
  • any I/O case allowed, as long as it's clear and mostly understandable.

Score

  • Lowest byte count per language wins!

Meta

any extra tag?

suggestions?

Rename question?

\$\endgroup\$
3
  • \$\begingroup\$ this looks like a 3d linear equation solving problem. \$\endgroup\$
    – Razetime
    Aug 19 at 4:02
  • \$\begingroup\$ Are the vectors 2-dimensional with integer components? \$\endgroup\$
    – Nitrodon
    Aug 27 at 14:53
  • \$\begingroup\$ @Nitrodon those are 2D vectors currently. \$\endgroup\$
    – okie
    Sep 1 at 1:33
2
\$\begingroup\$
\$\endgroup\$
1
  • \$\begingroup\$ Why radiation-hardening? This is the opposite, isn't it? \$\endgroup\$
    – pxeger
    Aug 21 at 14:21
2
\$\begingroup\$

Unfudge my terminal!

Intro

Today I fiddled around with termios for a program. The only thing I managed to do so far is fundging my terminal... can you help me out?

Challenge

Given a terminal input that contains fudged special chars, output the string that should be displayed if the terminal worked correctly. Here's a list of the broken special chars:

^B -> Backspace
^J -> (Fwd-) Delete
^W -> Discard
^D -> Cursor left
^C -> Cursor right
^F -> End
^H -> Start

How the special characters work

  • Backspace deletes the character behind the cursor and moves it one step back. Has no effect on the start of the string.
  • Delete deletes the character in front of the cursor. Has no effect on the end of the string.
  • Discard deletes the string typed up to this point.
  • Cursor left/right moves the cursor to the left/right by one. Has no effect on the end/start of the string.
  • End/Start move the cursor to the end/start of the string.

Undefined special characters are to be removed.

Input

  • Any represetation of a string/list of characters
  • Single lines only
  • The special characters may be either all capitalized or all not capitalized
  • The input will not contain a sequence that will result in a ^ in the output, nor will it contain a single ^ at the end.

Output

  • The unfudged input.
  • No leading/trailing whitespace that isn't part of the string.

Examples

abcd^B^B^B --> a

abcd^We^Af^Lgh --> efgh

 gof^D^D^D^Dcode^C^C^Cl --> code golf

ocde gol^H^J^Jco^Ff --> code golf

edgecase^H^D^B^J^F^C^J^B --> dgecas

Rules

  • This is , shortest answer wins
  • Standard loopholes are not allowed
  • A submissiom may be a program/function/link/lambda/chain/etc.

Tags:

Sandbox things

  • Is anything unclear?
  • Should any special char be added or removed?
  • Is there an edge case not covered by the examples?
  • Are the rules and I/O restrictions fine or should I change anything?
\$\endgroup\$
2
\$\begingroup\$

Snap (card game)

\$\endgroup\$
2
\$\begingroup\$

Display a number in Toki Pona

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Welcome to Code Golf and nice first question! Thank you for using the Sandbox first :) I've done some minor edits to add capitalisation and formatting. Tags wise, [integer-partitions] and [natural-language] both apply. This is a similar challenge, but that uses US coins \$\endgroup\$ Aug 12 at 22:49
2
\$\begingroup\$

Greedy queens sequence

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

Part 1 has been posted!

Best response to Evolution of Trust? - Part 2

This is a sequel to the first Evolution of Trust question, except it's a game!

The Game

This is a Prisoner's Dilemma question.

Make a strategy that cooperates (puts in a coin) and cheats (doesn't put in a coin). If one player puts a coin into the machine (that was mentioned before in the Part 1 question) the other player gets 3 coins.

However, either player has a 5% chance to make a mistake and do the opposite of what it meant to do.

I go into more detail about how to figure out moves below.

Code / API

For ease of judging, submissions are restricted to Python (but I'll add JavaScript soon).

A bot is a Python file that has 2 functions: move() and turn(state). move() will be called for the first move, and turn(state) for subsequent moves.

state is a list with 5 elements - the move number, your move without and with mistakes, your opponents moves with mistakes, your points, and your opponent's points.

state[0] is the move number. This will always be at least 2, as turn(state) is first called on the second move.

state[1] is a list of your intended moves so far. This does not take mistakes into account.

state[2] is the same as state[1] with one exception - this takes mistakes into account.

state[3] is your opponent's moves with mistakes taken into account. You don't know for which moves your opponent intended to do them or just made a mistake.

state[4] is your points. Similarly, state[5] is your opponent's points.

Here's an example submission that's my only submission:

Python 3.8, "alwayscheat", 20 bytes

move=turn=lambda*a:0

Yes, I know it's simple, but it's a start.

If you have time and you submission isn't 3.8, please put a 3.8 version below your main submission. In this case, your byte count will be for your non-3.8 solution, in case you're using an older version for less bytes.

Code Submission

To make a bot submission, simply post your submission here.

Each user may only make one submission, but you are allowed to edit your submission. Please don't do this too much though, as I'm manually putting all of the submissions in.

Leaderboard and Scoring

Every time you get an amount of (possibly negative) coins you have at the end of a round, they are added to your points.

<...just waiting for a few answers...>

How are the bots put against each other?

There's a tournament, the same kind as the official site's one.

We start with 10 of each bot in a tournament. Each pair of bots play 1 game against each other. The points of a bot are added up. The 5 bots with the least amount of points are deleted (if there are multiple, pick randomly). Then, the 5 bots with the most amount of points are duplicated (pick randomly - if there are still multiple). This is repeated until there is an equilibrium. The bots are ranked in order of how many of them remain when I stop the program.

If 2 bots tie for 1st place, the shortest one wins and gets accepted (it's , after all)

If you want to see the inner workings, here’s the judging source code

Sanbdox sandbox things

  • Anything that needs to be changed?
  • Any unclear bits? Probably a lot...
  • Any other things?
  • Any reason all my sandbox questions start with "Any"?
  • Any idea whether I should remove the "Any" before every sanBDox thing?

WD

\$\endgroup\$
2
\$\begingroup\$

Khinchin's constant bad estimate

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

Unicode Calendar Generator

Rules

Your program will receive a valid date in the format relevant to your language (date object or three int for year, month, day or whatever) and should returns a fancy unicode calendar as such (note that the title is right/left aligned):

Given Y-M-D as 2021-10-13
Then

╔════════════════════╗
║ October ░░░░░ 2021 ║
╟──┬──┬──┬──┬──┬──┬──╢
║░░│░░│░░│░░│░░│01│02║
╟──┼──┼──┼──┼──┼──┼──╢
║03│04│05│06│07│08│09║
╟──┼──┼──╔══╗──┼──┼──╢
║10│11│12║13║14│15│16║
╟──┼──┼──╚══╝──┼──┼──╢
║17│18│19│20│21│22│23║
╟──┼──┼──┼──┼──┼──┼──╢
║24│25│26│27│28│29│30║
╟──┼──┼──┼──┼──┼──┼──╢
║31│░░│░░│░░│░░│░░│░░║
╚══╧══╧══╧══╧══╧══╧══╝

Given Y-M-D as 2021-11-13
Then

╔════════════════════╗
║ November ░░░░ 2021 ║
╟──┬──┬──┬──┬──┬──┬──╢
║░░│01│02│03│04│05│06║
╟──┼──┼──┼──┼──┼──╔══╗
║07│08│09│10│11│12║13║
╟──┼──┼──┼──┼──┼──╚══╝
║14│15│16│17│18│19│20║
╟──┼──┼──┼──┼──┼──┼──╢
║21│22│23│24│25│26│27║
╟──┼──┼──┼──┼──┼──┼──╢
║28│29│30│░░│░░│░░│░░║
╚══╧══╧══╧══╧══╧══╧══╝

Given Y-M-D as 2021-06-15
Then

╔════════════════════╗
║ June ░░░░░░░░ 2021 ║
╟──┬──┬──┬──┬──┬──┬──╢
║░░│░░│01│02│03│04│05║
╟──┼──┼──┼──┼──┼──┼──╢
║06│07│08│09│10│11│12║
╟──┼──╔══╗──┼──┼──┼──╢
║13│14║15║16│17│18│19║
╟──┼──╚══╝──┼──┼──┼──╢
║20│21│22│23│24│25│26║
╟──┼──┼──┼──┼──┼──┼──╢
║27│28│29│30│░░│░░│░░║
╚══╧══╧══╧══╧══╧══╧══╝

This is , so you the shortest bytes of each language will be the winner.

Inspired by qwerty.dev

\$\endgroup\$
9
  • 1
    \$\begingroup\$ What does it need the day for? If you want to include the selection of the given day, perhaps you should include that in the challenge post in an example, to keep it self contained. also is the 00 intentional? \$\endgroup\$ Oct 13 at 20:29
  • \$\begingroup\$ @thejonymyster fixed. And the 00 was a mistake. Thank you :) \$\endgroup\$
    – aloisdg
    Oct 13 at 20:32
  • \$\begingroup\$ Are the month/year always to be left/right aligned, like ` May ░░░░░░░░░ 2021 `? What input formats (string, 3 integers, list, built-in date object, ...) are allowed? \$\endgroup\$
    – Dingus
    Oct 13 at 22:04
  • \$\begingroup\$ month year should be left/right aligned. For the inputs formats, what would be the most popular? \$\endgroup\$
    – aloisdg
    Oct 14 at 6:37
  • 1
    \$\begingroup\$ I'd recommend allowing any sensible input format (because the challenge is more about producing the calendar than parsing dates). You should explain the alignment rules in the post. Maybe it would be enough to swap one of the examples for a month with a shorter name, but probably better to be explicit. \$\endgroup\$
    – Dingus
    Oct 15 at 1:03
  • 2
    \$\begingroup\$ What date range is required to support? 1970~2038? Or maybe larger? \$\endgroup\$
    – tsh
    Oct 18 at 3:54
  • \$\begingroup\$ @Dingus lets use any sensible input format \$\endgroup\$
    – aloisdg
    Oct 18 at 12:31
  • \$\begingroup\$ @tsh I dont have a strong opinion about that. \$\endgroup\$
    – aloisdg
    Oct 18 at 12:32
  • \$\begingroup\$ tsh's question needs a definite answer because the date range could influence the input method and/or implementation. You should also mention that the Gregorian calendar is used. \$\endgroup\$
    – Dingus
    Oct 21 at 23:57
2
\$\begingroup\$
\$\endgroup\$
1
  • \$\begingroup\$ Name suggestion: Wheatian group :) \$\endgroup\$
    – Bubbler
    Oct 15 at 6:01
2
\$\begingroup\$

Pretty print a grid of polyominoes

Write a function that accepts a rectangular grid of ids in any reasonable format, for example a multi-line string

    
    IIILOO
    ILLLOO
    

and returns a pretty printed version,

    ╔═══════════╦═══╦═══════╗
    ║           ║   ║       ║
    ║   ╔═══════╝   ║       ║
    ║   ║           ║       ║
    ╚═══╩═══════════╩═══════╝

i.e. a rectangle made of unicode characters

0x256c: "╬" 0x2560: "╠" 0x2563: "╣" 0x2551: "║" 0x2566: "╦" 0x2554: "╔" 0x2557: "╗" 0x2569: "╩" 0x255a: "╚" 0x255d: "╝" 0x2550: "═" 0x20: " "

Rules

Shortest submission per language wins. Standard rules apply.

Note that to leave room for annotations and as the characters used are half width each unit square is 2x4 (3x5 but boundary fields are shared with neighbouring squares) characters in the output.

You may assume that input is clean rectangular and ids are unique to orthogonally connected regions.

More examples:

In:

    
    XXXSS
    RXSSL
    ROOOL
    RROLL
    

Out:

    ╔═══════════╦═══════╗
    ║           ║       ║
    ╠═══╗   ╔═══╝   ╔═══╣
    ║   ║   ║       ║   ║
    ║   ╠═══╩═══════╣   ║
    ║   ║           ║   ║
    ║   ╚═══╗   ╔═══╝   ║
    ║       ║   ║       ║
    ╚═══════╩═══╩═══════╝

In:

    
    1220003
    2240503
    2444666
    

Out:

    ╔═══╦═══════╦═══════════╦═══╗
    ║   ║       ║           ║   ║
    ╠═══╝   ╔═══╣   ╔═══╗   ║   ║
    ║       ║   ║   ║   ║   ║   ║
    ║   ╔═══╝   ╚═══╬═══╩═══╩═══╣
    ║   ║           ║           ║
    ╚═══╩═══════════╩═══════════╝

Feedback

both general and specific is most welcome. Hit me!

New contributor
loopy walt is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
\$\endgroup\$
3
  • \$\begingroup\$ For challenges which require Unicode, it's generally a good idea to let people count those characters as a single byte each. Aside from that, looks good! \$\endgroup\$
    – emanresu A
    2 days ago
  • \$\begingroup\$ @emanresuA Thank you very much for your feedback! Is there an easy way to make TIO count like that? Or perhaps as a workaround allow defining the special characters as constants in the header? \$\endgroup\$
    – loopy walt
    2 days ago
  • \$\begingroup\$ You just generally get people to count, I think. Or you could allow people to use any set of distinct characters instead of the box-drawing characters, or allow both. \$\endgroup\$
    – emanresu A
    2 days ago
2
\$\begingroup\$

Convert codepoint to UTF-9

UTF-9 was an April Fool's Day RFC joke specifications for encoding Unicode suitable for 9-bit nonet platforms.

Challenge

Your task is to implement a program or a function or a subroutine that takes one integer, who represents the codepoint of a character, to return a sequence of integers that represents its corresponding UTF-9 value.

Rules

  • Standard loopholes apply.
  • Standard I/O rules apply.
  • Shortest code wins.

Test cases

Leftmost column: Input in hexadecimal.

Right items: output as a sequence of octed integers.

0041     101
00c0     300
0391     403 221
611b     541 033
10330    401 403 060
e0041    416 400 101
10fffd   420 777 375
345ecf1b 464 536 717 033

Hint

Section 5.2 of RFC4042 has an example of the impmenentation.

Here is a non-competing Python function that represents the algorithm:

def ucs4utf9(x:int)->[int]:
 l=[]
 if x>0x100:
  if x>0x10000:
   if x>0x1000000:
    l.append(0x100|(x>>24)&0xff)
   l.append(0x100|(x>>16)&0xff)
  l.append(0x100|(x>>8)&0xff)
 l.append(x&0xff)
 return l

Test it online!

Meta

\$\endgroup\$
4
  • 5
    \$\begingroup\$ For clarity, I'd start octal constants with 0o. Also, an explanation of how UTF-9 works should probably be included here. \$\endgroup\$ Jun 19 at 1:39
  • 2
    \$\begingroup\$ Could you include the basic algorithm to encode UTF-9 in your post instead of require an external resource? So this question can be made self contained. \$\endgroup\$
    – tsh
    Oct 12 at 6:27
  • \$\begingroup\$ @tsh Should I do with actual program source or in pseudo code? \$\endgroup\$ Oct 12 at 12:26
  • \$\begingroup\$ first challenge that made me LOL \$\endgroup\$
    – don bright
    Oct 18 at 3:12
1
29 30
31
32 33
117

You must log in to answer this question.

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