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

4562 Answers 4562

1
63 64
65
66 67
153
1
\$\begingroup\$

Solve the Square-Sum problem

Based on these (very good) Numberphile videos:

The Square-Sum problem and its extra footage.

The Problem:

Given a list of integer numbers [1,n] where n≥15; n≠18, 19, 20, 21, 22, 24, your task is to arrange those numbers in a way such that the sum of two consecutive numbers is a square number.

Example for n=15:

Original sequence: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Square-sum of it: 8 1 15 10 6 3 13 12 4 5 11 14 2 7 9
                   | |  |  | | |  |  | | |  |  | | |
                  3² 4² 5² 4²3²4² 5² 4²3²4² 5² 4²3²4²

This problem can be solved by creating a graph of every sum of two numbers in the sequence that result in a square number:

Graph

From that graph, it's possible to find its Hamiltonian Path:

Hamiltonian Path

This path, if existing, is the solution to the square-sum problem.

Rules:

---Under Construction---

Sandbox:

  • Suggestions?
  • Dupe?
  • Test cases are under construction
\$\endgroup\$
1
1
\$\begingroup\$

Word ladder

A word ladder is a puzzle where the aim is to create the smallest sequence of steps between two fixed words (a starting word and a target word), where each step changes one letter to produce a new word. All the intermediate words must be recognised in a dictionary (which will be supplied).

If the target word is longer than the starting word, a step may add a letter at any position instead of changing one; if it's shorter than the starting word, a step may remove a letter instead of changing one.

Examples:

HAND
BAND
BOND
FOND
FOOD
FOOT
FINGER
FINER
FINE
TINE
TONE
TOE
EYES
EYED
DYED
DEED
TEED
TEND
TENT
TENTH
TEETH

The challenge

Write a program or function which accepts a dictionary of words and the two fixed words (i.e. a starting word and a target word), and produces an ordered list of intermediate words following the rules above. You may choose to output the starting word, the target word, both, or neither.

You may use any of the standard methods of input and output, and must not bypass the rules with any of the standard loopholes.

Scoring

(I need some help with this part).

The score is the number of dictionary lookups your program makes during a test run (or average of several test runs, if it's not deterministic) on a set of inputs with a simple English dictionary. Q: does this test set need to be prepared and included in the question?


Sandbox questions

I don't really want to make this a , as we'll just end up with simple brute-force algorithms; I really want to see creative use of the dictionary, either by pre-processing or perhaps by ordering candidate words.

Is there a way we can define a "dictionary lookup" and somehow separate the word generation/validation from knowledge of the fixed words, without making assumptions that the language has functions or other methods of isolating code?

Can we require the dictionary to be a separate process, and provide a reference implementation? I don't think we can, without excluding languages without reasonable inter-process communication (I'm thinking of PostScript, possibly JavaScript, and microcomputer BASIC).

\$\endgroup\$
9
  • \$\begingroup\$ I think this could be a test-battery challenge, with both different words and different dictionaries as tests. Different dictionaries are needed to avoid languages searching in a build-in English dictionary and only validating their finds in the provided dict. \$\endgroup\$
    – Laikoni
    Jan 18, 2018 at 14:33
  • \$\begingroup\$ I mentioned English because I would like entries to be able to use heuristics to choose a good way to search first - perhaps simple vowel/consonant rules, perhaps something more sophisticated (digraph tables?). Promising an arbitrary dictionary would prevent that kind of thinking, especially if there's nothing to say that "XYQQZ" won't be in it. @Laikoni, could your concern be addressed by a rule to outlaw built-in dictionaries? ("You must use only the supplied dictionary", for example) \$\endgroup\$ Jan 18, 2018 at 14:42
  • \$\begingroup\$ I see your point and also like the idea to incentive some form of language processing. However banning built-in dictionaries comes with the general problem of banning built-ins, namely what counts as a built-in dictionary. Just from the top of my head, if the scoring is only about look-ups in a provided English dictionary and built-in dicts as well as adding a dict in to your code are a banned, how about assessing built-in texts to sample a rough dictionary? I know that some languages can asses their own documentation from within the language itself. \$\endgroup\$
    – Laikoni
    Jan 18, 2018 at 14:52
  • \$\begingroup\$ Altogether, it might be a good idea to make the score a weighted combination of code length and the number of lookups. \$\endgroup\$
    – Laikoni
    Jan 18, 2018 at 14:53
  • \$\begingroup\$ How would you define "dictionary lookup"? A program may "copy" the dictionary and count that as one dictionary lookup. A check whether a word is in the dictionary? /// Also for the problem of built-in dictionary the solution is really simple: scramble the letters, and use different languages, or just use a random dictionary. For example bunny with the scramble b->x, u->y, n->q, y->z may well become xyqqz, and of course it won't change the challenge. /// What if there is no solution? \$\endgroup\$
    – DELETE_ME
    Jan 20, 2018 at 4:48
  • \$\begingroup\$ The core question is essentially codegolf.stackexchange.com/q/2478/194 so as code-golf I would vote to close this as a dupe. But with the current rules (and in particular the requirement to produce the smallest sequence of steps) I'm not sure how viable the proposed scoring system is. Basically answers will have to be equivalent to A* and there aren't that many admissible heuristics. In particular, heuristics for whether something is a word or not would only meet spec if they encode the entire dictionary. \$\endgroup\$ Jan 20, 2018 at 9:07
  • \$\begingroup\$ Thanks @Peter and others. I didn't manage to find the code-golf version, so the link is useful. I obviously need to think a bit further about the rules and scoring (in fact, I posted to Sandbox hoping to garner further ideas). I'm starting to agree that the dictionary can be abstract if the answer is allowed to generate heuristics from it before processing inputs. If I get any better ideas, I'll come back to this and update it. \$\endgroup\$ Jan 22, 2018 at 8:47
  • \$\begingroup\$ The obvious way to address the A* issue is to not require it to be a shortest path, but then you have to balance path length vs dictionary queries in the score, which is going to be messy. \$\endgroup\$ Jan 22, 2018 at 18:32
  • \$\begingroup\$ About "dictionary lookup"... check if a word in the dictionary using a black-box function seems good enough. Hopefully it won't make programs take awfully long time to run. / Restrict to a-z? Adding Unicode would be impossible to guess. \$\endgroup\$
    – DELETE_ME
    Jan 23, 2018 at 7:34
1
\$\begingroup\$

Objective

Given a 2D array (of x by x size), write a program or function to alternatively shift elements of the array along the anti-diagonals. (anti-diagonals are right to left, top to bottom). (first anti-diagonal moves down second anti-diagonal moves up with elements wrapping when they reach the end of the anti-diagonal)

Example

a b c d
e f g h
i j k l
m n o p

Will become:

a e i g
b c j n
f m h o
d k l p

I will follow the tradition of selecting the shortest working code as the best answer

**edited for user202729 suggestion

\$\endgroup\$
9
  • 1
    \$\begingroup\$ Should it be "antidiagonals"? \$\endgroup\$
    – DELETE_ME
    Jan 22, 2018 at 13:58
  • 1
    \$\begingroup\$ Dupe? \$\endgroup\$ Jan 23, 2018 at 8:22
  • \$\begingroup\$ @PeterTaylor im trying to shift the anti-diagonals not reverse them \$\endgroup\$ Jan 23, 2018 at 8:55
  • \$\begingroup\$ So is the question I linked. \$\endgroup\$ Jan 23, 2018 at 9:22
  • \$\begingroup\$ @PeterTaylor look at the 4x4 test case and compare it with mine. I have a different result for that case. I am asking people to shift the elements along the anti diagonals, not to rotate the anti diagonals themselves. \$\endgroup\$ Jan 23, 2018 at 9:39
  • 1
    \$\begingroup\$ Although the specification of this proposal is not especially clear, I think that the only difference is that the question I linked rotates all anti-diagonals in the same direction whereas this rotates them alternately in one direction and the other. \$\endgroup\$ Jan 23, 2018 at 12:18
  • \$\begingroup\$ @PeterTaylor i will again clarify i am not rotating them i am shifting them. for example if an anti diagonal was say - 1 2 3 4 5 6 my outcome would be: 6 1 2 3 4 5 (or 2 3 4 5 6 1 depending on which antidiagonal it was) instead of 6 5 4 3 2 1 (which is the rotation of that antidiagonal) \$\endgroup\$ Jan 23, 2018 at 12:27
  • 1
    \$\begingroup\$ Shifting and rotating are different words for the same thing: the only difference is that rotating makes it clearer that it wraps round rather than losing one element from one end and introducing a new one at the other end. You're thinking of reversal. \$\endgroup\$ Jan 23, 2018 at 12:38
  • \$\begingroup\$ @peter Taylor your right... I goofed up while matching the arrays thanks for the catch \$\endgroup\$ Jan 23, 2018 at 13:03
1
\$\begingroup\$

Shape sequence sums

0. DEFINITIONS

For the purposes of this challenge, a sequence refers to a list of numbers whose absolute values increment in steps of 1. A sequence begins with a value of 1, 0, or -1.
A positive sequence refers to the natural numbers: 1, 2, 3, 4, and so on.
A negative sequence refers to the additive inverses of the natural numbers: -1, -2, -3, -4, and so on.

1. CHALLENGE

