461
\$\begingroup\$

What is the Sandbox?

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

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

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

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

Add Proposal

Search the Sandbox

Browse your pending proposals

Get the Sandbox Viewer to view the sandbox more easily

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

\$\endgroup\$
  • \$\begingroup\$ How are tags added to questions? \$\endgroup\$ – guest271314 Jan 9 at 7:51
  • \$\begingroup\$ @guest271314 You can use this markup to create a tag in a draft: [tag:code-golf] \$\endgroup\$ – DJMcMayhem Aug 29 at 15:19
  • \$\begingroup\$ Why no featured anymore? Can't we have it auto-added or something? \$\endgroup\$ – JL2210 Sep 26 at 15:57
  • 1
    \$\begingroup\$ @JL2210 We now have a permanent info box that links to the Sandbox, so the featured tag isn't necessary \$\endgroup\$ – caird coinheringaahing Sep 29 at 13:43

2616 Answers 2616

2
\$\begingroup\$

King of the Grid

There's a side-project of mine, simply titled My Grid Game, that's been sitting on lefttwix.com for a while. It was only a matter of time before it went automatic.

Grid game image

The rules of the game are simple:

  • Each player plays as a colour.
  • Each player starts with a City (C) 2 spaces in from opposite corners.
  • Cities spawn soldiers, they start with 10 health.
  • Soldiers will all march in the same direction as the other soldiers of the same colour. They will spawn 1 at a time (denoted by the number 1).
  • Players can change the direction of their entire army.
  • When soldiers can't go any further (either because they reach the edge of the grid or a friendly city), they join each other, to become larger groups of soldiers. (Numbers 2 - 9)
  • When 10 soldiers group up, they form a new city.
  • When soldiers meet their enemies, they kill off the enemies. The largest group of soldiers survives. (e.g. if a 5 meets a 3, it survives, but is reduced to 2).
  • When soldiers meet an enemy city, they reduce the health of that city by the size of the group.
  • When cities lose health, it can not be regained.
  • When cities or soldiers run out of health, they are destroyed.

With the API enabled

My experimental API branch is enabled at https://ajfaraday.github.io/grid_game/

The coloured boxes in the grey box correspond to the 2 players.

There's 3 ways to choose a bot for a player:

  • Select 'Code on Page' to write the code in place. The game will stop when the code is invalid.
  • Choose 'Gist ID' and paste the id of a Github Gist onto the page.
  • Select one of the existing bots.

The buttons are self-explanitory.

  • Start Start the game running
  • Stop Halt the game
  • Reset Reset the game with the same bots

The API:

You can interact with the player by making these calls:

  • api.towardsX() Change direction horizontally towards the opponent.
  • api.awayX() Change direction horizontally away from the opponent.
  • api.towardsY() Change direction vertically towards the opponent.
  • api.awayY() Change direction vertically away from the opponent.
  • api.random_direction() Change to a random direction.
  • api.turn() Returns the numbered turn, starting at zero.

Writing a bot:

  • Only use the API calls to interact with the game.
  • It does not need to be defined as a function or any other wrapping code.
  • jQuery is available.
  • Your code will be called once every turn.
  • Please, only one direction call per iteration.

Example bot:

if (api.turn() < 400) {
  if ((api.turn() % 2) == 0) {
    api.towardsY();
  } else {
    api.towardsX();
  }
} else {
  if ((api.turn() % 20) == 0) {
    api.random_direction();
  }
}

The Rules

Answers should include:

  • A name for your bot.
  • The bot's code.
  • A Github Gist ID.

Optionally

Practicalities

Note: This is the part I'm least clear about. Please do clear up how this is to be done. I can think of 3 approaches.

(league approach)

For each pair of entries:

  • I'll try it against each other entry, best of 3.
  • The winner will get a point.
  • After a week(?) I'll finalise the results and declare a winner.

(tournament approach)

  • After a week(?) I'll set up a tournament bracket with all the entries.
  • I'll try a best of 3 for each pair in the tournament.
  • The winner wins.

(Challenge the champ approach)

  • All entries get added to a list.
  • When a new entry is added, it is at the bottom of the list.
  • It will then challenge the entry immediately above it (best of 3).
  • If it wins, it moves 1 up the list, then challenges the next one and so on.
  • After 1 week(?) the tournament closes and the top of the ladder wins.

Questions:

  • Which competition approach is best?
  • Is the Gist code distribution approach okay?
  • How long should the competition last?

Thanks for looking over this!

\$\endgroup\$
  • \$\begingroup\$ Won't new cities only be possible on the edges then? \$\endgroup\$ – fəˈnɛtɪk Aug 31 '18 at 21:40
  • \$\begingroup\$ @fəˈnɛtɪk Not quite, you can also build cities against your existing cities. \$\endgroup\$ – AJFaraday Aug 31 '18 at 21:46
  • \$\begingroup\$ So you should mention that soldiers cannot move over friendly cities \$\endgroup\$ – fəˈnɛtɪk Aug 31 '18 at 22:18
  • \$\begingroup\$ 1. What happens when a soldier hits an opponent's city. 2. What's the number of a spawned soldier? 3. I'd recommend doing a round-robin, randomly pairs, or using an ELO system and having similarly scored players play each other. 4. It seems simpler to me to have the method simply return an integer for the direction (N/E/S/W) than making these API calls. 5. Don't require a gist for bots. 6. Where do cities start? \$\endgroup\$ – Nathan Merrill Sep 1 '18 at 3:53
  • \$\begingroup\$ 7. Does the bot get the state of the map? 8. Are you going to have a maximum number of turns? 9. Despite all my feedback, I really like this challenge. Definitely ping me in chat if you want some help along the way. \$\endgroup\$ – Nathan Merrill Sep 1 '18 at 4:07
  • \$\begingroup\$ @NathanMerrill 1, 2, 6, Edited. 3. Thanks for the suggestions. 4. The relative directions are to accommodate a bot starting in either corner. It will rotate it's strategy. Perhaps both options, if we can find a data structure for the state of the grid. 5. Gists were an idea for quick deployment. You seem strongly against it. What issues does it present? 7. I considered this, but it seems it'll be a large, difficult-to-consume data structure. How would you like to see this data presented? 8. I wasn't planning to, although stale mates are quite common. 9. Glad you like this one! \$\endgroup\$ – AJFaraday Sep 1 '18 at 8:34
  • \$\begingroup\$ 4. Right. I'd propose you simply do NESW, but rotate the map when displaying it to the player (so it appears that both players are on the west side). 5. SE needs to be the authority, gists can disappear, and it's extra work players shouldn't need to do (IMO). 7. You need the map to make this a game of strategy. Give it as a 2D array of {count: 4, isCity: false} objects (or maybe a mixed type array?). 8. Right, you need to somehow detect stalemates (and then score them too) \$\endgroup\$ – Nathan Merrill Sep 1 '18 at 12:32
2
\$\begingroup\$

The Input String, But Every Time It Says The First Word, It's Recursion

You wanted to create the ultimate replacement remix, but didn't see a way to add more recursion that ends naturally. Then you saw The Entire Bee Movie But Every Bee Is Replaced With The Entire Bee Movie Without Bees. Unlike the other replacement remixes, all the inserted copies were from the same text. It was the answer - at each recursing, you could remove the word being replaced, making each copy shorter than the one before it and causing the recursion to eventually end. Your master plan was complete, all that was left was to write the program to fulfill it.

The Expansion Function

Let's define some function \$F\$ on a sequence of words. Words are sequences of characters not containing whitespace, which are separated by whitespace.

define \$F(S)\$:

if \$S\$ is empty, return nothing

let \$X\$ be the first word in \$S\$

let \$Y\$ be \$S\$ with all instances of the whole word \$X\$ removed

let \$Z=F(Y)\$

return \$S\$ with all instances of the whole word \$X\$ replaced by \$Z\$

Your task is to implement \$F\$.

Input

Input the sequence of words in some form. You may choose any input method.

Output

Output the sequence of words in some form. You may choose any output method.

Only the words in the output count for correctness. If you output as a string, the leading, trailing, and separator whitespace can be anything.

Scoring

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

Examples

Small case

Input:

b o o k k e e p e r

Output:

r r p r r r r p r r e e p e r r r p r r r r p r r e e p e r k k e e p e r o o k k e e p e r

See the recursion:

Format:

value of S
result of F

r


p r
r

e e p e r
r r p r r

k         k         e e p e r
r r p r r r r p r r e e p e r

o                             o                             k k e e p e r
r r p r r r r p r r e e p e r r r p r r r r p r r e e p e r k k e e p e r

b                                                                         o o k k e e p e r
r r p r r r r p r r e e p e r r r p r r r r p r r e e p e r k k e e p e r o o k k e e p e r

Large case

Input:

peter piper picked a peck of pickled peppers a peck of pickled peppers peter piper picked if peter piper picked a peck of pickled peppers wheres the peck of pickled peppers peter piper picked

Output:

218854 words

Hello Sandbox

This section will not appear when the challenge is posted to the main site.

I can't seem to get the quote Markdown right, it might just be a parser bug where it thinks the quote continues even if there are no >s.

I originally put a description of \$F\$ as an implementation in pseudocode, but I'm considering finding a more mathematical description which tells you less about how to go about implementing it yourself. Still though, there is a challenge in optimizing this for tiny code.

\$\endgroup\$
  • \$\begingroup\$ I think the title is a bit confusing (as not everyone knows about bee movie or somewhat similar). Maybe "Recursive replacement" a better one? \$\endgroup\$ – Shieru Asakoto Sep 10 '18 at 4:37
  • \$\begingroup\$ Oh btw does "occurrence" means the whole word or being a part of another word is also counted? \$\endgroup\$ – Shieru Asakoto Sep 10 '18 at 4:41
  • \$\begingroup\$ Only a whole word counts. I'll go rewrite that to be more clear. As for the title, you're right that what the challenge is is more important than the inspiration, but I'm not quite sure what wording would be good. I'm thinking something like The Input String, But Every Time It Says This Word, It's Recursion which would state the premise while also referencing the meme. \$\endgroup\$ – EPICI Sep 10 '18 at 5:02
  • \$\begingroup\$ Oh I didn't know about the meme either. The Input blah blah blah would be better for others who don't know about the meme I think, but if you want to retain the meme that's fine. \$\endgroup\$ – Shieru Asakoto Sep 10 '18 at 5:05
  • 2
    \$\begingroup\$ The introductory paragraph primes the reader to expect a very different challenge to the one given: firstly because it sets up a scenario of infinite recursion, and secondly because it sets up a scenario where elements of the input are replaced by elements which are not in the input. IMO it would be better to remove that introduction and use it instead for a challenge which implements the scenario described and asks for the nth word in the limit string (although this may be a dupe, so check for that first). \$\endgroup\$ – Peter Taylor Sep 10 '18 at 8:15
  • \$\begingroup\$ I don't follow how the input creates the output. Could you show a step-by-step example of how each level of recursion works? \$\endgroup\$ – Beefster Sep 11 '18 at 22:39
  • \$\begingroup\$ I added more details to the "bookkeeper" example, it should explain where each part is coming from, but it may still be too brief. // As for the misleading introduction, I attempted another rewrite, but I think it may need some more revisions before I get it right. \$\endgroup\$ – EPICI Sep 12 '18 at 0:51
  • \$\begingroup\$ I think that the current I/O rules are just a little too restrictive. I would allow other inputs and outputs than "space delemited string", such as "list of words". \$\endgroup\$ – Kamil Drakari Sep 13 '18 at 19:48
  • \$\begingroup\$ After a bit of thought, I relaxed the IO to allow other formats and methods. I figured you'll have some work to do either way, so I might as well let you choose the methods that result in the least bytes. I'm not too worried about dedicated data structures as an IO format, since that's probably already covered as a common loophole. \$\endgroup\$ – EPICI Sep 13 '18 at 22:20
2
\$\begingroup\$

Triangular snake

You're given a triangular field:

Triangular field

It has 4 ports.

You're also given five different pieces from A to E:

Pieces

Each piece has a little piece of path inside it.

Your basic goal is to build paths between ports. There are some rules:

  • Each cell of the field can be occupied by 0 or 1 pieces.
  • A port can either point to an empty cell or be an endpoint of a path. That is, this is illegal: enter image description here
  • The path starts with a port and ends with a port.
  • The path must not be broken up into pieces, i.e. every edge of a piece through which a path goes must not touch an empty cell or a border without a port.

This is an example of a legal path:

enter image description here

This path can be represented as "CBEDEAD" or "DAEDEBC".

Input

There is no input.

Output

Your ultimate task is to output all the possible paths. Your output must not contain illegal paths. You can output the paths in any readable way. Order, repetitions and letter case don't matter.

