568
\$\begingroup\$

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

Sandbox FAQ

Posting

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

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

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

Discussion

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

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

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

If you think one of your posts requires more feedback, but it's been ignored, you can ask for feedback in The Nineteenth Byte. It's not only allowed, but highly recommended! Be patient and try not to nag people though, you might have to ask multiple times.

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

Other

Search the sandbox / Browse your pending proposals

The sandbox works best if you sort posts by active.

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

\$\endgroup\$
0

4549 Answers 4549

1
112 113
114
115 116
152
0
\$\begingroup\$

The Shifty Maze


You are a wild mouse and you have stumbled on a maze that some human has constructed to observe your behavior. The maze is littered with blobs of peanut butter and has a cache of sunflower seeds near its center. After discovering the seeds, you decide that you want to take them all home to your personal cache. You must find your way to the seeds and exit the maze. Since there are so many seeds, it takes you many trips to get them all.

Things go well your first time. You find your way to the seeds, bring a few back, and return to the maze. To your surprise, when you return the second time, the maze looks nothing like it did before, but you quickly figure out that the entrance was simply in a different place and continue navigating as usual. The next time you return to the maze, you are once again lost, but you find a familiar pattern of peanut butter dabs and find your way to the sunflower seeds once again. Naturally, you catch onto this pattern and eventually retrieve all the sunflower seeds.

The Challenge

Your task is to make a "mouse" bot that navigates through a maze where the entrance moves to somewhere else on the edge of the maze every time you exit and enter it. You have no limits on memory, but no absolute sense of direction and a limited visual field. You can only exit the maze after finding the cache. Your goal is to get all of the seeds in as few steps as possible.

Mazes

A perfect maze is randomly generated using a randomized version of Prim's Algorithm starting from a cell near the center. The seed cache will be close to the center. 10% of the cells will be dabbed with 3-5 units of peanut butter. There will not be any peanut butter on the same cell as the seed cache. The maze used for scoring will be 30x30 cells.

Actions

Each turn, you can move forward or turn 90 degrees in either direction. If there is any peanut butter on your current cell, you may also eat one unit of it instead of moving or turning. (Partially eaten peanut butter can be used to create landmarks for navigation.)

Vision

You can see every cell in a straight line in front of you until a wall obstructs your view. You can also see one cell to your left and right, provided there is no wall between that cell and your current cell.

For each cell that you can see, you can see whether there is a wall on each of the four edges of the cell, how much peanut butter is on that cell, and whether it is the seed cache or the exit.

Example

Suppose you had this maze:

+-----+-------+-+---+
|     |  5    | |   |
| ----+-- +---+ | --+
|4    |   |@   3    |
| --+-+ --+---- | --+
|   | |    4   <|   |
| --+ | --+ | | +-+ |
|         | | |   | |
| | +-- --+-+ +-- +-+
| | |    3  | |     |
+-+-+-------+-+ ----+

@ is the seed cache. Numbers are blobs of peanut butter. < is the mouse (facing west)

The vision for the mouse would look something like this:

  +-+

  + +
  | |
  + +    
   4|
  + +
    |
+-+ + +
|.(^)3
+ +-+ +

No memory limit

You can remember as little or as much as you would like. The challenge is in figuring out where you are as quickly as possible and reduce the amount of time you spend wandering.

Test Driver

The test driver can be found here.

Coding

Your solution should be compatible with Python 3.7. You should implement a class with the following methods:

  • A constructor taking no arguments
  • get_action, which is called with one argument representing your vision on each step of navigation (more on that below). This should return a string representing the action to take: forward, left, right, or eat are valid values. If this returns an action that cannot be taken, an exception will be thrown and your solution will be considered invalid.
  • enter_maze, which is called without arguments each time the maze is entered. No return value is expected and the function doesn't actually have to do anything. The next time get_action is called, you are guaranteed to be on the cell on the edge of the maze facing away from the entrance/exit.

The Vision Object

You will receive an object with the following attributes:

  • left and right: the cells to your left and right. If there is a wall that obstructs your view, this will be '???' instead of the cell view object.
  • forward: a list of all the cells in your forward vision, starting with your current cell and continuing until the last cell in your vision.

Any of these cell views may also be None, indicating the entrance/exit of the maze.

Each visible cell inside the maze will be an object with the following attributes:

  • forward, left, right, back: booleans indicating whether there is a wall in the given directions, oriented the same way as the mouse.
  • contents: an integer representing the amount of peanut butter (if any), None (if nothing is on the cell), or 'cache' if the cell contains the seed cache.

Scoring and Rules

  • Standard loopholes apply.
    • If your bot only works on the scoring maze, it is an invalid solution. Your bot does not receive enough input to distinguish the scoring maze from another maze, so hard-coding a route will produce an invalid solution.
  • Run the test driver to score your result. It uses an isolated and seeded random number generator to ensure that all entries get the same maze and sequence of entrances. The total number of turns it took to retrieve all of the seeds (this takes 100 iterations through the maze) is your score.
  • Include your score, your code, and an explanation in your solution post.
  • You must output a valid move each turn. Moving into a wall or attempting to eat nonexistent peanut butter will result in an error that you have no opportunity to recover from.
  • You may not exit the maze until you have visited the cell containing the seed cache since the last time you entered the maze.
\$\endgroup\$
2
  • \$\begingroup\$ Is it guaranteed that when enter_maze is called, the mouse is on an edge of the maze? \$\endgroup\$
    – DELETE_ME
    Jul 20, 2018 at 6:54
  • \$\begingroup\$ @user202729 I should clarify that. Thanks for pointing that out. \$\endgroup\$
    – Beefster
    Jul 20, 2018 at 16:47
0
\$\begingroup\$

Encoding nested tuples

Tags: , , ,

Related: this


Working on my recent esolang μ6 I found myself a neat puzzle: Given the set of all natual numbers and the set of all nested tuples over the natural numbers, find a bijection between those two sets.

A nested tuple \$t \in T\$ is recursively defined, it is one of the two:

  • an natural (\$\ n \in \mathbb{N}_0\ \$) number itself: \$\;t = n\$
  • a tuple of two nested tuples (\$\ t_l,t_r \in T\ \$): \$\;t = (t_l,t_r)\$

If it helps you can think of a nested tuple as a binary tree that has only values in its leaves.

Challenge

Your task is to define two programs/functions, let's call them \$\ E\ \$ (encode) and \$\ D\ \$ (decode) which are each others inverses:

Given any natural number \$n \in \mathbb{N}_0\$ the output \$E(n)\$ is a unique element of \$\ T\$ and \$\ D(E(n)) = n\$.

Given any nested tuple \$\ t \in T\$ the output \$\ D(t)\$ is a unique element of \$\ \mathbb{N}_0\$ and \$\ E(D(t)) = t\$.

Rules

Inputs to the two programs/functions can be

  • an integer or a string representation thereof for \$\ E\$
  • a nested tuple/list, custom data-type1 for \$\ D\$

Outputs can either be of the same type as the input of the inverse function/program or printed to stdout.

Example

Since you're free to implement any bijection, it's difficult to give meaningful test cases. These are just a few examples using this encoding-function and this decoding-function:

0 <-> 0
1 <-> (0,0)
3 <-> ((0,0),0)
20415 <-> ((1,0),(1,2))
55340232221111877631 <-> ((0,(1,0)),(2,1))
1000000000000000000000000 <-> 500000000000000000000000

1: For example if your language doesn't support nested tuples/lists, you don't need to count its definition towards your byte count. As an example a Haskell submission could assume data T = El Integer | Nest T T.

Sandbox

  • Anything unclear?
  • Is this maybe too much to ask in a code-golf?
  • I could "simplify" it by asking for two \$\ E_k \$ and \$\ D_k \$ which would for all inputs \$ k \$ map \$\ \mathbb{N_0} \leftrightarrow \mathbb{N_0}^k\ \$..
\$\endgroup\$
1
0
\$\begingroup\$

Most Turing-incomplete Instruction Set

Tags: ,


This challenge expects you to define an instruction set \$I = \{ \texttt{instr}_1 \dots \texttt{instr}_n \}\$ which is provably Turing complete. The catch is that any subset \$I'\$ that is proper (ie. \$I' \neq I\$) must not be Turing complete.

Challenge

Your task is to define some environment (eg. a stack, an unbounded tape, tuples, integers, funcions etc.) over which you have complete freedom to choose, let us call this environment \$E\$.

To initialize \$E\$ you will define a way of transforming the source code \$s\$ and inputs \$in_0,\dots,in_r\$ to some \$E_{initial}\$. The same holds for the output of your programming language, you can define the output as any mapping of the end state \$E_{end}\$ to your output set.

The main task is to find an as large as possible number of instructions which define a Turing complete programming language, but removing any instruction from that set must result in a programming language that is not Turing complete.

An instruction \$\texttt{instr}_i\$ takes some non-negative number \$m\$ of arguments and modifies the environment, ie.

$$ \texttt{instr}_i : A_0 \times \cdots \times A_m \times E \to E $$

where \$A_0,\dots,A_m\$ are the sets of valid arguments, you're free to define these as you wish (eg. natural numbers, integers, Booleans, labels etc.).

Submission

Your submission will contain

  • the language specification
  • informal proof of validity
  • an implementation of the language.

Rules

  • this is a and your score will be the number of instructions, the goal is to maximize this number (ties will be broken by favouring the earliest submission)
  • your programming language only needs to support input by using some special initial environment \$E_{initial}\$
  • the same holds for the output(s), these only need to be encoded in the final \$E_{end}\$
  • the definitions of \$E\$ and the way of transforming input/output do not need to be formal (eg. it suffices to just say something along the lines of: "My language works with a stack of integers, initially it will contain all the inputs beginning with the first one at the bottom of the stack. Output will be the top of the stack or zero if it's empty.")
  • you will need to provide an informal proof of why your submission is valid, consisting of
    • an informal proof of Turing completeness of the instruction set \$I\$
    • an informal proof of why any proper subset of \$I\$ is not Turing complete
  • these proofs may rely on reductions to known Turing complete languages (eg. Turing machines, BitBitJump, brainfuck etc.)

Sandbox

As pointed out by Nathaniel, it is currently possible to get an arbitrary large score.. If anyone has a nice fix that will prevent that (and similar exploits), please leave a comment.

\$\endgroup\$
7
  • 2
    \$\begingroup\$ I like the idea, but the instruction set can easily be made arbitrarily large. E.g. environment starts in state 0. Instruction A1 changes the state to state 1 if it's in state 0, otherwise it's an error. Instruction A2 changes the state to state 2 if it's in state 1, otherwise it's an error. [...] Instruction A1000000 changes the state to state 1000000 if it's in state 999999, otherwise it's an error. Instructions S, K perform as per SK calculus, but only if the environment is in state 1000000. This scores 1000002. \$\endgroup\$
    – N. Virgo
    Aug 7, 2018 at 12:46
  • \$\begingroup\$ @Nathaniel: I didn't think of that :( Finding a nice definition/rule to prevent these kinds of exploits will be quite difficult. I'll see what can be done. \$\endgroup\$ Aug 7, 2018 at 12:51
  • \$\begingroup\$ For N*'s attack, a function can take binary input and decide one state per input \$\endgroup\$
    – l4m2
    Aug 10, 2018 at 15:54
  • \$\begingroup\$ @l4m2: I thought about that too, it's better than what I have now. But it would still allow an "attack" where you abuse the stack/tape/.., for example: Take a setup with a stack, A1 pushes 1, A2 pushes 2 if ToS=1 else pushes 0, .. A<really-large-number> acts as a Turing-complete instruction when ToS = <really-large-number>-1 and else it acts as clear stack. \$\endgroup\$ Aug 10, 2018 at 16:08
  • \$\begingroup\$ Oh and there might be some confusion about state and environment which are not distinguished in that definition. Only allowing moving to one state/environment would prevent a regular add instruction, since the resulting state would be different for a lot of operands. \$\endgroup\$ Aug 10, 2018 at 16:22
  • \$\begingroup\$ @OMᗺ It's still covered \$\endgroup\$
    – l4m2
    Aug 10, 2018 at 16:30
  • \$\begingroup\$ @l4m2: But that would mean that there needs to bean infinite amount of states, each configuration of state and tape/stack/.. would be state. Leaving us with the problem that there can't be an instruction put X where X is placed on the tape/stack because it would be different for different Xs. Or am I missing something? \$\endgroup\$ Aug 10, 2018 at 16:42
0
\$\begingroup\$

Define the structure X as a non-empty array of (smaller) X objects and "1". Split an X object into the smallest amount of continuous parts Y, length of each of Y don't exceed n, so that each X is either part of a Y, or exactly some Ys. It's fine if output only express which part has how many 1's.

Samples:

[1,[1,1,1]],3 => 1;111
[1,[1,1,1]],2 => 1;11;1 or 1;1;11
[[1,1,1],[1,1,1]],1 => 1;1;1;1;1;1
[[1,1,1],[1,1,1]],2 => 11;1;11;1 or etc.
[[1,1,1],[1,1,1]],3 => 111;111
[[1,1,1],[1,1,1]],4 => 111;111
[[1,1,1],[1,1,1]],5 => 111;111
[[1,1,1],[1,1,1]],6 => 111111
\$\endgroup\$
3
  • \$\begingroup\$ What is a "non-self-contain array"? \$\endgroup\$
    – DELETE_ME
    Aug 7, 2018 at 15:17
  • \$\begingroup\$ @user202729 Some languages allow array like A=[A], which is here not allowed \$\endgroup\$
    – l4m2
    Aug 7, 2018 at 15:18
  • \$\begingroup\$ I think you should work on the explanation, it's not very clear without looking at the testcases. Also what about languages that don't allow lists/arrays with different types? Would it be ok to define an appropriate type? Or should input be taken as string? \$\endgroup\$ Aug 7, 2018 at 18:04