Given an integer n, return a list of sequences such that the sum of all the numbers in the list is equal to n. Sequences must alternate in sign (see test cases). Solutions must produce the list with the fewest sequences; that is, the sign should change a minimal number of times. (Read: Don't do 1, 2, -1 over and over again.) The resulting list must be flat, not nested. The shortest working solution wins.

2. TEST CASES

 17: 1, 2, 3, 4, 5, 6, -1, -2, -3, 1, 2, -1
 18: 1, 2, 3, 4, 5, 6, -1, -2
 19: 1, 2, 3, 4, 5, 6, -1, -2, 1
 21: 1, 2, 3, 4, 5, 6
-21: -1, -2, -3, -4, -5, -6
 -5: -1, -2, -3, 1
  0: 0 or [] (null set)

You may choose to begin each sequence with 0 instead of 1 or -1. However, if you do this, every sequence must begin with a zero, not just the positives, the negatives, the first sequence, or any other strict subset. This also means that input 0 requires a list containing a single 0.

 17: 0, 1, 2, 3, 4, 5, 6, 0, -1, -2, -3, 0, 1, 2, 0, -1
  0: 0

\$\endgroup\$
7
  • 1
    \$\begingroup\$ Is there any requirement that answers provide an output with the smallest number of sequences, the fewest total numbers, or just any list of numbers which can be partitioned into alternating positive and negative sequences? I might recommend some restriction else repeating 1, 2, -1 will eventually reach any number \$\endgroup\$ Jan 23, 2018 at 20:48
  • 1
    \$\begingroup\$ Can the output for 0 be [], ie. is the empty sequence a sequence? \$\endgroup\$ Jan 23, 2018 at 20:49
  • \$\begingroup\$ @Kamil & BMO: Thanks, I've updated to address these. Also added requirement that list be flat. \$\endgroup\$
    – Joe
    Jan 23, 2018 at 21:49
  • \$\begingroup\$ Why do you require flatness? \$\endgroup\$ Jan 24, 2018 at 1:07
  • 1
    \$\begingroup\$ Idk, I just feel like it. I like flat lists :P \$\endgroup\$
    – Joe
    Jan 24, 2018 at 2:32
  • \$\begingroup\$ Title suggestion: "Shape sequence sums" \$\endgroup\$ Jan 24, 2018 at 5:31
  • 1
    \$\begingroup\$ 1. I think that this question would be a lot simpler to understand if it were rewritten in terms of triangle numbers rather than sequences. 2. Most of the test cases are wrong. Every integer can be produced with just two sequences. \$\endgroup\$ Jan 24, 2018 at 12:57
1
\$\begingroup\$

Different tasks, same characters, level 2

In this challenge, you need to solve 3 different tasks using the same set of characters. You can rearrange the characters, but you can't add or remove characters.

The winner will be the submission that solves all tasks using the smallest number of characters. All tasks must be solved in the same language.

Note that it's the smallest number of characters, not the smallest number of unique characters.

Twist: If one or more characters can be removed from a script without breaking it, then your submission is disqualified. This means that comments are out of the picture, as well as long variable names to get the character counts to match up.

You do not have to prove that it's impossible to remove characters and still have a functioning script, but you should try to make it impossible. If nobody bothers to look at it, then your submission is valid. If nobody sees a way to remove one or more characters, then your submission is valid. If however, someone looks at your post and sees something that can be removed without breaking it, then your submission is invalid.


Tasks:

I'll create 3 tasks that are fairly simple typical code-golf tasks.


So, what do you think about the idea?

\$\endgroup\$
11
  • 2
    \$\begingroup\$ I don't think the twist is going to be easily enforceable. For any program longer than a dozen bytes the computation time on checking that it fits this requirement becomes immense. \$\endgroup\$
    – Wheat Wizard Mod
    Nov 28, 2017 at 22:53
  • 1
    \$\begingroup\$ I think I'll let the burden of disproof (is that a thing?) lie with the viewers. Those posting answers will do their best to make it impossible to remove fluff without breaking it. If someone finds a way to do it, then the submission is invalid. If every character is there for a reason (it has a function) then it should be fairly hard to find something that can be removed that OP wouldn't already know of (for instance reversing something twice). It's not CNR, but if people find ways to golf an answer without breaking it, then it's invalid. \$\endgroup\$ Nov 29, 2017 at 7:22
  • 2
    \$\begingroup\$ If nobody bothers to look at it, then your submission is valid. If nobody sees a way to remove one or more characters, then your submission is valid. If however, someone looks at your post and sees something that can be removed without breaking it, then you submission is invalid. \$\endgroup\$ Nov 29, 2017 at 7:27
  • 1
    \$\begingroup\$ I think that would be generally effective; in practical languages with longer code, fluff is easier to spot in the syntax, and in recreational golfing languages the shorter code will be easier to manually check. \$\endgroup\$
    – FlipTack
    Nov 29, 2017 at 8:17
  • \$\begingroup\$ So if there exists a subsequence of the original program that also do the task the original program does (not necessarily equivalent), and there is someone point it out, the submission is invalid? \$\endgroup\$
    – DELETE_ME
    Nov 29, 2017 at 13:32
  • \$\begingroup\$ Do the removed characters need to be contiguous? \$\endgroup\$ Nov 29, 2017 at 14:41
  • \$\begingroup\$ @AdmBorkBork no. It's to avoid stuff like unnecessary long variable names etc. And then you'd need to remove character multiple places... \$\endgroup\$ Nov 29, 2017 at 15:53
  • \$\begingroup\$ Cool! I've had an idea like this, but using different languages to solve the same task (with the exact same twist) \$\endgroup\$
    – Sanchises
    Jan 25, 2018 at 21:15
  • \$\begingroup\$ @Sanchises you may go ahead and post it if you'd like! Either this version or a polyglot version. :) Interested? \$\endgroup\$ Jan 25, 2018 at 21:35
  • \$\begingroup\$ Oh you may have this one. I'm still stuck on thinking of one task.... \$\endgroup\$
    – Sanchises
    Jan 25, 2018 at 21:36
  • \$\begingroup\$ You have a very nice track record when it comes to challenges, so I'd like to see it :) \$\endgroup\$ Jan 25, 2018 at 21:37
1
\$\begingroup\$

What's in an ISBN?

Given an ISBN-10 code starting with 0 or 1, extract the registration group, registrant, publication, and checksum numbers.

Background

We've talked about International Standard Book Numbers before, including converting them and calculating their checksums. Now let's talk about parsing their data.

An ISBN-10 code has four parts; in order from left to right: registration group, registrant, publication, and checksum. We're only going to consider registration group numbers 0 and 1, which represent English-speaking areas. Take a look at these two ISBN-10 codes, shown with their parts separated:

  • 0-307-45547-5 – This book, from registration group 0, is printed by publishing giant Penguin Random House. Penguin prints thousands of books, so it's assigned ISBN blocks with few digits for registrar (307 here), leaving many digits for publication (45547). The checksum is 5.

  • 1-940696-27-5 – This book, from registration group 1, is printed by indie poetry press Wave Books, which prints just a few books each year, so its ISBN blocks have many digits for registrant (940696 here) and just a few for publication number (27). The checksum is also 5.

Specification

Write a program or function that takes a non-separated ISBN-10 code and return its four parts as distinct values.

ISBN-10 codes in registration groups 0 and 1 are separated according to the following scheme, where xx… is registrant number and y is checksum.

From            to                 From            to
-------------   -------------      -------------   -------------
0-00-xxxxxx-y … 0-19-xxxxxx-y      1-00-xxxxxx-y … 1-09-xxxxxx-y
0-200-xxxxx-y … 0-699-xxxxx-y      1-100-xxxxx-y … 1-399-xxxxx-y
0-7000-xxxx-y … 0-8499-xxxx-y      1-4000-xxxx-y … 1-5499-xxxx-y
0-85000-xxx-y … 0-89999-xxx-y      1-55000-xxx-y … 1-86979-xxx-y
0-900000-xx-y … 0-949999-xx-y      1-869800-xx-y … 1-998999-xx-y
0-9500000-x-y … 0-9999999-x-y      1-9990000-x-y … 1-9999999-x-y

For example, 0307455475 lies in the range 0-200-xxxxx-y … 0-699-xxxxx-y, so we know it has three digits for registrant and five for publication and the program, given this input, should return 0, 307, 45547, and 5.

Likewise, 1940696275 is in the range 1-869800-xx-y … 1-998999-xx-y, so the program should return 1, 940696, 27, and 5.

Input

  • Input may be in any convenient format, e.g. a string, list of characters, or list of numbers.
  • The input must be 10 or fewer characters or numbers, plus an optional trailing newline. Leading zeroes are optional.
  • In ISBN-10 codes the checksum 10 is represented with an X. If your program takes input as a list of numbers, the number 10 may be used. If it takes input as a string or list of characters, a single non-digit character of your choosing (e.g. X or x) must be used.
  • Otherwise, standard input rules apply.

Output

  • Output may be in any convenient format, as long as each part is easily distinguishable from the next, e.g. a delimited string, a list of four numbers, or a list of four lists of numbers.
  • Leading zeroes are optional.
  • If the checksum is 10, it may be 10 (as a number or string) or a single non-digit character of your choosing. For example, both 0 8044 2957 X and 0 8044 2957 10 are valid.
  • Otherwise, standard output rules apply.

Winning

This is ; the solution with the fewest bytes wins.

Standard loopholes are forbidden.

Test cases

Input       Output
0000000000  0-00-000000-0
0144751605  0-14-475160-5
0393765621  0-393-76562-1
0763320041  0-7633-2004-1
0859056018  0-85905-601-8
0906789222  0-906789-22-2
0958171947  0-9581719-4-7
0999999999  0-9999999-9-9
099999999X  0-9999999-9-X
1000000000  1-00-000000-0
1080925818  1-08-092581-8
1149092167  1-149-09216-7
1457721261  1-4577-2126-1
1578424693  1-57842-469-3
1973088617  1-973088-61-7
1999973361  1-9999733-6-1
1999999999  1-9999999-9-9
199999999X  1-9999999-9-X

Sandbox questions

  1. What are good tags for this?

  2. Is the description of the separation scheme clear?

  3. Any test cases missing (or wrong)?

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

Code Basketball

Programs are competing in a game of "basketball". They are given a 5x6 (Minus the top center character) grid on which to put either /, \, or ^. The programs can place two symbols every tick on the grid. If the programs try and place a symbol at the same place at the same time, neither symbol is placed.

On the first tick, a 'ball', o, is spawned at (3,6) on the grid. The ball falls by one character every tick. If the ball encounters a \ while falling, it moves to the right. If it encounters a /, it moves to the left. If the ball hits a ^, it moves back to the top of the grid at that x position. The ball only moves once every tick, and does not effect the map on it's own.

When the ball is on the bottom row, if it's on the left, it gives a point to the first program and respawns, if it's on the right, it gives a point to the second program and respawns. If it's in the center, it simply respawns without giving points to anyone.

If the ball tries to move off the map, it simply stays in place.

The grid is rotated when transfered to the contending programs so that it always appears that the left is that program's goal.

Program I/O

Programs use Standard Input and Standard Output to communicate to the contest framework. The program is sent a 30 byte buffer containing a map and a 2 byte buffer containing the position of the ball.

The program must send two 3 byte buffers in response with the character to put on the map, it's x position, and it's y position.

The framework gives each program 5 seconds to perform there action. If they fail to be within this 5 second window three times, they automatically lose to prevent the round from going on too long.

Competition

Programs will compete in pairs of two. The winner of each pair will move on to the next round, and be paired up with another winner.

Sandbox questions

  1. How can this be improved?

  2. What actions should I take to make sure rounds are fair?

  3. How should invalid data be handled when sent to the framework?

\$\endgroup\$
10
  • \$\begingroup\$ The execution of time is unclear here: What happens if a ball falls down on the following line: \\\\\ ? Does it move all the way across in a single move or does each step take a single move? Does the ball remove symbols that it hit? \$\endgroup\$ Feb 5, 2018 at 21:02
  • \$\begingroup\$ I think your IO is a bit cumbersome: Simply feed them all of the info at the start, and wait for them to output the two new symbols. \$\endgroup\$ Feb 5, 2018 at 21:05
  • \$\begingroup\$ I'll clear that up. The ball will move across one step at a time. Symbols are not removed, to prevent it from being the same thing each round. \$\endgroup\$ Feb 5, 2018 at 21:06
  • \$\begingroup\$ More questions: What happens if both programs place on the same square? If the ball is currently on a \ and I place a / on the square it currently is on, which action does it follow? \$\endgroup\$ Feb 5, 2018 at 21:10
  • \$\begingroup\$ Cleared that up as well. The write is canceled out. In terms of the ball, it follows the new symbol the next tick. \$\endgroup\$ Feb 5, 2018 at 21:14
  • \$\begingroup\$ Just making sure I understand: If two players write on the same square, nothing happens. If a ball is on (3,6) and the square is a / , but I write a \ , the ball won't be affected, because my symbol only affects things the next tick. \$\endgroup\$ Feb 5, 2018 at 21:17
  • \$\begingroup\$ Finally, (and the issue I don't see easily resolved): I feel like this has a really small search space, and very little room for different strategies. Technically, there are 7830 moves a turn, but most of the squares and moves are irrelevant and can be ignored. In essence, this game feels like a tug-of-war where both sides are equally as strong. Any push to the right is easily countered by a push to the left. \$\endgroup\$ Feb 5, 2018 at 21:21
  • \$\begingroup\$ Precisely. The programs make their changes after the ball has made it's move for that tick. \$\endgroup\$ Feb 5, 2018 at 21:22
  • \$\begingroup\$ @NathanMerrill I've been thinking that too. The grid space can be fairly easily expanded. The game is a game of "skill" between the two programs. They (The programmers) have to try and be inventive to force intresting situations and possibly win. If i do expand the grid space, how large should it be? \$\endgroup\$ Feb 5, 2018 at 21:24
  • \$\begingroup\$ Let us continue this discussion in chat. \$\endgroup\$ Feb 5, 2018 at 21:25
1
\$\begingroup\$

Basketball Recruitment

You're recruiting your local neighborhood for your Jr Basketball team. However, the opposing team also is recruiting!

  • You both stand at the end of the street of 100 houses. Each house has a kid with a unique, random height from 1 to 100. Taller is better.

  • Actions take different amounts of time. Your opponent may have a different turn order, or may even have more/less turns than you.

  • If you have spent less than or equal time than your opponent, then your turn is next (turns can be simultaneous)

On your turn you perform one of the following actions:

  • Recruit the kid at the Nth house. This takes N Time.
    • If you both recruit the same kid, you get into argument, and he decides not to play basketball this year. (Nobody gets him)
    • Once recruited, a kid won't switch sides.
  • Disqualify the kid at the Nth house. There are myriads of rules to Jr Basketball, and you know just which rules he's breaking. This takes 10 time.
    • You cannot disqualify a kid that has been recruited or is in the process of recruitment.
    • If you try to disqualify a kid on the same turn your opponent tries to recruit him, the disqualification fails.

After all of the boys have been recruited, been disqualified, or lost interest, we play the big game:

  1. We place the teams into two lines from shortest to tallest.
  2. Each pair of boys play each other.
  3. The taller one wins, and gives his team 1 point.
  4. If a team has more boys than the other, they get 1 point for each extra boy.
  5. The team with the most points wins.

Now, your goal is to become the top recruiter. This means you need to win as many games as possible. You will face many other recruiters at random until a clear victor is decided.

\$\endgroup\$
5
  • \$\begingroup\$ what happens if you recruit more people than your opponent? \$\endgroup\$ Feb 6, 2018 at 0:39
  • \$\begingroup\$ Oh, I totally forgot to add that to the post. Thanks! \$\endgroup\$ Feb 6, 2018 at 0:43
  • \$\begingroup\$ One thing I immediately notice is that recruiting more boys can be detrimental, if they're not as good as some other boys on the team: example: team 1: 3 5 7 9 11 vs team 2: 2 4 6 8 10. team 1 recruiting a boy of height 1 would cause team 1 to lose \$\endgroup\$ Feb 6, 2018 at 0:57
  • \$\begingroup\$ That sounds like a feature, not a problem :) \$\endgroup\$ Feb 6, 2018 at 1:14
  • \$\begingroup\$ I didn't say it was a problem, it was an observation. maybe i should have been clearer \$\endgroup\$ Feb 6, 2018 at 1:28
1
\$\begingroup\$

Fortnightly Challenge #8: A new kind of "asynchronous" KOTH

This is a placeholder for the challenge spec. You can discuss this challenge in a special chat room.


Ordinary KOTHs require that a single user take up the job of hosting the competition: running the whole competition at once by themselves. Everything is dependent on them, and they can only run so many competitions or update ever so frequently. I think this can be improved... somehow.

Here are some ideas, many of which would require an encryption scheme or something to ensure correctness.

  • Anybody can run the tournament and add their results to the current leaderboard somehow. This could be accomplished by some sort of cryptographic scheme to verify the results. Ideally the controller will be implemented via stack snippet to allow ordinary people to run it without downloading a controller.

  • When a bot is added/updated, only the new pairs of contestants should be tried, and nearly anyone can update the leaderboard by themselves. (Assuming a deterministic KOTH, which it will probably need to be in order to prevent people from simply uploading the results that occurred in their favor.)

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

Generate a maximal binary Gray code

Given an input integer n, find an n-bit gray code where the sum of the absolute difference between each adjacent pair of bits converted to decimal is maximized.

For example, if n = 3, there are 96 possible gray codes, and the maximal sum of deltas in decimal of those is 21. Out of the 96 total, only 8 have maximal deltas.

┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┐
│0 0 0│0 0 1│0 1 0│0 1 1│1 0 0│1 0 1│1 1 0│1 1 1│
│1 0 0│1 0 1│1 1 0│1 1 1│0 0 0│0 0 1│0 1 0│0 1 1│
│1 1 0│1 1 1│1 0 0│1 0 1│0 1 0│0 1 1│0 0 0│0 0 1│
│0 1 0│0 1 1│0 0 0│0 0 1│1 1 0│1 1 1│1 0 0│1 0 1│
│0 1 1│0 1 0│0 0 1│0 0 0│1 1 1│1 1 0│1 0 1│1 0 0│
│1 1 1│1 1 0│1 0 1│1 0 0│0 1 1│0 1 0│0 0 1│0 0 0│
│1 0 1│1 0 0│1 1 1│1 1 0│0 0 1│0 0 0│0 1 1│0 1 0│
│0 0 1│0 0 0│0 1 1│0 1 0│1 0 1│1 0 0│1 1 1│1 1 0│
└─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┘

Checking the first result, the decimal values are

0 4 6 2 3 7 5 1

and the deltas of each adjacent pair are

4 2 4 1 4 2 4

and the sum of that is 21.

Rules

  • The input will be an integer n > 0.
  • You may output either one or all possible gray codes that satisfy the condition.
\$\endgroup\$
2
  • \$\begingroup\$ Can we output the decimal values instead of the binary? \$\endgroup\$
    – DELETE_ME
    Feb 17, 2018 at 15:18
  • 1
    \$\begingroup\$ "the sum of the absolute difference between each adjacent pair of bits converted to decimal" doesn't make much sense. Decimal is irrelevant (a number's value does not depend on its representation) and mentioning it only serves to make the sentence harder to parse. And looking at the example, it's not about adjacent pairs of bits but adjacent numbers in the sequence. \$\endgroup\$ Feb 19, 2018 at 11:25