\$\endgroup\$
  • 1
    \$\begingroup\$ Aren't A en E the same piece? \$\endgroup\$ – Kroppeb Sep 17 '18 at 15:12
  • \$\begingroup\$ Yes they are, what a blunder. \$\endgroup\$ – int6h Sep 17 '18 at 15:16
  • \$\begingroup\$ It's sad you can only post comments with 50 reputation, otherwise I would have noticed that already :) \$\endgroup\$ – int6h Sep 17 '18 at 15:16
  • \$\begingroup\$ @int6h Out of interest ... What is the connection? \$\endgroup\$ – Jonathan Frech Sep 18 '18 at 21:12
2
\$\begingroup\$

Iterated Prisoner's Trilemma

Please send me problems or else I'm gonna post this on main.


Prisoner's dilemma ... with three choices. Crazy, huh?

Here's our payoff matrix. Player A on the left, B on the top

A,B| C | N | D
---|---|---|---
 C |3,3|4,1|0,5
 N |1,4|2,2|3,2
 D |5,0|2,3|1,1

The payoff matrix is engineered so that it's best for both players to always cooperate, but you can gain (usually) by choosing Neutral or Defection.

Here's some (competing) example bots.

# turns out if you don't actually have to implement __init__(). TIL.

class AllC:
    def round(self, _): return "C"
class AllN:
    def round(self, _): return "N"
class AllD:
    def round(self, _): return "D"
class RandomBot:
    def round(self, _): return random.choice(["C", "N", "D"])

class Grudger:
    def __init__(self):
        self.history = []
    def round(self, last):
        if(last):
            self.history.append(last)
            if(self.history.count("D") > 0):
                return "D"
        return "C"

class TitForTat:
    def round(self, last):
        if(last == "D"):
            return "D"
        return "C"

Your bot is a Python3 class. A new instance is created for every game, and round() is called each round, with your opponent's choice from last round (or None, if it's the first round)

If we get enough entries for the result to be statistically significant, there's a 50 rep bounty for anyone who can beat Tit For Tat.

Specifics

  • Round count: [REDACTED]
  • Standard loopholes disallowed.
  • No messing with anything outside your class.
\$\endgroup\$
  • \$\begingroup\$ I have no idea how to embed tags in a post. \$\endgroup\$ – SIGSTACKFAULT Sep 28 '18 at 15:56
  • 1
    \$\begingroup\$ [tag:something] should do the trick. \$\endgroup\$ – Alion Sep 28 '18 at 16:24
  • \$\begingroup\$ thanks @Alion <3 \$\endgroup\$ – SIGSTACKFAULT Sep 28 '18 at 16:28
  • 5
    \$\begingroup\$ Way too little substance. You should add a few paragraphs describing the prisoner's trilemma, the challenge, or anything else tangentially related. \$\endgroup\$ – RamenChef Sep 29 '18 at 0:22
  • 1
    \$\begingroup\$ Don't do a pretty payoff matrix image. Use text. That way you don't exclude people with limited vision who rely on screen readers. \$\endgroup\$ – Peter Taylor Oct 1 '18 at 15:09
  • \$\begingroup\$ How many rounds per game? And why does N/N suck so much? \$\endgroup\$ – Jo King Oct 10 '18 at 8:13
  • \$\begingroup\$ @JoKing Haven't decided the round count, and probably will never tell. Don't want defect-on-the-last-round bots. No idea why I did that; if it causes problems i'll change it. \$\endgroup\$ – SIGSTACKFAULT Oct 10 '18 at 12:33
  • \$\begingroup\$ Maybe a random amount of rounds within a certain range? Also, wouldn't it be better for the second argument to be a list of all your opponents moves, rather than the latest one? \$\endgroup\$ – Jo King Oct 10 '18 at 12:42
  • \$\begingroup\$ You can do watever you want within the class, so if you need to remember the entire history, that's your problem. \$\endgroup\$ – SIGSTACKFAULT Oct 10 '18 at 12:45
2
\$\begingroup\$

Posted: Find an array that fits a set of sums

\$\endgroup\$
  • \$\begingroup\$ I'd recommend showing the steps to generating f(A) (show each of the subarrays, then calculate their sums) \$\endgroup\$ – Nathan Merrill Oct 16 '18 at 21:29
  • \$\begingroup\$ The last requirement: "any way that is convenient to you" is abusable, and basically removes the requirement entirely. Either guarantee that there will be a solution, or require that submissions return a constant value (and add a test for it) \$\endgroup\$ – Nathan Merrill Oct 16 '18 at 21:31
  • \$\begingroup\$ @NathanMerrill I don't get this last point. Maybe I should ask them to return a Falsy value? \$\endgroup\$ – Anush Oct 16 '18 at 21:33
  • 4
    \$\begingroup\$ Now that this has been posted you can delete it to make it easier for people to skip past it. \$\endgroup\$ – Peter Taylor Oct 24 '18 at 10:10
2
\$\begingroup\$

Posted

Find the minimal initial values

Consider a sequence F of positive integers where F(n) = F(n-1) + F(n-2) for n >= 2. The Fibonacci sequence is one example of this type of sequence for F(0) = F(1) = 1, but any two initial values will yield a different sequence. For example F(0) = 3, F(1) = 1 produces these terms.

3, 1, 4, 5, 9, 14, 23, 37, 60, 97, ...

Challenge

The task is to find F(0) and F(1) that minimize F(0) + F(1) given some term of a sequence F(n). Write a function or complete program to complete the task.

Input

Input is a single positive integer, F(n). It may be accepted as a parameter or from standard input. Any reasonable representation is allowed, including direct integer or string representations.

Invalid inputs need not be considered.

Output

The output will be two positive integers, F(0) and F(1). Any reasonable format is acceptable. Here are some examples of reasonable formats.

  • Written on separate lines to standard output
  • Formatted on standard output as a delimited 2-element list
  • Returned as a tuple or 2-element array of integers from a function

Examples

60  -> [3, 1]
37  -> [3, 1]
13  -> [1, 1]
26  -> [2, 2]
4   -> [2, 1]
5   -> [1, 1]
6   -> [2, 2]
7   -> [2, 1]
12  -> [3, 2]
1   -> [1, 1]

Scoring

This is code golf. The score is calculated by bytes of source code.

\$\endgroup\$
  • \$\begingroup\$ Related :-) \$\endgroup\$ – ETHproductions Oct 29 '18 at 18:37
  • 1
    \$\begingroup\$ @ETHproductions: I haven't seen that one before, and the domain is basically identical. But I still think the challenge is sufficiently distinct, since it's an optimization problem as opposed to straight forward sequence generation. \$\endgroup\$ – recursive Oct 29 '18 at 18:58
  • 1
    \$\begingroup\$ @nwellnhof: That was an oversight. I fixed it and added some examples explicitly showing F(0) > F(1). \$\endgroup\$ – recursive Oct 29 '18 at 20:26
  • \$\begingroup\$ Spec seems watertight to me. \$\endgroup\$ – trichoplax Oct 29 '18 at 20:31
  • 1
    \$\begingroup\$ In general, if m<n, you can always replace [m,n] with [n-m,m] for a better solution, so F(0) >= F(1) for all optimal solutions. \$\endgroup\$ – nwellnhof Oct 29 '18 at 20:50
  • \$\begingroup\$ @nwellnhof: Yes, I see now. I've adjusted more of the test cases, and am considering removing the part about ambiguous solutions if it's irrelevant. I don't have any examples then where there multiple distinct optimal solutions. It kind of feels like that can't happen, but I don't have a proof to that effect. If I can sufficiently convince myself it is impossible, I'll remove the part about ambiguous solutions. \$\endgroup\$ – recursive Oct 29 '18 at 21:03
  • \$\begingroup\$ I believe I came up with a proof of uniqueness. I think it may not fit in a comment well, but the basic idea is to write any one of these sequences as s_k = f_k-2 s_21 + f_k-1 s_2 where f_k is the sequence starting with 1, 0 at k = -1, 0 instead of the usual indices. Then it is pretty clear that if two distinct sequences reached the same value at the same index, they must differ from each other by a constant times a ratio of two consecutive Fibonacci numbers. This is only an integer for the pair 1,1 and all such ambiguities are handled by you excluding 0 as a starting value. \$\endgroup\$ – FryAmTheEggman Oct 30 '18 at 0:15
  • \$\begingroup\$ @FryAmTheEggman: I removed the part about ambiguous solutions. I'm not following your proof outline at the moment, but I'll take your word for it. :) \$\endgroup\$ – recursive Oct 30 '18 at 0:24
  • 1
    \$\begingroup\$ I was bored so here's the full thing. I wound up changing some stuff around so hopefully it is easier to follow. Obviously I could have messed up so if anyone notices anything wrong let me know! \$\endgroup\$ – FryAmTheEggman Oct 30 '18 at 2:40
2
\$\begingroup\$

Implement LogiMuxi

The language

LogiMuxi is, as its name suggests, a programming language based on multiplexers.

Built-in gates

  • M(A,B,C) (Multiplexer): If A is 0, returns is B, otherwise returns C.
  • R() (Random): Returns either 0 or 1 uniformly randomly.
  • I() (Input): Reads a bit from STDIN and returns it. Terminates program execution on EOF.
  • O(A) (Output): Appends bit A to STDOUT and returns it.

Literals

0, 1 are literals. Literals are expressions, and can be used as values.

Gate calling

G(<arg1>,<arg2>,...,<argx>) calls gate G with the provided arguments in order. Gate calling is an expression.

Conditional loop

G
 <cmd1>
 <cmd2>
 <...>
 <cmdx>

Evaluates G. If G returns 1, the indented commands are executed, and this process repeats again. If G returns 0, the loop is skipped. If there are no indented commands under G, the loop is empty, and, therefore, if G is 0 then nothing happens, while if G is 1 we enter an infinite loop with no way out.

Value assignment

X=G

Assigns X to the result of G. After that, the identifier of the variable can be used as an expression, and it will evaluate to the current value of the variable.

Gate definition

G(<arg1>,<arg2>,...,<argx>)
 <cmd1>
 <cmd2>
 <...>
 <cmdx>

Defines gate G to take arguments <arg1> up to <argx> (actual argument identifiers are specified by the programmer) and return the result of H. The identifiers of the arguments are localized, as well as variables assigned inside the gate. This means that, if I assign variable X to value A outside of G and then there's an X=B command in the definition of G, calling G will not assign X to B. However, inside the gate's scope, X will take the new value B. Assigning the arguments themselves to new values is allowed. Example:

X=0
G(A,B)
 X=1
 O(X)
 :M(R(),A,B)
O(X)

This will output the bits 1 and 0 in order. For reference, G chooses randomly between A and B in this example.

Gate definitons may also be nested, in which case they will be localized too.

Returning happens by prepending a : (colon) to a value (e.g. to return value A, use command :A). This will exit the gate and return the value to the right of it. You can't leave the part to the right of : empty. A gate that doesn't return is invalid.

Additional notes

  • Commands are separated by line separators.
  • An identifier has to meet these criteria:
    • The first character has to be in ABCDEFGHIJKLMNOPQRSTUVWXYZ_
    • From the second character onward, the identifier must only be composed of characters in ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.
    • It can't be the identifier of any of the built-in gates.
  • A variable and a gate may use the same identifier. They can be separated by the way they are invoked. Of course, this is bad practice, but this language is already pretty esoteric. ;-)
  • Use of an undefined identifier is invalid.
  • A gate is always to be called with parentheses, even if it doesn't take arguments. This includes the built-in gates.
  • A gate may only return one output, and it must return one.
  • Nested loops or gates are represented with the appropriate number of spaces used as indentation.
  • Useless indentation is prohibited.
  • Lines may be empty, but their indentation is significant. Empty lines do nothing.
  • Calling gates with the wrong number of arguments is invalid.
  • If the number of bits sent to STDOUT isn't a multiple of 8, the bits are post-padded with 0s (e.g. if STDOUT is 00010000 11100, it will be converted to 00010000 11100000 before actual printing).
  • If 8 bits have been sent to STDOUT, they will be converted to a character and output immediately.
  • Any syntax not defined above should be considered undefined.

Reference gates

You may skip this section.

NOT:

NOT(A)
 :M(A,1,0)

AND:

AND(A,B)
 :M(A,0,B)

OR:

OR(A,B)
 :M(A,B,1)

XOR:

XOR(A,B)
 :M(A,B,M(B,1,0))

NAND:

NAND(A,B)
 :M(A,1,M(B,1,0))

NOR:

NOR(A,B)
 :M(A,M(B,1,0),0)

XNOR:

XNOR(A,B)
 :M(A,M(B,1,0),B)

Simplification tips

You may skip this section.

M(A,0,1)A

M(M(A,1,0),B,C)M(A,C,B)

M(0,B,C)B

M(1,B,C)C

Sample programs

You may skip this section.

Infinite loop, no output:

1

Cat:

1
 O(I())

Hello, World!:

O(0)
O(1)
O(0)
O(0)
O(1)
O(0)
O(0)
O(0)
O(0)
O(1)
O(1)
O(0)
O(0)
O(1)
O(0)
O(1)
O(0)
O(1)
O(1)
O(0)
O(1)
O(1)
O(0)
O(0)
O(0)
O(1)
O(1)
O(0)
O(1)
O(1)
O(0)
O(0)
O(0)
O(1)
O(1)
O(0)
O(1)
O(1)
O(1)
O(1)
O(0)
O(0)
O(1)
O(0)
O(1)
O(1)
O(0)
O(0)
O(0)
O(0)
O(1)
O(0)
O(0)
O(0)
O(0)
O(0)
O(0)
O(1)
O(0)
O(1)
O(0)
O(1)
O(1)
O(1)
O(0)
O(1)
O(1)
O(0)
O(1)
O(1)
O(1)
O(1)
O(0)
O(1)
O(1)
O(1)
O(0)
O(0)
O(1)
O(0)
O(0)
O(1)
O(1)
O(0)
O(1)
O(1)
O(0)
O(0)
O(0)
O(1)
O(1)
O(0)
O(0)
O(1)
O(0)
O(0)
O(0)
O(0)
O(1)
O(0)
O(0)
O(0)
O(0)
O(1)

1-bit half adder:

A=I()
B=I()
O(M(A,0,B))
O(M(A,B,M(B,1,0)))

Challenge rules

  • You may assume you'll not receive an invalid program, or a program with input that will make it do invalid actions, so you don't need to check it for validity.
  • The program can be either separated by line separators, or given as a list of lines. Acceptable line separators are \n, \r\n and \r (\n denotes character 0x0A, \r denotes character 0x0D).
  • Input can be taken in any reasonable form explicitly separated from the program, not necessarily from STDIN. Also, it can either be the actual input, or its bits (e.g. you can take 0100000001000001 instead of @A). It's guaranteed to be finite for this challenge.
  • Output can be provided in any reasonable form, either as bits or as text. Also, you don't actually need to output while the program is executing, unlike what the specification above says.
  • You may use any four distinct identifiers for the built-in gates M, R, I and O. Identifier rules will apply to your chosen identifiers in this case.
  • You may use [] instead of (), and/or tabs instead of spaces in indentation. You must be consistent with these choices.
\$\endgroup\$
2
\$\begingroup\$

Sock Drawer Simulator

Socks are often kept in drawers, and when people wear socks they like the left and right socks to match [citation needed].

Challenge

Given an array of the number of socks of each color, simulate the process of drawing socks, and output the color of the first pair found. You may assume that:

  • Socks are drawn sequentially, randomly and without replacement.
  • A pair is found when a sock of a color that has already been drawn is drawn.

Obviously, the precise algorithm doesn't matter as long as the output probability distribution is correct.

Input

A nonempty array of positive integers representing the frequency of each color of sock. For example, [3,1,4,1,5] could represent a drawer with three teal, one aquamarine, four green, one cyan, and five cerulean socks. There will always be at least one possible pair.

Output

A nonnegative integer representing the color (index) of the sock drawn. You may consistently use either one-indexed or zero-indexed arrays.

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

Survival Game: Alien Hunters (working title)

Based on Create Your Wolf, but the combat is very different.


Somewhere, deep in the heart of the galaxy, lies the planet Oizys. A toroidal planet in the habitable zone of its star, its bountiful land and beautiful oceans make it the perfect planet for your race of aliens to start colonizing as an interstellar civilization.

Unfortunately, a few dozen other alien races are also trying to colonize it, and you can't stand them. So you're going to have to kill them.

Your Alien

Your task is to write an implementation of the net.ramenchef.oizys.Alien class:

package net.ramenchef.oizys;

public class Alien {
    public enum Move {
        // a whole bunch of values; these are described in "the board"
    }

    /**
     * Used by the runner to keep track of the alien's energy.
     */
    double energy = 1.0;

    /**
     * Moves the alien.
     *
     * @param surroundings The alien's surroundings. The first
     *  dimension is North–South, with index 0 being North. The second
     *  dimension is East–West, with index 0 being West.
     * @return A {@code Move} object representing the direction to
     *  move the alien
     */
    public abstract Move move(char[][] surroundings);

    /**
     * Called when the alien is in battle.
     *
     * @param opponents The other aliens on this tile that need to be
     *  fought
     * @return The amount of energy to use in this battle
     */
    public abstract double attack(char[] opponents);
}

100 instances of your class will be spawned in random locations on the board for each trial. Each alien class will be assigned a unique character to represent them on the board.

There are a number of stock alien races that already inhabit Oizys:

  • Rocks: they do absolutely nothing and don't pose any sort of threat (i.e., they attack with 0 energy), but for some reason your generals don't know what rocks are, so they appear just like any other alien.
  • Random Bears: they act randomly. They move in a random direction (including possibly not moving at all) and attack using a random portion of their energy.

The Board

Oizys is a toroidal planet, so the board will be side-looped on both edges. The width and height of the board will be equal to \$\left\lceil\sqrt s\right\rceil\$, where s is the number of alien species. Each round, your aliens will have the option to move one tile horizontally and/or vertically with the move method. This method takes a 3x3 char[][] representing the alien's surroundings, with a[0][0] being Northwest and a[0][2] being Northeast, and returns a Move enum. The possible Move values are NORTHWEST, NORTH, NORTHEAST, WEST, HOLD, EAST, SOUTHWEST, SOUTH, and SOUTHEAST.

Combat

If two or more aliens attempt to move into the same tile, they will fight. What better opportunity to kill those annoying other aliens! Or maybe get killed yourself, who knows? Each alien starts with 1 energy, and uses it to fight other aliens. When aliens fight, they use the attack method, which takes a char[] representing their opponents and returns a double, to determine how much energy they will use for that battle. The alien that uses the most energy wins, and the others die. In the case of a tie, the winner is determined by coin flip. An alien cannot use more energy than it has or it will die; neither can it use a negative amount of energy.

Scoring

Five trials will be held, with each trial being scored by the portion of the aliens remaining that are your alien. These trials will be held on [1 month after the challenge is posted].

Other Rules

  • Standard loopholes are forbidden.
  • Aliens attempting to alter field visibility/writability will be met with mysterious SecurityExceptions.
  • The order that aliens' methods are called is undefined, though there is a happens-before relationship between calls on successive rounds, as well as between aliens moving and those same aliens attacking each other.
\$\endgroup\$
  • \$\begingroup\$ How do the aliens get energy? What is the energy limit mentioned in the description of the dragon? \$\endgroup\$ – Laikoni Apr 12 '18 at 8:54
  • \$\begingroup\$ @Laikoni the dragons have unlimited energy, and the rest of the aliens start with all the energy they'll get. \$\endgroup\$ – RamenChef Apr 12 '18 at 12:08
  • \$\begingroup\$ So the energy is a floating point number? Doesn't that cause potentially more trouble than just saying it's initially 100 and using ints? \$\endgroup\$ – Laikoni Apr 12 '18 at 12:35
  • \$\begingroup\$ @Laikoni how would using a floating point be a bad idea? \$\endgroup\$ – RamenChef Apr 12 '18 at 12:57
  • \$\begingroup\$ Testing for equality of floating point numbers can give imprecise results, see e.g. en.wikipedia.org/wiki/… \$\endgroup\$ – Laikoni Apr 12 '18 at 13:44
  • \$\begingroup\$ @Laikoni it's not testing for equality; it's comparing them. Whereas ints would not allow bots to divide their energy successively ad infinitum. \$\endgroup\$ – RamenChef Apr 16 '18 at 16:51
  • \$\begingroup\$ 1. You should disallow all reflection. 2. You need to run way more than 5 trials to get a good answer. 3. How are trial scores combined? What's the char for nothing? 4. You should add a helper method to get their own energy, as well as their own character. 5. I'd argue for int energy that is simply really high (like the maximum int or even maximum long). Then you don't deal with floating point imprecision, and will even improve calculation speed. 6. What happens when something attacks a rock? What does the rock return? \$\endgroup\$ – Nathan Merrill Apr 18 '18 at 14:52
  • \$\begingroup\$ 7. If I lose a battle, do I lose energy, or do I instantly die? 8. Re Dragons: I see two primary issues: The attack is so high to make fighting them pretty impractical. It's possible to identify them based off of their movement, but your field of vision is very small. If vision is bigger, then bots will learn to avoid them, but now many bots will start to imitate dragons. In essence, making dragons so strong changes the balance of the game drastically. Consider if that is really what you want. 9. Do you allow communication between instances of the same bot? What about different bots? \$\endgroup\$ – Nathan Merrill Apr 18 '18 at 14:57
  • \$\begingroup\$ @NathanMerrill 1) Why go beyond installing a SecurityManager? 2) The winner usually won't be determined by luck alone. 3) They're averaged. (will add this to the spec) 4) I had one for energy in the runner, but I forgot to document it. 5) ints can't go to 10^-300. 6) The rock returns 0. 7) You die instantly. The winner loses energy. 8) Noted. 9) Yes. Hiveminds are allowed. \$\endgroup\$ – RamenChef Apr 18 '18 at 23:46
  • \$\begingroup\$ 1) Because KotHs shouldn't be about the language, they should be about the core game rules. The instant you bring in reflection, you get in the world of one-upping: No matter how good my bot is, it can be one-upped. 2) Really? As of right now, I don't see any reason why not. Your starting position has a huge affect on how well you do. 3) Note that this means that winning by a large margin on a few games means more than consistently winning by a little. (This isn't bad, but its worth considering). 5)Ok? You don't need that much precision. 6,7,8) Please add to spec :) \$\endgroup\$ – Nathan Merrill Apr 19 '18 at 2:46
  • \$\begingroup\$ The aliens won't be given the classes of their opponents; only their character. If they want to keep pets of their opponents (like MultiWolf) I won't stop them \$\endgroup\$ – RamenChef Apr 19 '18 at 11:57
  • \$\begingroup\$ @RamenChef fair enough, but MultiWolf does't require reflection. He could simply have a function that builds the array by calling their constructors normally. \$\endgroup\$ – Nathan Merrill Apr 19 '18 at 15:03
  • \$\begingroup\$ @NathanMerrill Reflection is more streamlined though. \$\endgroup\$ – RamenChef Nov 21 '18 at 16:23
  • \$\begingroup\$ I'd love to see this make it to the main site. You can use something like this to open up the competition to other languages, but be warned, you may end up spending quite a few hair-pulling hours trying to get other people's code to work on your machine. I'll be the third to comment that using integers would be better. You commented that you won't be testing for equality but in the challenge spec you mention handling ties. How are multi-way ties handled? Maybe change "determined by coin flip" to "chosen at random". \$\endgroup\$ – Rainbolt May 22 at 23:27
  • \$\begingroup\$ Maybe I missed it, but what char represents an empty square? \$\endgroup\$ – Rainbolt May 22 at 23:27
2
\$\begingroup\$

Count smooth numbers

Define \$\Psi(x,B)\$ as the number of integers between \$1\$ and \$x\$, whose prime factors are all \$B\$ or less. (These are the \$B\$-smooth numbers.)

For example, there are 34 integers between 1 and 100 that have only 2, 3 and 5 as prime factors. These are:

 1  2  3  4  5  6  8  9 10 12
15 16 18 20 24 25 27 30 32 36
40 45 48 50 54 60 64 72 75 80
81 90 96 100

Therefore, \$\Psi(100,5)=34\$. The next prime is 7, so \$\Psi(100,6)\$ is also 34.

This is a challenge to calculate exact values of \$\Psi\$ as quickly as possible.

Methods

You may not use libraries or built-ins that calculate this function. That being said, I don't know any language that has a built-in for this (not even Mathematica?)

I also can't seem to find any fast algorithms for this problem, except for a basic meet-in-the-middle by Daniel J. Bernstein which might be a good starting point.

Bernstein also describes an approximation method that may or may not be useful.

Input range

You may assume that \$1<B\leq x\leq 10^{100}\$ and \$B<10^6\$.

Scoring

You will be scored on tiers of increasing difficulty.

Each tier has several inputs \$(x,B)\$ such that the \$\Psi(x,B)\$ have similar values, and the \$x\$ values are distributed exponentially. Tiers will start at around \$\Psi(x,B)\approx 10^9\$ and go up to \$\Psi(x,B)\approx 10^{20}\$ or more, depending on how fast the entries get.

The time limit for each tier is 60 CPU seconds per input on average. In other words, if a tier has \$n\$ inputs, you will essentially have \$n\$ CPU minutes to obtain the outputs. You are welcome to submit parallel code but each thread will count towards the time limit.

Your score is the highest tier that your program can solve. If there is a tie, the program that is fastest on the highest tier wins.

For practical reasons, your program will be limited to 15GiB of memory.

Sample tiers

Warm-ups:

3:
  Ψ(10^3, 997) = 1000
  Ψ(10^6, 7)   = 1273
  Ψ(10^9, 5)   = 1530