0
\$\begingroup\$

Game of Circles

This is a hidden-identity game with Detectives and Robbers. You will write either a Detective bot or a Robber bot. All Robbers know the identity of all other Robbers. Each turn, a bot must either:

  1. Draw a private circle:
    • The actual circle drawn is public information
    • Detectives receive the number of Robbers in the circle privately
  2. Draw a public circle
    • The player that draws the circle declares the number of robbers in the circle (may or may not be true)

Finally, the player with the most circles (public or private) around them dies. In the case of a tie, no player dies.

The game ends when a single side has been eliminated or when no players have died for 3 turns.

Each game consists of 17 Detective and 3 Robbers. (META: These numbers I'm not sure about).

The bots that will participate in each game will be chosen using two genetic algorithms. There will be 100 simultaneous games, and the first genetic algorithm will choose the 1700 players for the Detectives, while the second genetic algorithm will choose the 300 Robbers. The fitness function for each bot will be how long they survived in the game (by percentage).

After 1000 rounds, players are ranked by their population (two scoreboards, one for Detectives, one for Robbers)

\$\endgroup\$
4
  • \$\begingroup\$ Sounds kinda like the Werewolf/Mafia game. Makes me wonder how well The Resistance boardgame will translate to a KotH. \$\endgroup\$
    – Sundar R
    Aug 12, 2018 at 11:20
  • \$\begingroup\$ I don't understand the bit about genetic algorithms though - will the bots that we submit just be the base population for the GA then? Or will there be no mutation or crossover in the GA (in which case it's pretty much not a GA)? That bit needs some more elaboration and possibly some tweaking. \$\endgroup\$
    – Sundar R
    Aug 12, 2018 at 11:21
  • \$\begingroup\$ Yep, this is similar to Werewolf/Mafia. I considered starting out with that, but I thought it might cause some confusion as there is no "nighttime", and robbers have no extra powers outside of knowing all of the other robbers. \$\endgroup\$ Aug 12, 2018 at 13:41
  • \$\begingroup\$ The bots will be the base population. Breeding will be asexual (single parent), and mutations means randomly picking a bot. You are right, this isn't a string GA, but it's the best term I could come up with. \$\endgroup\$ Aug 12, 2018 at 13:43
0
\$\begingroup\$

4B/5B Encoding

Tags: , , ,


To transmit data in binary there's a technique called NRZI where a transition from +V to -V or vice-versa encodes a 1 and the absence of such a transition a 0.

In case there are a lot of 1 s this is a good method because there will be a lot of transmissions and the risk of getting out of sync is smaller, however it's still tricky for long runs of 0. One solution is 4B/5B encoding which takes 4bits and encodes it in 5bits in a way such that there are at most 3 consecutive bits. The encoding is as follows:

0000 -> 11110
0001 -> 01001
0010 -> 10100
0011 -> 10101
0100 -> 01010
0101 -> 01011
0110 -> 01110
0111 -> 01111
1000 -> 10010
1001 -> 10011
1010 -> 10110
1011 -> 10111
1100 -> 11010
1101 -> 11011
1110 -> 11100
1111 -> 11101

Challenge

Given an bytestring, you will need to encode it with the aforementioned encoding.

Rules

  • Input will be a bytestring
    • to avoid padding-issues, it will always have a length that is a multiple of 4 bytes
  • Output will be of the same a bytestring
  • You may not assume that input (nor output) is printable

Examples

Note: You need to handle both printable and unprintable examples!

ASCII examples

ORLY -> WWEis
OBMO -> WUEm]
SSePCcGG -> ]WW-~U]U=O
aHAHaHAHaHAHaHAHaHaO -> rU%%RrU%%RrU%%RrU%%RrU'%]
S#KPOCFWcSaOCR!@sz!\q9OKqY!L -> ]iU]~WUU9ouWW%]UWJ%^}_j%zzk5uWzW:%Z

Unprintables in hexadecimal

c0 ff ee 00 -> d7 bb de 73 de
66 6f 6f 00 -> 73 9d d7 77 de
50 50 43 47 -> 5f 97 e5 55 4f
48 65 6c 6c 6f 2c 20 57 6f 72 6c 64 21 00 00 00 -> 54 9c b7 69 da 77 69 aa 79 6f 77 5f 47 69 ca a2 7d ef 7b de
\$\endgroup\$
0
\$\begingroup\$

Drat! This was actually run three years ago! See Implement INTERCAL's Binary Operators

Mingle and Select


The programming language INTERCAL has two operators, "mingle" or "interleave" (represented by $), and "select" (represented by ~).

Mingle takes two 16-bit values and produces a 32-bit value by taking single bits alternately from its left and right operands, and concatenating them together - for example, 65535 $ 0 will yield -1431655766 as follows: 65535 is 0xFFFF, or 0b1111111111111111; 0 is 0b0000000000000000. Taking the bits alternately gives 0b10101010101010101010101010101010, or 0xAAAAAAAA, which evaluates to the signed integer -1431655766.

A simplified implementation of Select takes two 32-bit operands, and produces a 32-bit value by comparing the bits in the two operands, and wherever the right operand has a 1 bit, take the corresponding bit from the left operand. The resulting bits are compressed to the right, and zero-filled on the left - for example, an 8-bit version of select, given 79 ~ 42, would return 3, as follows: 79 is 0b01001111, and 42 is 0b00101010. Numbering the bits from the left starting with 1, we need to take the third, fifth, and seventh bits of 79, which are 0, 1, and 1, respectively. We then compress them to the right - 011 - and zero-fill, yielding 0b00000011, or 3.

The challenge