1
\$\begingroup\$

The Euler Masheroni Constant

The Euler Masheroni constant is a very interesting number. It is defined to be and appears seemingly everywhere in number theory. Famously, it is unknown whether it is rational, irrational, or transcendental.

The Challenge:

Pretty simple one here: Given N, your program should calculate the Euler Macaroni constant to at least N decimal places of prescision. Your score will be the maximum value of N for which the program is accurate, and ties will be won by the shortest code.

For refrence, the Euler Macaroni constant to 50 places is

0.57721566490153286060651209008240243104215933593992

Be sure to check out the wikipedia page for more formulas for the Oily Macaroni constant!

https://en.wikipedia.org/wiki/Euler%E2%80%93Mascheroni_constant

\$\endgroup\$
4
  • 4
    \$\begingroup\$ s/Macaroni/Mascheroni/g and s/Oily/Euler/g \$\endgroup\$
    – Beefster
    Feb 19, 2018 at 20:37
  • \$\begingroup\$ Mmmm. Oily Macaroni. Definitely doesn't stick together that way. \$\endgroup\$
    – Beefster
    Feb 19, 2018 at 20:50
  • \$\begingroup\$ The easy way to calculate this constant will definitely timeout for very small n, and I guess most programs will be infinite anyway. \$\endgroup\$
    – DELETE_ME
    Feb 20, 2018 at 4:06
  • \$\begingroup\$ You can use MathJax now: $$\gamma = \lim_{n\to\infty}\left(-\ln n + \sum_{k=1}^n\frac 1 k\right)$$ \$\endgroup\$
    – wastl
    Jun 26, 2018 at 12:25
1
\$\begingroup\$

Design a language and golf its interpreter

Your task is to design a language and write an interpreter for it. Your language must have the following properties:

  • Its source code will consist of strings of two characters. I will write them as ( and ) and refer to them as parentheses, but you can choose whichever two distinct characters you like. You can choose whether to ignore other characters.

  • Valid programs will consist of any string in which the parentheses are balanced, such as ()() or (()(()())). The empty string is a valid program. You may assume the input will be a valid program.

  • Programs will take an input and return an output. Valid inputs and outputs are of the same form as source code: they must be balanced strings of parentheses. This input and output may be accomplished by any method you like, e.g. command-line arguments or STDIN/STDOUT. You may assume your program's input will always be valid.

  • Your program must be Turing complete. That means that for every computable function from balanced strings to balanced strings, there must be a program in your language that computes it. Your answer must include a proof of Turing completeness, otherwise it is not a valid answer.

This is . Your score will be the size of your interpreter's implementation, measured in bytes. The lowest score wins.

Here are some additional rules and clarifications:

  • Your interpreter must be a complete program

  • You must include a description of your language's semantics. This is needed in order to prove that it's Turing complete.

  • Your interpreter must correctly implement these semantics. (Or at least, it must be able to in principle, given infinite machine resources.) If someone finds a bug in your interpreter, your answer becomes invalid until it's fixed.

  • You may not assume numerical types are of unlimited precision unless they actually are - be careful of integer overflow!

Here is the precise grammar for programs as well as input and output strings:

<expr> ::= "(" <expr_list> ")"
<expr_list> ::= "" | <expr_list> <expr>.
<program> ::= <expr_list>

You can optionally replace the last line with

<program> ::= <expr>

which means there must always be an enclosing pair of parentheses. (So ()() and the empty string would not be valid programs, for example.) If you do this, you must do it for input and output strings, as well as programs.

As mentioned above, ( and ) may be replaced with any two distinct characters.

Sandbox notes

I've been obsessed with designing a simple and elegant language with these properties for some time, but I've never come up with one that really satisfied me. It occurred to me that "source code size of the interpreter" might work as a proxy for simplicity and elegance, so I thought I'd give this a try. Suggestions for a better winning criterion (making it a ) would be welcome.

I'd also welcome suggestions for a snappier title.