6:
  Ψ(10^6,  999983) = 1000000
  Ψ(10^9,  59)     = 1060717
  Ψ(10^12, 29)     = 1469549
  Ψ(10^15, 17)     =  919814
  Ψ(10^36, 7)      =  936046

Tiers:

9:
  Ψ(10^9,  999983) =  616220853
  Ψ(10^10, 4567)   =  954965955
  Ψ(10^12, 337)    = 1180049403
  Ψ(10^15, 97)     = 1016358704
  Ψ(10^18, 59)     = 1106651678
  Ψ(10^24, 31)     =  791377032
  Ψ(10^30, 23)     =  812060729
  Ψ(10^48, 17)     = 1435897064
10:
  Ψ(10^11, 11987) = 10016301575
  Ψ(10^12, 1499)  = 10753426440
  Ψ(10^15, 199)   = 12766644440
  Ψ(10^18, 89)    =  9052115006
  Ψ(10^24, 47)    = 11298682134
  Ψ(10^30, 37)    = 14838208717
  Ψ(10^48, 19)    =  7868307089
11:
  Ψ(10^13, 2297) =  84344528150
  Ψ(10^15, 443)  =  96272828440
  Ψ(10^18, 163)  = 107816435926
  Ψ(10^36, 37)   =  94053521936
  Ψ(10^24, 67)   =  81421195505
  Ψ(10^48, 29)   = 151266342065

etc.

I may choose to do the actual scoring on different inputs, including using \$x\$'s that are not powers of 10.

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

Squish these Numbers

META: I think my wording is not very clear, if you have a suggestion to make it easier to understand, feel free add a commment or edit it directly in to this post.

Given a finite sequence of real floating point numbers, map it into the Interval \$[-1,1]\$, such that the order of these numbers is preserved.

Details

  • You can choose any mapping you like, it doesn't have to be linear.
  • The mapping you choose doesn't have to stem from a function, that means some number \$x\in \mathbb R\$ doesn't have to get mapped to the same number in \$[-1,1]\$, the value it does get mapped to can change depending on the other values in the input list.
  • Two equal values in the input list, should remain equal in the output.
  • If some value in the input list is strictly smaller than some other value, then the corresponding values in the output should satisfy the same relation, in theory. In practice it might happend that two different numbers will get mapped to the same output due to floating point arithmetic issues, which is fine - as long as it would work with an arbitrary precision.
  • You can assume the input sequence contains at least two distinct entries.

Examples

Following example finds a linear map that maps the least entry to \$-1\$ and the greatest entry to \$1\$. Note how this map depends on the sequence.

$$ (x_1,x_2,\ldots,x_n) \mapsto \left( \frac{x_i - \min_k x_k}{\max_k x_k - \min_k x_k} \right)_{i=1}^n $$

Following example is a fixed function that always behave the same. Because it is monotonic and strictly increasing, it satisfies all conditions. $$ (x_i)_{i=1}^n \mapsto \left(\frac{\arctan(x_i)}{\pi} \right)_{i=1}^n$$

Thanks @PeterTaylor for following example. Here \$\operatorname{sort}(x)\$ sorts the input sequence in ascending order and \$\operatorname{indexof}(u,v)\$ returns the index of the first occurence of \$v\$ in the sequence \$u\$.

$$(x_i)_{i=1}^n \mapsto \left( \frac{1}{n} \operatorname{indexof}(\operatorname{sort}(x),x_i)\right)_{i=1}^n$$

\$\endgroup\$
  • \$\begingroup\$ How about a function which sorts the array and then maps \$x_i \to \frac1n \textrm{indexof}(\textrm{sorted}(x), x_i)\$? \$\endgroup\$ – Peter Taylor Dec 18 '18 at 14:59
  • \$\begingroup\$ Yeah that looks fine (assuming for e.g. \$x_1 = x_2\$ we get the same index). - If you do not mind I'll add that as an example too. \$\endgroup\$ – flawr Dec 18 '18 at 17:22
  • 2
    \$\begingroup\$ I think many languages have builtin tanh which trivializes this. Are you sure there are enough languages where this challenge is interesting? \$\endgroup\$ – lirtosiast Dec 19 '18 at 0:40
  • 2
    \$\begingroup\$ I expect it will be hard for a list-aware function to beat a general mapping like x->1+1/(1+2**-x), or just tanh if that's available, but maybe Peter Taylor's method will be shorter in golfing languages. I think it's worth noting in the spec that it's OK if due to float inaccuracies two very close values are mapped to the same value in practice. \$\endgroup\$ – xnor Dec 19 '18 at 0:42
  • \$\begingroup\$ @xnor I'll add the comment about the floating point problems, that is a good point. I'm convinced that there will be a lot of different approach that will be optimal in the different languages. \$\endgroup\$ – flawr Dec 19 '18 at 9:16
2
\$\begingroup\$

Shortest JsFuck code for a number