Without using INTERCAL, and without using in any other language any operator builtin that amounts to either mingle or select, implement both operators. You may implement them for 16- or 32-bit integers, and as either operators or functions, but input and output must be UNsigned decimal integers. (I'm not going to require input or output in INTERCAL-style insanity!)

Further constraint: The minimum bit width of the operands must be 16 bits for mingle (no constraint for select), and if they are unequal in width, the shorter is zero-filled on the left to match the width of the longer (zero fill applies to both mingle and select).

test cases to be written and inserted here

This is , so shortest solution in each language 'wins'. (Naturally, the standard loopholes are forbidden.)

\$\endgroup\$
11
  • \$\begingroup\$ "You may implement them for 16- or 32-bit integers, and as either operators or functions, but input and output must be signed decimal integers." This puts languages such as CJam which only have unbounded integer types at a disadvantage. Is that intended? \$\endgroup\$ Aug 13, 2018 at 11:03
  • \$\begingroup\$ @PeterTaylor - The intent here is not to exclude or disadvantage any particular language (other than INTERCAL), but to 'force' zero-fill on select, and return negative values for some cases of mingle. Would it be better to say that values returned must be some power of 2 times 16-bits wide? \$\endgroup\$ Aug 13, 2018 at 11:32
  • \$\begingroup\$ I'm not sure why an integer width is necessary for select: just say that it's zero-filled and make sure that the corner case of a ~ -1 (the only way that there's nothing to fill) is covered by test cases for a positive, zero, and negative. \$\endgroup\$ Aug 13, 2018 at 11:49
  • \$\begingroup\$ For mingle, it seems to me that if the operands are really 16-bit values then the example should be -1 $ 0, and if you require the output to be negative iff the first operand is negative then it easily generalises to unbounded integer types. However, the result of -1 $ 0 in an unbounded type is unbounded, so there is a genuine problem there. I suggest mentioning that briefly as a rationale for why languages without bounded integer types must nevertheless implement a bounded mingle. \$\endgroup\$ Aug 13, 2018 at 11:52
  • \$\begingroup\$ @PeterTaylor - but zero-filled to what width? One could argue that if an arbwidth is allowed, then no zeros need to be added, and 79 ~ 10 could validly be argued to be -1. \$\endgroup\$ Aug 13, 2018 at 11:52
  • \$\begingroup\$ To infinite width. The most significant bit is effectively a sign bit. \$\endgroup\$ Aug 13, 2018 at 11:57
  • \$\begingroup\$ @PeterTaylor - Good catch on 65535 vs -1. I think that this and the arbwidth problem can be addressed by simply changing the 'signed' constraint to 'unsigned'. \$\endgroup\$ Aug 13, 2018 at 12:06
  • \$\begingroup\$ But how do I tell the (selected) MSB from presumed zero-filling? Is 79~10 equal to 3, or to -1? \$\endgroup\$ Aug 13, 2018 at 12:07
  • \$\begingroup\$ UPDATE: Constraints changed. \$\endgroup\$ Aug 13, 2018 at 12:19
  • \$\begingroup\$ "But how do I tell the (selected) MSB from presumed zero-filling?" The answer would have been that you can only get a negative result if both operands are negative, but now that you've changed to unsigned this is no longer an issue. \$\endgroup\$ Aug 13, 2018 at 13:44
  • \$\begingroup\$ @PeterTaylor - It's been rendered academic; the challenge has already been run - see codegolf.stackexchange.com/questions/54412/… \$\endgroup\$ Aug 13, 2018 at 18:30
0
\$\begingroup\$

Lucas and Fibonacci are in pair

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

Delimiter-Chaos

Write a program of at most 150 bytes length that produces different outputs (to stdout) if you insert token-delimiters into the source code.

Score

The program with the highest number of different outputs wins.

Rules

For this challenge, we assume that the source code is tokenized prior to compilation/ interpretation. A delimiter is any character which, when inserted at a given position, changes the way the source code is tokenized, but is not part of a token on its own.

Example

(python)

a = "0"
b = "0"
ainb="12"
print(ainb)

This prints 12. If you insert two spaces, you get:

a = "0"
b = "0"
ainb="12"
print(a in b)

which prints "True"

This gives a total score of 2 for 2 (known) different outputs

Rule clarifications

  • Only program versions that exit with zero error code count towards the score.
  • All versions have to be listed explicitly in the answer.
  • Put the score into the title of the answer.
  • If your code produces different outputs in different programming languages, they count.
\$\endgroup\$
0
\$\begingroup\$

Write in Ge'ez!

Ge'ez is a now-dead language used for liturgy in the Ethiopian Orthodox Church. It's traditionally written in a very distinctive script with many loops and curves. But for ease of reading, it's often transliterated into Latin letters.

Your task here is to take some writing in Latin characters and convert it to the Ge'ez script. For example, the input gəʿəz (the name of the language) should give the output ግዕዝ.

Details

Every letter in the Ge'ez script represents both a consonant and the following vowel. There are eight vowels

ä u i a e ə o wa

and twenty-six consonants

h l ḥ m ś r s ḳ b t ḫ n ʾ k w ʿ z y d g ṭ p̣ ṣ ḍ f p

which give 208 combinations. (In reality, some of these combinations like "wwa" don't actually happen, and there are some extra letters like "mya" not covered by this system, but ignore all that for the purposes of the challenge.)

The combinations are encoded in a convenient way in Unicode. The consonant defines the starting position, and the vowel defines the offset.

C    start (hex)
----------------
h    1200
l    1208
ḥ    1210
m    1218
ś    1220
r    1228
s    1230
q    1240
b    1260
t    1270
x    1280
n    1290
ʾ    12A0
k    12A8
w    12C8
ʿ    12D0
z    12D8
y    12E8
d    12F0
g    1308
ṭ    1320
p̣    1330
ṣ    1338
ḍ    1340
f    1348
p    1350

V    offset
-----------
ä    +0
u    +1
i    +2
a    +3
e    +4
ə    +5
o    +6
wa   +7

(Again, reality is a bit more complicated, but ignore that for the challenge.)

Your task is to take a string written in Latin letters, and output the corresponding Ge'ez syllables. If a consonant is followed by a vowel, add the consonant's start point to the vowel's offset, and print the corresponding Unicode character. If a consonant is not followed by a vowel, use the start point with no offset (as if the vowel were ä).

Input is a Unicode string, or a list of Unicode codepoints as integers. Output is a Unicode string, or a list of Unicode codepoints as integers. A "Unicode string" here can be in any official encoding (UTF-7, UTF-8, UTF-16, UTF-32…). NFC and NFD are both acceptable.

This is code golf; shortest code (in bytes) in each language wins. Standard loopholes forbidden.

Test cases:

gəʿəz    ግዕዝ
[TODO more to come here]
\$\endgroup\$
1
  • 1
    \$\begingroup\$ One option would be replacing the Unicode characters in the input with ASCII digraphs. Would this make the challenge better? \$\endgroup\$
    – Draconis
    Aug 25, 2018 at 3:15
0
\$\begingroup\$

Cleanup after Easter

As most people (probably) know, Easter was about a month ago. But around the community park, there're still some eggs hidden! Can you build a (Javascript only, please) bot to help us find them?

The Course:

The bots will compete on a 201 by 201 field, with coordinates ranging from (-100,-100) to (100,100). All bots will start at (0,0) and will begin. The course has 3 types of areas: wall, egg, and grass.

Finding Eggs:

You will build a function to find the Easter eggs. To see, use the function checkZone(x,y). The ouputs are:

0=Grass
1=Wall
2=Egg
3=Bot

To find a player, use findPlayer(name) (Returns coordinates array) or detectPlayers(x,y) (Returns name or null). If your bot lands on a spot with an egg, it will not be able to pick it up until it uses the function fetchEgg(). If there is not an egg, your turn will stop.

Moving:

Moving is done by returning a string. This string can be north, south, east, west, or none. Assume that directions are like a compass placed on a Cartesian plane:

North=Y+1
East=X+1
South=Y-1
West=X-1

Winning:

When all eggs are found, the game is over. If you move North to an egg, you must pick it up on the next turn in order to obtain it. If you try to move into a wall, nothing will happen. To get your current position, use getLocation(), which returns an array [x,y]. Use getBasket() to get how many eggs you have. The course will be designed so that all eggs are accessible, but some may be hard to get. If an egg is found by two bots in the same turn, each bot get 0.5 added to their basket, as they split the reward.

Functions list:

checkZone(x,y): Returns an integer, takes 2 integers as parameters between -100 and 100
    0=Empty
    1=Wall
    2=Egg
findPlayer(name): Takes string as parameter, returns player's position as an array of integers or null if player is nonexistant
detectPlayers(x,y):  Returns an array of player names, takes 2 integers as parameters between -100 and 100
fetchEgg(): Fetches egg in current position if exists
getLocation(): Returns array with x and y coordinates
getBasket(): Returns number of eggs in basket
move functions: Returns true or ends turn (Ends turn if cannot move)

Example:

function rabbitInDisguise() {
    var loc = getLocation();
    if (getLocation(loc[0], loc[1]) == 2) {
        fetchEgg();
    } else {
        if (getLocation(loc[0], loc[1] + 1)) {
            moveNorth();
        } else {
            moveEast();
        }
    }
}

UPDATE 1: Added findPlayer(name) and detectPlayers(x,y) functions, made locating functions "background", and added simultaneous egg finding rules

UPDATE 2: Added functions list

\$\endgroup\$
34
  • \$\begingroup\$ 1. I don't see the competition here. I find egg, and I grab it as fast as I can. 2. You don't describe what other players look like. \$\endgroup\$ Apr 18, 2018 at 15:05
  • \$\begingroup\$ @NathanMerrill Whichever bot is best at searching for the eggs will win. If Bot A moves in circles around the board, but Bot B scans a 5 x 5 area around it and makes a map, who do you think would win? Also, what do you mean by "You don't describe what other players look like." \$\endgroup\$ Apr 18, 2018 at 15:08
  • \$\begingroup\$ @user202729 Mistype...I'm about to fix it \$\endgroup\$ Apr 18, 2018 at 15:09
  • \$\begingroup\$ And how does program interact with each other? Is there any limit on how many (library) function call can be done in each function? \$\endgroup\$
    – DELETE_ME
    Apr 18, 2018 at 15:12
  • \$\begingroup\$ it cannot run more than one function per turn \$\endgroup\$ Apr 18, 2018 at 15:16
  • \$\begingroup\$ 2. You said that 0=grass, 1=Wall, and 2=Egg. What does a player look like? 1. Right, let me check all the locations nearest me, and walk to the closest one. (You can slightly improve on this by identifying eggs that other players will go for). it cannot run more than one function per turn: Your example bot breaks that. \$\endgroup\$ Apr 18, 2018 at 15:17
  • \$\begingroup\$ Players are invisible, since it could complicate things. I'll edit to address the problems, though. \$\endgroup\$ Apr 18, 2018 at 15:18
  • \$\begingroup\$ If players are invisible, then this is not a KotH. This is a code-challenge to retrieve the eggs as fast as possible. \$\endgroup\$ Apr 18, 2018 at 15:19
  • \$\begingroup\$ @NathanMerrill Fixed. Players can be found using findPlayer() and detectPlayers() \$\endgroup\$ Apr 18, 2018 at 15:27
  • \$\begingroup\$ So they can investigate the whole board in one turn? Sounds more interesting then. \$\endgroup\$
    – DELETE_ME
    Apr 18, 2018 at 15:40
  • \$\begingroup\$ @user202729 I think moveRandom() would be fine (It just makes it easier to program), but I'll add more info on the functions. \$\endgroup\$ Apr 18, 2018 at 15:45
  • \$\begingroup\$ @user202729 Good point. Feature eliminated. \$\endgroup\$ Apr 18, 2018 at 15:51
  • \$\begingroup\$ Any other problems you can think of? \$\endgroup\$ Apr 18, 2018 at 15:54
  • 2
    \$\begingroup\$ @PeterTaylor (what does KISS stand for?) \$\endgroup\$
    – DELETE_ME
    Apr 19, 2018 at 13:58
  • 1
    \$\begingroup\$ @user202729, softwareengineering.stackexchange.com/a/87/13258 \$\endgroup\$ Apr 19, 2018 at 14:02
0
\$\begingroup\$

Compute strings with a fixed distance

Consider a binary string of total length N. For example 000111000111 with \$N=12\$. We can store this string more efficiently by just recording the indices where bits are first flipped. In this case \$(3, 6, 9)\$ is sufficient information to reproduce the string. Here are some more examples using this representation:

10101010 is represented inefficiently by (0, 1, 2, 3, 4, 5, 6, 7)
1111100000 is represented by (0, 5)
0000011111 is represented by (5)

Let us call this representation of a string its compressed representation (even though sometimes the compression is worse than doing nothing).

Now recall the Levenshtein distance between two strings. This is the minimum number of single character insertions, deletions and substitutions needed to transform one string into the other.

Task

Given a compressed representation of a string \$S\$ of uncompressed length \$N\$ and two positive integers \$k\$ and \$d\$, the task is to output the compressed representation of \$k\$ distinct strings of uncompressed length \$N\$, each with Levenshtein distance exactly \$d\$ from \$S\$. If there are not that many distinct strings possible, simply output as many as possible.

Your code must run with \$N = 1000000\$ and \$k, d < 20\$ in less than a minute on a normal desktop PC.

\$\endgroup\$
5
  • \$\begingroup\$ I feel like I'm missing something here. Everything above "Task" is clear, but I don't understand what's going on below. If S = "0000", k = 1, and d = 1, then I simply print out one of "1000", "0100", "0010","0001" (in compressed format)? \$\endgroup\$ Aug 30, 2018 at 20:09
  • \$\begingroup\$ @NathanMerrill Yes. It’s less trivial with other starting strings and larger d. \$\endgroup\$
    – user9207
    Aug 30, 2018 at 20:26
  • \$\begingroup\$ Right. There seems to be two parts to this challenge then: Iterating through Levenshtien mutations, and converting to/from the compressed representation. Unless I'm missing how they are related, I'd argue that you remove one of the parts. \$\endgroup\$ Aug 30, 2018 at 20:32
  • \$\begingroup\$ It appears that iterating Levenshtien mutations would be a duplicate \$\endgroup\$ Aug 30, 2018 at 20:33
  • \$\begingroup\$ @NathanMerrill Thanks for the possible dupe link. For your first comment, the idea was to do it without first uncompressing. I will try to improve the question. \$\endgroup\$
    – user9207
    Aug 31, 2018 at 9:10
0
\$\begingroup\$

Find the fixed point prime


Definition

Let f(n) be the sum of the sums of each possible factor permutation of n. Determine (Y f)(n) (a fixed-point combinator) for all n from 2 to the input i (where i is an integer greater than 2).

Example

A quick example of f(n) first:

f(8) = (2 + 2 + 2) + (2 + 4) + (4 + 2) + (8)
f(8) = 26

An example of (Y f)(n):

(Y f)(8)
  f(8) = 26 (shown above)
  f(26) = (2 + 13) + (26) = 41
  f(41) = (41) = 41
(Y f)(8) = 41

Let g(i) define a function which implements the described problem.

g(2)
2

g(4)
2
3
41

g(8)
2
3
41
5
11
7
41

Competition

This is a challenge, which means that the solution with the lowest asymptotic time complexity (in Θ(...)) wins!

In the case of a tie, the winner will be determined by rules, so please submit an implementation of your code along with the algorithm. Tie-break will occur on a Google Compute Engine n1-standard-8 instance.

\$\endgroup\$
8
  • 1
    \$\begingroup\$ In your example of f(8), why do you include 1 in (8+1)? Should it not be just (8)? I could make (2+2+2) into (2+2+2+1). \$\endgroup\$ Sep 3, 2018 at 16:22
  • \$\begingroup\$ @RushabhMehta You're entirely correct! My bad, let me fix that. \$\endgroup\$ Sep 3, 2018 at 16:27
  • \$\begingroup\$ I'm also pretty sure that in your system, the only fixed points are prime numbers. Is that desired functionality? \$\endgroup\$ Sep 3, 2018 at 16:33
  • \$\begingroup\$ @RushabhMehta See the title. :P \$\endgroup\$ Sep 3, 2018 at 16:45
  • 1
    \$\begingroup\$ Finally, I would mention that permutations are distinct, just so that its obvious how you are counting all the different factors. \$\endgroup\$ Sep 3, 2018 at 16:47
  • \$\begingroup\$ @RushabhMehta Is that a sufficient change? \$\endgroup\$ Sep 3, 2018 at 16:49
  • 1
    \$\begingroup\$ That should be fine. Nice challenge! \$\endgroup\$ Sep 3, 2018 at 16:52
  • \$\begingroup\$ 1. What's a factor permutation? 2. I doubt anyone can give even a moderately tight analysis of the runtime for an implementation of g without a very tight analysis of the output of f, so I don't think it makes sense to post this without first editing in tight bounds on the output of f. \$\endgroup\$ Sep 5, 2018 at 10:18
0
\$\begingroup\$

Bijective base banana to decimal

I'm trying to decide between 2 versions of this challenge:


Prefixes version

Let bijective base banana be bijective base 6 with each digit represented by a different prefix of the word "banana" as follows:

1: "b"
2: "ba"
3: "ban"
4: "bana"
5: "banan"
6: "banana"

The input will be a string made up of a concatenation of zero or more of only these strings. This represents a number in bijective base 6 (with most significant digit first).

The output will be the same number in (non-bijective) decimal.

For example: (input : output)

"" : 0
"b" : 1
"bb" : 7
"bbanana" : 12
"bananab" : 37
"bananabanana" : 42

A worked example:

bananabanbana
banana ban bana
6      3   4
6*36 + 3*6 + 4*1
216  + 18  + 4
238

This is code golf, so the winner for each language is the code with the fewest bytes.


Suffixes version

Let bijective base banana be bijective base 6 with each digit represented by a different suffix of the word "banana" as follows:

1: "a"
2: "na"
3: "ana"
4: "nana"
5: "anana"
6: "banana"

The input will be a string made up of a concatenation of zero or more of only these strings. This represents a number in bijective base 6 (with most significant digit first).

The output will be the same number in (non-bijective) decimal.

For example: (input : output)

"" : 0
"a" : 1
"aa" : 7
"abanana" : 12
"bananaa" : 37
"bananabanana" : 42

A worked example:

bananaananana
banana ana nana
6      3   4
6*36 + 3*6 + 4*1
216  + 18  + 4
238

This is code golf, so the winner for each language is the code with the fewest bytes.


Sandbox questions

  • Is this a duplicate or near enough a duplicate to be worth changing?
  • Are there any flaws that would make the challenge uninteresting?
  • I'm considering changing from prefixes to suffixes following this comment from H.PWiz
  • I currently prefer the suffixes version, but the worked example shows that the interpretation is no longer unique. It would either need to be specified that the match must be greedy (or non-greedy) or a different word would need to be chosen. I lean towards choosing a word which still gives enough ambiguity to force looking ahead, while still keeping the overall conclusion unique. I can't see a way of doing this without making the last character unique though, which reduces to a reversed version of the prefixes version (you can still ignore all other letters).
\$\endgroup\$
7
  • \$\begingroup\$ This is interesting, but I can't help but feel like this is two problems glued into one. \$\endgroup\$ Sep 3, 2018 at 16:27
  • \$\begingroup\$ It's definitely 2 problems glued onto 1. What I'm wondering is will that make for additional golfing opportunities in at least some languages? I suspect it will, and I'd expect myself to underestimate the possibilities since there are many more insightful people tackling challenges, in many languages. \$\endgroup\$ Sep 3, 2018 at 17:58
  • \$\begingroup\$ Hmm, It seems like all that matters is where the bs are. I wonder if it would be a more or less interesting challenge with a different word \$\endgroup\$
    – H.PWiz
    Sep 3, 2018 at 18:18
  • \$\begingroup\$ Good point. Suffixes instead of prefixes might give a bit more of a challenge. As long as the output is still guaranteed unique \$\endgroup\$ Sep 3, 2018 at 18:34
  • 1
    \$\begingroup\$ @trichoplax I'm pretty sure you can't do suffixes, since its no longer unique. \$\endgroup\$ Sep 3, 2018 at 20:24
  • \$\begingroup\$ @RushabhMehta yes it stops working for the word "banana" then (I added a note about this in my 4th sandbox point). It would still work for words that don't contain any of their own suffixes as non-suffix substrings. Like "aardvark". I'm not sure which way to go yet \$\endgroup\$ Sep 3, 2018 at 20:37
  • \$\begingroup\$ @trichoplax Your last bullet was exactly my issue. Suffixes don't help at all. \$\endgroup\$ Sep 3, 2018 at 22:34
0
\$\begingroup\$

Facto-RLE

Task

Given a non-empty string containing non-numeric printable ASCII characters, compute its facto-run-length encoded version.

Definition

Let \$S\$ be a non-empty string of length \$l\in\mathbb{N}^+\$ containing non-numeric printable ASCII characters. For each positive factor \$n|l\$ one can represent \$S\$ as a \$n\times(l/n)\$ matrix of characters. Let \$M^n\$ denote these matrices.
For a given \$n\$ and \$j\in\{1,\dots,l/n\}\$, let \$C^n_j\$ be the string representing the \$j\$-th column of \$M^n\$. Let \$E^n_j := \text{RLE}(C^n_j)\$ denote the array of this string's run-length encoded version.
Let \$R^n := \text{CNCT}(\text{ZIP}(E^n_1,\dots,E^n_{l/n}))\$ denote the string representation of all \$E^n_j\$ zipped together.
The facto-run-length encoding of \$S\$ is defined as the string array \$\text{FRLE}(S):=[R^n:n|l]\$.

For a family of \$k\in\mathbb{N}^+\$ arrays \$A^i\$ with respective lengths \$l^i, i\in\{1,\dots,k\}\$ and elements \$A^i_j,j\in\{1,\dots,l^i\}\$, let \$Z_j:=[A^i_j:i\in\{1,\dots,k\}\land j\leq l_i]\$ denote the array of elements with index \$j\$, if present. Furthermore, define \$\text{ZIP}(A^1,\dots,A^k) := Z_1\Vert\dots\Vert Z_{\max\{l_i\}}\$ as the concatenated array of all \$Z_j\$.
For an array of strings \$A\$ of length \$j\$, define \$\text{CNCT(A)}:=A_1\Vert \dots\Vert A_j\$ as the concatenation of all strings of \$A\$.

Example

Let \$S:=\text{"Hello world!"}\$, therefore \$l=12\$ with positive factors \$\{1,2,3,4,6,12\}\$. $$ M^2=\begin{pmatrix} \text{H}&\text{e}&\text{l}&\text{l}&\text{o}&\text{ }\\ \text{w}&\text{o}&\text{r}&\text{l}&\text{d}&\text{!} \end{pmatrix}, \\C^2_1=\text{"Hw"}, C^2_2=\text{"eo"}, C^2_3=\text{"lr"}, \\C^2_4=\text{"ll"}, C^2_5=\text{"od"}, C^2_6=\text{" !"}, \\E^2_1=[\text{"H"},\text{"w"}], E^2_2=[\text{"e"},\text{"o"}], E^2_3=[\text{"l"},\text{"r"}], \\E^2_4=[\text{"l2"}], E^2_5=[\text{"o"},\text{"d"}], E^2_6=[\text{" "},\text{"!"}], \\R^2=\text{"Hell2o word!"} $$

$$ M^4=\begin{pmatrix} \text{H}&\text{e}&\text{l}\\ \text{l}&\text{o}&\text{ }\\ \text{w}&\text{o}&\text{r}\\ \text{l}&\text{d}&\text{!}\\ \end{pmatrix}, \\C^4_1=\text{"Hlwl"}, C^4_2=\text{"eood"}, C^4_3=\text{"l r!"}, \\E^4_1=[\text{"H"}, \text{"l"}, \text{"w"}, \text{"l"}], E^4_2=[\text{"e"}, \text{"o2"}, \text{"d"}], E^4_1=[\text{"l"}, \text{" "}, \text{"r"}, \text{"!"}],\\ R^4=\text{STR}([\text{"H"},\text{"e"},\text{"l"},\text{"l"},\text{"o2"},\text{" "},\text{"w"},\text{"d"},\text{"r"},\text{"l"},\text{"!"}])=\text{"Hello2 wdrl!"} $$

$$ M^{12}=\begin{pmatrix} \text{H}\\ \text{e}\\ \text{l}\\ \text{l}\\ \text{o}\\ \text{ }\\ \text{w}\\ \text{o}\\ \text{r}\\ \text{l}\\ \text{d}\\ \text{!}\\ \end{pmatrix}, \\C^{12}_1=\text{"Hello world!"}, \\E^{12}_1=[\text{"H"},\text{"e"},\text{"l2"},\text{"o"},\text{" "},\text{"w"},\text{"o"},\text{"r"},\text{"l"},\text{"d"},\text{"!"}], \\R^{12}=\text{"Hel2o world!"} $$

Therefore the following follows. $$ \text{FRLE}(\text{"Hello world!"}) = [\dots, \text{"Hell2o word!"}, \dots, \text{"Hello2 wdrl!"}, \dots, \text{"Hel2o world!"}] $$

Tags , ,

\$\endgroup\$
7
  • \$\begingroup\$ If you can't think of a way to put it into words, you could put it into code, and then someone here can translate that reference implementation into a description. Plus you can then include the reference implementation in the spec for people who read code better than prose \$\endgroup\$ Sep 4, 2018 at 19:13
  • \$\begingroup\$ Okay,I can do that! \$\endgroup\$
    – Adalynn
    Sep 5, 2018 at 13:50
  • \$\begingroup\$ @Zacharý I have attempted to write a task definition. If this is not what you intended, you can simply roll back. \$\endgroup\$ Sep 7, 2018 at 3:37
  • \$\begingroup\$ By the way, I think giving a factor as input would be a nicer challenge than adding a wrapper to encode for every factor. \$\endgroup\$ Sep 7, 2018 at 3:40
  • \$\begingroup\$ @JonathanFrech, there isn't universal agreement on the meaning of zip applied to a non-square 2D array, so you need to define it unambiguously. \$\endgroup\$ Sep 7, 2018 at 10:13
  • \$\begingroup\$ @PeterTaylor Attempted to do so. I intend to only zip one-dimensional arrays. \$\endgroup\$ Sep 7, 2018 at 10:46
  • \$\begingroup\$ Thanks! I think this definition works! \$\endgroup\$
    – Adalynn
    Sep 7, 2018 at 14:58
0
\$\begingroup\$

I have an idea for a KOTH challenge (that is marginally similar to the current Reaper KOTH), but none of the expertise required to make it work. The idea is based on the card game Diamant aka Incan Gold, and the rules of the game are:

  • The game is played over 5 expeditions, each with the same structure.
  • At the start of each expedition, a special deck of cards is shuffled, containing gem cards and hazard cards (and in some versions of the game, one artifact card is added to the deck every expedition).
  • Every turn, a card is revealed from the deck.
    • If a hazard card is revealed and another copy of the same hazard has already been revealed in the expedition, the expedition immediately ends and all remaining players lose their accumulated gems. The revealed hazard card is removed from the deck for future expeditions.
    • If a gem card is revealed, the number of gems shown on the card is shared evenly between remaining players, with any remainder placed in a common pool.
  • After the card is revealed, if the expedition has not ended, then players simultaneously decide whether they want to "Stay" or "Go Home".
    • All players who choose "Go Home" share the gems in the common pool between them (leaving any remainder), and then bank all of their gems. They are no longer in the expedition.
    • If a single player chooses "Go Home", they claim all of the gems in the common pool plus any artifacts that were revealed.
  • If there are players remaining in the expedition, then a new turn begins.
  • If there are no players remaining in the expedition, then the expedition ends.
    • If this was the last expedition, then players count up the gems they banked plus bonus gems for artifacts they claimed, and the player with the most gems wins.

My thought is that we could simplify the game for KOTH - one expedition, no artifacts - and run games which pit 4 bots against each other in some configuration, with each bot's overall rating being its average score per game.

The problem is that I have no experience in any meaningful programming languages. The other problem is that I don't know how to run a contest like that. The other other problem is that I don't know whether it's worth running.

Can anyone offer assistance or advice on any of those three problems?

\$\endgroup\$
1
  • \$\begingroup\$ For problem 1, there are 2 optinos, either ask somebody else to write the bot (if the challenge is interesting enough), or to learn a programming language. \$\endgroup\$
    – DELETE_ME
    Sep 14, 2018 at 5:32
0
\$\begingroup\$

Output the answer after yours

Related: Output the answer above yours

This challenge is very similar to the above, but I hope it's different enough to warrant posting. The difference is that you need to post the answer that is posted after yours (the whole answer, not just the <code> block). Also, your output can be the answer text or the HTML code of the answer. When your post is still the newest post, your program should just output nothing.

Rules

  1. No URL Shorteners
  2. No programs that need to be run at a specific URL.
  3. No updating your answer with information gained after posting (i.e your answer id, text or answer id of post that comes after yours). Exception: It's OK to hardcode the page number of your answer (on 'oldest' sort).

I think mine is different enough from the linked question, because that has some different rules, and my version closes loopholes used on the other question. Also, no one utilizes the StackAPI on that one.

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

Put +, -, * into 1 _ 2 _ 3 ... n to make the expression equal 0, for a given 3 <= n <= 30, and output the valid equation (0=1+2-3). Exactly one operator between each number.


There exists some patterns, such as ((1-2)-(3-4))+((5-6)-(7-8))... and 1+((2-3)-(4-5))+(6-7). Maybe we can find patterns that solve the whole problem?

There are no solutions without * for at least n={5,6,9,10,13,14,17,18,21,22}, so it looks like we need * for n=4x+1 and n=4x+2.

There are no solutions without + for n < 18.

There are no solutions without - (obviously).


Brute-forced examples:

  1. 0=1+2-3
  2. 0=1-2-3+4
  3. 0=1*2-3-4+5
  4. 0=1+2*3+4-5-6
  5. 0=1+2-3-4+5+6-7
  6. 0=1*2*3+4-5-6-7+8
  7. 0=1-2+3*4*5+6-7*8-9
  8. 0=1-2*3+4*5-6*7+8+9+10
  9. 0=1*2+3*4+5*6-7*8-9+10+11
  10. 0=1-2+3*4-5*6-7-8*9+10*11-12
  11. 0=1+2*3+4+5-6-7-8+9+10+11-12-13
  12. 0=1*2+3*4+5*6+7+8*9+10-11*12+13-14
  13. 0=1-2-3-4-5-6-7+8-9+10-11+12-13+14+15
  14. 0=1*2*3*4*5*6+7+8-9*10*11-12+13+14+15*16
  15. 0=1*2*3*4*5*6+7*8*9+10-11*12*13+14*15+16*17
  16. 0=1*2*3*4*5*6-7*8-9-10-11*12-13-14*15-16*17-18
  17. 0=1*2*3*4*5*6-7-8-9*10-11-12-13-14-15*16-17*18-19
  18. 0=1*2*3*4*5*6-7-8-9*10-11-12-13*14-15-16-17-18*19-20
  19. 0=1*2*3*4*5*6-7-8-9-10-11-12*13-14-15-16-17-18-19-20*21
  20. 0=1*2*3*4*5*6-7-8-9-10-11*12-13-14-15-16-17-18-19-20*21-22
  21. 0=1*2*3*4*5*6*7-8*9-10*11-12-13*14-15*16*17-18-19-20-21-22*23
  22. 0=1*2*3*4*5*6*7-8*9*10-11-12-13-14*15*16-17-18-19*20-21*22-23-24
  23. 0=1*2*3*4*5*6*7-8*9*10-11-12*13*14-15*16-17-18*19-20*21-22*23-24*25
  24. 0=1*2*3*4*5*6*7*8-9*10*11-12*13*14-15*16*17-18*19*20-21*22*23-24*25*26
  25. 0=1*2*3*4*5*6*7*8-9*10*11-12-13*14*15-16-17-18*19*20-21-22*23*24-25*26*27
  26. 0=1*2*3*4*5*6*7*8*9-10-11*12*13*14*15-16-17-18-19-20-21*22-23*24-25*26-27*28
\$\endgroup\$
3
  • \$\begingroup\$ Related Also, do you want this to be code golf (shortest code) or a different type of challenge? \$\endgroup\$
    – geokavel
    Sep 23, 2018 at 21:15
  • \$\begingroup\$ Very related. \$\endgroup\$
    – DELETE_ME
    Sep 26, 2018 at 15:22
  • \$\begingroup\$ @user202729 yep. Unlike that one, this doesn't allow turning the 1 negative, which does seem to make the problem unsolvable without multiplication. \$\endgroup\$ Sep 26, 2018 at 15:52
0
\$\begingroup\$

There is a nice task One Ring to rule them all. One String to contain them all. But rule define a string as a linear buffer. A linear buffer is not a Ring :)

My suggestion is:

  • create a new task with title "One Ring to rule them all. One Ring to bring them all"
  • add link to old task in the body of the new task
  • modify an Objective: Output a String which contains every positive integer strictly below 1000 and the String is a Ring.
\$\endgroup\$
4
  • 1
    \$\begingroup\$ It would be a dupe \$\endgroup\$ Sep 28, 2018 at 11:32
  • \$\begingroup\$ ok. thanks, Peter \$\endgroup\$
    – mazzy
    Sep 28, 2018 at 11:52
  • \$\begingroup\$ I've been thinking about it - no, It is not a duplicate. Main different: 0, 00, 000, ... are different elements in a de Bruijn sequence and same element in a Ring of numbers. This moment make golfed algoritms different. \$\endgroup\$
    – mazzy
    Oct 1, 2018 at 8:08
  • 1
    \$\begingroup\$ In a de Bruijn sequence containing all 3-digit sequences over 0-9, 000 is an element but 0 and 00 are not. Moreover, if the ring contains 100, 200, etc. then it must contain 00 at least nine times. See my comment of Nov 5 '13 at 11:28 on /q/13088. \$\endgroup\$ Oct 1, 2018 at 9:51
0
\$\begingroup\$

Make words (need a better title)

Write a program or function that takes a string and an integer \$ n \$ as input and outputs all the \$n\$-letter words formed using only the letters in the string.

Notes:

The input string will have only small alphabets \$a-z\$.

All the letters in the input string will be unique.

Input integer will be positive.

Winner: This is code-golf so shortest code wins. (Fastest algorithm will also be good in this right?)

Examples:

input:"abcd",5
output: "aaaaa","aaaab","aaaac",.....,"ddddc","ddddd"

P.S. The output does not have to be sorted.

Any input and output format will do as long as its distinguishable.

Example:

input: abcd,5 (ok)
       abcd 5 (ok)
       abcd5 (not allowed)
output: ["aaaaa","aaaab",.... (ok)
        "aaaaa","aaaab",.... (ok)
        "aaaaa""aaaab""aaaac"..... (ok)
        aaaaa aaaab aaaac ..... (ok)
        aaaaaaaaabaaaac...... (not allowed)
\$\endgroup\$
5
  • \$\begingroup\$ Related, related, related. \$\endgroup\$
    – Arnauld
    Oct 1, 2018 at 10:18
  • 3
    \$\begingroup\$ For this kind of challenge, neither fastest-algorithm nor fastest-code should be used. For the first one: all answers are likely to have the same time complexity. For the 2nd one: ~99% of CPU time is going to be spent printing the results. \$\endgroup\$
    – Arnauld
    Oct 1, 2018 at 10:24
  • \$\begingroup\$ BTW: this is basically count from \$0\$ to \$b^n\$ in custom base \$b\$, which may have already been covered in some other challenge. I failed to find one, though. \$\endgroup\$
    – Arnauld
    Oct 1, 2018 at 11:24
  • \$\begingroup\$ It's product in python: docs.python.org/2/library/itertools.html (May help giving a title to the challenge, or searching for duplicates) \$\endgroup\$ Oct 2, 2018 at 2:54
  • 1
    \$\begingroup\$ @Arnauld It's mostly a duplicate of Cartesian product of a list with itself n times. The only difference is that builtins aren't allowed in that linked challenge, which is probably better since this is 3 bytes in 05AB1E due to an optional parameters requiring an explicit input and even just 1 byte in Jelly (not sure how to pretty-print it as a list in the footer..). \$\endgroup\$ Oct 3, 2018 at 8:13
0
\$\begingroup\$

Golf A Programming Language


Code golf languages are languages built to complete programming challenges in few lines of code. Instead of creating a code golf language, you will be creating an interpreter for a programming language in as few bytes as possible.

Scoring

As you are not creating a code golf language, instead your score will be based on the number of bytes in the interpreter.

I/O

You may provide a program as input to your interpreter as input using any standard input method

Output provided by a program in your language may be passed on through your interpereter using any standard output method

Tasks

You must write a program to solve each task in the language you created:

  • Hello World - Output the string "Hello World"

  • Fizz Buzz - List numbers from 1 to 100 replacing multiples of 3 with Fizz, 5 with Buzz, and 15 with FizzBuzz

  • Prime Check - Check if a given number is prime

Loopholes

Your programming language must be implemented yourself. Using builtin functions such as Javascript's eval or CHIQRSX9+'s I on input makes this not very interesting.

\$\endgroup\$
4
  • \$\begingroup\$ This is too broad, as defining "interpreter" is pretty impossible. The only way this is viable is if you specify the language to be interpreted. \$\endgroup\$ Oct 2, 2018 at 2:48
  • \$\begingroup\$ @NathanMerrill Anything can be built for the interpreter. It could have 3 instructions, one for each challenge, but that could mean the interpreter increases length because it has the tasks built in. It might need more tasks, 3 tasks might mean building an actual language takes more code than just hardcoding 3 functions \$\endgroup\$
    – pfg
    Oct 2, 2018 at 3:39
  • 1
    \$\begingroup\$ Writing a general purpose language will take more characters than providing built-ins for those. In essence, you're looking for a program that returns a program that takes 1 of 3 characters and evals it. You are correct that eval makes this not interesting, but it's also the best way. Unless you make the language significantly harder (and specify the input required to do each of the tasks), I don't see this being interesting. \$\endgroup\$ Oct 2, 2018 at 3:44
  • 3
    \$\begingroup\$ codegolf.stackexchange.com/questions/111278/… \$\endgroup\$
    – DELETE_ME
    Oct 2, 2018 at 5:27
0
\$\begingroup\$

Eeny Meeny Miny Moe

Inspired (somewhat) by this question:

Where should I stand to be captain of my team?

Introduction

The childhood song Eeny, meeny, miny, moe was often used to select who was a captain when playing some game. Everyone on one team would stand in a line and someone would point at the first person in the line. Although there are several variations, where I grew up, they would sing:

Eeny, meeny, miny, moe,
Catch a tiger by the toe.
If he hollers, let him go,
Eeny, meeny, miny, moe.

adding to the traditional:

My mother told me to pick the very best one and you are not it.

As we sung each word, we pointed at the next person in line, then (if the rhyme wasn't over yet) we would continue the rhyme and start over at the beginning of the line. The person being pointed to when the final "it" was sung would be removed from the line, eliminating them from being captain. Then the rhyme would start over at the beginning of the line to remove the next person. This continued until only one person was left, and that person would be captain.

It didn't take long for me to recognize that if there were two people left (or if we started with just two people), it seemed like the second person would always win. Studying this for a bit I realized that since there are 35 beats this would always happen. I further figured out if there are 3 people, the third would win. So I wondered: could I chart it out for any number? Can I create a formula for it?

Challenge:

Write a program, function or (etc. as standard) where given input of an integer number of starting children greater than one, output what starting child number will be the winner, and where I need to stand so that I can be captain!

Examples:

Input        Output
  2             2
  3             3
4,5,6or7        4
 8 or 9         5
  10            6
11,12or13       7
  14            8
  15            9
  16           10
17,18,19or20   11 

Winner for each language is that with the least number of bytes. And of course, standard loopholes and all that legal jazz are not allowed as is typically expected in these challenges.

\$\endgroup\$
5
  • 1
    \$\begingroup\$ aka, the Josephus problem, possibly duplicate \$\endgroup\$
    – ngn
    Oct 2, 2018 at 19:49
  • \$\begingroup\$ @ngn Wow! I learn something new every day! Is this a duplicate, then? \$\endgroup\$ Oct 2, 2018 at 19:50
  • \$\begingroup\$ I'm not sure, yours is a special case for k=35 \$\endgroup\$
    – ngn
    Oct 2, 2018 at 19:52
  • \$\begingroup\$ by the way, you may find this video enlightening :) \$\endgroup\$
    – ngn
    Oct 2, 2018 at 19:53
  • \$\begingroup\$ Different from listed duplicate in several ways. Mine restarts at the beginning after each elimination (which really makes it questionable whether it is Josephus or not). Mine requires only one input. Mine is a firm case for k and mine has a cool backstory :) \$\endgroup\$ Oct 3, 2018 at 12:16
0
\$\begingroup\$

Permutations to the nines

This question is based on an unresolved inquiry which began at Permutations without recursive function call and was followed up at How to improve efficiency of algorithm which generates next lexicographic permutation? (TL;DR), after finding help removing duplicate numbers at Most efficient method to check for range of numbers within number without duplicates, where after performing arithmetic by hand found that for an array having length less than or equal to 9, if we ignore the value held at each index of the initial array and instead convert the indexes to a whole number, the next lexicographic permutation can be determined by adding 9 to the current index as number until a whole number, e.g., [1,2,3] // 123 1-based index or 23 0-based index is reached that satisfies two the conditions

  • Contains only the numbers of the indexes of the original array

  • Does not contain any duplicate numbers

e.g., 123+9=132 // "abc" -> "acb" 132-9=123 // "acb" -> "abc"; the graph for "abcd" is

[9,81,18,81,9,702,9,171,27,72,18,693,18,72,27,171,9,702,9,81,18,81,9]

which does not appear to be linear.

As the linked answers disclose, adding 9 to a whole number is not the most efficient method of determining the next lexicographic permutation, and what found independently by hand has been found by others, consider OEIS A217626

A217626 First differences of A215940, or first differences of permutations of (0,1,2,...,m-1) reading them as decimal numbers, divided by 9 (with 10>=m, and m! > n).

1, 9, 2, 9, 1, 78, 1, 19, 3, 8, 2, 77, 2, 8, 3, 19, 1, 78, 1, 9, 2, 9, 1, 657, 1, 9, 2, 9, 1, 178, 1, 29, 4, 7, 3, 66, 2, 18, 4, 18, 2, 67, 1, 19, 3, 8, 2, 646, 1, 19, 3, 8, 2, 67, 1, 29, 4, 7, 3, 176, 3, 7, 4, 29, 1, 67, 2, 8, 3, 19, 1, 646, 2, 8, 3, 19, 1

Also of interest is that the graph of the specific multiples of 9 to derive all lexicographic permutations of a set can be found by computing only half 1/2 of the total permutations +1, as the declination slope is identical to the inclination slope of multiples of 9, for example, given an input of the string "abc" or array ["a","b","c"], we only need to reach the inverted peak of the graph, that is bca 120 3 18, where the previously calculated values can be reversed and added to the current whole number, 120, to generate the remainder of the lexicographic permutations

abc 012 0
acb 021 1 9
bac 102 2 81
bca 120 3 18
cab 201 4 81
cba 210 5 9

 /\/\
/    \

Errata

This challenge is not to determine the most efficient algorithm to calculate permutation 9!, as, again, adding 9 to a whole number to reach that goal can be outperformed by swapping values or other method, as demonstrated at the accepted at the first SO link above.

This challenge is to derive the most efficient method of determining the next lexicographic permutation by calculating the next multiple of 9 that meets the above listed criteria, preferably directly using math, if possible.

The reason am posting this question here and now is because was reminded by the graph of the peaks (particularly the third item) in this question Different combinations possible

Just to give a visual example, they are the following:

   /\     /\      /\/\
/\/  \   /  \/\  /    \

that in spite of performing various calculations using the index of the !n within the resulting array of permutations, e.g.,

var n = N = 1234;
var res = [9,81,18,81,9,702,9,171,27,72,18,693,18,72,27,171,9,702,9,81,18,81,9].map((x)=>n=n+x);
// try to determine the rate of growth
var j = res.map((x)=>x/N);

console.log(res, j);

var tryStuff = 1234*(4321/1234);
console.log(tryStuff, (4321/1234));

am still vexed by and have not been able to independently determine the mathematical formula to derive the next lexicographic permutation directly without adding 9 multiple times to reach the required number; or if that is even mathematically possible for any input set from 2! through 9!. That is, this code

function getNextLexicographicPermutation(arr) {

  for (var l = 1, i = k = arr.length; l < i; k *= l++);

  function checkDigits(min, max, n) {
    var digits = 0;
    while (n) {
      d = (n % 10);
      n = n / 10 >> 0;

      if (d < min || d > max || (digits & (1 << d)))
        return false;
      else
        digits |= 1 << d;
    }
    return true;
  }

  var len = arr.length,
    idx = arr.map(function(_, index) {
      return index
    }),
    p = 9,
    min = 0,
    max = len - 1,
    last = Number(idx.slice().reverse().join("")),
    curr = Number(idx.join("")),
    res = [curr],
    diff = [],
    result = [],
    next, times = 0;

  while (res.length < (k / 2) + 1) {
    ++times;
    next = (curr += p);
    if (checkDigits(min, max, next)) res[res.length] = next;
    curr = next;
  };

  for (var i = 0; i < res.length; i++) {
    var item = res[i];
    item = String(item).split("").map(Number);
    item = (item.length < arr.length ? [0].concat(item) : item)
      .map(function(index) {
        return arr[index]
      }).filter(Boolean);
    result.push(item)
  }

  res.reduce(function(a, b) {
    diff.push(b - a);
    return b
  });

  for (var i = 0, curr = res[res.length - 1], n = diff.length - 2; result.length < k; i++, n--) {
    curr = curr + diff[n];
    result.push(
      String(curr).split("")
      .map(function(index) {
        return arr[index]
      })
    );
  }
  return [result, diff, res, times];
}

var arr = ["a", "b", "c", "d"];

console.log(getNextLexicographicPermutation(arr));

which generates the second half-1 of the permutations from the first half+1 of the permutations checks if the next whole number meets the necessary conditions 210 times for an input array of ["a","b","c","d"] which has a resulting .length of 24. Ideally, we want to generate 24 lexicographic permutations using only 12 or 13 checks; or no checks at all, by determining the irrational number or other mathematical algorithm which will directly calculate (or approximate close enough to determine the next multiple of 9) the next whole number which meets the necessary criteria.

Kindly disregard the length of this post, as am trying to include as much information as consider relevant to the inquiry.

Rules

This challenge must use the number 9 (addition, multiplication, division, other mathematical operation) to determine the next lexicographic permutation using the indexes of the current lexicographic permutation converted to a whole number, ideally, in a single operation, else in the least amount of operations necessary to achieve the expected result.

Again, this challenge is not asking how to code the most efficient code which determines the next lexicographic permutation, but what is the most efficient approach is using only the number 9 and math to generate the permutations.

Since we can get the first and last lexicographic permutations by reversing the indexes of the input array, that is not counted as an operation within the program.

Input

An array or sting having .length less than or equal to 9!.

Output

Lexicographically sorted array of permutations of input.

Task

Remaining within the Rules above, determine a mathematical algorithm which directly generates the next lexicographic permutation using only the current indexes of the original input or current permutation. Ideally, directly, without having to add 9 in multiple operations until the listed criteria is met, that is, we want a single algorithm to calculate that we need to add 81 to 132 to get the sum 213 and add 702 to 321 to get the sum 1023 and so forth. Explain the math in the algorithm. Note: The requirement might not be possible. If that is the case, explain why.

\$\endgroup\$
14
  • 1
    \$\begingroup\$ 1. As I commented elsewhere, it's hard to separate the core challenge from the fluff. 2. I assume there's a typo in the "Input" section, because an array of the permutations of 9! elements would take more memory than is physically possible in this universe. \$\endgroup\$ Oct 4, 2018 at 21:37
  • \$\begingroup\$ @PeterTaylor Kindly indicate specifically what content in the question that you are referring to. From perspective here, there is no "fluff" in the question. No, there is no typo in the "Input" section. The algorithm MUST be true for 9!->362880 if true for 4!->24. We can check the result of the algorithm by incremental sections and by hand. Simplified core challenge: Find the multiple of 9 required to precisely equal the next p lexicographic permutation (as a whole number) from current p number in least math computations. \$\endgroup\$ Oct 4, 2018 at 22:06
  • \$\begingroup\$ @PeterTaylor E.g., if we have input ['a','b','c'] we ignore values and "see" 12, 012 (or, as described at this question for simplification 1-based indexing 123). The next lexicographic permutation is one computation 123+(9*1)=132 from we can "see" ['a','c','b']. In JavaScript we could even use Math.pow(9,1), but that would be a false-positive for a method or pattern to use, because the next multiple is 132+(9*9)=213 (we can "see" ['b','a','c']). How to get from 132 to 213 without adding 9 nines times (Task: least mathematical computations in this step) to 132? \$\endgroup\$ Oct 4, 2018 at 22:33
  • \$\begingroup\$ Should we take an array of items (['a','b','c']), an array of indices ([1,2,3]) or its value converted to decimal (123) as input? And what should be the output -- 132, ['1','3','2'] or 9? \$\endgroup\$
    – DELETE_ME
    Oct 5, 2018 at 13:08
  • \$\begingroup\$ @user202729 The input is a decimal derived from the first lexicographic permutation or an array of items from which the decimal will be derived; e.g., 123 from ['a','b','c'], or 123456789 (1-based indexing) or 012345678 (0-based indexing) derived from ["a","b","c","d","e","f","g","h","i" ]. The maximum number is the reverse order of the decimal number, 987654321 or 876543210, which is the last lexicographic permutation (as a decimal number) of the input number or array [8,7,6,5,4,3,2,1,0] (0-based) or [9,8,7,6,5,4,3,2,1] (1-based). \$\endgroup\$ Oct 5, 2018 at 20:48
  • \$\begingroup\$ @user202729 We can derive all lexicographic permutations of input up to 9! by adding 9 to the first lexicographic permutation as decimal and following the two conditions at the question; that is, by adding 9 to the initial decimal number where no duplicate numbers are found within the resulting number and each number is found within the original decimal number. Example "abc"->curr=123->123+9=132->"acb"; curr becomes 132. We are trying to reduce the number of additions to meet the two conditions by creating a formula to determine the precise number of 9's to add to curr. \$\endgroup\$ Oct 5, 2018 at 21:09
  • \$\begingroup\$ @user202729 Is the question clear to you now? \$\endgroup\$ Oct 5, 2018 at 21:43
  • \$\begingroup\$ @user202729 The output is n<=9! permutations. We can already achieve that by the code at the question. However the challenge is to reduce the mathematical steps required to reach the result consider "How to get from 132 to 213 without adding 9 nines times (Task: least mathematical computations in this step) to 132". When curr is 132, we do not necessarily know that we will have to add 9 to 132 nine times (81) to reach the sum 213. We find that out now by nine computations, adding. The challenge is to reach the sum 213 using what we have in less than nine computations. \$\endgroup\$ Oct 5, 2018 at 23:27
  • \$\begingroup\$ @user202729 There are other mathematical relationships between the indexes of the lexicographically sorted permutations. For example, if we have the input ['a','b','c'] or "abc", when we ignore the values, using 1-based indexing, we can "see" 123 at index 1. 123+90=213 our lexicographically sorted permutation at index 3, 132 at index 2 is 132+90=231; max number is always input reversed. We only need to find 132 (3 operations) to derive all 6 permutations, as the declination slope of [123,132,213] is the reverse order of each number; this relationship differs for 1234. \$\endgroup\$ Oct 5, 2018 at 23:46
  • \$\begingroup\$ What is n in that case? /// Consider a specific example. If the input is 132 (1-indexing) what should the output be? \$\endgroup\$
    – DELETE_ME
    Oct 6, 2018 at 11:13
  • \$\begingroup\$ @user202729 The output is always n! lexicographic permutations. We already are able to achieve that. Whether the input is 123 or 132 makes no substantial difference here; we "see" that 132 is greater than its constituent parts, 123 and thus know that we are at index 2 (1-indexing), 321 is always the max, and n! is 6. What this challenge is asking is how to use this specific method of determining permutations, that is, adding 9 to the indexes as a whole number until the listed conditions are met, in less mathematical operations that is currently being used - simple addition. \$\endgroup\$ Oct 7, 2018 at 16:55
  • \$\begingroup\$ Let me see. So, if 132 is given, the output should be [123,132,213,231,312,321], but with a restriction -- only addition, subtraction, multiplication, and division is allowed. Correct? \$\endgroup\$
    – DELETE_ME
    Oct 7, 2018 at 16:59
  • \$\begingroup\$ @user202729 There is no restriction on the mathematical methods which can be used. You can use calculus if that will generate 132 from 123 in the least amount of calculations - using 9 within the calculations. If you can use mathematical relationships between the expected resulting set which uses other numbers, then those methods should be described in detail. The code at the question uses only the number 9 to add to the indexes represented as a whole number, though for some 90 or 711 could be used. The challenge is to use the least number of total math computations. \$\endgroup\$ Oct 7, 2018 at 17:05
  • \$\begingroup\$ @user202729 We are trying to generate the next lexicographic permutation using only 1) the current permutation; 2) the maximum possible number (our last permutation); 3) mathematics; as our resources. We begin with a number less than 321 and know that our first permutation must be 123, our last 321, and that between 321 and 123 there are relationships between the numbers which allow us to derive each number that meets our criteria. In the code at the question 9 is suitable to achieve that goal by adding 9 to the number where the sum contains no duplicate and only input numbers. \$\endgroup\$ Oct 7, 2018 at 17:12