\$\endgroup\$
20
  • 1
    \$\begingroup\$ What prevents us from trivially decoding balanced parentheses to an existing programming language, evaluating, and then encoding the result back to balanced parentheses? Try it online! \$\endgroup\$
    – Adám
    Feb 19, 2018 at 17:56
  • \$\begingroup\$ Must all strings of balanced parentheses be valid inputs and programs, or can some of them result in errors? \$\endgroup\$
    – Zgarb
    Feb 19, 2018 at 20:31
  • \$\begingroup\$ i feel like requiring the program to have to be covered in parentheses to work sort of adds an unnecessary step. i would like it if that were removed, or if it was an option whether or not it counts as invalid to have ()() etc. \$\endgroup\$ Feb 19, 2018 at 22:15
  • \$\begingroup\$ @Adám unfortunately nothing really prevents this. I'd realised that a while after posting this. I'm not sure how to resolve that currently, so I probably won't post this challenge unless I figure out a good way. \$\endgroup\$
    – N. Virgo
    Feb 19, 2018 at 23:54
  • \$\begingroup\$ @Zgarb I intended it that every balanced string is a valid program. (But one could always just return the empty string if there's an error. This is another thing I don't like but don't have an easy way to fix.) \$\endgroup\$
    – N. Virgo
    Feb 19, 2018 at 23:55
  • \$\begingroup\$ what if you had to implement the language in two distinct languages or something? actually now that i think about it, a bunch of golf languages have python eval... \$\endgroup\$ Feb 20, 2018 at 2:00
  • \$\begingroup\$ @DestructibleLemon that's not a bad idea, but the languages would need to be sufficiently different in order for it to work. I wonder how we could specify that? \$\endgroup\$
    – N. Virgo
    Feb 20, 2018 at 4:27
  • \$\begingroup\$ it might be a better idea, in fact, to go to the esolangs room, design a language, then make the challenge be implementing that. perhaps as a bonus, you could have spec options (features or syntax or something which is optional or can be from different choices, with the stipulation that the chosen version of the language has to be as functional as the normal version of the languge) \$\endgroup\$ Feb 20, 2018 at 6:40
  • 1
    \$\begingroup\$ @DestructibleLemon I really want language design to be the focus of the challenge, though. (By the way I changed the grammar spec according to your suggestion.) \$\endgroup\$
    – N. Virgo
    Feb 20, 2018 at 7:35
  • \$\begingroup\$ "Your program must be Turing complete. That means that for every computable function from balanced strings to balanced strings, there must be a program in your language that computes it" Does it? Turing completeness implies the ability to compute any computable function, but the ability to compute a subset of computable functions does not in general imply Turing completeness. \$\endgroup\$ Feb 20, 2018 at 12:08
  • \$\begingroup\$ Moreover, Turing completeness doesn't say anything about representation. Minsky register machines are TM-complete, and their state could be put into bijection with balanced strings generated by the grammar <n> ::= "(" ")" | "(" <n> ")" <state> ::= <n> | <state> <n> giving a Turing-complete system which only computes computable functions from restricted balanced strings to restricted balanced strings. \$\endgroup\$ Feb 20, 2018 at 12:08
  • \$\begingroup\$ "Your interpreter must correctly implement these semantics. If someone finds a bug in your interpreter, your answer becomes invalid until it's fixed. Be careful of integer overflow!" is just asking the impossible. No physical implementation can have access to unbounded memory, so strictly speaking no physical implementation can be Turing complete. \$\endgroup\$ Feb 20, 2018 at 12:09
  • \$\begingroup\$ @PeterTaylor your second comment answers the question in your first comment. Do you think I should change anything or is it fine how it is? For your third comment I meant given infinite resources of course - I've amended the text. \$\endgroup\$
    – N. Virgo
    Feb 20, 2018 at 12:31
  • \$\begingroup\$ I think my second comment answers the question in my first comment in the negative, meaning that this question would incorrectly disqualify an implementation along the lines sketched in the second comment. BTW I'm pretty sure there are existing languages meeting some of these criteria, if not all, with single combinators. And if there aren't, it's a straightforward thing to do. \$\endgroup\$ Feb 20, 2018 at 12:40
  • 2
    \$\begingroup\$ I can't think of an objective measure for elegance, that's fairly subjective and considering the issue Adám pointed out, code-golf won't do very well. What's your reasons against making it a popcon? \$\endgroup\$ Feb 20, 2018 at 19:19
1
\$\begingroup\$

Find Graph Isomorphism

Meta:

I don't know whether there are any known algorithms for solving this problem, that also means I'm not sure whether this is an interesting challenge. EDIT: Ok it is probably equally hard as the graph isomorphism problem.

Inspired by this puzzle

Given two isomorphic directed (unweighted) graphs with labelled nodes, find an isomorphism between the two graphs.

Details

  • You have to provide a working implementation of your algorithm.
  • You have to provide the complexity expressed in the number of nodes, edges (or possibly other numbers?)
  • The graphs can be represented as an adjecency matrix, as set of pairs that represent edges, as an adjecency list or as a native graph type etc.
  • The output can be a function that maps the labels of one graph to the labels of the other, as a list as a graph etc.
  • If necessary, you can assume that there are no edges with the same start as end node.

Examples

to be added...

\$\endgroup\$
1
  • \$\begingroup\$ (What if it's unknown-complexity? Some heuristics can be quite fast in practice but formally reason about the complexity can be very hard) \$\endgroup\$
    – DELETE_ME
    Feb 22, 2018 at 2:31
1
\$\begingroup\$

Assemble an XOISC program

Tags: , ,


Recently I solved this challenge, for which I created XOISC - a very low-level functional language. To compile a program (written in the absurdly high-level lambda calculus programming language) it must first be translated into an expression consisting only of X combinators and from there it can be translated to the "machine language".

There's an initially empty stack and the program only consists of a stream of integers. For each integer the following happens:

Pop N elements f1,...,fN and push X (f1 (..(fN-1 fN)..)) - ie. it right-folds function application and applies this to another X.

Eventually we'll end up with a stack of functions which gets left-folded with function application. That's it.

How does it work?

When parsing such an expression, one thing to keep in mind is that function application is left-associative - meaning that X (X X) X is read as (X (X X)) X rather than X ((X X) X).

If we have an expression f g with sub-expressions f and g (in the code below App f g - eg. X (X X) X would be f = X (X X) and g = X), there's a simple recursive algorithm to assemble it:

-- Base case: We simply need to pop the accumulated functions 
asm' n X         = [n]
-- Recurse: First build the left function, then the right one. 
--          Incrementing n ensures that we leave (f g) on stack
asm' n (App f g) = asm' 0 f ++ asm' (n+1) g

-- Now we start with 0 functions on the stack:
asm expr = asm' 0 expr

For those unfamiliar with Haskell:

  • this algorithm assumes an already parsed expression in the form of of a binary tree (the definition of the data structure would be data Exp = X | App Exp Exp where X would be a leaf and App f g would be a node with children f and g that are Exps as well)*
  • asm' n exp does a case distinction by matching a pattern on exp:
    • if the expression is X (ie. exp = X) it's the base case and just returns a singleton list containing n (an integer)
    • else it's of the form f g (with f,g some sub-expressions) which is expressed as App f g, so it will recursively build the list for f and append the list of g
  • to assemble an expression exp we begin initialize the recursive algorithm with n = 0 (asm' 0 exp)

Note: Since a lot of people here know Python, you can find a horrible but very well documented Python reference implementation here which does the parsing as well as the assembling!


* The | means that an Exp type can be constructed of either the left constructor (X) or of the right one (App Exp Exp where the two Exp are Exp two sub-expressions).

For example the expression X (X X) X would be expressed as App (App X (App X X)) X.

Example

Having an expression X (X X) X, it helps to think of the implicit parentheses: (X (X X)) X

Translating this with the above algorithm:

  • Assemble (X (X X)):
    • Assemble X:
      • Base case => 0
    • Now Assemble X X, making sure it gets applied to the previous one (+1)
      • The first X gives us a 0
      • The second one gives us 0 + 1 + 1 = 2 (apply to X and previous one)
  • So the left (X (X X)) gave us [0,0,2], assembling the right X:
    • This gives us 0 + 1 (apply to the previous one)

And we end up with the program [0,0,2,1].

Note: While this algorithm ensures that there's a program for every expression, there can be other solutions too. For example [0,0,1,0] would be a valid one for X (X X) X as well.

Challenge

Given an expression consisting of X combinators, translate it to the XOISC machine language:

  • Input will be a string encoding such an expression
    • The input will be a valid expression and non-empty
    • You may choose to require an input string that contains no spaces
    • You may choose the characters encoding parentheses and the combinator itself (as long as it's consistent, eg. using [,],x instead of (,),X)
    • You're guaranteed that there are no unnecessary parentheses (eg. (X X) X would result in undefined behaviour)
  • Output can be a list of integers, a string separated by new-lines or whitespaces

Testcases

These testcases assume that the input contains whitespaces and choose X to encode the combinator.

Note that there may be multiple valid outputs, you're free to choose one* - I'll only show the solution resulting from the above algorithm:

X -> [0]
X X X -> [0,1,1]
X (X X) -> [0,0,2]
X (X X) X -> [0,0,2,1]
X (X (X (X X X))) -> [0,0,0,0,1,4]
X (X X) (X X) (X X) -> [0,0,2,0,2,0,2]
X (X X X (X X)) -> [0,0,1,1,0,3]
X (X (X X) (X X)) -> [0,0,0,2,0,3]
X X (X X (X (X (X (X (X X X)))) X) X) -> [0,1,0,1,0,0,0,0,0,1,5,2,2]
X (X (X X) X (X X X)) X (X (X (X X) X)) -> [0,0,0,2,1,0,1,3,1,0,0,0,2,3]
X (X (X (X (X X) X X) X X X) X X X X) X X X X X -> [0,0,0,0,0,2,1,2,1,1,2,1,1,1,2,1,1,1,1,1]
X (X (X X (X X) (X X) (X X) X) X (X X) X) X (X X X) X -> [0,0,0,1,0,2,0,2,0,2,2,1,0,2,2,1,0,1,2,1]

* Here's a program to validate alternative solutions

Sandbox

  • I already posted this to main, but apparently I did a bad job of explaining it.. It's hard to tell what's missing, I'd be happy for feedback (feel free to edit this)!
\$\endgroup\$
2
  • \$\begingroup\$ I think you need to move away from Haskel syntax and jargon. Just as one example: I have no idea what the point of "Having an expression X (X X) X, it helps to think of the implicit parentheses: (X (X X)) X" is. The whole explanation seems reliant on an understanding of concepts I personally don't usually think about. Also it's confusing having an example as code that is only thinking about the problem in one way and outputting only a single solution of many possible while trying to understand what the possibilities are. Since I can't understand it it is hard for me to help make it clearer :( \$\endgroup\$ Feb 23, 2018 at 22:12
  • \$\begingroup\$ @JonathanAllan: Thanks a lot for the feedback! It's not necessarily Haskell jargon, but I think I see what you mean. I'll rewrite this completely, it's probably the easiest way. \$\endgroup\$ Feb 23, 2018 at 22:22
1
\$\begingroup\$

Convert Arabic Numbers to Chinese Numbers

There EXISTS a similar question, "Convert Chinese numbers", but the question itself differs from that question by:

  1. That question asks for a shortest code converting Chinese numbers to Arabic numbers, but this asks for a shortest code converting in the opposite direction.
  2. That question limits the range of 1 <= N < 10^3, but this has the range far larger than that -- 1 <= N < 10^8192.
  3. Due to the range of that question, that question only considers one type of representation on Chinese numbers, but this considers four -- the commonly used Wan Jin (萬進) and other ancient systems. These terms will be explained in the introduction part.

There EXISTS another similar question "Convert a number to Korean", but there is essential difference because Korean number only uses Wan Jin, always omits "一(일)"s before "十(십)"s, "百(백)"s and "千(천)"s and all "零"s between digits, and so does Japanese.

Sandbox

  • I have edited the challenge description so that the rules are now outlining the process of conversion. Although this will be clearer in illustrating the rules, will this be restricting the choice of algorithms?

Introduction

Chinese numbers, literally, is the number still in use in societies which uses Chinese characters. Although Arabic numbers are also in use nowadays, Chinese numbers still have an important role.

The system Chinese people in Taiwan are using is called Wan Jin (萬進), which names 1,000,000,000,000 (1 trillion) as Yi Zhao (一兆). However, according to Wu Jing Suan Shu (五經算術) ,in the history there existed 3 different kinds of such large-number representations. The reference says:

按黃帝為法,數有十等。及其用也,乃有三焉。十等者,謂「億、兆、京、垓、秭、壤、溝、澗、正、載」也。三等者,謂「上、中、下」也。其下數者,十十變之。若言十萬曰億,十億曰兆,十兆曰京也。中數者,萬萬變之。若言萬萬曰億,萬萬億曰兆,萬萬兆曰京也。上數者,數窮則變。若言萬萬曰億,億億曰兆、兆兆曰京也。

(Translation) According to Huang Di, there are 10 "ranks" of numbers. Regarding the usages, there are three. The 10 ranks are called (億), Zhào (兆), Jīng (京), Gāi (垓), (秭), Ráng (穰), Gōu (溝), Jiàn (澗), Zhèng (正), Zài (載). The three usages are called "Upper", "Middle" and "Lower". For the "Lower", the rank changes if multiplied by 10. We call 10 Wàn as , 10 as Zhào, and 10 Zhào as Jīng. For the "Middle", the rank changes if multiplied by 100,000,000. We call 100,000,000 Wàn as , 100,000,000 as Zhào, and 100,000,000 Zhào as Jīng. And for the "Upper", the rank changes if the rank exhausts its numbers. We call 1 Wàn Wàn as , 1 as Zhào, and 1 Zhào Zhào as Jīng.

To sum up, we have 4 systems which is, or was in use in Chinese history:

  • Xia Shu (下數): Starting from wan (萬, 10,000), the rank changes by multipling by 10. 10 wan is called yi (億, 100,000), 10 yi is called zhao (兆, 1,000,000), 10 zhao is called jing (京, 10,000,000), etc.
  • Zhong Shu (中數): Starting from wan (萬, 10,000), the rank changes by multipling by 108, with the exception of yi, which represents 10^8. 10,000 wan is called yi (億, 10^8), 108 yi is called zhao (兆, 10^16), 108 zhao is called jing (京, 10^24), etc.
  • Shang Shu (上數): Starting from wan (萬, 10,000), the rank changes by squaring. 10,000 wan is called yi (億, 10^8), 108 yi is called zhao (兆, 10^16), 1016 zhao is called jing (京, 10^32), etc.
  • Wan Jin (萬進): Starting from wan (萬, 10,000), the rank changes by multipling by 10,000. 10,000 wan is called yi (億, 10^8), 10,000 yi is called zhao (兆, 10^12), 10,000 zhao is called jing (京, 10^16), etc.

Table 1: Rank markers in Chinese numbers

 Name    Wan Jin      Xia Shu      Zhong Shu   Shang Shu
(十               commonly representing 10^1            )
(百               commonly representing 10^2            )
(千               commonly representing 10^3            )
(萬               commonly representing 10^4            )
 億      10^8         10^5         10^8        10^8
 兆      10^12        10^6         10^16       10^16
 京      10^16        10^7         10^24       10^32
 垓      10^20        10^8         10^32       10^64
 秭      10^24        10^9         10^40       10^128
 穰      10^28        10^10        10^48       10^256
 溝      10^32        10^11        10^56       10^512
 澗      10^36        10^12        10^64       10^1024
 正      10^40        10^13        10^72       10^2048
 載      10^44        10^14        10^80       10^4096

For numbers smaller than 10, this works as

零:0 一:1 二:2 三:3 四:4 五:5 六:6 七:7 八:8 九:9

Challenge

In this challenge, you are required to write the shortest code, accepting two inputs: the number N, and a number S indicating the system used, converts N into the corresponding Chinese representation according to the given system, and output the representation. Here are some basic rules about converting Chinese numbers:

For numbers less than 10,000 and Xia Shu numbers:

  1. Append position markers digit by digit first.
    • 1234 => 一千二百三十四
    • 1234567 => 一兆二億三萬四千五百六十七
  2. Strip away all position markers prepended by "零", coalesce all consecutive "零"s into a single "零", and remove the leading/trailing "零"s.
    • 5 => 五, 25 => 二十五, 125 => 一百二十五
    • 20 => 二十, 100 => 一百, 5000 => 五千.
    • 1001 => 一千零一

For Wan Jin numbers:

  1. Divide the digits into subgroups of at most 4 digits each from the right.
    • 12345678900004321 => 1'2345'6789'0000'4321
  2. Apply to each subgroup the conversion for numbers less than 10,000 (as above), and append each subgroup with the corresponding rank markers. If there is any "0" at the subgroup boundary, append "零" after the rank marker.
    • 1'2345'6789'0000'4321 => (一)京(二千三百四十五)兆(六千七百八十九)億零(零)萬零(四千三百二十一)
  3. Discard the subgroups with "零", together with their rank markers, and remove redundant "零"s.
    • (一)京(二千三百四十五)兆(六千七百八十九)億零(零)萬零(四千三百二十一) => 一京二千三百四十五兆六千七百八十九億零四千三百二十一

For Zhong Shu numbers:

  1. Divide the digits into subgroups of at most 8 digits each from the right.
    • 12345678900004321 => 1"23456789"00004321
  2. Apply to each subgroup the conversion for Wan Jin numbers (as above), and append each subgroup with the corresponding rank markers. If there is any "0" at the subgroup boundary, append "零" after the rank marker.
    • 1"23456789"00004321 => (一)兆(二千三百四十五萬六千七百八十九)億零(四千三百二十一)
  3. Discard the subgroups with "零", together with their rank markers, and remove redundant "零"s.
    • (一)兆(二千三百四十五萬六千七百八十九)億零(四千三百二十一) => 一兆二千三百四十五萬六千七百八十九億零四千三百二十一

For Shang Shu numbers:

  1. Divide the digits into 2 subgroups: the least significant one with number of digits equals to the least power of 2 not less than half of the original length, and the most significant one with the remaining digits.
    • 123456789012345678901234567890 => (12345678901234)(5678901234567890)
  2. Append the most significant subgroup with the corresponding rank marker. If there is any "0" at the subgroup boundary, append "零" after the rank marker.
    • (12345678901234)(5678901234567890) => 12345678901234兆5678901234567890
  3. Discard the subgroups with "零", together with their rank markers
  4. Recursively apply all steps to each subgroup with a lower rank marker, until the number of digits in a subgroup is less than 4, which then apply the conversion for numbers less than 10,000 (as above).
    • 12345678901234兆5678901234567890 => 123456億78901234兆56789012億34567890 => 12萬3456億7890萬零1234兆5678萬9012億3456萬7890 => 十二萬三千四百五十六億七千八百九十萬零一千二百三十四兆五千六百七十八萬九千零一十二億三千四百五十六萬七千八百九十

And at last...

  1. If "一十" is at the beginning, remove the "一".
    • 15 => 十五
    • 114514 => 十一萬四千五百一十四, 10011 => 一萬零一十一.
  2. Remove redundant "零"s, and if an empty string occurs, return with "零".

For more details, the reference implementation in JSFiddle gives the reference code.

Requirements

  • Your code must be a full program or a function. Defining helper functions are allowed. Snippets are not allowed.
  • Standard loopholes are not allowed by default.
  • You can use any methods of I/O that are considered "standard" by PPCG community.
  • You must receive 2 inputs, one number N, and one number S. You can pass the inputs as strings or as integers. Please indicate your choice.
  • You may assume the input is always valid, i.e. S in [0, 1, 2, 3] and N is within the corresponding range:

Table 2: Number systems and their representable number range

S (System)       N (Number Range)
0 (Wan Jin)      1 <= N < 1E+48
1 (Xia Shu)      1 <= N < 1E+15
2 (Zhong Shu)    1 <= N < 1E+88
3 (Shang Shu)    1 <= N < 1E+8192
  • In case Unicode is not supported by the interpreter and/or the language, or for any reasons, you may use one of the two Chinese Pinyins in place of the corresponding Chinese characters as output as follows. Your choice must be consistent over all outputs. One space must be added between the pinyins of 2 characters. You must indicate if you choose to do so.

Table 3: The Chinese characters and their pinyin representations

Character  Pinyin              Character  Pinyin
一         yī or yi1           二         èr or er4
三         sān or san3         四         sì or si4
五         wǔ or wu3           六         liù or liu4
七         qī or qi1           八         bā or ba1
九         jiǔ or jiu3         十         shí or shi2
百         bǎi or bai3         千         qiān or qian1
萬         wàn or wan4         億         yì or yi4
兆         zhào or zhao4       京         jīng or jing1
垓         gāi or gai1         秭         zǐ or zi3
穰         ráng or rang2       溝         gōu or gou1
澗         jiàn or jian4       正         zhèng or zheng4
載         zài or zai4         零         líng or ling2

Example I/O (Only the first Pinyin format is displayed)

In these examples, I use ' => 萬, " => 億, (...) => 兆, [...] => 京, {...} => 垓, <...> => 秭 in the grouping for clarity. The grouping is only for illustration, and you do not need to print the groupings.

Input:    18446744073709551616 0
Grouping: [1844](6744)0737"0955'1616
Output:   一千八百四十四京六千七百四十四兆零七百三十七億零九百五十五萬一千六百一十六
    or    yī qiān bā bǎi sì shí sì jīng liù qiān qī bǎi sì shí sì zhào líng qī bǎi sān shí qī yì líng jiǔ bǎi wǔ shí wǔ wàn yī qiān liù bǎi yī shí liù

Input:    1234567890 1
Grouping: <1>{2}[3](4)5"6'7890
Output:   一秭二垓三京四兆五億六萬七千八百九十
    or    yī zǐ èr gāi sān jīng sì zhào wǔ yì liù wàn qī qiān bā bǎi jiǔ shí

Input:    1267650600228229401496703205376 2
Grouping: [126'7650](6002'2822)9401'4967"0320'5376
Output:   一百二十六萬七千六百五十京零六千零二萬二千八百二十二兆九千四百零一萬四千九百六十七億零三百二十萬零五千三百七十六
    or    yī bǎi èr shí liù wàn qī qiān liù bǎi wǔ shí jīng líng liù qiān líng èr  wàn èr qiān bā bǎi èr shí èr zhào jiǔ qiān sì bǎi líng yī wàn sì qiān jiǔ bǎi liù shí qī yì líng sān bǎi èr shí wàn líng wǔ qiān sān bǎi qī shí liù

Input:    8749002899132047697490008908470485461412677723572849745703082425639811996797503692894052708092215296 3
Grouping: {[8749](0028'9913"2047'6974)9000'8908"4704'8546}[(1412'6777"2357'2849)7457'0308"2425'6398](1199'6797"5036'9289)4052'7080"9221'5296
Output  : 八千七百四十九京零二十八萬九千九百一十三億二千零四十七萬六千九百七十四兆九千萬零八千九百零八億四千七百零四萬八千五百四十六垓一千四百一十二萬六千七百七十七億二千三百五十七萬二千八百四十九兆七千四百五十七萬零三百零八億二千四百二十五萬六千三百九十八京一千一百九十九萬六千七百九十七億五千零三十六萬九千二百八十九兆四千零五十二萬七千零八十億零九千二百二十一萬五千二百九十六
    or    bā qiān qī bǎi sì shí jiǔ jīng líng èr shí bā wàn jiǔ qiān jiǔ bǎi yī shí sān yì èr qiān líng sì shí qī wàn liù qiān jiǔ bǎi qī shí sì zhào jiǔ qiān wàn líng bā qiān jiǔ bǎi líng bā yì sì qiān qī bǎi líng sì wàn bā qiān wǔ bǎi sì shí liù gāi yī qiān sì bǎi yī shí èr wàn liù qiān qī bǎi qī shí qī yì èr qiān sān bǎi wǔ shí qī wàn èr qiān bā bǎi sì shí jiǔ zhào qī qiān sì bǎi wǔ shí qī wàn líng sān bǎi líng bā yì èr qiān sì bǎi èr shí wǔ wàn liù qiān sān bǎi jiǔ shí bā jīng yī qiān yī bǎi jiǔ shí jiǔ wàn liù qiān qī bǎi jiǔ shí qī yì wǔ qiān líng sān shí liù wàn jiǔ qiān èr bǎi bā shí jiǔ zhào sì qiān líng wǔ shí èr wàn qī qiān líng bā shí yì líng jiǔ qiān èr bǎi èr shí yī wàn wǔ qiān èr bǎi jiǔ shí liù

Here is a reference implementation in JS, not golfed at all

Winning Criteria

As this is a , so shortest code measuring in bytes wins. Accented Latin alphabets and Chinese characters must be measured in UTF-8 unless they are included in the SBCS of the language and can be used in the string literals.

Reference

Wikipedia - 中文數字

\$\endgroup\$
8
  • \$\begingroup\$ I think you should also add an explanation for numbers less than 10,000. What's even 1, 2, 3, ...? \$\endgroup\$
    – wastl
    Feb 25, 2018 at 19:25
  • \$\begingroup\$ @wastl Added back details about 0~9. For numbers less than 10,000, Xia Shu algorithm applies \$\endgroup\$ Feb 26, 2018 at 3:06
  • \$\begingroup\$ no example for coalesce all consecutive "零"s into a single "零", e.g. 4002 \$\endgroup\$
    – tsh
    Feb 26, 2018 at 3:56
  • \$\begingroup\$ what is the result of WanJin(10010)? 一萬零一十? 一萬零十? \$\endgroup\$
    – tsh
    Feb 26, 2018 at 3:59
  • \$\begingroup\$ @tsh Added. and WanJin(10010) should be 一萬零一十 because the 一十 is not at the beginning. (一萬零十 should be something in like dialect?) There is an example of WanJin(10011) though \$\endgroup\$ Feb 26, 2018 at 4:00
  • \$\begingroup\$ @user71546 The example is for XiaShu(10011), not WanJin(10011). \$\endgroup\$
    – tsh
    Feb 26, 2018 at 4:02
  • \$\begingroup\$ Oh I should indicate that the replacement is only at the final step. \$\endgroup\$ Feb 26, 2018 at 4:06
  • \$\begingroup\$ @tsh Grouped the removal of redundant "零"s and removal of leading "一" before "十" at the very end. \$\endgroup\$ Feb 26, 2018 at 4:10
1
\$\begingroup\$

Build a cardinal cyclic quine

A cardinal cyclic quine is a cyclic quine with four states, one for each orientation of the cardinal directions.

See also Build a half cardinal cyclic quine and Take a stand against long quine lines.

Rules

You can decide which rotation you want to implement, clockwise or counter-clockwise.

Once rotated, any gaps in your code should be replaced with spaces to preserve the positioning.

Each program must be unique, you cannot use a quine that has the same layout regardless of orientation.

Your program must satisfy the community definition of a quine.

This is so the shortest program in each language wins. Your first program is used for your byte count.

Standard loopholes are forbidden.

Examples

If your program is:

$_=q{print};eval

Then the next iterations must be either:

$
_
=
'
p
r
i
n
t
'
;
e
v
a
l

lave;}tnirp{q=_$

l
a
v
e
;
'
t
n
i
r
p
'
=
_
$

or

l
a
v
e
;
'
t
n
i
r
p
'
=
_
$

lave;}tnirp{q=_$

$
_
=
'
p
r
i
n
t
'
;
e
v
a
l

Or if your program is:

;$_=';
;$_=';
print

Then the next iterations must be either:

;;
''t
==n
__i
$$r
;;p

;'=_$;
;'=_$;
 tnirp

p;;
r$$
i__
n==
t''
 ;;

or:

p;;
r$$
i__
n==
t''
 ;;

;'=_$;
;'=_$;
 tnirp

;;
''t
==n
__i
$$r
;;p

\$\endgroup\$
6
  • \$\begingroup\$ Hope that the source is not a one-line palindrome (specifically, not a palindrome constructed by padding the source with comments) \$\endgroup\$ Feb 28, 2018 at 21:38
  • \$\begingroup\$ ^ Yeah you might want to prevent this by requiring all four programs to be different. \$\endgroup\$ Feb 28, 2018 at 21:40
  • \$\begingroup\$ @MartinEnder I guess my comments here apply to the open question too, but a palindrome with comments probably wouldn't be an optimal solution, so I'm not sure about banning that. I feel that might exclude many languages in which this challenge wouldn't otherwise be possible. Do you think banning them is for the best for the challenge? Can you forsee low-effort answers without banning them? \$\endgroup\$ Mar 1, 2018 at 8:51
  • \$\begingroup\$ @WeijunZhou ^^ :) \$\endgroup\$ Mar 1, 2018 at 8:51
  • \$\begingroup\$ Those cases may be just as well submitted to your existing challenge of half cardinal cyclic quine, and copying answers from your existing challenge to this one is no fun. \$\endgroup\$ Mar 1, 2018 at 9:03
  • \$\begingroup\$ @WeijunZhou Of course. Ok, since that stipulation wasn't added to the original, I'll ensure that's added to this one. Thanks for taking the time to check this out! \$\endgroup\$ Mar 1, 2018 at 9:23
1
\$\begingroup\$

Safely check a password against HIBP v2 range API

Per https://www.troyhunt.com/ive-just-launched-pwned-passwords-version-2/, what would be the shortest code to safely check a password against the Have I Been Pwned? k-anonymity (range) API, as mentioned in the article?

API overview

Specifically, the API is at:

https://api.pwnedpasswords.com/range/$FIRST_5_CHARS_OF_SHA1

and returns a list of SHA1 hashes beginning with the specified 5 chars (more precisely: it returns only the substrings of hashes after $FIRST_5_CHARS_OF_SHA1).

For example, given a password P@ssw0rd, its SHA1 hash is:

21BD12DC183F740EE76F27B78EB39C8AD972A757
\---/\---------------------------------/
  |                     |
  `-- first 5 chars     `-- rest of chars

and thus for a request like one of below:

https://api.pwnedpasswords.com/range/21BD1
https://api.pwnedpasswords.com/range/21bd1

the API gives a response like below (... represents more lines):

...
29B59205F57C2608CAE47E8157621FF7645:1
2B766777053A89201D8257221BBC161E279:2
2D10A6654B6D75908AE572559542245CBFA:2
2D6980B9098804E7A83DC5831BFBAF3927F:1
2D8D1B3FAACCA6A3C6A91617B2FA32E2F57:1
2DC183F740EE76F27B78EB39C8AD972A757:47205
2DE4C0087846D223DBBCCF071614590F300:2
2DEA2B1D02714099E4B7A874B4364D518F6:1
2E90B7B3C5C1181D16C48E273D9AC7F3C16:1
2EAE5EA981BFAF29A8869A40BDDADF3879B:1
2F1AC09E3846595E436BBDDDD2189358AF9:1
...

Existence of 2DC183F740EE76F27B78EB39C8AD972A757 in the response means that P@ssw0rd was found in some breach and should be considered unsafe. Number 47205 signifies how many times such a password occurs in all the contributing breaches.

Rules details

  • The password must be read from user's keyboard. Per the next rule, it should not be displayed on screen, thus if read from standard input, usually the "character echo" would need to be disabled (e.g. read -s in bash). If implemented as a GUI app, e.g. a standard "password input" widget may be used, which would replace typed characters with asterisks or black dots.
  • "Safely" means that the solution should not leak raw password to other users of a machine (e.g. the raw password should never appear as part of command line of any subcommand, and should never appear on screen) or outside the machine (websites, etc.). The full hash should not be shared outside the machine either.
    • Specifically, it must be clear (for an experienced user of the language) from the code comprising the solution that the raw password (and the SHA) do not leak (as mentioned above). So, for example, the solution's code cannot be downloaded from a remote repository (not sure if it's already included in default forbidden loopholes list).
  • The SHA sum of the checked password should be printed on screen, to make it possible to verify correctness of the solution, e.g. by checking SHA sum for P@ssw0rd. Other hashes can be printed too or not, but the one matching the checked password must be easy to see (i.e. always first/last/highlighted/...)
  • The solution should also display the number of occurrences of the password "in the wild" as returned by the API (i.e. 47205 for P@ssw0rd).
  • The solution should print at least a 1 character of prompt before reading the answer, so that user knows console is safely in "no echo" mode.

Extra tag

To keep with the site's sport spirit, I'm putting no formal restrictions on language. However, personally I'm particularly interested in and curious about "real-world usable" answers. As such, if your answer has the following "extra" attributes:

  • can be typed in bash as a one-liner (with appropriate preamble like perl -ne if needed)
  • is composed only of printable ASCII characters (no Unicode)

please append an extra marker/tag like below in the "title" line of your answer:

[bash oneliner: 30 +7]

where 30 is the length of the actual code in your preferred language, and +7 is the length of the required preamble/postamble. For pure bash answers, this can be +0. Please then also include the actual oneliner, together with the preamble/postamble.

As an explanation, the benefits of a one-liner I'm interested in for "real world users", are such that a one-liner is easy to re-type and execute in console for paranoid users, who would prefer to do it instead of Ctrl-C & Ctrl-V.


Sample naive answer in bash

Split to multiline with \s purely for readability:

$ (sha=$(IFS= read -s -p "pwned? " pw; tr -d '\n' <<<$pw | shasum ); \
  curl -s https://api.pwnedpasswords.com/range/${sha:0:5} | \
  (grep -i ${sha:5} || echo "${sha:5}:0") | \
  sed "s/^/${sha:0:5}/")
pwned? 21bd12DC183F740EE76F27B78EB39C8AD972A757:47205

One-liner:

$ (sha=$(IFS= read -s -p "pwned? " pw; tr -d '\n' <<<$pw | shasum ); curl -s https://api.pwnedpasswords.com/range/${sha:0:5} | (grep -i ${sha:5} || echo "${sha:5}:0") | sed "s/^/${sha:0:5}/")
pwned? 21bd12DC183F740EE76F27B78EB39C8AD972A757:47205
\$\endgroup\$
11
  • 2
    \$\begingroup\$ By the way -- Welcome to PPCG, and thanks for using the sandbox and understanding the site guidelines! \$\endgroup\$
    – DELETE_ME
    Mar 1, 2018 at 13:38
  • \$\begingroup\$ (to be self-contained, you should also briefly explain what the API does) \$\endgroup\$
    – DELETE_ME
    Mar 1, 2018 at 13:59
  • \$\begingroup\$ @user202729 Sure, you can; but this loses the usability benefits of it being a one-liner, such as easy re-typing and easy immediate execution. Arguably removing the request (and restriction) for "one-liner" is similar in spirit to removing request for "as few characters as possible"/"code-golf". I.e. why even bother with any request... \$\endgroup\$
    – akavel
    Mar 1, 2018 at 15:06
  • \$\begingroup\$ Then how do you define one-liner? Doesn't have any 0x0A char? Doesn't have any 0x0D char? Doesn't have any char in that code-page that is used for line feed? What if a programming language uses a code page without any line-feed character? What if a language uses a code page where the newline can be replaced by other character? \$\endgroup\$
    – DELETE_ME
    Mar 1, 2018 at 15:37
  • 1
    \$\begingroup\$ I tried to modify the question to mention "bash one-liner" only as an "extra", non-required attribute, but asking for it to be clearly labeled. I also removed most of my previous comments to de-noise the conversation. \$\endgroup\$
    – akavel
    Mar 1, 2018 at 16:02
  • 3
    \$\begingroup\$ Why restrict the input to stdin or tty? Any special reasons here that do not accept a GUI version answer? \$\endgroup\$
    – tsh
    Mar 2, 2018 at 5:33
  • \$\begingroup\$ @tsh Good question and good idea. My intention was to focus on requiring "no echo", but now I look at it I see I didn't convey that well. I'll try to edit this, though I feel it may be tricky. And also add your idea about GUI, absolutely an oversight on my side. Hm, if you'd have some ideas how to better express this, I'm absolutely interested! \$\endgroup\$
    – akavel
    Mar 2, 2018 at 17:31
  • \$\begingroup\$ @tsh Uh, and I forgot to say the most important thing: Thanks! :) \$\endgroup\$
    – akavel
    Mar 2, 2018 at 17:40
  • \$\begingroup\$ ... would reading from a file that other users don't have access considered safe? \$\endgroup\$
    – DELETE_ME
    Mar 8, 2018 at 3:39
  • \$\begingroup\$ @user202729 "The password should be read from user's keyboard" is important for me, so reading from a file is not allowed. Should I change the "should" to "must" to make it clear? \$\endgroup\$
    – akavel
    Mar 8, 2018 at 9:45
  • \$\begingroup\$ Looks good. As it's observable whether the SHA/raw password leak (just check what the computer sent to the internet and see if the password is there), the "specifically..." part doesn't seem necessary. \$\endgroup\$
    – DELETE_ME
    Mar 8, 2018 at 11:21
1
\$\begingroup\$

Image to HTML ASCII-Art


Given an input image n, output each pixel as a 0 using HTML for coloring and <br/> as a delimiter for the rows.


Example:

Input Image:

Input Image 1

Example HTML Output: https://pastebin.com/jDHZwb4P

Rendered Output:

Output rendered as HTML...


Rules:

  • You may color the 0's using any HTML trick you know of (CSS Style, JavaScript, etc)...
  • You may use any character other than 0 that shows visible color if you so wish.
  • Colors must be exact down to the RGB of the pixel, alpha can be assumed non-existent.
  • If you get a malformed image, or an image with transparency, you may error.
  • This is , lowest byte-count wins.
\$\endgroup\$
7
  • \$\begingroup\$ I think you should specify the image format and IO much more. For example PPM would be much easier compared to PNG (example image) or other image formats. Does the full [insert format here]-specification need to be supported? What kind of input (eg. string/bytestring, filename, url,...)? What about the output, does it need to be valid HTML or does successfully rendering with ABC-browser (version XYZ) count? \$\endgroup\$ Mar 13, 2018 at 23:43
  • \$\begingroup\$ @bmo good ideas on all fronts. Im on mobile but Ill make updates. I was expecting a this is a dupe comment though tbh. \$\endgroup\$ Mar 13, 2018 at 23:59
  • \$\begingroup\$ Wanted to leave it open as much as possible. Just anything that can be rendered by a browser as colored text from an image, but Isee no reason to disallow personal browser specifications. Like i could see some dumb IE5 trick to render text being neat as long as they explain it. \$\endgroup\$ Mar 14, 2018 at 0:17
  • \$\begingroup\$ Can we use a space instead of 0? \$\endgroup\$
    – DELETE_ME
    Mar 14, 2018 at 8:34
  • \$\begingroup\$ @user202729 Of course! Wait... no, good point. \$\endgroup\$ Mar 14, 2018 at 12:44
  • \$\begingroup\$ Why should we assume alpha is nonexistent when the opacity property exists? \$\endgroup\$
    – RamenChef
    Mar 15, 2018 at 11:55
  • \$\begingroup\$ @RamenChef For simplicity sake. \$\endgroup\$ Mar 15, 2018 at 12:09
1
\$\begingroup\$

Find most isolated point

Given a finite set S of points in d dimensions, find the most isolated points, that is the point with the greatest distance to its closest neighbours.

Or more mathematically, the point p ∈ S that maximizes min {d(p,q) | q ∈ S, q ≠ p}.

Details

  • You can return the coordinates of the actual point, or you can alternatively return the index of the point in the input list.
  • The most isolated point as defined above is not necessarily unique. But you can assume that the given input results in an unique such point.

Examples

1D:

  • [0,1] (invalid, no unique result)
  • [0,1,3] -> 3,

2D:

  • [(0,0),(0,1),(1,2)] -> [(1,2)]

more to be added...

This challenge was inspired by this question. If you find a particularly time-efficient solution please post it there!

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

Implement RaGOL

RaGOL (Random Game of Life) is a randomized cellular automaton based on GOL (Game of Life). For reference, here are the rules of GOL (B3/S23):

  • Moore neighborhoods are used, that is, a cell # looks at its neighbors * as in here:

    .......
    .......
    ..***..
    ..*#*..
    ..***..
    .......
    .......

  • A cell can have 2 states: dead or alive

  • If a dead cell has 3 alive neighbors, it becomes alive.
  • If an alive cell does not have exactly 2 or 3 alive neighbors, it becomes dead.

In this challenge, we will assume the board is unbounded, and the default state of a cell is dead.

However, since we have already implemented GOL, it's time to change the rules a bit. Here are the differences between GOL and RaGOL:

  • If a dead cell has 3 alive neighbors, there is 1/3 of a chance it becomes alive.
  • If an alive cell has 2 alive neighbors, there is 1/5 of a chance it becomes dead.
  • If an alive cell has 3 alive neighbors, there are 2/5 of a chance it becomes dead.

Note that if an alive cell doesn't have exactly 2 or 3 alive neighbors, it still becomes dead just like in GOL.

Challenge

Your challenge is to get an x×y RaGOL board B where x > 0 and y > 0 and a number N > 0 and return the board after N generations starting from B.

Please note that the result isn't deterministic.

You will also need to expand the board to simulate an unbounded-board automaton in some cases.

Rules

  • You can get B and N in any reasonable way.
  • Errors due to floating-point imprecision do not matter, be it a slight difference due to how floats work or a precision limit of the float datatype you use. Otherwise, you must adhere to the aforementioned probabilities.
  • You may expand the board as much as you like, as long as 1) the result will be theoretically returned at some point in time and 2) the whole expected result is shown.
    • Note: If your language has a board datatype which natively supports unbounded boards, you can use that instead of manually expanding the resulting board, as long as the correct result is returned sometime. You may also use third-party modules which provide such a datatype, or even implement your own, just as long as there is an implementation available online!