JsFuck is a language using only []()!+ to run and express anything in JavaScript. Below is a simplified model of JavaScript to express numbers:

  • Types
    1. Number
    2. String
    3. Boolean (true)
    4. Array
  • Functions
    • IEEEdouble(x):
      • Let \$u\$ is the number in \$\{a\cdot 2^{b}|-2^{53}<a<2^{53}, b>-1075, a,b\in \mathbb Z\}\$ nearest to x, maximizing \$b\$ on tie
      • If \$|u|<2^{1024}\$, return \$u\$
    • toNumber(x):
      • If x is a Number, return x;
      • If x is a Boolean, return 1;
      • If x is an Array [y], return toNumber(y);
      • If x is an Array [], return 0;
      • Otherwise, x is a String. In this case,
      • If x matches /^([\+\-]?(?:\d*\.?\d+|\d+\.))(?:e([\+\-]?\d+)?$/, let \$v=\text{$1}\times 10^\text{$2}\$ ($2 is zero if not present)
      • Return IEEEdouble(\$v\$)
    • toString(x):
      • If x is a String, return x;
      • If x is a Boolean, return 'true';
      • If x is an Array [y], return toString(y);
      • If x is an Array [], return '';
      • Otherwise, x is a Number. In this case,
      • Find \$p, q\in \mathbb Z\$ such that IEEEdouble(\$p\times 10^q\$)=x, maximizing \$q\$(there may be multiple \$p\$ satisfying the restriction, in which case choosing which one is unknown);
      • Let \$y=p\times 10^q\$;
      • If \$y=0\$ or \$10^{-6}\leq|y|<10^{21}\$, write it normally without scientific notation mapping the RegEx /^([1-9]\d*|0)(\.\d*[1-9])?$/;
      • Otherwise, write it in scientific notation mapping the RegEx /^[1-9](\.\d*[1-9])?e[\+\-][1-9]\d*$/
    • x+y
      • If either x or y is a String or an Array, return toString(x) concatted with toString(y);
      • Otherwise, return IEEEdouble(the sum of toNumber(x) and toNumber(y))
    • +x
      • Return toNumber(x)
    • [] and [x]
      • Return an Array.
    • x[y]
      • If x is a String, return the yth character(0-index) in x
    • !![] and !+[]
      • Return a Boolean

A valid JsFuck code is always parenthesis balanced without two symbols + together. Expression in parenthesis is calculated before the one out. On the same layer operations go from left to right.

You are required to output the shortest JsFuck code that generates a given IEEE double (A possible output of IEEEdouble). Shortest generator wins.

It's fine if your generator runs slow, but beware of potential infinite loop if you eval.

Samples

1     -> +!![]
2     -> !![]+!![]
10    -> +[+!+[]+[+[]]]
1e10  -> +(+!![]+(!![]+[])[!![]+!![]+!![]]+(+!![])+(+[]))
0.1   -> +((+(+!![]+[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+!![])+(+[]))+[])[+!![]]+(+!![]))
1e-10 -> +((+(+!![]+[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+!![])+(+[]))+[])[+!![]]+(+[])+(+[])+(+[])+(+[])+(+[])+(+[])+(+[])+(+[])+(+[])+(+!![]))
5e-324-> +(!![]+!![]+!![]+(!![]+[])[!![]+!![]+!![]]+(+((+(+!![]+[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+!![])+(+[]))+[])[+!![]]+(+[])+(+[])+(+[])+(+[])+(+[])+(+[])+(+!![]))+[])[!![]+!![]]+(!![]+!![]+!![])+(!![]+!![])+(!![]+!![]+!![]+!![]))
9999999999
      -> +(+!![]+(!![]+[])[!![]+!![]+!![]]+(+!![])+(+[]))+(+((+((+(+!![]+[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+!![])+(+[]))+[])[+!![]]+(+[])+(+[])+(+[])+(+[])+(+[])+(+[])+(+!![]))+[])[!![]+!![]]+(+!![])))

SN: Another way to ask is requiring to be testable and shouldn't be longer than a chosen generator

\$\endgroup\$
  • 2
    \$\begingroup\$ Challenge seems a bit too long-- maybe restrict the domain to integers? Also I can't see any competitive solution actually finishing for nontrivial test cases because they'd just eval all valid JSFuck strings in parallel. \$\endgroup\$ – lirtosiast Jan 6 at 3:41
  • \$\begingroup\$ @lirtosiast Do your "integer" mean safe integer? Also I don't see how it simplifies the problem much \$\endgroup\$ – l4m2 Jan 6 at 7:30
2
\$\begingroup\$

Is it shifted?

Consider a standard US-International QWERTY keyboard, without a numeric keypad, and Caps Lock mysteriously missing.

< insert image >

The goal is to write two programs or functions that take no input, and each give a distinct output through any default output method: Shift and No shift respectively. The program that outputs No shift has to be written without use of the ⇧ Shift key. The program that outputs Shift has to be written while holding the ⇧ Shift key throughout. Both programs have to be written using the exact same sequence of keypresses. A valid entry would be a1b2 + A!B@, if they output No shift and Shift respectively.

The symbols allowed for the "No-shift" program are as follows:

`1234567890-=
qwertyuiop[]\
asdfghjkl;'
zxcvbnm,./
<space> <newline> <tab> 

The symbols allowed for the "Shift" program are as follows:

~!@#$%^&*()_+
QWERTYUIOP{}|
ASDFGHJKL:"
ZXCVBNM<>?
<space> <newline>

Note that Tab ↹ is missing, since Shift+Tab ↹ does not produce a \t tab symbol in most editors.

Sandbox note

I think using case-sensitive output makes the challenge more challenging, but it might become too challenging. What are your thoughts?

\$\endgroup\$
  • \$\begingroup\$ This already appears to be impossible in most productive languages, so I would allow output in any case. \$\endgroup\$ – Laikoni Jan 13 at 8:53
2
\$\begingroup\$

Touch-typing distance

Tags: ,

Related: Levenshtein distance


There are many different string metrics, a simple one is the Levenshtein distance given by \$\texttt{ld}_{a,b}(|a|,|b|)\$:

$$ \texttt{ld}_{a,b}(i,j) = \begin{cases} \max(i,j), & \text{if $i = 0$ or $j = 0$} \\ \\ \min \begin{cases} \texttt{ld}_{a,b}(i-1,j) + c_\text{deletion} \\ \texttt{ld}_{a,b}(i,j-1) + c_\text{insertion} \\ \texttt{ld}_{a,b}(i-1,j-1) + w(a_i, b_j) \end{cases}, & \text{otherwise} \end{cases} $$

The avid reader may have noticed that there are missing pieces in the above definition, it makes use of a weight function \$w\$ which was never defined and the costs \$c_\text{deletion}\$ as well as \$c_\text{insertion}\$.

The Levenshtein distance uses an indicator function which evaluates to \$1\$ if the two characters are not equal and \$0\$ otherwise and costs \$1\$ for deletion and insertion. This does not take into account that a mistake of typing u instead of w should cost more than mistakenly typing an e. Let's try to fix this!

Challenge

For this challenge we'll assume a QWERTY keyboard and only take lower-case letters into account. We will use the usual letter-to-finger assignment (left-most finger to right-most) ["qaz","wsx","edc","rtfgvb","yuhjnm","ik","ol","p"]:

Left Hand

  • pinky: qaz
  • ring finger: wsx
  • middle finger: edc
  • index finger: rtfgvb

Right Hand

  • index finger: yuhjnm
  • middle finger: ik
  • ring finger: ol
  • pinky: p

Now, to define a new string metric we will use the following definitions in the above generalized Levenshtein distance: Set \$c_\text{deletion} = c_\text{insertion} = 8\$ and for \$w(a_i,b_j)\$ we will use the distance of the two characters plus \$1\$ according to the above assignments (unless they are equal, then we'll use \$0\$). Here are a few examples:

'q' 'q' -> 0
'q' 'a' -> 1
'q' 'w' -> 2
'l' 'g' -> 4
'p' 'a' -> 8

Rules

Input will be two strings \$a\$ and \$b\$ which

  • are non-empty
  • only contain lower-case letters (ie. match ^[a-z]+$)

Output will be the "touch-typing distance" as defined above.

Test cases

"todo" "todo" → 0
\$\endgroup\$
2
\$\begingroup\$

Shift right by half a bit

The challenge is to implement a program or function (subsequently referred to as "program") that takes a nonnegative integer \$n\$ as input and returns \$n\over\sqrt{2}\$ (the input divided by the square root of two) as output, rounded to a nonnegative integer.

You may take your input and output in any reasonable format; for example stdin/stdout, files, or arguments/return values would all be acceptable.

You are required to use, at minimum, the largest fixed-size integer type offered by your language, and if an unsigned variant of this is available, you must use it. If your language has no built-in integer type (e.g. JavaScript) you are allowed to use its default numerical type (e.g. floating point); for languages with no concept of a number (e.g. regex), input and output can be e.g. the length of a string.

It is not required to reject negative integers; a submission that returns correct answers for negative inputs is allowed, but not required. Undefined behavior with negative inputs is allowed.

You are allowed and encouraged to use arbitrary-precision integer types if you so desire, but the type must either be a built-in, part of a standard library, or implemented from scratch in your program.

Despite what the title might imply, you may use any rounding algorithm you want (floor, ceiling, nearest half up, nearest half even, arbitrary, or even random), as long as the difference between the integer returned value and the theoretical exact (irrational) value is always less than \$1\$ for all inputs that fit in your chosen integer type. All inputs up to the maximum representable value must return a correct output.

In a way, the job of this program is to calculate the irrational number \$\sqrt{2}\$ to the requested precision, presenting it in the form of an integer. This is why solutions using arbitrary-precision types are encouraged, but not required.

This is a challenge. Standard loopholes are denied. The program with the least number of bytes wins. If there's a tie, the choice of accepted answer will be at my discretion. That said, this challenge is not only about which answer wins; it's also about seeing how concisely the challenge can be solved in each language, and seeing how each language "prefers" to handle rounding. And for those submissions that choose to use arbitrary precision, it's about seeing how concisely this can be done in the language.

Meta

The primary reason for the question is that I want to post my ECMAScript regex solving it. Currently all I have is an 849 byte (very heavily golfed down from an initial 1159 bytes) ECMAScript + molecular lookahead regex, i.e. not purely ECMAScript-compatible and only works on my regex engine, so this question can stew in the Sandbox for a while until I port the regex to pure ECMAScript at some point, and/or put the regex engine on TIO.

That said, I am genuinely interested in what submissions PPCGers will come up with for this challenge (including in the languages more frequently seen in PPCG posts), and will treat the hosting of it seriously. Also there's the chance that someone will attempt solving it in a more powerful regex flavor, and I'd be fascinated to see if this could be done in significantly less length than ECMA (I actually doubt it can). Or somebody could come up with a crazy solution for it in some other language that has limits imposed which make it hard to do.

And if somebody could think of a way to solve it in ECMA in fewer bytes than I have (or even just golf down my regex), that would be fascinating (or thrilling) as well.

I'd be interested in putting up a bounty for the regex aspects of this question, and would appreciate any suggestions people would have as to how to do this and how much the bounty should be.

\$\endgroup\$
  • 2
    \$\begingroup\$ The whole stuff about type widths is confusing and I think it gets self-contradictory. E.g. "You are required to use an integer type of at least the precision of a native int. If your language has a native unsigned integer type, you must use it (if you're using a native type)". Java has signed 8-, 16-, 32- and 64-bit integers, and unsigned 16-bit integers. Which should it use? What does "native int" even mean in the context of languages which aren't C? Why should I get a better score in C if I'm using an underpowered computer which doesn't distinguish between uint and long long uint? \$\endgroup\$ – Peter Taylor Jan 26 at 9:11
  • 1
    \$\begingroup\$ @PeterTaylor What I'm really trying to achieve with that requirement is increasing the likelihood that in at least some languages, simply calculating it using floating point, e.g. convert the int to double, divide by sqrt(2) and convert back to int, would lose precision, making it necessary to implement the sqrt function in integer math. But I wanted to not actually prohibit floating point from being used. I agree with your criticism though. What if I simply require that the largest built-in fixed-size integer type be used at minimum if it exists (or arbitrary-precision if desired)? \$\endgroup\$ – Deadcode Jan 26 at 10:13
  • 1
    \$\begingroup\$ Thanks for explaining your goal. I'll think about it and see whether I can think of another way of achieving it. If you haven't already done it, you could pop into chat and ask the people there to think about it too. \$\endgroup\$ – Peter Taylor Jan 26 at 20:00
  • \$\begingroup\$ Thank you, @PeterTaylor. I actually did talk about it a bit in the chat earlier, which is actually why I required native ints in the original version... \$\endgroup\$ – Deadcode Jan 26 at 20:20
  • 2
    \$\begingroup\$ I hadn't noticed your edit. That's probably as good a solution as is possible. One other minor suggestion: how about changing the title to "Shift right by half a bit"? \$\endgroup\$ – Peter Taylor Jan 27 at 8:30
  • \$\begingroup\$ @PeterTaylor I love your title suggestion. Thank you so much! I kept the text "divide by the square root of two" and moved it to the description, in case of Math Processing Errors and also so it will show up in searches more easily. \$\endgroup\$ – Deadcode Jan 27 at 8:53
  • 3
    \$\begingroup\$ Can you add some test cases? \$\endgroup\$ – 640KB Jan 27 at 15:37
2
\$\begingroup\$

Irregular English Verbs

Given the infinitive of an irregular English verb, output its simple past and its past participle.

Rules

  • The input and output can be given in any convenient format.
  • No need to handle verbs not in the given list.
  • Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
  • If possible, please include a link to an online testing environment so other people can try out your code!
  • Standard loopholes are forbidden.
  • This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

Example

fall    --> fell; fallen
beat    --> beat; beaten or beat
bereave --> bereaved or bereft; bereaved or bereft
shall   --> should;(no participle)

List of Irregular Verbs

Infinitive;Simple Past;Past Participle
alight;alighted or alit;alighted or alit
arise;arose;arisen
awake;awoke or awaked;awoken or awaked
be;was or were;been
bear;bore;borne or born
beat;beat;beaten or beat
become;became;become
beget;begot;begotten
begin;began;begun
bend;bent;bent
bereave;bereaved or bereft;bereaved or bereft
beseech;besought or beseeched;besought or beseeched
bet;bet or betted;bet or betted
bid;bade or bid;bidden or bid or bade
bide;bade or bided;bided
bind;bound;bound
bite;bit;bitten
bleed;bled;bled
bless;blessed or blest;blessed or blest
blow;blew;blown
break;broke;broken
breed;bred;bred
bring;brought;brought
broadcast;broadcast or broadcasted;broadcast or broadcasted
build;built;built
burn;burnt or burned;burnt or burned
burst;burst;burst
bust;bust or busted;bust or busted
buy;bought;bought
can;could;(no participle)
cast;cast;cast
catch;caught;caught
choose;chose;chosen
cleave;cleft or cleaved or clove;cleft or cleaved or cloven
cling;clung;clung
clothe;clothed or clad;clothed or clad
come;came;come
cost;cost;cost
creep;crept;crept
crow;crowed;crew or crowed
cut;cut;cut
deal;dealt;dealt
dig;dug;dug
do;did;done
draw;drew;drawn
dream;dreamt or dreamed;dreamt or dreamed
drink;drank;drunk
drive;drove;driven
dwell;dwelt or dwelled;dwelt or dwelled
eat;ate;eaten
fall;fell;fallen
feed;fed;fed
feel;felt;felt
fight;fought;fought
find;found;found
flee;fled;fled
fling;flung;flung
fly;flew;flown
forbid;forbad or forbade;forbid or forbidden
forecast;forecast or forecasted;forecast or forecasted
forget;forgot;forgotten
forsake;forsook;forsaken
freeze;froze;frozen
geld;gelded or gelt;gelded or gelt
get;got;got or gotten
gild;gilded or gilt;gilded or gilt
give;gave;given
gnaw;gnawed;gnawed or gnawn
go;went;gone
grind;ground;ground
grip;gripped or gript;gripped or gript
grow;grew;grown
hang;hung;hung
have;had;had
hear;heard;heard
heave;heaved or hove;heaved or hove
hew;hewed;hewed or hewn
hide;hid;hidden or hid
hit;hit;hit
hold;held;held
hurt;hurt;hurt
keep;kept;kept
kneel;knelt or kneeled;knelt or kneeled
knit;knitted or knit;knitted or knit
know;knew;known
lay;laid;laid
lead;led;led
lean;leant or leaned;leant or leaned
leap;leapt or leaped;leapt or leaped
learn;learnt or learned;learnt or learned
leave;left;left
lend;lent;lent
let;let;let
lie;lay;lain
light;lit or lighted;lit or lighted
lose;lost;lost
make;made;made
may;might;(no participle)
mean;meant;meant
meet;met;met
melt;melted;molten or melted
mow;mowed;mown or mowed
pay;paid;paid
pen;pent or penned;pent or penned
plead;pled or pleaded;pled or pleaded
prove;proved;proven or proved
put;put;put
quit;quit or quitted;quit or quitted
read;read;read
rid;rid or ridded;rid or ridded
ride;rode;ridden
ring;rang;rung
rise;rose;risen
run;ran;run
saw;sawed;sawn or sawed
say;said;said
see;saw;seen
seek;sought;sought
sell;sold;sold
send;sent;sent
set;set;set
sew;sewed;sewn or sewed
shake;shook;shaken
shall;should;(no participle)
shear;sheared;shorn or sheared
shed;shed;shed
shine;shone;shone
shit;shit or shitted or shat;shit or shitted or shat
shoe;shod or shoed;shod or shoed
shoot;shot;shot
show;showed;shown or showed
shred;shred or shredded;shred or shredded
shrink;shrank or shrunk;shrunk
shut;shut;shut
sing;sang;sung
sink;sank;sunk
sit;sat;sat
slay;slew;slain
sleep;slept;slept
slide;slid;slid
sling;slung;slung
slink;slunk;slunk
slit;slit;slit
smell;smelt or smelled;smelt or smelled
smite;smote;smitten
sow;sowed;sown or sowed
speak;spoke;spoken
speed;sped or speeded;sped or speeded
spell;spelt or spelled;spelt or spelled
spend;spent;spent
spill;spilt or spilled;spilt or spilled
spin;spun;spun
spit;spat;spat
split;split;split
spoil;spoilt or spoiled;spoilt or spoiled
spread;spread;spread
spring;sprang or sprung;sprung
stand;stood;stood
steal;stole;stolen
stick;stuck;stuck
sting;stung;stung
stink;stank or stunk;stunk
stride;strode;stridden
strike;struck;struck
string;strung;strung
strive;strove;striven
swear;swore;sworn
sweat;sweat or sweated;sweat or sweated
sweep;swept;swept
swell;swelled;swollen or swelled
swim;swam;swum
swing;swung;swung
take;took;taken
teach;taught;taught
tear;tore;torn
telecast;telecast or telecasted;telecast or telecasted
tell;told;told
think;thought;thought
throw;threw;thrown
thrust;thrust;thrust
tread;trod;trodden
understand;understood;understood
wake;woke or waked;woken or waked
wear;wore;worn
weave;wove;woven
wed;wed or wedded;wed or wedded
weep;wept;wept
wet;wet or wetted;wet or wetted
win;won;won
wind;wound;wound
wring;wrung;wrung
write;wrote;written
\$\endgroup\$
  • 2
    \$\begingroup\$ So this is a simple lookup, meaning that the bulk of the challenge is compressing the data? \$\endgroup\$ – Adám Jan 24 at 12:48
  • 1
    \$\begingroup\$ Shouldn't the correct output from can be could;was able to rather than could;(kein Participle)? \$\endgroup\$ – Adám Jan 24 at 12:49
  • \$\begingroup\$ @Adám what about simply can -->could; ? \$\endgroup\$ – mdahmoune Jan 24 at 12:54
  • \$\begingroup\$ Up to you. Using (kein Participle) makes the challenge more interesting, as it has the only uppercase character, and the only parentheses. \$\endgroup\$ – Adám Jan 24 at 14:02
  • 3
    \$\begingroup\$ @Adám, no. It should be could or was able to or were able to;been able to. It certainly shouldn't be (kein Participle): the spec asks for output in English, not German. \$\endgroup\$ – Peter Taylor Jan 24 at 15:04
  • \$\begingroup\$ @PeterTaylor OP hasn't answered, but to me it looks like lookup KC, so the actual content doesn't actually matter. \$\endgroup\$ – Adám Jan 24 at 16:59
  • \$\begingroup\$ @Adám Yes, I think it's a simple lookup, it can be other than that? \$\endgroup\$ – mdahmoune Jan 28 at 10:39
  • \$\begingroup\$ Imho, it would be much more interesting to take a regular verb as input, and output the past tense: Add "ed" or "d" if verb ends with "e", but change final consonant-"y" to "consonant-"i" and insert "k" if verb ends in "c" and double final consonant if verb ends with a single vowel followed by a single consonant. \$\endgroup\$ – Adám Jan 28 at 13:04
  • \$\begingroup\$ Suggested tag: kolmogorov-complexity \$\endgroup\$ – ბიმო Jan 28 at 13:19
  • \$\begingroup\$ @Adám Do u mean adding the rules, or extending the current list with some regular verbs? \$\endgroup\$ – mdahmoune Jan 28 at 14:00
  • \$\begingroup\$ I meant replacing the list, so the challenge will only concern completely regular verbs. It is of course your choice. I can also post this related (but not really related, just inspired by) challenge myself. Let me know. \$\endgroup\$ – Adám Jan 28 at 14:39
  • \$\begingroup\$ @Adám Using only regular verbs would make it a very different challenge. I think this one is interesting as-is. Even if these verbs are irregular, they do follow some rules of their own (such as i becomes u). You may want to identify and store the transformation rules that are common to several verbs rather than just do string compression. \$\endgroup\$ – Arnauld Feb 5 at 23:21
  • \$\begingroup\$ @Arnauld can I use your comment to improve the text of the challenge? \$\endgroup\$ – mdahmoune Feb 6 at 12:00
  • \$\begingroup\$ Sure. (But maybe you should use a better example than just 'i becomes u' and make it clear that this is not a general rule but just a rule that applies to several verbs.) \$\endgroup\$ – Arnauld Feb 6 at 13:53
2
\$\begingroup\$

Generate a 3D spiral

Inspired by this chat message

The spiral used in The Path Of The Wildebeest is a contiguous mapping of the positive integers to lattice points in 2D. Your task is to generalize this to 3D.

Specifically, create a function \$f\$ from \$\mathbb Z^+\$ to \$ \mathbb Z^3\$ with the following properties:

  • \$f\$ is a bijection (All points are eventually reached).
  • \$f(1) = (0,0,0)\$ (The spiral starts at the origin).
  • \$ |f(n+1) - f(n)| = 1\$ (The spiral is contiguous).
  • The Chebyshev distance from the origin \$ |f(n)|_\infty \$ is a nondecreasing function (\$f\$ fills all points in each concentric cubical shell \$k\$ before moving to shell \$k+1\$).

One possible \$f\$ is given by this Python implementation, but any \$f\$ that satisfies the above properties is allowed. Please describe the function your answer generates.

Because all your computer's memory is taken up by the wildebeest simulation you're running, typing is very slow, so your code must be as short as possible.

I/O

As is standard with questions, either 1-indexing or 0-indexing is allowed. Any of these I/O formats are acceptable:

  • Receive \$n\$ as input and output the \$n\$th point in the sequence
  • Receive \$n\$ as input and output the first \$n\$ points
  • Take no input and output the sequence infinitely.
\$\endgroup\$
  • \$\begingroup\$ Editing this from "is an increasing function" to "is a nondecreasing function" doesn't fix the problem... the function will sometimes have to decrease, because it has to hop over its own path and come back down. If you're already taking this into account, could you please be clearer about what you mean? \$\endgroup\$ – Deadcode Jan 30 at 1:40
  • \$\begingroup\$ @Deadcode I'm not sure what you mean by hopping over its own path. This challenge is just to generate the spiral, not the path of any chess piece. \$\endgroup\$ – lirtosiast Jan 30 at 1:45
  • \$\begingroup\$ Okay, imagine an actual ball of yarn. But to simplify things, let's imagine you start with a sphere. Start wrapping a string around it. After you make 1 revolution, you must adjust the angle of the string so that it crosses over its previous path. This will make a small bump in the path the string takes on its 2nd revolution. And on its 3rd revolution, there will be more bumps. Now imagine the analogy with a cube, quantizing the path to a cubical grid. The 2nd revolution will have to cross over the path the 1st revolution took, making a bump, 1 up, 1 down. \$\endgroup\$ – Deadcode Jan 30 at 1:56
  • \$\begingroup\$ I think in the cubical case, the path of the yarn can be arranged such that it never goes over bumps. \$\endgroup\$ – lirtosiast Jan 30 at 1:58
  • \$\begingroup\$ Okay, but then it will bear much less resemblance to a ball of yarn. \$\endgroup\$ – Deadcode Jan 30 at 2:04
  • \$\begingroup\$ @Deadcode the key point here is that it's the Chebyshev distance that's non-decreasing. So the 3d lattice is divided into cubic shells centered on the 0 point, and the function has to map to all of the points in shell n before moving on to shell n+1 \$\endgroup\$ – trichoplax Jan 30 at 21:37
  • \$\begingroup\$ (in that sense it's analogous to the 2d case) \$\endgroup\$ – trichoplax Jan 30 at 21:41
2
\$\begingroup\$

Countries by Area

\$\endgroup\$
  • \$\begingroup\$ You can remove the backticks before and after the list then select it and press Ctrl + K, it will show as a single block of code then \$\endgroup\$ – RedClover Apr 19 '18 at 13:59
  • \$\begingroup\$ @user202729 This isn't a KC because an answer to the challenge should accept inputs. \$\endgroup\$ – Shieru Asakoto Nov 19 '18 at 8:05
2
\$\begingroup\$

Least efficient field order

Background:

In C and other languages, a struct is a data type composed of fields of other data types. These fields may be different sizes (in bytes) and may have different alignment requirements (e.g. an int field may need to be on a 4-byte boundary).

Padding is added to a struct to keep all of its fields aligned, and to keep its size a multiple of each field's alignment.

For example:

struct test {
    char  a; // 1-byte, 1-byte aligned
    short b; // 2-byte, 2-byte aligned
    int   c; // 4-byte, 4-byte aligned
}

In this struct, there will be 1 byte of padding after a (to keep b on a 2-byte boundary), no padding after b (as c is already on a 4-byte boundary) and no padding after c (as the size is already a multiple of 2 and 4 bytes), so the total size of the struct is 8 bytes (1 + 2 + 4 + 2). However, if we rearrange the order of the fields, the struct size can be bigger.

struct test_2 {
    char  d; // 1-byte, 1-byte aligned
    int   e; // 4-byte, 4-byte aligned
    short f; // 2-byte, 2-byte aligned
}

In this struct, there will be 3 bytes of padding after d (to keep e on a 4-byte boundary) and there will be 2 bytes of padding after f (to keep the size a multiple of 2 and 4 bytes), so the total size of this struct is 12 bytes (1 + 4 + 2 + 3 + 2).

Challenge:

Given a list of pairs of positive integers (each pair representing the size and alignment of a field), return the same pairs in an order such that a struct with fields in that order would require the most padding, i.e. be the least space-efficient.

Givens:

  • A field's size will always be greater than or equal to its alignment. (e.g. (4, 8) is not a valid input pair)

  • A field's size will always be a multiple of its alignment. (i.e. (12, 5) is not a valid input pair)

Test cases: (other outputs that give the same total size are valid as well)

[(1, 1), (1, 1), (4, 4)] -> [(1, 1), (4, 4), (1, 1)] # size 12
[(12, 4), (1, 1), (2, 2), (8, 8)] -> [(12, 4), (8, 8), (1, 1), (2, 2)] # size 32
[(7, 7), (5, 1), (2, 2)] -> [(7, 7), (2, 2), (5, 1)] # size 28
[(6, 6), (6, 3), (4, 2), (2, 2)] -> [(6, 3), (4, 2), (6, 6), (2, 2)] # size 24
[(1, 1)] -> [(1, 1)] # size 1

Test case checker online!

\$\endgroup\$
  • 1
    \$\begingroup\$ I think in your explanation (1 + 2 + 4 + 2) should be (1 + 2 + 4 + 1). The only thing I see about this challenge that is questionable is whether having separate alignments is interesting or tedious. Would this lose much by assuming each field's alignment is equal to its size? \$\endgroup\$ – FryAmTheEggman Feb 25 at 21:25
2
\$\begingroup\$

The Minigame Challenge

The idea of this CnR is fairly simple: The Cops must create a simple minigame (explained in more detail below), with a definite goal. That goal may or may not be achievable. The Robbers must then either complete the minigame, or prove its goal is not achievable.

Rules

The Minigame

The Cops will create a suitably simple minigame with a definite goal.

Acceptable minigame examples are functions that take some input and return some output, with the goal being to either achieve a specific output, or make the program terminate or error.

Minigames considered complex (and thus unnacceptable) would be programs/functions that will never terminate in up to 60s (using TIO as a benchmark here), or that simulate complex games (such as blackjack, chess, etc).

Note: I'll try to expand further on what kinds of minigames are acceptable or not. Suggestions are appreciated.

Cops:

The Cops must provide one of the following:

  • A solution for your minigame that achieves the goal, or
  • A proof that the goal for your minigame is not achievable.

at least 7 days (168h) after the answer was posted for their answer to be considered safe.

If your minigame's goal is achievable, it must always be achievable, and it must not contain "insider information", such as a fixed seed for a pRNG, or pregenerated primes as factors of a number to be factored.

Robbers:

To crack an (unsafe) answer, the robber must provide either a solution to the minigame that achieves the stated goal, or a proof that the goal is not achievable.

Scoring:

Cops will be scored based on standard rules, with the fewest number of bytes in an answer being better. Cracked answers will always have a score of \$\infty\$.

Robbers are scored according to the number of answers they've cracked.

Standard loopholes are, as usual, forbidden.

Challenge is still under construction

This is the first CnR I've ever come up with. Suggestions and observations are always appreciated.

\$\endgroup\$
  • 5
    \$\begingroup\$ This seems a lot like PCG inside PCG. \$\endgroup\$ – Beefster Mar 15 at 19:16
2
\$\begingroup\$

Challenge

Create a function takes in two 2-dimensional arrays of Characters (or Strings if the programming language does not have characters as a datatype) as inputs: a and b.

Your task is to determine if b contains a. If this is so, return true. Otherwise, return false.

Sample Test Cases

a:

123
456
789

b:

123
456
789

should return true.

a:

code
golf

b:

thisis
code!!
golf!!
ohyeah

should return true.

a:

abcd
efgh
ijkl

b:

abcdef
ghijkl
mnopqr

should return false.

Least bytes wins.

\$\endgroup\$
  • \$\begingroup\$ does the block need to be as-is? No lines inbetween? No characters? i.e. does code\golf appear in `code!!\trucking!!\golf!!`? \$\endgroup\$ – Ven Mar 25 at 11:04
2
\$\begingroup\$

(No title yet)

I'm traveling away from home, and while visiting a fair a dart-throwing game catches my eye.

To play, I can buy \$d\$ darts at a time. There are no other options for purchase.

There are \$t\$ identical targets, but since I'm not a great shot, I can't consistently aim at just one. Instead, I can hit one (at random) with nonzero probability \$p\$.

Of course, just to make it harder for me management also decided it would be too easy if players won a prize immediately upon hitting a target. Rather, I need to hit the same target \$n\$ times in order to get the prize. As long as I keep playing, darts that have already landed on targets will remain there, but if I leave, they will be reset.

I'd rather not be scammed though, so I would like to know how many times I should expect to purchase darts in order to win at least one prize.

Task

Given \$d\$, \$t\$, \$p\$, and \$n\$, find the expected cost for me to get at least one prize.

Test cases

(just some basic ones, for now)

  d,  t,  p,  n  -> E

 __, __, __,  1  -> 1/(1-(1-p)^d)
 __, __,  1, __  -> t*n

Comments

Any suggestions to improve wording or formatting? Is anything unclear or confusing?

Would it be more interesting to ask for the expected cost to get at least \$x\$ prizes, instead? In that case, a target would award a prize for every \$n\$ darts landed, i.e. at \$n,2n,3n,\ldots\$ darts.

What level of accuracy should be required?

Ideas for test cases?

Not entirely sure what other tag(s) I'd like to work with here. Golf should be interesting... I'd also like to see faster solutions though, and I would expect golfy solutions to be very inefficient.

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

Finding Points in Convex Hulls

Convex hulls are notoriously hard to deal with, so today's challenge will deal with a relatively simple premise: given a convex hull defined by a set of points, and an additional point, find whether the additional point lies in the hull.

Now, for some definitions

  1. The convex hull of a finite set X, a subset of R^n, is the set of convex combinations of points of $X$.
  2. A convex combination of points x1,x2,...,xn is a point of the form a1x1+a2x2+...+anxn such that all ai>=0 and the sum of all of the ai is 1.

Input/Output

The input is rather flexible, as long as it contains the appropriate information to express the convex hull and additional point.

An example of a valid input format to express the convex hull represented by (0,1,2),(4,3,2),(8,8,8) and the point (5,5,5) is

([(0,1,2),(4,3,2),(8,8,8)],(5,5,5))

The output is a truthy/falsy value, depending on whether the point is contained in the hull.

Remarks

There are a lot of packages and libraries that deal with convex hulls, such as scipy.spatial. Such libraries/packages are explicitly banned. Libraries that facilitate matrix computations, such as numpy, are permitted.

The winning criterion is .

There is no limit on the number of dimensions the points can lie in, as long as they all lie in the same number of dimensions.

Test Cases

I will be using the following tio link for testing the validity of solutions.

Some smaller test cases:

([(1,1)],(1,1)) - True
([(1,1)],(1,2)) - False
([(1,1,1),(3,3,1)],(2,3,1)) - False
([(1,1,1),(3,3,1)],(2,2,1)) - True
([(0,0),(3,3),(0,6)],(2,4)) - True
([(0,0),(3,3),(0,6)],(1,1)) - True
([(0,0),(3,3),(0,5)],(2,4)) - False

Questions for Sandbox

Is code golf the best criteria for this? That might encourage brute force searches on every combination of points... any suggestions?

\$\endgroup\$
  • \$\begingroup\$ You mention R^n but all the examples use Z^n (which is much easier to work with computationally). Please clarify the expected input. Also, what about libraries for linear programming? \$\endgroup\$ – Peter Taylor Apr 1 at 10:03
  • \$\begingroup\$ @PeterTaylor I was thinking of making it R^n only, since one can bash out the answer if it is in Z^n. And, linear programming libraries probably also should be banned. \$\endgroup\$ – Don Thousand Apr 1 at 13:08
  • \$\begingroup\$ I'm not sure how easy it is to bash out the answer. The weights could be rational, and it's not obvious to me that the denominators can be bounded because the entire system can be translated. \$\endgroup\$ – Peter Taylor Apr 1 at 20:35
  • \$\begingroup\$ @PeterTaylor Hmm, I'll think about how to revise this. \$\endgroup\$ – Don Thousand Apr 1 at 22:05
2
\$\begingroup\$

This is a post to pre-test for a duplicate question before I spend the time to finish the full post and add test cases.

So, have we ever had a question for a "snake rotation" of a matrix:

    +--------------+
      1  2  3  4  5|
    +------------  |
    |10  9  8  7  6|
    |  +-----------+
    |11 12 13 14 15
    +--------------+


    +--------------+
-->  13 14 15  1  2|
    +------------  |
    | 7  6  5  4  3|
    |  +-----------+
    | 8  9 10 11 12  -->
    +--------------+

The ascii walls are there only for clarity. Actual input/output would be normal matrices

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

Sample Input    Sample Output
/abcd/          /dcba/
/[^abc]/        /(?!a)[^bc]/
/[^abc]/        /[^abc]/
/(.)abc\1$/     /^(.)cba\1/
/$1/            /10% of $10/
/\123/          /S/

Shortest code win

TODO: List of allowed RegEx features, mainly if (?<=xxx) is allowed

\$\endgroup\$
  • 2
    \$\begingroup\$ What's the regex flavor/set of allowed features/inputs? Is it for a full or partial match? \$\endgroup\$ – feersum May 10 at 9:07
  • \$\begingroup\$ @feersum Allowed features need discuss. To be a full match ^ and $ can be added \$\endgroup\$ – l4m2 May 10 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\$ – Kevin Cruijssen May 10 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 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\$ – Kevin Cruijssen May 10 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\$ – FryAmTheEggman May 11 at 21:28
2
\$\begingroup\$

WordArt reader

I've decided to leave this very open ended, so that I can write it based on community input. There are a lot of questions in the bottom. All feedback is appreciated, even minor suggestions/comments. :)

,,.


Did you know WordArt is still a thing in MS Word? Let's parse it!

1]

(I'll remove the Swag format)

The challenge will contain a test battery with X jpg.files each with a word or sentence shown in WordArt. Your task is to parse as many as you can. The winner will be the submission that correctly parses the most images, with date stamp being the tie breaker.


Sandboxing:

  • Good idea or not?
  • Should there be many different styles, or should I stick to one? Colors? Shade/mirroring?
  • How many test cases?
  • Is jpg the best format (it was used in the Upgoat/Downgoat challenge)
  • Should I have a more refined scoring mechanism? It's hard to mix two quantities into one score.
  • Should I stick to just letters / alphanumeric / all printable ASCII / multiple lines? Long sentences or single words?
  • Orientation? Waves? Circular?
  • Resolution?
  • Builtin functions?
  • Should I require a complete match of images, or character by character?
\$\endgroup\$
  • \$\begingroup\$ Nice challenge! 1 WordArt is a completely objective (good) definition. 2 Some of the questions was mainly for the problem of the challenge being "too hard", so if you want any answer at all you should simplify those. (somehow most PPCG users are lazy). 3 Format is not a very important problem (conversion is easy), but just to be sure, use a lossless format. \$\endgroup\$ – user202729 Nov 7 '17 at 16:48
  • \$\begingroup\$ There is another problem of the font used. \$\endgroup\$ – user202729 Nov 7 '17 at 16:49
  • \$\begingroup\$ The challenge is supposed to be hard. Scoring based on the success rate would be useless if not. But it's of course possible to change the scoring, and make the test cases easier. \$\endgroup\$ – Stewie Griffin Nov 7 '17 at 17:00
  • 4
    \$\begingroup\$ 1. optical-char-recognition. 2. Upgoat/Downgoat used JPG because it used photos. IMO it's preferable in general to allow any raster image format, because otherwise you pretty much force people to use languages with library support for image decoding. 3. The "Swag" example is ambiguous: is it "Swag Swag"? 4. If you want to refine the scoring mechanism, I would do it as the sum of Levenshtein distances from the correct results. But the big problem with scoring test-battery is the tension between keeping the tests secret (to prevent overfitting) and public (for objective scoring). \$\endgroup\$ – Peter Taylor Nov 8 '17 at 7:25
  • 1
    \$\begingroup\$ 3. I can avoid the Swag-type format. Are the other formats unambiguous? 4. I can either show all the possible formats, and say that I will use words that are say 4-15 characters, or maximum 15 characters per example. I can then pre-select the input list, and provide a hash that ensures I won't change the input list after answers are posted. People can then try their code on some random strings of their own choosing on various formats and approximate their results, while the final score is made public later...? \$\endgroup\$ – Stewie Griffin May 22 at 6:43
  • \$\begingroup\$ Thanks for the link to the other challenges, they are useful as references when writing this challenge. Do you think this is different enough by the way? \$\endgroup\$ – Stewie Griffin May 22 at 6:58
2
\$\begingroup\$

How many right triangles can you find?


Challenge

You will be given an input represented by x, which is a string containing at least 3 characters. It will consist only of the standard numeric characters, 0 through 9. Your job is to find and output how many right triangles can be formed with the given numbers.

Rules

  • Numbers must be kept in the order they were given in. No mixing them up!

  • The numbers for each right triangle must be consecutive.

  • The order of numbers has to be a first, b second, and c third, and must satisfy the formula a² + b² = c². a can be greater than or less than b, as long as it satisfies the formula.

  • Decimal points may be added between any numbers.

  • Decimals require one or more numbers to be placed before them, e.g. .5 cannot be used as a number but 0.5 and 12.5 can.

  • Decimals with at least 4 digits after the decimal point truncated to the third digit, e.g. 1.2345 would truncated to 1.234 and 1.9999 would be truncated to 1.999.

  • Numbers can be used more than once in 2 or more different triangles, but cannot be used multiple times in the same triangle.

  • Multiple representations of the same value can count multiple times.

  • Repeating zeros are allowed, e.g. 000.5 counts as a number.

  • All possible combinations must be taken into account for your program to be valid.

Example Inputs and Outputs

Input: 345
Output: 1
This can be split into 3, 4, and 5, which, of course, form a right triangle.

Input: 534
Output: 0
While this does include the necessary numbers to form a right triangle, they are not in the correct order. It has to follow the formula a² + b² = c², but in this case it follows c² = a² + b². The order of numbers cannot be changed from the original input, so in this case no right triangles can be formed.

Input: 3415
Output: 0
This does contain a 3, 4, and a 5, which can form a right triangle, but they are not consecutive; there is a 1 splitting the 5 from the 3 and 4.

Input: 5567507
Output: 1
Because decimals can be added anywhere, it can be changed to 55.67.507, which allows splitting it into 5, 5.6, and 7.507 to form a right triangle. Remember that decimals are truncated to the third digit after the decimal point, which is how we get 7.507.

Input: 345567507
Output: 2
The first right triangle is formed by 3, 4, and 5. The second one is formed by 5567507 (read the previous example for explanation). Numbers can be used more than once, so the first 5 was used in the first and second triangles.

Input: 51125
Output: 0
Because of rule 5, you cannot use .5, 1, and 1.25. An integer is required before .5 for it to work.

Input: 051125
Output: 0
Unlike the previous example, there is a number before the first 5, so it is now legal to use 0.5, 1, and 1.25.

Input: 121418439
Output: 2
The numbers 12 and 14 would form a right triangle where side c has a length of approximately 18.43908891458577462000. Because long decimals are truncated to the third digit after the decimal point, we would be left with 18.439. This fits in with the original input, 121418439. Additionally, 1.2, 1.4, and 1.843 counts as a separate combination, thus giving us our second right triangle.

Input: 10011005
Output: 8
Numbers count separately if they're represented in different ways, so this allows for (1, 00, 1), (1.0, 0, 1), (1, 0, 01), (1, 0.01, 1), (1, 0.01, 1.0), (1, 0.01, 1.00), (1.0, 0.1, 1.005), and (1, 00.1, 1.005).


This is code golf, so shortest answer in bytes wins. Good luck!

\$\endgroup\$
  • \$\begingroup\$ So if I understand correctly we do the following things: get all substrings of the input; get all 3-part partitions of each substring; insert a comma at each possible position in each possible partition; check any combination of three in order is approximately truthy for \$a^2+b^2=c^2\$ (approximately, because the decimals have been truncated, so aren't exactly a right triangle in some cases). Do I understand this correctly? \$\endgroup\$ – Kevin Cruijssen May 8 at 7:07
  • \$\begingroup\$ @KevinCruijssen almost correct, except you must find all combinations both with and without decimals at any given location. So it's not necessarily just adding a decimal point at every possible place; it's checking the results that would occur both by adding and not adding a decimal. \$\endgroup\$ – Pika the Wizard of the Whales May 8 at 14:19
  • \$\begingroup\$ "Numbers can be used more than once." - Could you provide some examples of this or otherwise clarify what you mean? \$\endgroup\$ – Beefster May 10 at 19:52
  • \$\begingroup\$ @Beefster see the fifth example: one of the 5's is used to form two different right triangles. \$\endgroup\$ – Pika the Wizard of the Whales May 10 at 19:57
  • \$\begingroup\$ Perhaps a better way to explain it would be something like "Right triangles that only use a subsequence of the digits can overlap with other triangles made from the same sequence of digits" or "You do not need to use all the digits for a single triangle and you may re-use digits that were used in previous triangles". What confused me about the way it's currently written is that it could be taken to mean that you can re-use a digit for the same triangle, so 125059 could be split into 12, 22, 25.059. \$\endgroup\$ – Beefster May 13 at 22:45
2
\$\begingroup\$

\$n\$-Chess KotH

Introduction

Inspired by the challenge N-movers: How much of the infinite board can I reach?, I came up with an idea of applying the \$n\$-mover rules in chess.

\$n\$-Chess™ is a board game played on a 8x8 grid like the original chess. However, the pieces are very different from chess - they are named \$n\$-movers (\$n\$ can be any natural number) and can only move by the rules set on them (see Rules: Pieces).

Rules

Pieces

In \$n\$-chess, a piece is called an \$n\$-mover, where \$n\$ denotes its possible movements. Specifically:

  1. The \$n\$-mover can only move one step of Euclidean distance \$\sqrt n\$ each time, i.e. for a move with \$x\$ units horizontal and \$y\$ units vertical, \$x\$ and \$y\$ must fulfill the equation \$x^2+y^2=n\$ in order to be valid.
    • For example, a 5-mover can only move 1 unit in one direction and 2 units in the another at the same time; while a 25-mover can move 5 units in either direction, or 3 units in one direction and 4 units in the another at the same time.
  2. A piece can have at most 2 rules set at the same time. For a piece that can act as either an \$m\$-mover or an \$n\$-mover, we can call it an \$(m,n)\$-mover. An \$(m,n)\$-mover is allowed to move one step of Euclidean distance of either \$\sqrt m\$ or \$\sqrt n\$ or \$\sqrt{m+n}\$.
    • It is allowed to have \$m=n\$.
    • Only pieces that has captured other pieces can have multiple rules (See Rules: Capture).
  3. If more than 2 rules are set on a piece, only 2 rules can be reserved. You can choose which 2 rules to reserve.

Board

The chess is played on a 8x8 board. The initial setup is as follows: Initial board setup

Capture

  1. If a piece lands on a grid that an opponent piece has occupied (capture), that opponent piece shall be moved away from the board.
  2. After that, the piece will be granted rules from the captured opponent piece. As stated in Piece, if there are more than 2 rules in total, only 2 shall be reserved.

Playing

  1. In a turn, White and Black play a move in turn. White always moves first.
  2. Only one piece can be move per turn.
  3. You cannot move a piece in the way that is not allowed by the rules set on it, beyond the boundaries of the board, or onto a grid already occupied by your other pieces.
  4. You cannot move your last piece in the way that after moving it it can be captured instantly.

Victory Condition

The game ends with either player winning if:

  1. The last piece of the opponent is being checkmated, i.e. no possible moves that can save this last piece from being captured; or
  2. The opponent resigns and loses. (In this challenge, no resignation will be allowed)

The game ends with a draw if :

  1. No checkmate is possible for both sides;
  2. Either player has no more possible moves, but is not in checkmate;
  3. There is no capture in 50 moves; or
  4. The identical board arrangement has appeared 3 times with the same player to move.

Implementation

A player bot is a class that implements a function nextMove(). This function receives 3 arguments and output an array of 6 integers:

function nextMove(
    color: int,                    // Your color: 0 = white, 1 = black
    board: int[8][8][3],           // Current board:
                                   //  First index: x-coordinate
                                   //  Second index: y-coordinate
                                   //  The third layer will be as follows - 
                                   //   [0]: the color of the grid
                                   //       (-1: Not occupied; 0: white; 1: black)
                                   //   [1]: rule 1 (0 if not exists)
                                   //   [2]: rule 2 (0 if not exists)
    moves: int[][10]               // Previous moves:
                                   //  First index: move number (0-indexed)
                                   //  The second layer will be as follows - 
                                   //   [0]: the color of the player
                                   //   [1]: is this a capture (0: no, 1: yes)
                                   //   [2]: source x-coordinate
                                   //   [3]: source y-coordinate
                                   //   [4]: source rule 1
                                   //   [5]: source rule 2 (0 if not exists)
                                   //   [6]: target x-coordinate
                                   //   [7]: target y-coordinate
                                   //   [8]: target rule 1
                                   //   [9]: target rule 2 (0 if not exists)
): int[6]                          // Return value: as follows:
                                   //  [0]: source x-coordinate
                                   //  [1]: source y-coordinate
                                   //  [2]: target x-coordinate
                                   //  [3]: target y-coordinate
                                   //  [4]: target rule 1
                                   //  [5]: target rule 2 (0 if not exists)
  • Rule 1 and Rule 2 denotes the 2 rules a piece has.
  • Source rule entries are used to denote which rules a piece has, while target rule entries are used to denote which rules are decide to keep.

You may use JavaScript, pseudo-codes, or any languages similar to JavaScript, but using JavaScript is strongly encouraged, because all submissions will be translated to JavaScript before using for competition, and the test drive only supports JavaScript.

Restriction

  1. Standard loopholes are forbidden by default.
  2. You cannot by any means read or modify other bots. You can only use data within the class and inputs passed to nextMove() function.
  3. You may define other variables inside your class if needed.
  4. You may use a random number generator.
  5. Your bot, specifically the nextMove() function, must return value in 10 second per move. Timeout leads to disqualification.

Procedure

Round-robin will be used to determine the opponents, i.e. all bots will face each of the other bots twice, one as black and one as white. For each game, a win gets 2 points, a lose gets 0 points, and a draw gets 1 points.

The bot will the highest points wins, and if there are any ties, they will be broken by:

  1. Number of victories;
  2. Average time to checkmate opponent (shorter is better); and
  3. Drawing lots. (Hopefully this step is not necessary)

TODO

  • Add a sample implementation.
\$\endgroup\$
  • 2
    \$\begingroup\$ KISS: since I assume that this is actually a game you've made up for the question, why not ditch checkmate and make the win condition that you capture all of the opposing pieces? I'm not sure about n-Chess™ for a name, either: it feels more like checkers than chess to me. \$\endgroup\$ – Peter Taylor May 29 at 16:34
  • \$\begingroup\$ @PeterTaylor I'd say the question I had my inspiration from had its inspiration from chess, so I chose chess, and tbh I don't even know what checkers is until I've googled it right now. Well, it does look like checkers in the way capturing occurs, but I think I need to borrow some rules from chess, especially the ending rules, because I need to draw a line if the game never ends. Anyway thanks for your useful feedback! \$\endgroup\$ – Shieru Asakoto May 30 at 2:41
2
\$\begingroup\$

Proposed alternative to this

Golf an H interpreter

H is a text-based, weakly-typed string concatenation language. You task is to run an H script. You may do so by creating an interpreter, a compiler, a transpiler, or by any other reasonable means.

Definitions

Anything not defined herein is undefined behaviour and your implementation does neither have to support it nor does it need to throw an error. This includes unmatched quotes, invalid escapes, usage of variables before definition, etc. All given H scripts will abide by all the rules as stated.

General H syntax

Scripts: One or more lines, each containing zero or more statements, optionally followed by a comment.

White-space: you only have to support spaces in strings (tabs are escaped), plus tabs and/or spaces leading up to a comment.

Operators: There's only one, +, which is string concatenation.

Comments begin with # and continue until the end of the line. # may be prefixed by one or more spaces and/or tabs.

name: a sequence of exactly 4 single-case ASCII letters [A-Z] or [a-z] (you decide the scheme)

value: a +-delimited sequence of one or more strings (see below) and/or previously defined names. The combined value will never exceed 1000 characters.

Strings

Opened and closed by " and support ASCII 32–126 but with the following escape sequences:

\\: the literal backslash character; \

\n: a line break; CR, LF, CRLF, or LFCR (you decide)

\": a quotes symbol; "

\t: a tab character; (HT) or 2, 4, or 8 spaces (you decide)

A string matching the regex 0|-?[1-9]\d?\d? (i.e. look like an integer) may be left unquoted.

Statements

Terminated by ; but may not span multiple lines. There are only three types of H statements:

def name=value; sets the variable name to the given value.

print(value); prints value without trailing line break.

input(value;name); prints value without trailing line break, allows the user to enter a sequence of characters that extend that line, and assigns the characters to name. Any subsequent output begins on the next line.

Test script

The following assumes you have decided on the uppercase variable name scheme:

def HELO="Hello, ";
def HSMO=HELO+"strange"+-1;print("");
input(HSMO+"what is your name?";NAME);         #enter "User A" via stdin
#print(-123)   # nope
print(HELO+"\""+NAME+"\"\n\tthis isn't APL\\"+360+"!");

#done
print(-12+34)	# note the tab before #

Here is the equivalent using a lowercase variable name scheme:

def helo="Hello, ";
def hsmo=helo+"strange"+-1;print("");
input(hsmo+"what is your name?";name);         #enter "User A" via stdin
#print(-123)   # nope
print(helo+"\""+name+"\"\n\tthis isn't APL\\"+360+"!");

#done
print(-12+34)	# note the tab before #

Running the appropriate script, and entering User A should, according to the scheme where \t means ASCII 9 (HT), leave the console/screen/window showing:

Hello, strange-1what is your name?User A
Hello, "User A"
	this isn't APL\360!-1234

If instead you decided that \t means four spaces, it should show:

Hello, strange-1what is your name?User A
Hello, "User A"
    this isn't APL\360!-1234

\$\endgroup\$
  • 1
    \$\begingroup\$ You may want to explicitly state that User A is the STDIN-input in the Test script. I must admit I just can't read and read past the explanation of input(value;name); when going through the test script and was thinking: where is def name="User A";. And based on "Anything not defined herein is undefined behaviour and your implementation does neither have to support it nor does it need to throw an error." we can assume all scripts are valid, so no " that are unmatched, and no variable used before it is defined, and stuff like that? \$\endgroup\$ – Kevin Cruijssen Jun 28 at 13:45
  • 1
    \$\begingroup\$ @KevinCruijssen How is it now? \$\endgroup\$ – Adám Jun 28 at 15:50
  • 1
    \$\begingroup\$ Perfect. :) I had already upvoted I see. Everything is clear to me now. \$\endgroup\$ – Kevin Cruijssen Jun 28 at 16:40
  • 1
    \$\begingroup\$ @UserA No. There is an overwhelming consensus that one should avoid bonuses in code golf. \$\endgroup\$ – Adám Jul 3 at 13:23
  • 1
    \$\begingroup\$ @UserA It is very probably that many of the solutions will allow all of those any way. \$\endgroup\$ – Adám Jul 3 at 13:24
2
\$\begingroup\$

Multi-Digit × Single-Digit Checker

Introduction

The story below is fictional, don't worry.

Times table hard. More curriculum. Class advance. Son behind. Horror. Help.

ahem Pardon me.

So... I've got a big problem. The times table is huge, and all the mnemonic rules we've taught our son haven't make him fully memorize it yet. However, his class must advance to the next chapter, long multiplication. As a result, he is prone to making many mistakes while multiplying numbers.

See, they're already making the students multiply a multi-digit number by a single-digit number. My son often forgets to carry digits over and, of course, his times table. The good thing is that he never misses digits!

The situation is awful. Help me before they start with two multi-digit numbers!


Challenge

Your challenge is to write a program that takes a multiplier, a multiplicand and a product, and analyzes the product for any of the following mistakes. Here's how:

  • If a digit is the correct ones digit of the product of the multiplicand times the digit of the multiplier he's currently multiplying, but a non-zero carryover was supposed to be added to it, then this digit has a carryover error.
  • If a digit is otherwise wrong, there's a times table error around it (we can't be sure if the ones digit was wrong or a carryover digit was wrong), so it has a times table error.
  • There will never be another kind of mistake in the product, my son doesn't skip digits.

For each wrong digit, return an array of two or three elements:

  • Position of the digit from the left or right, 0- or 1-indexed (your choice must be consistent). Keep in mind that, if the leftmost digit is absent due to a carryover error, then it's still the leftmost digit and the place has the relevant index.
  • Correct carryover, if the mistake was a carryover error, or omitted otherwise. You may also put a 0 instead of omitting the element (you can't blame my son for forgetting to add a zero carryover!), but be consistent.
  • Correct digit.

Rules

  • The numbers will all be positive integers.
  • The multiplicand will be an integer from 1 to 9, inclusive.
  • You can get the three numbers via any reasonable way you want.
  • The output can be in any order, as can the elements of each array, as long as the latter is consistent.
  • You may not make use of any standard loophole.
  • This is a challenge, so the shortest answer, measured in bytes, wins.

Test cases

Multiplier, Multiplicand, Product -> Mistakes (0-indexed from the left, possibly absent carryover)

5, 3, 15 -> [] (15)
3, 5, 5 -> [[0, 1, 1]] (05 -> 15)
7, 3, 31 -> [[0, 2]] (31 -> 21)
1551, 9, 4959 -> [[0, 1, 1], [1, 4, 3]] (04959 -> 14959 -> 13959)
2121, 7, 14847 -> [] (14847)
2121, 7, 4727 -> [[0, 1, 1], [2, 1, 8], [3, 4]] (04727 -> 14727 -> 14827 -> 14847)
33333, 9, 11111 -> [[0, 2, 2], [1, 9], [2, 9], [3, 9], [4, 9], [5, 7]] (011111 -> 211111 -> 291111 -> 299111 -> 299911 -> 299991 -> 299997)

Sandbox

  • Is the challenge unclear?
  • Is the output format weird or too strict?
\$\endgroup\$
  • \$\begingroup\$ I think it's a pretty interesting challenge! My only nitpick is in the introduction, when you're bringing up 'My son makes these mistakes:': make this section a bit more formal/a bit less story-level detail. The rest of the introduction is funny and gives some good context, but while reading the challenge I was kind of thrown off by the unnecessary detail in that section, e.g 'Ah, the crux of my worries.' \$\endgroup\$ – Geza Kerecsenyi Jul 9 at 21:25
  • \$\begingroup\$ @GezaKerecsenyi That might be because those were part of the challenge text before I decided to move it all to the Challenge section. I'll shorten them to one sentence. EDIT: I've removed that part. \$\endgroup\$ – Erik the Outgolfer Jul 9 at 22:01
  • \$\begingroup\$ Also, I think that making the carryover optional is quite confusing, and it also means that you have to check if it was a carryover error just to know whether to output it or not. I would suggest to make them always give the correct carryover or 0, even if it wasn't a carryover error. \$\endgroup\$ – Geza Kerecsenyi Jul 10 at 7:46
  • \$\begingroup\$ @GezaKerecsenyi I'm giving two options for times table errors, either exclude the carryover or make it 0. The answerer can choose one of the two consistently. Do you think there's an issue with the first one? \$\endgroup\$ – Erik the Outgolfer Jul 10 at 17:48

You must log in to answer this question.

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