0
\$\begingroup\$

Qwixx KoTH

In this King of the Hill, our bots will be playing Qwixx. In Qwixx each player will try to get as many points by picking the sum of two dices and marking that number on your own scoresheet. The scoresheet has four rows with different colors (red, yellow, green, blue) with numbers ranging from 2 to 12, where green and blue have the numbers ranked in descending order. You can only mark out a number if you haven't marked a number to the right of it, i.e. after marking red 3 you cannot mark red 2 anymore.

Rules

All of the rules of Qwixx are:

  • Red and yellow have numbers 2, 3, ..., 12, and a padlock.
  • Green and blue have numbers 12, 11, ..., 2, and a padlock.
  • There are 6 dices: red, yellow, green, blue and two white dices.
  • On your turn you will throw all the dices, except for deleted ones.
  • Everyone can mark one number on one color equal to the sum of the white dices. Also if it is not your turn.
  • If it is your turn, you can also mark one number in a specific color, with the sum of one colored dice and one white dice. The colored dice that you pick denotes in which color you need to mark the number.
  • You can only mark numbers to the right of already marked numbers.
  • The last number can only be marked if you have already marked at least 5 numbers before. If you do this, you will automatically also mark the padlock, which will give you extra points. If you do this, that colored dice is not thrown anymore and nobody can mark a number in that color. This dice is deleted from the game (thrown as 0).
  • Only on your turn you need to mark at least one number. If you don't do this, you will automatically mark a penalty box, which costs you 5 points.
  • The amount of points is equal to the sum of 1 up to the amount of marks in each color, minus 5 times the amount of penalties. I.e.: 4 in red, 3 in green and 2 penalties is 4+3+2+1 + 3+2+1 = 16 - 2 * 5 = 6 points.
  • Each turn is simultanouesly.
  • The game ends when the second dice is deleted or when a scoresheet contains 4 penalties.