\$\endgroup\$
7
  • \$\begingroup\$ I expect Stencil to win on this one. \$\endgroup\$
    – Adám
    Jan 29, 2018 at 17:30
  • \$\begingroup\$ @Adám Sure, that could very well be the case, but what is the problem exactly? Of course some types of challenges are better answered by languages made especially for them, however should we stop posting challenges altogether? ;) \$\endgroup\$ Jan 29, 2018 at 17:35
  • \$\begingroup\$ It wasn't intended as a criticism. \$\endgroup\$
    – Adám
    Jan 29, 2018 at 17:42
  • \$\begingroup\$ Have you tried making a reference implementation? The rules tend to cause extinction. I think changing the chances to 2/3, 3/5, 4/5 works better. \$\endgroup\$
    – Adám
    Jan 29, 2018 at 17:47
  • \$\begingroup\$ @Adám I may change the ratios, yeah. I haven't yet gotten around to making a reference implementation. \$\endgroup\$ Jan 29, 2018 at 17:48
  • \$\begingroup\$ Here you go. N is in the Command-line option. The ratio settings should be obvious. \$\endgroup\$
    – Adám
    Jan 29, 2018 at 18:03
  • \$\begingroup\$ @Adám Uh, I was planning to make it myself, but thanks! EDIT: Hm, looks like the implementation is a little bit wrong...maybe this fixes it? \$\endgroup\$ Jan 29, 2018 at 18:50