Tournament

The tournament rules are as follows:

  • The tournament consists of 10000 * amount of bots games.
  • Each game will be played with 5 random bots, in a randomized order.
  • If multiple bots end up with the same amount of points in one game, each bot gets a win.
  • The winner of the tournament is the bot who has the highest win percentage.

Bots

The bot needs to be defined in Python and needs to have two functions:

  • __init__(self, index) with the index in scoresheets, so that you know which scoresheet is yours
  • turn(self, scoresheets, dices, my_turn), with the current scoresheets, the dices of this turn and a boolean being True when it is your turn. This function needs to return a tuple of two tuples containing (color, number) with what your bot wants to mark, where the first tuple is for the white dices, and the second tuple only if its your turn.

The simplest bot can be defined as:

class DoNothing:
    def __init__(self, index):
        return
    def turn(self, scoresheets, dices, my_turn):
        return ([],[])

Which does absolutely nothing.

A randomized bot that tries to always mark something when possible is:

class RandomAllowedCombinations:
    def __init__(self, index):
        self.index = index
        return
    def turn(self, scoresheets, dices, my_turn):
        (any_combs, turn_combs) = scoresheets[self.index].allowed_combinations(my_turn, dices)

        any_comb = []
        if any_combs:
            any_comb = any_combs[random.randint(0, len(any_combs)-1)]

        turn_comb = []
        if my_turn and turn_combs:
            turn_comb = turn_combs[random.randint(0, len(turn_combs)-1)]

        return (any_comb, turn_comb)

This also shows some of the utility functions: you can use scoresheets[self.index].allowed_combinations(my_turn, dices) to check what you can mark with the white dices, and if its your turn with one of the colored dices as well.

Both classes (Dices and Scoresheet) have several utility functions. You can check themselves to improve your bot. Note that Dices also contains the indices for each color. And the value of a dice is 0 if it is deleted (i.e. when someone in the game marked the last number and thus the padlock in one of the previous turns).

Controller

The controller contains 5 example bots. These will not be used in the tournament, unless there are too few participants.

import random
import numpy

### Bots ###
class DoNothing:
    def __init__(self, index):
        return
    def turn(self, scoresheets, d, my_turn):
        return ([],[])

class AlwaysWhitesInRed:
    def __init__(self, index):
        return
    def turn(self, scoresheets, d, my_turn):
        return ((d.red, d.dices[d.white1] + d.dices[d.white2]),[])

class AlwaysBlueOnlyTurn:
    def __init__(self, index):
        return
    def turn(self, scoresheets, d, my_turn):
        return ([],(d.blue, d.dices[d.blue] + d.dices[d.white2]))

class RandomAllowedCombinations:
    def __init__(self, index):
        self.index = index
        return
    def turn(self, scoresheets, dices, my_turn):
        (any_combs, turn_combs) = scoresheets[self.index].allowed_combinations(my_turn, dices)

        any_comb = []
        if any_combs:
            any_comb = any_combs[random.randint(0, len(any_combs)-1)]

        turn_comb = []
        if my_turn and turn_combs:
            turn_comb = turn_combs[random.randint(0, len(turn_combs)-1)]

        return (any_comb, turn_comb)

class RandomButOnlyOwnTurn:
    def __init__(self, index):
        self.index = index
        return
    def turn(self, scoresheets, dices, my_turn):
        (any_combs, turn_combs) = scoresheets[self.index].allowed_combinations(my_turn, dices)

        turn_comb = []
        if my_turn and turn_combs:
            turn_comb = turn_combs[random.randint(0, len(turn_combs)-1)]

        return ([], turn_comb)

### Classes ###
class Dices:
    def __init__(self):
        self.dices = []
        self.deleted = []
        self.red = 0
        self.yellow = 1
        self.green = 2
        self.blue = 3
        self.white1 = 4
        self.white2 = 5
        self.colors = [self.red, self.yellow, self.green, self.blue]
        self.whites = [self.white1, self.white2]
        self.diff_dices = self.colors + self.whites

    def roll_dice(self):
        self.dices = [0,0,0,0,0,0]
        for i in range(6):
            if i not in self.deleted:
                self.dices[i] = random.randint(1, 6)

    def delete_dice(self, color):
        if not color in self.deleted:
            self.deleted.append(color)
        return len(self.deleted) > 1

    def combinations(self):
        combs = [(color, white) for color in self.colors for white in self.whites]

        any_combs = [(color, self.dices[self.white1] + self.dices[self.white2]) for color in self.colors if self.dices[color] >= 1]
        turn_combs = [(color, self.dices[color] + self.dices[white]) for (color, white) in combs if self.dices[color] >= 1]

        return (any_combs, turn_combs)

class Game:
    def __init__(self, bots):
        self.bots = [bots[i](i) for i in range(len(bots))]
        self.scoresheets = [Scoresheet() for i in self.bots]
        self.dices = Dices()
        self.turn_number = 2

    def round(self):
        self.dices.roll_dice()
        (any_combs, turn_combs) = self.dices.combinations()

        finished = False

        for i, bot in enumerate(self.bots):
            my_turn = self.whos_turn() == i
            moves = bot.turn(self.scoresheets, self.dices, my_turn)
            deleted_colors = self.scoresheets[i].mark(moves, my_turn, any_combs, turn_combs, self.dices)
            if deleted_colors:
                finished = finished or any([self.dices.delete_dice(deleted_color) for deleted_color in deleted_colors]) 
            finished = finished or self.scoresheets[i].too_many_penalties()

        self.turn_number += 1

        return finished

    def whos_turn(self):
        return (self.turn_number - 1) % len(self.bots)

    def runGame(self):
        finished = False
        while not finished:
            finished = self.round()
        #for i, scoresheet in enumerate(self.scoresheets):
            #print self.bots[i], scoresheet.values, scoresheet.penalties, scoresheet.points()

class Scoresheet:
    def __init__(self):
        self.red = []
        self.yellow = []
        self.green = []
        self.blue = []
        self.penalties = 0
        self.values = [self.red, self.yellow, self.green, self.blue]

    def points(self):
        points = self.penalties * -5
        for color in self.values:
            points += sum(range(len(color)+1))
        return points

    def allowed_combinations(self, my_turn, dices):
        (any_combs, turn_combs) = dices.combinations()
        any_combs = [(color, number) for (color, number) in any_combs if self.allowed(color, number, any_combs, dices)]
        turn_combs = [(color, number) for (color, number) in turn_combs if self.allowed(color, number, turn_combs, dices)]

        if not my_turn:
            turn_combs = []

        return (list(set(any_combs)), list(set(turn_combs)))

    def allowed(self, color, number, combs, d):
        if color not in d.deleted:
            if (color, number) in combs:
                if color == d.red or color == d.yellow:
                    if not self.values[color] or max(self.values[color]) < number:
                        if number < 12 or self.end_number(color, number, d):
                            return True
                if color == d.green or color == d.blue:
                    if not self.values[color] or min(self.values[color]) > number:
                        if number > 2 or self.end_number(color, number, d):
                            return True
        return False

    def end_number(self, color, number, d):
        if len(self.values[color]) > 5:
            return (number == 2 and (color == d.green or color == d.blue)) or (number == 12 and (color == d.red or color == d.yellow))
        return False

    def mark_one(self, color, number, combs, deleted, d):
        if self.allowed(color, number, combs, d):
            self.values[color].append(number)
            if self.end_number(color, number, d):
                self.values[color].append(0)
                deleted.append(color)
        return deleted

    def mark(self, moves, my_turn, any_combs, turn_combs, d):
        beforePoints = self.points()

        deleted = []
        if moves[0]:
            deleted = self.mark_one(moves[0][0], moves[0][1], any_combs, deleted, d)
        if my_turn and moves[1]:
            deleted = self.mark_one(moves[1][0], moves[1][1], turn_combs, deleted, d)

        if my_turn and beforePoints == self.points():
            self.penalties += 1

        return deleted

    def too_many_penalties(self):
        return self.penalties >= 4