1
\$\begingroup\$

Square Number Chains

Background

Given a positive integer n >= 25, it is conjectured that there exists a permutation of the positive integers which are less than or equal to n in which every adjacent pair of numbers adds up to a square number. There are also several numbers less than 25 that this is also true for - 15, 16, 17, and 23.

The Challenge

Write a program or function which accepts a positive integer, n, and returns all positive integers less than or equal to n, ordered such that each adjacent pair adds up to a square number. If there are multiple valid orderings, only one needs to be returned, but your program must be deterministic - that is, for a particular input, your answer should return the same output every time.

You can assume that the input will always have at least one solution, so you don't have to deal with inputs 1-14, 18-22, or 24. If you prefer, you can require that input to your submission will always be greater than 24 - if so, please specify in your submission.

Output may be in the form of a list, or written to STDOUT, so long as there is a consistent and identifiable seperator between them - for example, a space, newline, comma, tab, etc are all fine.

You can validate your program's output by using this TIO link. It supports input as a string with any consistent separator, and will tell you what criteria (if any) your list is failing on.

Inspiration

The Square-Sum Problem - Numberphile

Test cases

Input    Example output
15       9,7,2,14,11,5,4,12,13,3,6,10,15,1,8
23       18,7,9,16,20,5,11,14,2,23,13,12,4,21,15,10,6,19,17,8,1,3,22

Winning Criteria

This is , so the shortest answer in bytes will be the winner! Good luck and happy golfing!


TODO

-More test cases

Feedback requested:

The Python program I've thrown together to provide solution verification is probably a bit shonky, I'm not that strong a Python programmer. If anyone has any comment/criticisms feel free to let me know, or improve it yourself!

As has been pointed out that this challenge is similar to a few others which ask for a Hamiltonian cycle. In my opinion this is suitably different, as this is looking for a Hamiltonian path, and the input is far simpler than the other challenges. What do people think?

\$\endgroup\$
5
  • \$\begingroup\$ Numberphile's conjecture :P \$\endgroup\$
    – Mr. Xcoder
    Jan 11, 2018 at 17:17
  • \$\begingroup\$ What's the winning criterion? Since the conjecture talks about integers >= 25, you should add testcases for those and probably restrict input to that range as well. \$\endgroup\$ Jan 15, 2018 at 22:02
  • \$\begingroup\$ @BMO Oops, you're right, I'd forgotten to mention that this is intended to be code golf, good spot. I've mentioned in the 2nd paragraph of The Challenge that you can expect the input to result in at least one solution, does that cover your concern about restricting the input range? \$\endgroup\$
    – Sok
    Jan 16, 2018 at 8:58
  • 2
    \$\begingroup\$ Dupewatch: this is Hamiltonian path, which is rather similar to Hamiltonian cycle, which has been done at least three times: codegolf.stackexchange.com/q/11310/194 , codegolf.stackexchange.com/q/31898/194 , codegolf.stackexchange.com/q/67611/194 \$\endgroup\$ Jan 16, 2018 at 13:01
  • \$\begingroup\$ @Sok: Yeah I read that I just thought that it'll make the challenge more consistent. \$\endgroup\$ Jan 16, 2018 at 23:50
1
\$\begingroup\$

The Challenge

The goal is to write a complete program that prints out every possible tetris block made up of #.

The blocks must have an equal chance of printing in any order and must appear exactly once each. The blocks may have any rotation, rotation may be consistent between executions. No two blocks can be touching. All blocks must have settled on the "floor".

ValidExample.exe
                    #   #
## ###      ##   ## #   #
##  #  ####  ## ##  ## ##

TouchingExample.exe
      #
      #  # ##
## ####  #  # ##   ## 
##  # # ##  #  ## ##   

FloatingExample.exe
       #   #             
## ### ## ## #     # ####
##  #   # #  ### ###     

Use the language of your choice, lowest number of bytes wins

Questions

  • Is the wording clear enough?
  • Does the challenge meet the expectations for a challenge here?
  • What can I do to remove any ambiguity if there is any?
  • Is the formatting for the question / examples ok?
  • Would the challenge be "better" if the blocks had to be made up of their corresponding letter (IOJLZST)
\$\endgroup\$
4
  • \$\begingroup\$ This could be a dupe of codegolf.stackexchange.com/questions/2223/polyomino-generator \$\endgroup\$
    – Sok
    Mar 21, 2018 at 9:22
  • \$\begingroup\$ @someone is the new wording better? Replaced random order with a requirement that each order have equal odds. \$\endgroup\$
    – Southpaw
    Mar 21, 2018 at 10:02
  • 1
    \$\begingroup\$ I think it is. I don't think the blocks-made-of-letters is a good idea. \$\endgroup\$ Mar 21, 2018 at 10:04
  • \$\begingroup\$ @Sok No input, random order, only tetrominos, no floating restriction. Those seem to be the main differences. Are they enough to distinguish it? \$\endgroup\$
    – Southpaw
    Mar 21, 2018 at 10:05
1
\$\begingroup\$

Hyperprogramming: X×Y, X^Y, X^^Y all in two

, just like the original.

Heavily inspired by Hyperprogramming: N+N, N×N, N^N all in one.

Your task is to write two programs so that they compute different hyperoperations when they are placed in relation to each other in the form of the mathematical notation for that hyperoperation.

Full rules:

Write two rectangular programs of the same size — call them "program A" and "program B" — that each take a single positive integer as input and output that integer. In this case, "rectangular" means that every line is the same length, and that there is no trailing newline. Thus, your two programs will each be composed of M lines of N bytes each.

The catch is that when the two programs are placed next to each other in various positions, they will act as a single program that takes two positive integers, X and Y, as input and outputs either X×Y, X^Y, or X^^Y (tetration), depending on the position. Moreover, when the locations of the two programs are reversed, the resulting program will print Y×X, Y^X, or Y^^X — e.g., with X and Y reversed.

The precise location of the two programs with respect to each other is determined by the notation for that particular operation. For instance, if your program A reads

*this* is
program A

and your program B reads

*this* is
program B

your program to output X×Y must contain both program's source codes placed horizontally adjacent without any filler inserted, like so:

*this* is*this* is
program Aprogram B

Because multiplication is commutative, both [AB] and [BA] must function identically.

Your programs to output X^Y and Y^X must contain the code of programs A and B in the locations [ᴀᴮ] and [ʙᴬ], with spaces padding the "exponent" program to the correct horizontal position and optional trailing spaces after each line of the "base" program to pad the layout into a rectangle — no partial padding allowed, it's all or nothing. Padding must be consistent for both X^Y and Y^X (as well as X^^Y and Y^^X later). Illustrated without trailing spaces:

         *this* is
         program B
*this* is
program A

and

         *this* is
         program A
*this* is
program B

Finally, your programs to output X^^Y and Y^^X must contain the code of programs A and B in the locations [ᴮᴀ] and [ᴬʙ], with spaces padding the "base" program, and trailing spaces after each line of the "superexponent" program to pad the layout into a rectangle if and only if your X^Y and Y^X programs included trailing spaces as padding. Illustrated without trailing spaces:

*this* is
program B
         *this* is
         program A

and

*this* is
program A
         *this* is
         program B

You do not have to support arbitrarily large integers, but your answer should work for a reasonable range of X and Y — that is, it should probably at the very least support all combinations of X and Y up to 3 except maybe 3^^3 = 7625597484987.

Source code reading is allowed, as it would be very difficult to otherwise distinguish X^Y and X^^Y in many languages.

As this is , fewest bytes wins.

Note: your score is the total byte count of a single one of your original two programs, not any of the hyperoperation-computing ones — for example, if your programs A and B are each 5×5, your score will be 5×5 + 4 newlines = 29. Since both programs A and B will have identical byte counts, it doesn't matter which one you pick.

Is there anything unclear about this? If so, how could I fix it?

\$\endgroup\$
1
  • \$\begingroup\$ You may want how exacly do you define "newline". See this. \$\endgroup\$
    – DELETE_ME
    Apr 2, 2018 at 15:20