class Qwixx:
    def __init__(self, bots, bots_per_game):
        self.bots = bots
        self.games = [0 for i in range(len(self.bots))]
        self.points = [0 for i in range(len(self.bots))]
        self.wins = [0 for i in range(len(self.bots))]
        self.amountOfGames = len(bots) * 1000
        self.bots_per_game = bots_per_game

    def run_tournament(self):
        for g in range(1, self.amountOfGames + 1):
            bot_indices = numpy.random.choice(range(len(self.bots)), self.bots_per_game, replace=False)
            bots_this_game = [self.bots[i] for i in bot_indices]

            game = Game(bots_this_game)
            game.runGame()

            maxPoints = max([game.scoresheets[i].points() for i in range(len(bot_indices))])
            for bot_index_game, bot_index_total in enumerate(bot_indices):
                points = game.scoresheets[bot_index_game].points()
                self.points[bot_index_total] += points
                self.games[bot_index_total] += 1
                if points == maxPoints:
                    self.wins[bot_index_total] += 1
                    print "GAME", g, "is",  self.wins[bot_index_total], "th win by", self.bots[bot_index_total].__name__

    def tournament(self):
        self.run_tournament()

        win_rates = {i: self.wins[i] / float(self.games[i]) for i in range(len(self.bots))}
        format_result = '{:>30}: {:.4f}  {:>6} {:>8} {:>8}' 
        format_header = '{:>30}: {:>6}  {:>6} {:>8} {:>8}' 
        print(format_header.format('Name', 'Win %', 'Wins', 'Games', 'Points'))
        for j, i in enumerate(sorted(win_rates, key=lambda i: win_rates[i], reverse=True)):
            print(format_result.format(self.bots[i].__name__, win_rates[i], self.wins[i], self.games[i], self.points[i]))

### List of all bots ###
all_bots = [DoNothing, BadRandom, RandomAllowedCombinations, Random50, RandomButOnlyOwnTurn]

### Run tournament ###
Qwixx(all_bots, 5).tournament()

Sandbox

  • If someone can check my Python programming capabilities that would be great. I'm no native Python programmer.
  • There are quite some rules. Maybe I should simplify it? These are the official rules, but for example I could change that even on your turn you can only move once instead of twice.
  • This is my first challenge, so any feedback is welcome.
  • Note that I have not yet tested my controller thoroughly, I will do this before posting it as an actual challenge.
\$\endgroup\$
2
  • 1
    \$\begingroup\$ 1. Simplification of the rules is definitely needed. This post is hard to understand and even harder to come up with strategies about. Under "Rules", I'd immediately start explaining the actions bots can perform and their consequenses. 2. Why are there two types of turns (only-white turn, vs color turn)? How does this affect strategies? 3. What's the purpose of marking the last box to prevent other players? How does this affect strategies? 4. I don't understand the scoring, please expound. \$\endgroup\$ Oct 8, 2018 at 16:56
  • \$\begingroup\$ 1. It's not entirely clear to me whether on my turn I can choose to make my "colour mark" before my "white mark" if they're on the same colour. 2. Dice is an irregular noun in English: the singular is die and the plural is dice. 3. 10000 * number of bots games is a lot, so it's going to be slow to run the tournament, but at the same time with 13 bots it's too few to run every possible combination once. This might need a more complicated tournament structure with elimination rounds. \$\endgroup\$ Oct 11, 2018 at 14:20
0
\$\begingroup\$

Roulette Bots II

Last week I posted Roulette Bots, which was a lot of fun. I think the basic format has potential to be even more interesting, so I've been shopping some tweaks in my head and I'd like to hear feedback before I give it another shot. In a nutshell, the first iteration of the game was as follows:

Everyone starts with 100 hp. Each round, 2 players are chosen at random from the pool of contestants who have not yet competed in that round. Both players pick a number between 0 and their current hp, and reveal those numbers at the same time. The player who chose the lower number immediately dies. The other player subtracts their chosen number from their remaining hp and goes on to the next round.

From the bracket of contestants, 2 are chosen at random. They face off, and one or both of them dies. A player dies if:

  1. They choose a number smaller than that of their opponent
  2. Their hp drops to or below zero
  3. They tie three times in a row with their opponent

In the case of ties, both players simply generate new numbers, up to 3 times. After the faceoff, the survivor (if any) is moved to the pool for the next round, and the process repeats until we have exhausted the current round pool. If there is an odd number in the pool, then the odd one out moves on to the next round for free.

Players were given as input their own hp, and their opponent's complete betting history for that round. The idea being that players must balance resource consumption and long-term performance against the danger of dying right now if they don't bid high enough.

There are two things I'd like feedback on:

  1. The minimal set of restrictions on user submissions required to make an interesting game without limiting creativity
  2. Format tweaks that will allow for more creativity within the scope of the rules

The rule set I ended up on for the last game was that you were not allowed to take any action that unambiguously identified your opponent. This was for the purpose of avoiding things like players simply reading the stack to figure out exactly who their opponent was, since then you can simply simulate your opponent and more or less guarantee a win. While clever, it's doesn't really fit the spirit of the game. So the first question is whether or not there is a less restrictive rule that could be applied, or if someone can see a glaring loophole in that rule which would allow for game-breaking behavior in future versions of a similar game.

On the subject of format tweaks, the biggest issue I found with the game was that with a relatively small pool of contestants, very little history was actually generated and so bots that tried to use history to predict opponent guesses fared poorly overall. The first tweak I had in mind was to bootstrap a very large (256 or 512, maybe) initial tournament by random resampling of existing bots so that there would be many rounds and a good history pool to work with by the end of it.

Coupled with the larger pool, I intend to change the scoring system to reward longevity, to encourage more careful resource management, as compared to the previous game which rewarded just living through the first round. Something like making participating in the nth rounds worth n points, so that a player which survives to the nth round gets n(n-1)/2 points total. This puts more stringent constraints on resource management, since you need to survive a lot of rounds to do well. I'd probably bump the starting hp up to 1000, so that there is a bit more room to refine bets. and to make ties even less likely.

Second, there were a couple of attempts to make teams of bots that communicated via betting history in order to feed easy wins to one of them. I like the idea, but but because of the limited options presented by betting history they didn't fare very well. I am considering having bots exchange a "greeting" before each fight - a string or integer which they send to their opponent before battling, which could be used to identify teammates or clones of yourself. Does it add enough possibilities to gameplay to be worth the extra effort? Since with a resampled population you would likely be competing with yourself fairly regularly, having a way to recognize yourself (while at the same time avoiding others being able to recognize you from your greeting) seems like it could be interesting, but I worry that it will just degenerate into people updating their greeting at the last second to avoid other people using them, which would make it pointless to use the greeting to recognize opponents and make a lot of work for me. Can anyone suggest a good way to handle this? I want a way for people to recognize an opponent as probably (but not certainly) friendly without making it a game of "who updates last".

Feedback on the proposed gameplay tweaks, or ideas for others that I have not considered, would be appreciated!

\$\endgroup\$
13
  • \$\begingroup\$ Please do not allow the "feed" strategy. We want all of the bots to be competitive, and the feeder bots aren't competitive, and creates an unfair advantage to individual bots (hmm...I wonder who will win 3v1). I also am not a fan of "send a message" actions: They either don't work or they make abuse possible. (The only exception is if you are making a team-based KotH) Scoring based on longevity is a good idea. If you want a longer history, you can also do a lives-based mechanic where a player has 3 lives. If they choose the lower number 3 times, then they are out of the tournament. \$\endgroup\$ Oct 10, 2018 at 14:55
  • \$\begingroup\$ @NathanMerrill the idea for the feeding was that if I have to have multiple copies of each bot in the tournament to get a large pool, then it would be useful to recognize yourself. By default, you will always have "teammates" as long as resampling happens. But I understand the objection. How would lives work, practically? If a bot bids lower, how would I handle that? Ignore the result up to 3 times, and just let them through to the next round without cost to either player? \$\endgroup\$
    – KBriggs
    Oct 10, 2018 at 15:32
  • \$\begingroup\$ Oh, I like the idea of feeding copies of your bot. Perhaps giving them a single boolean variable that indicates if it's a clone or not (or something along those lines?). If both both Bot A and B have multiple lives, they would both have their HP removed, but the one that bid lower would have a life removed. Perhaps "life" is the wrong term here: Maybe they get a "strike", and 3 strikes and you are out. \$\endgroup\$ Oct 10, 2018 at 15:36
  • 1
    \$\begingroup\$ Actually! If you have multiple clones of a bot, there's an easier solution than a 3-strike system: Simply give the opponent the entire history of all of the clones. \$\endgroup\$ Oct 10, 2018 at 15:39
  • \$\begingroup\$ I think if I used the 3 strike system what would happen is that everyone would just bid 0 twice in a row to get into the later rounds with full hp and go from there. Realistically I can't stop the feeding strategy, since you can use betting history to set up a recognizable pattern, so I think it's better to build it into the game somehow. Simply telling people if it's a clone is an option, but then it would just advance one to the next round for free without generating a meaningful bid history data point, so why have the clones in the first place? The entire history of clones is a neat idea... \$\endgroup\$
    – KBriggs
    Oct 10, 2018 at 15:49
  • \$\begingroup\$ You tell people if they are playing against their own clone. There's not like an "original bot" or a "clone bot". You simply have a variable that is true if it is Bot 1 vs Bot 1 and false if it is Bot 1 vs Bot 2. You are right that there are no systematic ways to stop feeding, but we have rules against that on SE, and so you can use human judgement to disallow those bots. \$\endgroup\$ Oct 10, 2018 at 15:58
  • \$\begingroup\$ I know what you mean. But if I tell them that, then they get to advance deterministically with a bet of 1, which is not a useful data point for anyone else predicting their behavior. I would like to find a solution that forces at least a meaningful bet (or that they have to take the risk of mistaken identity to make the 1-bet). If they know for certain they are facing a clone, then there is no value to having clones at all, since their purpose was to make a longer tournament with more history to use in predictions. But I realize as I say this that the "message passing" idea doesn't work either \$\endgroup\$
    – KBriggs
    Oct 10, 2018 at 16:01
  • \$\begingroup\$ Yeah. Perhaps you setup the tournament so that clones never actually fight each other. These battles aren't interesting, and only hurt the bot that randomly got assigned itself. The existence of clones would solely be to have a longer history. \$\endgroup\$ Oct 10, 2018 at 16:26
  • 1
    \$\begingroup\$ The only really sound way to avoid the who updates last problem is to host it in such a way that people can't see their competitors' code - i.e. somewhere other than PPCG. On this site you'll always have people special-casing specific opponents. \$\endgroup\$ Oct 11, 2018 at 11:54
  • \$\begingroup\$ @PeterTaylor probably true. Perhaps I could collect submissions by some other means and just ask players to put a placeholder answer which they can edit with code after the deadline. Would that be allowed? I'd have to keep the controller private, and maybe provide a suite of unit tests that entries should pass before submission. \$\endgroup\$
    – KBriggs
    Oct 11, 2018 at 15:16
  • \$\begingroup\$ Something vaguely similar has been done once (a Kolmogorov-complexity question where OP asked people to post a hash of their code, and then after the deadline to post their actual code, so that people couldn't just port someone else's answer to a golfier language), but it's a lot of hassle. Really when you're having to fight the site's design that much, you may as well not bother and just accept that some challenges don't work here. \$\endgroup\$ Oct 11, 2018 at 15:23
  • \$\begingroup\$ Looking at what happened with your previous challenge, though, I would suggest requiring that answers be self-contained so that the deletion of a function defined in someone else's answer won't break them. \$\endgroup\$ Oct 11, 2018 at 15:24
  • \$\begingroup\$ @PeterTaylor fair enough, that does seem like a lot of unnecessary work. I'll shop the format a bit more and see if I can come up with something a little simpler. Disallowing interaction between entries is certainly doable, but having people post lat-second updates will always be a problem, I think. \$\endgroup\$
    – KBriggs
    Oct 11, 2018 at 15:24
0
\$\begingroup\$

Is it a valid snooker break?

In snooker, the objective is to score as many points as possible by potting two types of balls: red balls, 15 of them, each valued 1 point, and colour balls, 6 of them, valued 2, 3, 4, 5, 6 and 7 points. A break is a sequence of potted balls. The balls must be potted in a predetermined order: the break must start with potting a red ball, then a colour ball and continued with alternating in potting red and colour balls until all of the red balls are potted, then potting colour balls in ascending order of their values (if all of the red balls have already been potted, start with the colour ball with the lowest value). However, if a free ball is declared after an opponent's foul, the break may start with any ball, replacing the ball that should be usually potted first (red if some red balls are still on the table, colour with the lowest value if all reds are potted).

Your task is to determine if the given sequence of balls adheres to the rules mentioned above.

Input

A list of integers representing values of snooker balls. The list will not be empty.

Output

A truthy value if the list is a valid snooker break and falsey if it isn't.

Test cases

Truthy:

6
1,7
2,5
2,3,4
1,5,1,5,1
1,3,1,5,1,4
6,4,5
5,2,1,4,1,6,1,6
1,6,2,3,4,5,6,7
3,2,3,4,5,6,7
4,4,1
5,6,1,7
1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,2,3,4,5,6,7 //"maximum break"
7,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,2,3,4,5,6,7

Falsey:

1,1
4,4,4
4,2,3,1
1,2,3
5,1,7,1
2,5,6,7 //2 is already off the table
5,4,2,3
1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,2,3,4,5,6,7     //one red too many
7,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,2,3,4,5,6,7 //as well as here

To sandbox:

I am thinking about including lists with values out of range of snooker balls' values (less than 1 or greater than 7) in which cases the result should be falsey. As this is a decision problem, I think that these cases should be covered as well.

\$\endgroup\$
1
  • \$\begingroup\$ Maybe you can let the submissions assume that only a list of [1-7]s are inputted. This would be more flexible for the submissions to do. \$\endgroup\$ Oct 12, 2018 at 7:48
0
\$\begingroup\$

Implement JavaScript's Abstract Equality Comparison Algorithm.

Background

As many know, JavaScript has quite confusing equality rules and it's generally recommended to use === instead to avoid the weird corner cases that come with using ==.

The logic behind the == operator is documented as "The Abstract Equality Comparison Algorithm" in the ECMAScript specification. For this particular question we will be implementing from the ECMAScript 5.1 edition specification. The algorithm is documented in section 11.9.3 of this specification.

Task

Implement the abstract equality comparison algorithm in JavaScript without using == or !=.

Input & output

The input is two variables. These variables can be anything that is not a Reference type. The output is a truthy or falsy value that represents the result of performing the abstract equality comparison algorithm.

Test Cases

Since there are a lot of edge cases, I took these test cases from the test262 repository.

Examples that return truthy values:

true == true
false == false
true == 1
false == "0"
0 == false
"1" == true
+0 == -0
-0 == +0
Number.POSITIVE_INFINITY == Number.POSITIVE_INFINITY
Number.NEGATIVE_INFINITY == Number.NEGATIVE_INFINITY
Number.POSITIVE_INFINITY == -Number.NEGATIVE_INFINITY
1.0 == 1
"" == ""
" " == " "
"string" == "string"
1 == "1"
1.100 == "+1.10"
255 == "0xff"
0 == ""
"-1" == -1
"-1.100" == -1.10
"5e-324" == 5e-324
undefined == undefined
void 0 == undefined
undefined == eval("var x")
undefined == null
null == void 0
null == null
{ var x, y; x = {}; y = x; x == y; } // two variables pointing to same object
new Boolean(true) == true
new Number(1) == true
new String("1") == true
true == new Boolean(true)
true == new Number(1)
true == new String("+1")
new Boolean(true) == 1
new Number(-1) == -1
new String("-1") == -1
1 == new Boolean(true)
-1 == new Number(-1)
-1 == new String("-1")
new Boolean(true) == "1"
new Number(-1) == "-1"
new String("x") == "x"
"1" == new Boolean(true)
"-1" == new Number(-1)
"x" == new String("x")
{valueOf: function() {return 1}} == true
{valueOf: function() {return 1}, toString: function() {return 0}} == 1
{valueOf: function() {return 1}, toString: function() {return {}}} == "+1"
{valueOf: function() {return "+1"}, toString: function() {throw "error"}} == true
{toString: function() {return "+1"}} == 1
{valueOf: function() {return {}}, toString: function() {return "+1"}} == "+1"
true == {valueOf: function() {return 1}}
1 == {valueOf: function() {return 1}, toString: function() {return 0}}
"+1" == {valueOf: function() {return 1}, toString: function() {return {}}}
true == {valueOf: function() {return "+1"}, toString: function() {throw "error"}}
1 == {toString: function() {return "+1"}}
"+1" == {valueOf: function() {return {}}, toString: function() {return "+1"}}

Examples that return falsy values:

true == false
false == true
Number.NaN == true
Number.NaN ==  1
Number.NaN == Number.NaN
Number.NaN == Number.POSITIVE_INFINITY
Number.NaN == Number.NEGATIVE_INFINITY
Number.NaN == Number.MAX_VALUE
Number.NaN == Number.MIN_VALUE
Number.NaN == "string"
Number.NaN == new Object()
true == Number.NaN
-1 == Number.NaN
Number.POSITIVE_INFINITY == Number.NaN
Number.NEGATIVE_INFINITY == Number.NaN
Number.MAX_VALUE == Number.NaN
Number.MIN_VALUE == Number.NaN
"string" == Number.NaN
new Object() == Number.NaN
1 == 0.999999999999
" " == ""
" string" == "string "
"1.0" == "1"
"0xff" == "255"
1 == "true"
"false" == 0
undefined == true
undefined == 0
undefined == "undefined"
undefined == {}
null == false
null == 0
null == "null"
null == {}
false == undefined
Number.NaN == undefined
"undefined" == undefined
{} == undefined
false == null
0 == null
"null" == null
{} == null
new Boolean(true) == new Boolean(true)
new Number(1) == new Number(1)
new String("x") == new String("x")
new Object() == new Object()
new Boolean(true) == new Number(1)
new Number(1) == new String("1")
new String("1") == new Boolean(true)
{valueOf: function() {return {}}, toString: function() {return "+1"}} == "1"
"1" == {valueOf: function() {return {}}, toString: function() {return "+1"}}

Examples that throw an error:

{valueOf: function() {throw "error"}, toString: function() {return 1}} == 1 // throws "error"
{valueOf: function() {return {}}, toString: function() {return {}}} == 1 // throws TypeError
1 == {valueOf: function() {throw "error"}, toString: function() {return 1}} // throws "error"
1 == {valueOf: function() {return {}}, toString: function() {return {}}} // throws TypeError

Rules

Standard rules apply. The shortest code in bytes wins.

Sandbox Questions

  • Is it ok that I am restricting the language to JavaScript? Should I allow languages that compile to JavaScript or have the types listed here?
  • Have I got too many test cases here? Should I cut it down? Perhaps instead I could create a tio.run template which runs all the tests instead of listing them all out here.
  • Is the requirement of not using == and != strict enough? I feel that I want to avoid answers where some inbuilt function indirectly calls == and getting around it that way but I don't know how to enforce that.
\$\endgroup\$
6
  • \$\begingroup\$ I'd say the number of test cases is still acceptable, though creating a TIO template sounds like a good idea anyway. \$\endgroup\$
    – Laikoni
    Oct 14, 2018 at 12:43
  • \$\begingroup\$ We still can use === and !==, can't we? \$\endgroup\$ Oct 15, 2018 at 9:07
  • \$\begingroup\$ @ShieruAsakoto yes \$\endgroup\$ Oct 15, 2018 at 9:48
  • \$\begingroup\$ @CameronAavik Build a custom Javascript interpreter where calls to == errors out, then use that. \$\endgroup\$
    – DELETE_ME
    Oct 15, 2018 at 10:18
  • \$\begingroup\$ Here's a link to a test framework in TIO. I don't think it's possible to overload operators in javascript though \$\endgroup\$
    – Jo King Mod
    Oct 17, 2018 at 9:06
  • \$\begingroup\$ (for example when someone edits the interpreter to ban some features, see i.snag.gy/7ELPOt.jpg - the link "this branch" links to github.com/Mego/Seriously/tree/… --- of course that's a lot of work, but that would make sure that people definitely don't cheat) \$\endgroup\$
    – DELETE_ME
    Oct 19, 2018 at 1:40
0
\$\begingroup\$

Cologne Phonetics

From Wikipedia: Cologne phonetics is a phonetic algorithm which assigns to words a sequence of digits, the phonetic code. The aim of this procedure is that identical sounding words have the same code assigned to them. The algorithm can be used to perform a similarity search between words. For example, it is possible in a name [collection?] to find entries like "Meier" under different spellings such as "Maier", "Mayer" or "Mayr".

The Cologne phonetics matches each letter of a word to a digit between 0 and 8. To select the appropriate digit, at most one adjacent letter is used as context.

Procedure:

Processing of a word is done in three steps:

  1. Encode letter by letter from left to right according to the conversion rules below.
  2. Remove all digits occurring more than once next to each other.
  3. Remove all code "0" except at the beginning

Conversion rules

  • A, E, I, J, O, U, Y become 0
  • H becomes nothing
  • B becomes 1
  • P becomes 1, unless it's before H
  • D, T become 2, unless they're before C, S, Z
  • F, V, W become 3
  • P becomes 3, if it's before H
  • G, K, Q become 4
  • C becomes 4 in initial position before A, H, K, L, O, Q, R, U, X
  • C becomes 4, if it's before A, H, K, O, Q, U, X, except after S, Z
  • X becomes 48, unless it's after C, K, Q
  • L becomes 5
  • M, N become 6
  • R becomes 7
  • S, Z become 8
  • C becomes 8, if it's after S, Z
  • C becomes 8 in initial position except before A, H, K, L, O, Q, R, U, X
  • C becomes 8, if it's not before A, H, K, O, Q, U, X
  • D, T become 8, if they're before C, S, Z
  • X becomes 8, if it's after C, K, Q

Challenge

Implement a program or a function that takes a single string as input and returns the phonetic code according to the rules stated above. You may choose your own output format, but keep in mind that the expected output may have leading zeros. The input string is guaranteed to match /^[a-zA-Z ]*$/, this means it may contain characters from the lowercase and uppercase alphabet, as well as spaces.

Test cases

Input                 Output

[empty string]        [empty]
Kolner Phonetik       45673624
Meier                 67
Mayer                 67
Augsburg              048174
Xanten                48626
Telephon              2356
Chemie                46
Muller Ludenscheid    65752682

This is , the shortest code for each language wins.

\$\endgroup\$
4
  • \$\begingroup\$ Related: Soundex function \$\endgroup\$
    – Laikoni
    Oct 14, 2018 at 12:49
  • \$\begingroup\$ What's the difference between "initial sound" and "initial position"? \$\endgroup\$
    – Laikoni
    Oct 14, 2018 at 12:58
  • \$\begingroup\$ Apparently there is none, from what I was able to find \$\endgroup\$
    – oktupol
    Oct 15, 2018 at 7:11
  • \$\begingroup\$ Ideally there would be a test case for each conversion rule as the challenge is probably mainly about handling those edge cases in the rules. \$\endgroup\$
    – Laikoni
    Oct 15, 2018 at 13:27
0
\$\begingroup\$

Keyboard Row Shift

Given an input string of characters, output the number of times we have to shift to another row while typing that string using a qwerty keyboard.

The input string will contain lower case alphabets,numbers and spaces. The newline key(enter) must also be considered at the end (only at the end). All shifts, from any row to any other will be considered as 1 shift only.

Layout:

1234567890
qwertyuiop
asdfghjkl enter
zxcvbnm
space

Examples:

"sdkflsd" -> 0
"asdwexc" -> 3 # to end the string one enter has to pressed which is in the middle
"poierlkdjfpoeirldskjf" ->3
"123 jkjk" -> 2
"llsdkfj ldkfj" -> 2
"lkasdjmnbcv " -> 3
"jnjn 5" -> 6

This is code-golf, so shortest code wins.

\$\endgroup\$
4
  • \$\begingroup\$ You need some test cases that contain a space and numbers. I'd also make it clear in your description that a shift can go any distance (going from the top row to the bottom is only 1 shift) \$\endgroup\$ Oct 16, 2018 at 12:48
  • \$\begingroup\$ Done, @NathanMerrill \$\endgroup\$ Oct 17, 2018 at 5:36
  • \$\begingroup\$ How flexible is input? Is uppercase OK? How about an array of character strings or even an array that mixes digits and character strings? \$\endgroup\$
    – Shaggy
    Oct 18, 2018 at 21:47
  • 1
    \$\begingroup\$ I have mentioned only lower case, input has to be string only not an array. \$\endgroup\$ Oct 19, 2018 at 5:15
0
\$\begingroup\$

Given a program in your language, generate another program that do exactly the same thing so every bytes in it are prime.

Shortest generator in every language win. No acception.

Nop in languages that only allow prime bytes are legit, but just don't post them(or make a community answer to put them)

\$\endgroup\$
6
  • \$\begingroup\$ Upvote this comment if you think that the idea of the challenge is not interesting and it should not be posted. \$\endgroup\$
    – DELETE_ME
    Oct 26, 2018 at 10:46
  • 1
    \$\begingroup\$ Upvote this comment if you think that the idea is fine, but the challenge is unclear or needs fixing; in that case also leave a comment. \$\endgroup\$
    – DELETE_ME
    Oct 26, 2018 at 10:47
  • \$\begingroup\$ I made a small poll above ↑. I think the idea is interesting, and if it's poorly worded, the post can't be fixed without suggestions. Note that the challenge is already fully specified in the current state (task description, winning criteria), and it's impossible to give sample input/output to test programs (if you understand the challenge, you will see why). \$\endgroup\$
    – DELETE_ME
    Oct 26, 2018 at 10:49
  • \$\begingroup\$ Lots of languages quite rely on composite(not prime) bytes, so upvote this comment if you think it's too restrict \$\endgroup\$
    – l4m2
    Oct 26, 2018 at 12:40
  • \$\begingroup\$ I think the idea is interesting, especially in languages like Jelly which can do most anything with small subsets of its character set. My main problem is: how much of the language do we have to support in the input to our generator? Many languages which are capable of this task have far too many possible instructions, etc., every one of which would need to be remapped to an all-prime version. Unless perhaps it's possible to simply generate any given string and execute it whilst using only prime bytes... \$\endgroup\$ Oct 27, 2018 at 3:14
  • \$\begingroup\$ @ETHproductions I think a subset of an existing language can be considered another language? \$\endgroup\$
    – DELETE_ME
    Nov 11, 2018 at 4:23
1
112 113
114
115 116
152

You must log in to answer this question.

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