1
\$\begingroup\$

Sandbox Notes

  • Which tags should go?
  • Is this uncomputable?
  • Should I add more test cases?

Solve logical statements about arithmetic

Ok, some of these need to go.

Your task is to determine the truth or falsehood of boolean statements about integer expressions.

Integer Expressions:

  • 1 is an integer expression.
  • If a is an integer expression, then (-a) is an integer expression representing its negative.
  • If a and b are integer expressions, then (a+b) and (a*b) are integer expressions representing their sum and product, respectively.
  • A string of lowercase Latin letters is an integer expression if it is in scope. A value in scope in an integer or boolean expression is always in scope in all of its subexpressions.

Boolean Expressions:

  • If a and b are integer expressions, then (a>b) is a boolean expression representing whether a is greater than b.
  • If a and b are boolean expressions, then (a&b) is a boolean expression representing whether they are both true.
  • If a is a boolean expression, then (!a) is a boolean expression testing whether a is false.
  • If v is some string of lowercase letters, and e would be a boolean expression if v was in scope, then (v^e) is a boolean expression that represents whether e is true for any integer value of v.

Task

You will be given a boolean expression in any reasonable format (such as a string or a parse tree). You should output one of two distinct outputs depending on whether this boolean expression can be shown to be true or false.

Test Cases

(x^(!(y^(x>y)))) => True

Read: for all x, it is not the case that any y is less than x.
In other words, there is no number greater than all other numbers.

(!(x^(!(y^((y*y)>x))))) => True

Read: there is a number x which is less than the square of any y.
In other words: there is a number smaller than all squares (any negative number).

(x^(x>5)) => False

Read: all numbers are greater than 5.

(!(x^(!(x>x)))) => False

Read: it is not the case that all numbers are not greater than themselves.
In other words: there is a number greater than itself.

(y^(x^(!((!(y>(2*x)))&(!((2*x)>y)))))) => False

Read: for every two integers x and y, y is neither greater than nor less than 2x.
In other words: there is no number divisible by 2.

(x^((x*x)>x)) => False

Read: all numbers are less than their squares.

(x^(!(x>(x*x)))) => True

Read: there is no integer greater than its square.

\$\endgroup\$
18
  • \$\begingroup\$ why not have - as the inverter for integers? \$\endgroup\$ Apr 3, 2018 at 3:46
  • \$\begingroup\$ @DestructibleLemon That was originally because I planned to add subtraction, but then decided to keep it minimal. I'm going to change that. Thanks for catching it! \$\endgroup\$ Apr 3, 2018 at 3:51
  • \$\begingroup\$ What about !y^(x^!(x>y&x^(a^(b^(x<a*b+1&x>a*b+-1))))&(a^(b^(x+2<a*b+1&x+2>a*b+-1))))))? (Hopefully I got that right.) Read as "for all y there exists x greater than y, such that x is prime and x+2 is prime." \$\endgroup\$
    – N. Virgo
    Apr 3, 2018 at 4:23
  • 1
    \$\begingroup\$ In short, yes, it is uncomputable I'm afraid. There's a lot of potential for interesting challenges based on this idea though! One way would be to specify a set of axioms and have it determine whether the statement is provable from those axioms, allowing the possibility that it fails to halt if it isn't. That might be quite complicated for a code-golf challenge though. \$\endgroup\$
    – N. Virgo
    Apr 3, 2018 at 4:23
  • \$\begingroup\$ @Nathaniel I somehow failed to realize that you can do prime checking facepalm \$\endgroup\$ Apr 3, 2018 at 4:30
  • \$\begingroup\$ @Nathaniel Do you think it's uncomputable if you remove logical negation? \$\endgroup\$ Apr 3, 2018 at 4:31
  • \$\begingroup\$ Do you mean logical negation (!) or integer negation (-)? (Either way it's not obvious whether it stays uncomputable, I'll have to think about it.) \$\endgroup\$
    – N. Virgo
    Apr 3, 2018 at 4:32
  • \$\begingroup\$ @Nathaniel Logical. \$\endgroup\$ Apr 3, 2018 at 4:32
  • \$\begingroup\$ @EsolangingFruit I thought about it for a while and it still wasn't obvious, so I posted a question here \$\endgroup\$
    – N. Virgo
    Apr 3, 2018 at 4:49
  • \$\begingroup\$ @Nathaniel The question you posted isn't exactly the same; my axioms are slightly restricted. There are only integers (and therefore there is no division), and without negation there's no way to simulate logical OR or a "there exists" qualifier. If you allow the "there exists" qualifier your Twin Prime example should be fairly easy to rewrite. \$\endgroup\$ Apr 3, 2018 at 4:58
  • \$\begingroup\$ Ah, you're right, I'd for some reason transposed existential (there exists) and universal (for all) quantifiers in my question --- and your point about and vs or is relevant too. I'll reformulate it and repost. \$\endgroup\$
    – N. Virgo
    Apr 3, 2018 at 5:11
  • \$\begingroup\$ I've fixed the math.SE question and undeleted it. \$\endgroup\$
    – N. Virgo
    Apr 3, 2018 at 5:15
  • \$\begingroup\$ Exactly same model \$\endgroup\$
    – l4m2
    Apr 3, 2018 at 5:28
  • \$\begingroup\$ @EsolangingFruit the math.SE question got an answer that looks correct - even without logical negation it's still undecidable, because it contains a known undecidable problem about whether a polynomial has integer roots. \$\endgroup\$
    – N. Virgo
    Apr 3, 2018 at 12:28
  • \$\begingroup\$ Info: l4m2 attempted to make this computable by using program halt status the output (which is in turn uncomputable) in a separate sandbox post. \$\endgroup\$
    – DELETE_ME
    May 9, 2018 at 11:46
1
\$\begingroup\$

Antigerrymandering

From this question:

The United States has a unique love of gerrymandering––the deliberate manipulation of an electoral district to predict certain voting results. Just recently there was a gerrymandering case brought before the Supreme Court. Gerrymandering, especially when related to race, is ruled illegal and results in the requirement to redraw the district lines.

Gerrymandering has recently been getting even more attention in the news due to this year's congressional elections. Wouldn't it be nice if we could all decide on a simple, nonpartisan way to determine congressional districts?

Your task is to fix settle this discussion once and for all with a determinate program to partition a map into districts.

What you gotta do

Write a program or function that takes a positive integer n and a map (described below) and partitions the map into n contiguous districts of equal population (as nearly as possible) while minimizing the total length of the districts' borders.

The map

The map is a two-dimensional, rectangular matrix of one or more integers, each integer representing the population of its cell. This can be in any convenient format—an array of arrays, a stream of numbers, or even a JPEG, if desired! You are allowed to take the dimensions of the map as additional inputs.

The borders

Each cell in the map is to be treated as a square of side length 1. Total border length is the sum of the lengths of all edges of cells that are also the edge of a district. Note that this will necessarily include the entire perimeter of the map.

The partition

The n districts must have the lowest possible maximum difference in population from total population / n. In the case of a tie, they must have the lowest possible total border length, ensuring compact districts.

Take the following map:

1 5 7 8
7 4 2 5
8 5 3 5

It has total population 60. To divide it into two districts, each must have population 30. Additionally, each district must be orthogonally contiguous. Both of the following accomplish just that:

1│5 7 8
 └───┐
7 4 2|5
     │
8 5 3│5


1 5│7 8
   │
7 4│2 5
   │
8 5│3 5

Of these two partitions, the upper has total border length 14 (perimeter) + 5 (border) = 19, while the lower has length 17. Of these two options (and the other one I can see at the moment, the vertical line down the middle is to be chosen, since its border length is the lowest.

Now consider:

2 1 2

This again has two possible partitions into two districts, but these are tied in border length. Your program or function can return either partition, but it must return the same one each time.

Output

Lots of options. A string using one non-numeric character for border and another for no border. An array of numbers, with a surjection to the sixteen possible states of a cell's edges. A JPEG, with borders shaded. A pirate's map: "3 steps south. 2 steps east..." Really, anything that can be mapped to a partition. The output format must be consistent.

This is , so the shortest solution (in bytes) in each language wins!


Sandboxy stuff

Any clarification needed?

I'm making some test cases (based on real states' population distributions!); these'll be added soon.

Anything else worth mentioning?

Thanks!

\$\endgroup\$
5
  • \$\begingroup\$ While flexible output formats are commendable, I personally wouldn't want to check the validity of a program with output formats as broad as "anything that can be mapped to a partition". Now, checking validity of every answer isn't my job or anything, but I would want to have the option not be prohibitive. \$\endgroup\$ Apr 4, 2018 at 19:39
  • \$\begingroup\$ thematically related, although going in the opposite direction \$\endgroup\$
    – Giuseppe
    Apr 4, 2018 at 19:59
  • \$\begingroup\$ @KamilDrakari I'll think further on it. Thanks. \$\endgroup\$ Apr 4, 2018 at 20:06
  • \$\begingroup\$ @Giuseppe Yep. Meant to link in the question, but wrong link :) \$\endgroup\$ Apr 4, 2018 at 20:07
  • \$\begingroup\$ Will the "real" test cases be small? I ask because a golfed answer to the question as it stands is likely to be geologically slow. \$\endgroup\$ Apr 6, 2018 at 10:00
1
\$\begingroup\$

Find the Intersection

Challenge

Given some planes in an n-dimensional space, return the intersection of these planes with the highest degree, if it exists.

Details

You will be given two integers, n and k, such that 0 < k ≤ n and 1 < n. You will also be given (n-k) hyperplanes within the space Rn. (A hyperplane in the space Rn has (n-1) dimensions.) Your task is to find the intersection between them that has the highest number of dimensions, if it exists. This intersection will have at least k dimensions; it may have more than k dimensions if the inputs are not independent.

For example, if we are working in the 3-dimensional space (R3), you would be given planes with 2 dimensions. If you are given 3 distinct planes, you would at best be able to find a single point where they all intersect (0 dimensions). If you are given 2 distinct planes, you could find a line where they intersect (1 dimension). Et cetera.

Input format

You may choose any standard format to represent hyperplanes in Rn. Here are two formats that I suggest:

  1. vn = c1v1 + c2v2 + ... + cn-1vn-1 + cn, where v represents a variable and c represents a scalar constant.

  2. c1v1 + c2v2 + ... + cnvn + cn+1=0.

For example, consider the plane z=2x-3y in R3. In format 1, I would write this as v3=2v1-3v2+0, so my program would take in the tuple of scalar constants (2, -3, 0). In format 2, I would rewrite this as 2x-3y-z+0=0, and similarly take the tuple (2, -3, -1, 0). You can choose one of these two formats or another standard format, so long as you provide details in your answer.

You may take in n and k explicitly if you wish, though you should be able to determine both from the list of planes (k is the number of planes, n is one more than the number of dimensions in a plane).

Output format

You should output a single plane in the same format as your input. If no intersecting plane exists, you should return something recognizably distinct from other valid outputs of your program (such as an empty tuple, false, a thrown exception, etc.).

Test Cases

These use suggested input format 1, with n and k provided implicitly.

[(c1, c2, ..., cn), (...), ...] => (c1, c2, ...)

In R3, the intersection of z=-3x-2y, z=5+2x+3y, and z=-x-y-1 is the point (2, -3, 0)

[(2, 3, 5), (-3, -2, 0), (-1, -1, -1)] => (2, -3, 0) // This doesn't work

In R3, the intersection of z=4x+y and z=x+2y+1 is the line y=3x-1

[(4, 1, 0), (1, 2, 1)] => (3, -1)

Scoring criteria

This is , so the shortest answer in each language wins.


Meta

Can you follow the goal of the challenge and the details I've provided? I've tried to be as clear as possible, but I think I may have been too verbose.

I think my output format needs to change - there's no way to represent a point in Rn the way I've phrased it...any suggestions?

More test cases coming soon.

\$\endgroup\$
4
  • \$\begingroup\$ The specified input formats force the hyperplane to pass through the origin, but nothing else in the question indicates that restriction. \$\endgroup\$ Mar 29, 2018 at 13:56
  • \$\begingroup\$ Good point. I will fix that, thank you \$\endgroup\$ Mar 29, 2018 at 16:25
  • \$\begingroup\$ "this can be higher if some of the inputs are equal" should really be "this can be higher if some of the inputs are not independent": three planes can pass through a line without any of them being equal. Other than that, I think you just need the test cases. \$\endgroup\$ Apr 3, 2018 at 13:48
  • \$\begingroup\$ Thanks, this is the feedback I was looking for. I knew there were some holes in my math :) \$\endgroup\$ Apr 4, 2018 at 14:09
1
\$\begingroup\$

Get Rid of GoTo's

My (pseudo) code is full of goto's! What a mess... Let's change it into a more iterative code.

SPECIFICATION

Each input consists of:

<HEADER> { 
  0: <code> 
  1: <code> (optional) 
  2: <code> (optional) 
  ... 
  99: <code> (optional) 
}

where:

<HEADER>: It is the method signature, but it can be anything. Just repeat it in the output.

<code>: It is the main code that contains the unwanted goto's and need to be refactored. It is always numbered, starting at 0 and increasing sequentially. code can be one of:

  • if [condition] goto [number] [trailing]: this is where the goto's are. The if clause contains any text as a condition, that should be repeated in the output. The number should be between 0 and 99, and should point to a valid line in the input. The trailing could be a semicolon, a text comment or even nothing at all, but it will not appear in the output.
  • return: the return clause is special because it ends the method execution. In the input code, a return could be followed by others lines reachable by a goto. But in the output code, a return is never followed by a code line. The return can be followed by a semicolon or nothing at all.
  • anything: anything else is just code clauses that should be repeated somewhere in the output code.

EXAMPLES

BEFORE:

method1() {
    0: printMessage("This is the firstMethod");
    1: if (inputString(0)) goto 3;
    2: return;
    3: setVar(10);
    4: printMessage("Var is set to 10");
}

AFTER:

method1() {
    0: printMessage("This is the firstMethod");
    1: if (inputString(0)) {
    2:  setVar(10);
    3:  printMessage("Var is set to 10");
    4: } else {
    5:  return;
    6: }
}

This is the simplest example. The goto is changed into an if/else structure. The 'return' clause always ends a block (i.e., the code does not continue after it).

BEFORE:

public method2() {
    0: addFlag(char, 1);
    1: play(22, 3468, 4433);
    2: int rndNum = random(3)
    3: if(rndNum == 1) goto 6
    4: if(rndNum == 2) goto 8
    5: if(rndNum == 3) goto 10
    6: addItem(36, 54, 0, 0);
    7: return;
    8: addItem(37, 54, 0, 0);
    9: return;
    10: addItem(38, 54, 0, 0);
    11: return;
}

AFTER:

public method2() {
    0: addFlag(char, 1);
    1: play(22, 3468, 4433);
    2: int rndNum = random(3)
    3: if(rndNum == 1) {
    4:     addItem(36, 54, 0, 0);
    5:     return;
    6: } else {
    7:     if(rndNum == 2) {
    8:         addItem(37, 54, 0, 0);
    9:         return;
    10:    } else {
    11:        if(rndNum == 3) {
    12:            addItem(38, 54, 0, 0);
    13:            return;
    14:        } else {
    15:            addItem(36, 54, 0, 0);
    16:            return;
    17:        }
    18:    }
    19: }
}

This example is trickier. The three gotos end up creating nested if/else clauses. Also, as the transpiler can't know if rndNum(3) returns something from [1-2-3], there is also an ultimate else clause afterwards.

BEFORE:

public method3() {
    0: int curChar = whoMenu("Test", "Super");
    1: if (firstChar(currentChar, 1)) goto 5;
    2: printMessage("The sun is hot.");
    3: if (YesNo(1)) goto 17;
    4: return;
    5: addVar(currentChar, 10);
    6: addVar(currentChar, 20);
    7: addVar(currentChar, 30);
    8: addVar(currentChar, 40);
    9: addVar(currentChar, 50);
    10: addVar(currentChar, 60);
    11: addVar(currentChar, 70);
    12: addVar(currentChar, 80);
    13: addVar(currentChar, 90);
    14: addVar(currentChar, 100);
    15: printMessage("You feel good");
    16: if (YesNo(1)) goto 17;
    17: addFlag(currentChar, 82);
}

AFTER:

public method3() {
    0: int curChar = whoMenu("Test", "Super");
    1: if (firstChar(currentChar, 1)) {
    2:    addVar(currentChar, 10);
    3:    addVar(currentChar, 20);
    4:    addVar(currentChar, 30);
    5:    addVar(currentChar, 40);
    6:    addVar(currentChar, 50);
    7:    addVar(currentChar, 60);
    8:    addVar(currentChar, 70);
    9:    addVar(currentChar, 80);
    10:   addVar(currentChar, 90);
    11:   addVar(currentChar, 100);
    12:   printMessage("You feel good");
    13:   if (YesNo(1)) {
    14:         addFlag(currentChar, 82);
    15:   }
    16: } else {
    17:     printMessage("The sun is hot.");
    18:     if (YesNo(1)) {
    19:         addFlag(currentChar, 82);
    20:     } else {
    21:         return;
    22:     }
    23: }
}

This example is not so hard, but note there are two goto's going to the same line. As this line does not create a loop, it is permitted (see rules below).

BEFORE:

method4() {
    0: printMessage("This is the firstMethod");
    1: if (inputString(0)) goto 4;
    2: printMessage("End is near.");
    3: return;
    4: setVar(10);
    5: if (inputString(1)) goto 2;
    6: printMessage("Var is set to 10");
}

AFTER:

method4() {
    0: printMessage("This is the firstMethod");
    1: if (inputString(0)) {
    2:     setVar(10);
    3:     if (inputString(1)) {
    4:         printMessage("End is near.");
    5:         return;
    6:     } else {
    7:         printMessage("Var is set to 10");
    8:     }
    9: } else {
    10:    printMessage("End is near.");
    11:    return;
    12: }
}

This example is also tricky, because it contains a goto to a previous line. This does not create a loop, but it also creates a block that is repeated twice in the code.

CONSIDERATIONS:

1) Goto's are always associated with an 'if' clause. Replace the goto with a start block '{' clause.

2) Goto's always create an 'if', but not necessarily an 'else'.

3) Some clauses can repeat due to more than one goto's going to the same line (directly or not).

4) There won't be loops. Example of invalid code:

public methodInvalid() {
    0: if(YesNo(1)) goto 2;
    1: printMessage("this code is invalid.");
    2: if(NoYes(1)) goto 0;
    3: printMessage("still invalid.");
}

5) Identation in the output is desirable. Each if/else block must be nested with a tab for each nested level. If you want to replace the tab for 2, 3 or 4 spaces, ok, just state it and make it coherent on your code.

6) As there won't be more goto's, the line numbers are optional in the output code. Just don't put them out of order, if you want to keep them.

7) The first line can be ignored (just repeat it in the output) and the last line is always the close statement ('}'). These lines are never numbered.

8) The input will always contains line numbers, starting with 0 and a colon. The next line will be 1 and a colon, and so on. No more than 99 lines will be present.

9) There is also at least one space (or tab or opening parenthesis) after the if statement, one space before the goto statement and one space before the number after it. So "1:ifagoto2" is invalid, but "1:if a goto 2" is valid and also valid is "1: if(a) goto 2". Spaces (or tabs) are optional before the line numbers and between the semicolon and the start of the code.

10) You only need to worry with (a) 'goto's; (b) line numbers; (c) the 'return' clause; and (d) the end of the code (last line). Everything else is gibberish, you don't need to interpret the code. See a valid input below:

BEFORE:

fun with code {
    0: gibberish
    1: if a goto 3
    2: gibberish
    3: gibberish
    4: gibberish
}

AFTER:

fun with code {
    0: gibberish
    1: if a {
    2:  gibberish
    3:  gibberish
    4: } else {
    5:  gibberish
    6:  gibberish
    7:  gibberish
    8: }
}

Standard loopholes apply, shortest answer in bytes wins!

\$\endgroup\$
5
  • \$\begingroup\$ Will line number always start with 0 and increase by 1? Is there any un-conditional goto? Will there be any dead code in the input? \$\endgroup\$
    – tsh
    Apr 8, 2018 at 1:32
  • \$\begingroup\$ @tsh Yes, the number always start with 0 and increase by 1. No, goto's are always preceded by if's. Dead code in the input? I think so, there is no restrictions against that. \$\endgroup\$
    – Chaotic
    Apr 8, 2018 at 23:54
  • \$\begingroup\$ Suggested title: Code golf considered harmful. \$\endgroup\$
    – N. Virgo
    Apr 9, 2018 at 4:13
  • \$\begingroup\$ Is if(a)goto 2 allowed? \$\endgroup\$
    – l4m2
    Apr 9, 2018 at 12:57
  • \$\begingroup\$ @l4m2 No, because "There is at least ... one space before the goto statement" \$\endgroup\$
    – Chaotic
    Apr 9, 2018 at 15:08
1
\$\begingroup\$

Scoring a Game of Composite Boards

The Game

Given a board size n which must be a composite number, the game is played on m boards in parallel which correspond to the m factors of n, excluding 1 and n itself.

E.g. if n = 12, we get the following 4 boards, where the same character represents the same field:

01     012     0123     012345
23     345     4567     6789AB
45     678     89AB
67     9AB
89
AB

Two players, Zero and One, take turns in writing a 0 or 1 respectively on an empty field, which makes that number appear on all boards at the corresponding field.

On each board their goal is to get more rows or columns filled with just their number than their opponent, resulting in the board being either a win for Zero, a win for One or a draw if both players fill the same number of rows or columns.

The game is won by the player who wins the majority of boards, or results in a draw if both players win the same number of boards.

Example

Let's say we have the game 010111010100 of size 12, which corresponds to the following boards:

01
01
11 <- row for player One
01
01
00 <- row for player Zero
no columns for either player -> draw

010
111 <- row for One
010
100
-> One wins this board

0101
1101
0100
 ^^
 one column for each player -> draw

010111
010100
^^^^
two columns for each player -> draw

As player One wins one board and player Zero wins none, player One wins the game.

The Task

Given a completed game as input, output which player won or whether the game was a draw. This is , so the smallest answer in bytes in each language wins.

Input

A one-dimensional array/list/string of two distinct values representing the fields of the boards when read left-to-right and top-to-bottom. You can assume that the input describes a valid game, that is the length will always be a composite number and the two values appear either the same number of times for even board lengths or with a difference of one for odd board lengths.

Output

Three distinct constant values which correspond to player Zero wins, player One wins or draw.

Test Cases

Draw: (All games of size 2*p where p is prime necessarily result in a draw)

0110
101010
11010010
010101010
11001111000100

Zero wins:

110110000
001001110101
1000110101011001

One wins:

111100001
010111010100
1100111100010010
0111010001001101
\$\endgroup\$
1
\$\begingroup\$

Curve Matching

Given two lists a, b of the same length n find a third list x of indices such that a(i) = b(x(i)) for all indices i and x(i) <= x(i+1) for all applicable indices i and x(1) = 1 and x(n) = n.

Details

  • The list x is not necessarily unique (for instance when b has a run of two or more equal entries).

  • In the challenge description we use 1-based indices, but you can also use 0-based indices.

  • You can assume that a and b contain integers, floating point numbers, characters or any other types that have a natural order and have at least 256 distinct values.

  • You can assume that such an x exists. (You can for instance assume that a=[1,2,3], b=[1,2,1] are never passed as an input.)

Examples

a = b = [1,2,3]
x = [1,2,3]

a = [1,3,3], b = [1,1,3]
x = [1,3,3]

a = [1,1,2,3,4,4], b = [1,2,2,3,3,4]
x = [1,1,2,4,6,6] or [1,1,3,5,6,6] etc

a = [1,1,2,3,2,1,1], b = [1,2,1,2,3,2,1]
x = [1,3,4,5,6,7,7]

This challenge was inspired by this question on math.SE.

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

Unless someone can convince me otherwise I think this is too close to Are the brackets fully matched? to be an interesting new challenge, so I won't submit it.

Well-formed Parentheses Gone Wild

The object is to determine if the "parentheses" in a string are well-formed, in the sense that they are balanced and well-nested.

For example [(ab(c!{})n)] is such a string, while [(ab(c!(d)x){)}] is not (balanced, but not well-nested due to the last closing ) appearing before the closing }).

But wait, there's more

Those examples took advantage of the commonly understood meanings of the pairs (), {}, and []. But any characters could be opening and closing parentheses, and not just the obvious ones.

Input

The input consists of two strings with optional trailing newlines. The characters can be any ASCII printable character (hex 20 to hex 7E).

The first string has an even number of characters with no duplicates. Each successive pair of characters defines a pair of opening and closing parentheses. The second string is the test string.

Output

Truthy or falsy value (with optional trailing whitespace) for whether or not the parentheses in the test string are well-formed (balanced and well-nested). If either the first or second strings are empty, the answer is defined to be truthy.

Some Tests

Format:

String1
String2
Output

Tests:

(){}[]
[(ab(c!{})n)]
truthy

(){}[]
[(ab(c!(d)x){)}]
falsy

()[]<>
[(ab(c!(d)x){)}]
truthy

                      <---- empty parenthesis string
%$w%jS(5gS
truthy

(){}[]
                      <---- empty test string
truthy 

qwertyuiop
q##qCfet^Hy&&r$wuiwgJo7({)}erxp
truthy

@#$%^&
super b$fox$#@%%g ongshow^&
falsy

Scoring and Rules

  • This is . Shortest entry wins.
  • Standard loopholes forbidden and standard rules apply.
\$\endgroup\$
10
  • \$\begingroup\$ I believe this is a duplicate \$\endgroup\$ Apr 20, 2018 at 21:03
  • 1
    \$\begingroup\$ @NathanMerrill this challenge has the input define its own parentheses and require that it's well-formed. That would definitely need different code. \$\endgroup\$
    – Nissa
    Apr 20, 2018 at 21:19
  • 2
    \$\begingroup\$ Why not go with 2 separate strings in any convenient format? Can the open and close parentheses be the same, e.g. quotes? \$\endgroup\$
    – Nissa
    Apr 20, 2018 at 21:23
  • \$\begingroup\$ @StephenLeppik - two strings in a convenient format would be better. The , and ! are not relevant to the problem. Would it be canonical to say "two strings with optional trailing newlines"? I want to include the space ` ` as a possible character in either string. \$\endgroup\$
    – ngm
    Apr 20, 2018 at 22:08
  • \$\begingroup\$ @StephenLeppik Open and close parentheses must be different, as implied by the even number of characters with no duplicates in the first string. \$\endgroup\$
    – ngm
    Apr 20, 2018 at 22:16
  • \$\begingroup\$ Is it possible to take a list of length-2 string (for the first input)? \$\endgroup\$
    – DELETE_ME
    Apr 21, 2018 at 10:09
  • 1
    \$\begingroup\$ This is a better dupe. The 05AB1E answer and the (20-byte) Pyth answer can be directly ported to this challenge. The Javascript answer... need some join-with-| and regex construction. \$\endgroup\$
    – DELETE_ME
    Apr 21, 2018 at 10:13
  • \$\begingroup\$ I'm thinking codegolf.stackexchange.com/questions/77138/… is close enough to make this challenge uninteresting. What's the protocol? Do I delete this or just leave it so nobody else tries the same? \$\endgroup\$
    – ngm
    Apr 21, 2018 at 17:21
  • 1
    \$\begingroup\$ You could always spice up the rules to make your challenge unique. \$\endgroup\$ Apr 21, 2018 at 19:23
  • \$\begingroup\$ What if there was an order on the different parenthesis so that () has to be closed before [] can be open or something along these lines? So your String1 in the example would define an order. \$\endgroup\$
    – JayCe
    Jun 11, 2018 at 3:42
1
63 64
65
66 67
153

You must log in to answer this question.

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