490
\$\begingroup\$

What is the Sandbox?

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

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

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

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

Add Proposal

Search the Sandbox

Browse your pending proposals

Get the Sandbox Viewer to view the sandbox more easily

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

| |
\$\endgroup\$

2968 Answers 2968

1
49 50
51
52 53
99
1
\$\begingroup\$

Convert A String To Shorthand

Shorthand has been used for hundreds of years to compress and speed up the speed at which someone can write down what is said.
It does this using several abbreviating methods; three of which will be used here to compress a sentence.

Challenge

When given a sentence, alongside a set of 'briefs', 'prefixes' and 'suffixes' (defined below), print or return the sentence in its compressed form.

Definitions

  • Brief: A word that can be entirely substituted by another string of characters.
    I.E. Would: D, Be: B, Able: Ab. "I would be able...": "I D B Ab
  • Prefix: The beginning of a word that can be substituted by another string of characters; the prefix will either be joined or dis-joined.
    After(Joined): Af. Afternoon = Afnoon.
    Enter/Inter/Intra(Dis-joined): N. Internet = N-net
  • Suffix: The ending of a word that can be substituted by another string of characters; the suffix will either be joined or dis-joined.
    ful/ify(Joined): F. Clarify = Clarf
    ification(Dis-joined): F. Clarification = Clar-f

Input Structure

  1. The first input will be the sentence to be converted
  2. The second input is a collection of the briefs. Each brief is a collection itself, in which the first element represents the shortened form of that brief, while the rest of the elements are all strings that map to the brief. Example: [ [d, would], [m, much, more], [a, at, an] ]
  3. The third and fourth inputs are collections of prefixes and suffixes. The first element of each prefix/suffix is the shortened form, the second element is a flag (of your choosing) that represents whether it is joined or dis-joined. Everything else are the strings that match the prefix/suffix.
    Prefix: [ [af, true, after], [n, false, enter, inter, intra] ]
    Suffix: [ [f, true, ful, ify], [f, false, ification] ]

Sample Input:

"a shipment of letters was delivered to the postshop", [["of", "o"], ["t", "to"], ["was", "os"], ["the", "th"]], [["sh", false, "ship"], ["d", true, "de"], ["po", false, "post"]], [["rs", true, "ers"], ["m", true, "ment"], ["d", true, "ed"]]

Rules, Assumptions and Freedoms

  • You may assume all input is lowercase letters.
  • A brief will always take priority over prefixes and suffixes.
  • you can indicate a dis-joined suffix/prefix however you wish, as long as you mention how you are indicating it.
  • The input may be rearranged however you like, as long as you specify how your input is structured
  • Output may be returned, printed or the nearest equivalent.

Test Cases

"a shipment of letters was delivered to the postshop", [["of", "o"], ["t", "to"], ["was", "os"], ["the", "th"]], [["sh", false, "ship"], ["d", true, "de"], ["po", false, "post"]], [["rs", true, "ers"], ["m", true, "ment"], ["d", true, "ed"]]

a sh-m o lettrs os dliverd t th po-shop

"shorthand was once a common skill among woman", [["was", "os"]], [["sh", false, "ship", "short"], ["cm", true, "com"]], [["mn", true, "mon", "man"]]

sh-hand os once a cmmn skill among womn"

"the electrician will be able to fix it", [["th", "the"], ["l", "will"], ["b", "be"], ["ab", "able"], "t", "to", "it"]], [["el", false, "electr"]], [["sh", true, "cian", "sion"]]

th el-ish l b ab t fix t

| |
\$\endgroup\$
  • \$\begingroup\$ Looks like a nice challenge, I don't think there's much that needs to B clar-f-ed \$\endgroup\$ – Redwolf Programs Sep 7 at 14:12
1
\$\begingroup\$

Keep the symmetry

SANDBOX: I am aware that the language in this challenge, as it stands, is quite... fluffy. If anyone could help me firm it up, I would be grateful. Also, would this be better as a cops-and-robbers style challenge, where the cops are trying to make the output more symmetrical, and the robbers make it less symmetrical?

Given a 2D array of 1s and 0s, flip a 1 to a 0 and output the resulting array.

The output array must be "closer to being symmetrical" than the input.

In the case where the array is already symmetrical, it must still flip a 1 to a 0, breaking as little symmetry as possible - e.g for

1,0,1
1,0,1
1,0,1

In the above case, changing the top-left 1 to a 0 will break symmetry in both directions, whereas changing the middle-left 1 will only break symmetry one way.

The output must be in the same form as the input (so that your program or function could take it in again).

What is symmetry?

I am talking about reflectional symmetry along both the horizontal and vertical axes.

Where the array has an even number of entries in a row/column, the axis is between the two central rows/columns:

1,0,|,0,1
1,0,|,0,1
-,-,-,-,-
1,0,|,0,1
1,0,|,0,1

otherwise it's down the middle of the middle row/column (and the numbers in that row/column count on both sides).

   |  
 1,0,1
-1,0,1-
 1,0,1
   |

Some Examples

Each pair of grids below is input .. output, which then becomes the next input, etc. iteratively:

1,0,0,1      1,0,0,1      1,0,0,1      1,0,0,1      1,0,0,0      0,0,0,0      0,0,0,0
0,0,1,0  ..  0,0,0,0  ..  0,0,0,0  ..  0,0,0,0  ..  0,0,0,0  ..  0,0,0,0  ..  0,0,0,0
1,0,0,1      1,0,0,1      0,0,0,1      0,0,0,0      0,0,0,0      0,0,0,0      0,0,0,0
1,1,1      1,0,1      1,0,1      1,0,1      1,0,1
1,1,1  ..  1,1,1  ..  1,0,1  ..  0,0,1  ..  0,0,0
1,0,1      1,0,1      1,0,1      1,0,1      1,0,1

| |
\$\endgroup\$
  • \$\begingroup\$ Is the program supposed to find the shortest path, or any path? Are we supposed to display each step? Should the choice of flipping a 1 to a 0 be random, or can it be calculated? A reference implementation would be very useful in this question. \$\endgroup\$ – Razetime Aug 26 at 13:03
  • \$\begingroup\$ The program is only supposed to flip one, calculated, bit from 1 to 0 and return the new grid. so iterative calls to the program would ultimately lead to all 0s. I guess I'm unclear exactly how I want the concept to be translated into a challenge, which is why I put the sandbox text at the top \$\endgroup\$ – simonalexander2005 Aug 26 at 13:38
  • \$\begingroup\$ The program must be trying to make the array symmetrical This needs to be defined precisely. What does it mean that the program "tries" to make it symmetrical? That repeated application of the program eventaully gives a symmetrical array? That it does it in a "small" (to be defined) number of steps? Same with as easy as possible: this needs to be defined precisely. I'm afraid I don't get the main idea of the challenge, actually \$\endgroup\$ – Luis Mendo Aug 26 at 17:21
1
\$\begingroup\$

Balanced Beams

Here are some examples of beams that balance:

X Y A   | X Y B Y
--+-----+---+---+
  |         |   |
X X   Y Y   Y X X
--+---- ----+-- +

A X X Y | A B Y Y
+---+---+-+-----+
|   |     |     |
B A | A AAB B   A
+ --+-- --+--   +

X Y X X | Y B   X
+-+-+---+---+----
| | |       |
Y A X Y Y X X X X
+ + + ------+----

The diagram will always be 17 characters wide and the top beam always balances in its centre. The other +s on the top beam indicate the point from which a lower beam hangs and the + on the lower beam indicates the point at which it balances. Your input does not need to include the |s if you don't need them. Lower beams with a width of 1 balance by default of course. The balancing of the top beam has to take the total weight of each lower beam into account.

As you can see, for each example, there are two positions marked A and B where I have forgotten whether they should be an X or a Y.

Please write a program a function which will accept the above diagram as input and output which of X and Y belong in each of the two positions A and B.

Your output should be something along the lines of A=X, B=X although any unambiguous output suffices e.g. you could output the diagram with the A and B substituted accordingly or you could modify the input in-place. You do not have to output values for X or Y, although for each diagram they always have a fixed ratio which will allow all beams to balance.

Other input formats could be acceptable but they need to get suggested as comments to the sandbox post.

This is , so the shortest program or function that breaks no standard loopholes wins!

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

Posted: Prime Power Switch

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

Sandbox Question

Do people think this is worth posting, given it only really requires a prime check along with getting digit prefixes? There are multiple implementations (possibly including hard-coding in some languages) to consider which might be enough. Please vote!


Produce all 83 base-ten right-truncatable primes in as few bytes as possible in the language of your choice.

  • Order is irrelevant, but the production must terminate.
  • You may produce a list, a set, or an equivalent object.
  • You may print them (e.g. space-separated, each on a line, or formatted as a list or set (e.g. {2; 3; 293; 5; ...})
  • You may give the numbers themselves as strings.
  • You may produce an iterator (but evaluating it must terminate).

Right truncatable primes

A right truncatable prime is a prime for which removing any number of trailing decimal digits is also prime.
For example, \$7193\$ is a right truncatable prime since \$719\$, \$71\$, and \$7\$ are all prime.

There are only 83 such numbers in base-ten, when sorted they are:

[2, 3, 5, 7, 23, 29, 31, 37, 53, 59, 71, 73, 79, 233, 239, 293, 311, 313, 317, 373, 379, 593, 599, 719, 733, 739, 797, 2333, 2339, 2393, 2399, 2939, 3119, 3137, 3733, 3739, 3793, 3797, 5939, 7193, 7331, 7333, 7393, 23333, 23339, 23399, 23993, 29399, 31193, 31379, 37337, 37339, 37397, 59393, 59399, 71933, 73331, 73939, 233993, 239933, 293999, 373379, 373393, 593933, 593993, 719333, 739391, 739393, 739397, 739399, 2339933, 2399333, 2939999, 3733799, 5939333, 7393913, 7393931, 7393933, 23399339, 29399999, 37337999, 59393339, 73939133]

This is A024770 in the Online Encyclopedia of Integer Sequences.


For some mathematician-written* Python see https://youtu.be/f2lEB4nMmyI.
* Fair warning, it might well make you cringe.

| |
\$\endgroup\$
  • \$\begingroup\$ I don't really mind prime challenges, just that most people who have been here a while have a stigma against it. Related. \$\endgroup\$ – Razetime Sep 5 at 14:26
  • \$\begingroup\$ The code in the link contains what appears to be a partially censored racial slur, so I think you should probably drop the youtube reference. \$\endgroup\$ – FryAmTheEggman Sep 9 at 21:32
  • \$\begingroup\$ Otherwise I think this is probably interesting enough, as these primes have several other non-prime features. It might be problematic if too many answers are just primality checks wrapped in terminating loops, though? \$\endgroup\$ – FryAmTheEggman Sep 9 at 21:35
  • \$\begingroup\$ @FryAmTheEggman Oh wow, I didn't notice; that's pretty sad. \$\endgroup\$ – Jonathan Allan Sep 9 at 22:15
1
\$\begingroup\$

Move the Knight!

Your knight is on (0, 0) on an infinite (to all of the four edges, not just two) chessboard, and you need to move it to (a, b). You can use arbitrary (but finite) number of moves to do that. Since the chessboard is infinite, you can use squares with negative coordinates.

Since you only have 2 knights (if no promotion occured) to type the program, your program needs to be as short as possible.

Input

The input is two integers, a and b.

Output

You output a sequence of characters, each represents a move. There are eight directions to move, so your output should contain eight distinct characters, each represents one direction. They can be any eight characters, as long as they are all unique.

Test Cases

The characters used here is:

 A B
C   D
  N
E   F
 G H
0 0 -> ""
1 1 -> "GD" or "DEGD" or "DG" etc.
3 3 -> "DDDGGG" (one possible version)
2 3 -> "FGD"

Rules

  • Standard Loopholes are forbidden.
  • This is , so shortest code wins.
| |
\$\endgroup\$
  • \$\begingroup\$ @Razetime I did... "They can be any eight characters, as long as they are all unique." \$\endgroup\$ – null Sep 15 at 12:30
  • \$\begingroup\$ oh, sorry about that. \$\endgroup\$ – Razetime Sep 15 at 12:31
  • \$\begingroup\$ @Razetime I intend to make this challenge have many different, unique, interesting approach, and which one is shorter highly depends on the language. \$\endgroup\$ – null Sep 15 at 12:33
1
\$\begingroup\$

Do my data follow Benford's law or a uniform distibution?

Background

Benford's law, also known as the law of anomalous numbers, describes the distribution of the leading digit in many numerical data sets. Let \$X\$ be the leading digit of an observation (in base 10). According to Benford's law, \$P[X=i]=\log_{10}(1+\frac1i)\$ for \$i=1\ldots 9\$.

For instance take the yearly reputation change of the top 1000 users on CGCC. For a user with reputation change 3522, keep only the leading digit, 3. Repeat this for all users, and you get this distribution, which is far from uniform:

enter image description here

This has been shown to apply to vary different data sets, from town populations to stock prices, and is used to detect tax and election fraud.

On the other hand, for some other data sets, the distribution of the leading digit is a uniform distribution: \$P[X=i] = \frac19\$ for \$i=1\ldots 9\$.

Given some observed frequencies \$(f_i)_{i=1\ldots 9}\$, we shall measure the distance to these two distributions using the sum of the errors in absolute value: \$\sum_i \left|f_i-\log_{10}(1+\frac1i)\right|\$ and \$\sum_i\left|f_i-\frac19\right|\$, respectively.

Task

Take as input a list of non-zero numbers. For each number, keep only the leading digit, which is defined as the first non-zero digit. Compute the observed frequencies of leading digits, and output one of two values, depending on whether the observed frequencies are closer to Benford's law or to a uniform distribution.

Input

Input format is flexible. Note that input may include negative values, as well as non-integers.

Output

Either two consistent values, one for Benford's law and one for the uniform, or a truthy/falsey value.

Test cases

To be added

This is , so shortest answer in bytes wins.

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

Finding the densest crossword puzzles

I love crosswords, and nothing beats a super densely packed puzzle. But how dense can the puzzles get?

Here's a sample puzzle I made a few years ago:

enter image description here

Certainly not great, but can we do better?

Given any list of characters, a crosswordification of that list is a crossword puzzle consisting of characters from that list. For example, given the list ['b','a','d','a','d'], the following is a valid crosswordification:

enter image description here

but this isn't

enter image description here

Clearly, the order of the list is irrelevant.

Given a valid crossword, the area of the crossword is the area of the smallest rectangle containing the crossword. In the above examples, the smallest rectangle containing the crosswords are 3x3 squares, which have area 9.

Challenge

In this challenge, you must write a function which takes two arguments

  • A list-like structure containing english characters

  • A list-like of valid words consisting of english characters

and outputs an integer, representing the minimal area of a crosswordification of the list of english characters, where the second input defines the set of valid words.

I will be using this english dictionary for my test cases. Any code that is used to import/parse the dictionary into a list-like structure won't be counted in the byte-count, just the function.

Test Cases

More to be added:

['d','a','a','a','t','n','m'] -> 7 (adamant is a word)

['k','a','s','a'] -> 6
| |
\$\endgroup\$
  • \$\begingroup\$ Here's what I understand: Our programs need to calculate the smallest possible corssword from the given characters, display the size alone. correct? \$\endgroup\$ – Razetime Sep 17 at 5:04
  • \$\begingroup\$ @Razetime correct \$\endgroup\$ – Don Thousand Sep 17 at 13:51
  • \$\begingroup\$ Do you suspect there is any other way to do this apart from brute forcing all possible arrangements and picking the minimal area one that meets the requirements? \$\endgroup\$ – Sisyphus Sep 18 at 4:40
  • \$\begingroup\$ @Sisyphus yes, but not revealing, as thats part of the challenge \$\endgroup\$ – Don Thousand Sep 18 at 11:17
1
\$\begingroup\$

Posted.

| |
\$\endgroup\$
  • \$\begingroup\$ "one or more of the options for the longest palindromic run of digits in its binary representation can be removed" Does this mean I can remove several runs? For example, 945770 = 11100110111001101010_2 has 110011 as the longest palindromic run, it occurs twice and if I remove both occurrences, the result is 10101010. On the other hand, 944522 = 11100110100110001010_2 has 110011 and 001100 as longest palindromic runs, and removing both gives 10101010. \$\endgroup\$ – Zgarb Sep 12 at 10:25
  • \$\begingroup\$ Don't forget Dennis, Dennis 2.0 or Calvin numbers :P \$\endgroup\$ – caird coinheringaahing Sep 12 at 15:37
  • \$\begingroup\$ @Zgarb No; you should only remove a single run before splitting the remaining digits. I've clarified this in the challenge text. \$\endgroup\$ – sporeball Sep 13 at 0:50
1
\$\begingroup\$

Posted

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ I think the notation is fine, you could let people use any 4 distinct characters instead. You should mention that gravity is tward the center of the pattern. \$\endgroup\$ – Razetime Sep 18 at 2:33
  • 1
    \$\begingroup\$ left/right/up/down is more suitable for dominoes, I think. I don't know how walls and splits would change this, but go for it if you're fine with lesser answers. finding if a target domino falls is a different question altogether. \$\endgroup\$ – Razetime Sep 18 at 2:35
  • \$\begingroup\$ @Razetime There's no gravity, the example just happened to go towards the center. The direction relies solely on the pieces (I'll clarify that) \$\endgroup\$ – user Sep 18 at 17:09
  • \$\begingroup\$ You mix a lot of terminology about the directions, i.e. using "north" and "below" in the same description. I think you would be better off editing the descriptions to all use the same convention. Separately, truthy and falsy aren't really good terms to use, since some languages don't have a concept of truth. I'd recommend saying something like "one consistent value for true and anything else for false or the reverse", or something similar. \$\endgroup\$ – FryAmTheEggman Sep 18 at 18:10
  • 1
    \$\begingroup\$ Related, outputting the result after dominoes fall in 1D. \$\endgroup\$ – xnor Sep 18 at 20:56
  • \$\begingroup\$ @FryAmTheEggman I started out with just north/south/east/west, and then changed it after Razetime's comment. I guess I left out some parts. I will change the falsy/truthy part too \$\endgroup\$ – user Sep 18 at 23:39
1
\$\begingroup\$

Secret ">" Stacking Challenge: cheating

Sequel to Secret ">" Stacking Challenge: grading. You can skip the whole Background section if you already read the first one.

Background

Tetris Grand Master 3 has a hidden grading system based on the shape of the stack at the end of the game, which is called Secret ">" Stacking Challenge. It consists of entirely filling the lowest rows except for the zigzag pattern which starts at the left bottom cell and spans the entire width:

#
.#########
#.########
##.#######
###.######
####.#####
#####.####
######.###
#######.##
########.#
#########.
########.#
#######.##
######.###
#####.####
####.#####
###.######
##.#######
#.########
.#########

The board is graded by how many lines follow this exact pattern from the bottom line. Note that the topmost hole in the pattern must be blocked by an extra piece of block. If you consider the #s and .s as the mandatory pattern (blanks can be anything), you can get the score of 19 only if the exact pattern above is matched from the bottom line. Analogously, if the board matches this pattern

   #
###.######
##.#######
#.########
.#########

but not

    #
####.#####
###.######
##.#######
#.########
.#########

then the score is 4.

For this challenge, consider a board of arbitrary size (other than 20 cells high and 10 cells wide). We can grade the board for the same pattern: for example, if the board has width 4, this is the pattern for score 3:

  #
##.#
#.##
.###

and this is the pattern for score 10:

   #
###.
##.#
#.##
.###
#.##
##.#
###.
##.#
#.##
.###

Challenge

Given the board width and the desired score for Secret ">" Stacking Challenge, pick a sequence of tetrominoes and generate the sequence of moves that will achieve the score. The Tetris moves can be represented in any ways that clearly specify where each tetromino is placed in which orientation, optionally along with the board state after each placement.

For the Tetris movement rules, we use simple permissive rule as in this challenge: you can place a tetromino anywhere (even in closed rooms), as long as it doesn't float in the air or overlap with existing pieces. Therefore, if you plan to use coordinates, you need to specify both x and y coordinates (the y coordinate should be counted from the bottom, as the board can grow upwards without bound).

You can assume the width is at least 5 and the score is nonzero. You should theoretically support arbitrarily high score. The generated sequence doesn't need to be minimal.

Standard rules apply. The shortest code in bytes wins.

Output example

For board with 6 and score 2, one possible way is as follows: (As are the tetromino placed at each turn, # are existing pieces on the board, and . are empty cells)

......  ......  ......  ......  ......
A.....  #.....  #.....  .AA...  .##AA.
AA....  ##AA..  ####AA  #.AA..  #.##AA
.A....  .#AA..  .###AA  .#####  .#####

The above is a valid output format (you can choose any distinct chars/values in place of .A#). The following is also valid (although it is less obvious, it is indeed an unambiguous description of tetromino placements):

......  ......  ......  ......  ......
A.....  ......  ......  .AA...  ...AA.
AA....  ..AA..  ....AA  ..AA..  ....AA
.A....  ..AA..  ....AA  ......  ......

And this: (tetromino code, rotation, x and y coordinates from bottom left, 0 indexed)

S 1 0 0
O 0 2 0
O 0 4 0
Z 0 1 1
Z 0 3 1

And anything in between (e.g. showing tetrominos as a canonicalized matrix instead of a code).


Meta

  • For the output format, I originally thought of requiring to output the sequence of board states after each placement, in the sense of but allowing and all frames to be output at once. Do you have a better suggestion for output format?
| |
\$\endgroup\$
1
\$\begingroup\$

The ASCII character countdown!

Your task is simple: Choose any printable ASCII character that's not chosen in the previous answers. And then, you need to print your chosen character in your program to standard output. (You can ONLY print your chosen character, without printing other garbage to STDOUT)

The catch

Let's say you picked x as your chosen character, and your answer is the answer numbered y. You have to insert y x's into the previous source code, at any position you like. For the first answer, the previous answer is the empty program.

An example

Answers have to start with the number 1. So for example, I chose the character #, and I posted a 1 byte answer in /// that prints the # mark.

#

And then, the second answer (numbered 2) has to insert 2 of their picked x character into the previous source code, such that the modified code will print their x character. So assume this is written in Keg:

x#x

And then, the third answer has to do the same, and so on, until 95 is reached.

The winning criterion & other rules

  • The first user whose answer stays without a succeeding answer for a month wins the challenge. If that's not satisfied, the first person who reaches the number 95 wins the challenge.
  • You are not allowed to put any other character in your code other than printable ASCII characters.
  • You need to wait for an hour before posting a chaining answer.
  • You need to wait 2 answers before you post a new answer after your submission.
  • Please make sure your answer is valid. If yours is not valid, chaining answers aren't allowed to be posted.
  • The answers are allowed to be in different languages.
  • Each submission doesn't have to be in a unique language.
  • You could only insert y x's into the source code.
| |
\$\endgroup\$
  • \$\begingroup\$ Can the answers be in different langauges? \$\endgroup\$ – fireflame241 Jul 20 at 4:03
  • 1
    \$\begingroup\$ What is the motivation for the number 95? \$\endgroup\$ – fireflame241 Jul 20 at 4:03
  • \$\begingroup\$ This isn't a radiation hardening challenge, as those require programs to still work / do something different if any single character is removed. \$\endgroup\$ – Lyxal Jul 21 at 9:15
  • 1
    \$\begingroup\$ @fireflame241 Because there are 95 ASCII characters of course... \$\endgroup\$ – user202729 Jul 21 at 12:50
  • \$\begingroup\$ Must we only insert y xs, or may we also insert other (printable ASCII) characters apart from our chosen character? If the latter, are the additional characters limited to those not already used in previous answers? \$\endgroup\$ – Dingus Jul 21 at 15:02
  • \$\begingroup\$ "I chose the character ?" -> "I chose the character #"? \$\endgroup\$ – user202729 Jul 22 at 6:10
  • \$\begingroup\$ "has to insert their picked x character into the previous source code," -> edit this part too. \$\endgroup\$ – user202729 Jul 22 at 6:11
  • \$\begingroup\$ @Dingus Now you may only insert y xs. \$\endgroup\$ – user92069 Jul 23 at 0:56
  • 1
    \$\begingroup\$ "I chose the character ?" has crept back in. Other than that it's clear now. (Seems difficult too, but maybe not in the golfing langs - I don't know.) \$\endgroup\$ – Dingus Jul 23 at 2:18
1
\$\begingroup\$

Question Posted   

| |
\$\endgroup\$
  • \$\begingroup\$ So what's the scoring citeria? \$\endgroup\$ – null Jul 18 at 23:57
  • \$\begingroup\$ @HighlyRadioactive The maximum string length found between the RNA representation of MN908947.3 and the DNA or RNA representation of some other non-coronavirus organism. Or the maximum length multiplied by three of the maximum string found in common between the representation of a protein of MN908947.3 and that of a living non-coronavirus organism. \$\endgroup\$ – user58988 Jul 19 at 2:36
  • \$\begingroup\$ Then a random brute-force solution would win as long as it's acturate. \$\endgroup\$ – null Jul 19 at 2:41
  • \$\begingroup\$ Or is this not a code-challenge, but a programming puzzle? \$\endgroup\$ – null Jul 19 at 2:41
  • \$\begingroup\$ Yes possible is a programming puzzle, code is only for find string equal ... but strings are long and the algo seems to me at last O(n^2) \$\endgroup\$ – user58988 Jul 19 at 3:13
  • 1
    \$\begingroup\$ Code Golf Stack Exchange is a site for recreational programming competitions, not general programming questions. Challenges must have an objective scoring criterion, and it is highly recommended to first post proposed challenges in the Sandbox. \$\endgroup\$ – null Jul 19 at 3:15
  • \$\begingroup\$ Obiective score exist, i explain it above for the remain free of downvote that \$\endgroup\$ – user58988 Jul 19 at 3:21
  • \$\begingroup\$ What program would win then? \$\endgroup\$ – null Jul 19 at 3:22
  • \$\begingroup\$ The winner is the one who finds in GenBak the genetic code or a protein of a being that is not a coronavirus (but it can be a virus), that has L genomic lenght as calculate above for genome or for proteine, more big respect to sarscov19 virus (the one name MN908947.3 in GenBank) ). \$\endgroup\$ – user58988 Jul 19 at 3:23
  • \$\begingroup\$ How would multiple programs compete? \$\endgroup\$ – null Jul 19 at 3:25
1
\$\begingroup\$

Circumference of an ellipse

Challenge

Unlike the circumference of a circle (which is as simple as \$2\pi r\$), the circumference of an ellipse is hard.

Given the semi-major axis \$a\$ and semi-minor axis \$b\$ of an ellipse (see the image below, from Wikipedia), calculate is circumference. The output value must be within \$10^{-6}\$ relative error from the expected answer for the given test cases.

enter image description here

Standard rules apply. The shortest code in bytes wins.

Formulas

Relevant information can be found on Wikipedia and MathWorld. \$C\$ is the value of the circumference; \$e\$ and \$h\$ are helper values. The last two are Ramanujan's approximation. (Meta: Do you want to have the two approximation formulas allowed or banned?)

$$ e = \sqrt{1-\frac{b^2}{a^2}} \\ C = 4aE(e) = 4a\int^{\pi/2}_{0}{\sqrt{1-e^2 \sin^2 \theta} \;d\theta} \\ C = 2 \pi a \left(1-\sum^{\infty}_{n=1}{\left(\frac{(2n-1)!!}{(2n)!!}\right)^2 \frac{e^{2n}}{2n-1}}\right) \\ h = \frac{(a-b)^2}{(a+b)^2} \\ C = \pi (a + b) \left( 1 + \sum^{\infty}_{n=1} { \left( \frac{(2n-1)!!}{2^n n!} \right)^2 \frac{h^n}{(2n-1)^2} } \right) \\ C = \pi (a + b) \sum^{\infty}_{n=0} { \binom{1/2}{n}^2 h^n } \\ C \approx \pi \left( 3(a+b) - \sqrt{(3a+b)(a+3b)} \right) \\ C \approx \pi (a+b) \left( 1+ \frac{3h}{10 + \sqrt{4-3h}} \right) $$

Test cases

Coming soon.

| |
\$\endgroup\$
  • \$\begingroup\$ You should definitely explain in at least some detail how to do it (list formulas, etc.). I think the consensus is challenges should be mostly self contained. Seems like it might be an interesting challenge! \$\endgroup\$ – Redwolf Programs 3 hours ago
1
\$\begingroup\$

Palindrome distance

Find what is the distance for a given string to its closest palindrome of the same length.

For this task I decided to give the characters further away from the string's center more weight (think of it as contributing more torque), proportional to their distance to the center.

Let's define the palindrome distance for a string \$s\$ as the sum of all products of the absolute difference of the corresponding pairs, equally spaced from the string's centre, and their distance to the center.

\$D_p=\displaystyle\sum_{i=1}^{d}\left(d-i+1\right)|s_i-s_{l-i+1}|\$

where \$l\$ is the length of \$s\$ and \$d = \left\lfloor\frac{l}{2}\right\rfloor\$

Since the middle character doesn't contribute anything to the sum, \$d\$ for strings with odd length \$l\$ is equal to \$d\$ for strings with length \$l-1\$.

Task

Given string \$s\$ with length > 1 find \$D_p(s)\$

Input

One of the following:

  • a string;
  • a list of characters;
  • a list of numbers.

Output

An integer - the palindrome distance of the input string.

Test cases

"aa" -> 0
"bab" -> 0
"abca" -> 1
"cbade" -> 6
"hello" -> 21
"code-golf" -> 45
"neveroddoreven" -> 0
"Neveroddoreven" -> 224

Winning criteria

The shortest code in bytes in every language wins.

| |
\$\endgroup\$
  • \$\begingroup\$ Hmm.. Seems to be an "implement this formula" challenge, which doesn't give much room for interesting optimizations. \$\endgroup\$ – Beefster yesterday
  • \$\begingroup\$ @Beefster I have given the formula for clarity only. You might be right, but I still hope that different languages would allow for different solving opportunities. \$\endgroup\$ – Galen Ivanov yesterday
  • 1
    \$\begingroup\$ This seems relatively fine to me, given that the way one chooses to iterate over the palindrome should add enough heterogeneity. However, I think the square root is rather pointless in this scenario. Separately, you can use \left and \right to make brackets the correct size. \$\endgroup\$ – FryAmTheEggman 12 hours ago
  • \$\begingroup\$ @FryAmTheEggman Thank you, I was wondering about the square root myself too. I'll remove it. Thanks for the advice on brackets. \$\endgroup\$ – Galen Ivanov 11 hours ago
0
\$\begingroup\$

Write a compiler/interpreter for ...

Inspired by the lisp challenge here.
It is a series of puzzles.

I don't like to see a simple eval solution, so:

  • interpreting the language is fine
  • translating the language to a different language is fine.

I think this is specific for each language.

Only the syntax and the basic commands.
Also specific.

Winning criteria should not be code golf.
The goal should be that you can "learn" an other language by looking at the code.

Languages that might be good candidates:

  • Lisp
  • APL
  • J
  • Brainfuck (already posted)
  • Whitespace
  • Forth
| |
\$\endgroup\$
  • 1
    \$\begingroup\$ This only works for languages which are small and well defined. BF fits those criteria. Whitespace does too. The others may not. Lisp and Forth have so many dialects that you would have to specify exactly which dialect to support; Lisp, Forth, APL and J might have too many built-ins to fit in an answer: there are character limits. \$\endgroup\$ – Peter Taylor May 12 '13 at 15:16
  • \$\begingroup\$ You don't have to provide all the built-ins, but that is why it is here. \$\endgroup\$ – Johannes Kuhn May 12 '13 at 15:38
  • \$\begingroup\$ What defines the "basic commands"? \$\endgroup\$ – ASCIIThenANSI Aug 31 '15 at 17:54
  • \$\begingroup\$ I don't know? Maybe that you can do the basic stuff with it like +,-,print,... \$\endgroup\$ – Johannes Kuhn Aug 31 '15 at 18:22
  • 1
    \$\begingroup\$ I suggest a programmer can implement the tiniest subset of those languages in order to be Turing-complete, as these are non-trivial subsets that can theoretically simulate the rest of the language... \$\endgroup\$ – user85052 Jun 28 '19 at 4:17
  • \$\begingroup\$ Which human is learning the programming language by looking at the code? \$\endgroup\$ – MilkyWay90 Aug 26 '19 at 3:23
0
\$\begingroup\$

Find Maximum number of 4+ letter words from Scabble Tiles

The challenge is to find the most words with 4 or more letters you can make with one set of scrabble tiles.

The tile distribution is as follows:

2 Blank Tiles
A 9  N 6    +====+===========+
B 2  O 8    | 01 | K J X Q Z |
C 2  P 2    | 02 | B C M P F |
D 4  Q 1    | 02 | H V W Y * |
E 12 R 6    | 03 | G         |
F 2  S 4    | 04 | L S U D   |
G 3  T 6    | 06 | N R T     |
H 2  U 4    | 08 | O         |
I 9  V 2    | 09 | A I       |
J 1  W 2    | 12 | E         |
K 1  X 1    +====+===========+
L 4  Y 2
M 2  Z 1

Valid words are any words that are 4+ that are available in this file, the official scrabble dictionary.

Tiles cannot be used twice. This means you can only have 1 word with a K, J, X, Q, and/or Z unless you use a blank tile to represent one of these letters.

I'm not sure how I'd do scoring on this. I want shorter code to score better, but I don't want a short piece of code that finds a lot less words to score better than a longer piece that finds many more words.

| |
\$\endgroup\$
  • \$\begingroup\$ Meh. I don't like dependency on external files; are we allowed to load it, or even embed it into the source code? \$\endgroup\$ – John Dvorak Dec 17 '13 at 20:00
  • \$\begingroup\$ as for finding more vs. shorter code, you could demand all words be found \$\endgroup\$ – John Dvorak Dec 17 '13 at 20:19
  • \$\begingroup\$ @JanDvorak Any way to use it. It's a text version of the official scrabble dictionary, it seemed to be the most fitting word list for the task. "All words being found" might be hard, considering there are probably many combinations of words that would deplete all the tiles. It's a maximum of 25 words, (25 words, 4 letters each, 100 tiles), but I don't know if it's possible to use all tiles with just 4 letter words. After so many words, you might not have enough tiles to make an actual word, which means you'd either have to go back or accept that you're not using all the tiles. \$\endgroup\$ – Rob Dec 17 '13 at 20:23
  • 5
    \$\begingroup\$ As currently described, this is a no-input task, which means that the answer can be precomputed and then the program only needs to decompress it. Consider rewriting it to take input (either of the word list or of the tiles available). \$\endgroup\$ – Peter Taylor Dec 18 '13 at 8:01
  • \$\begingroup\$ I suggest taking a list of tiles as input, loading the list of words from a predefined file and requiring all combinations / best combination to be found. Of course, if the input is the full list of tiles, the computation is going to take ages. I might allow preprocessing the word list outside the program itself (up to a certain point; a linearithmic growth?) \$\endgroup\$ – John Dvorak Dec 18 '13 at 8:32
  • 1
    \$\begingroup\$ I suggest modifying this so that input is a list of tiles, limited to a full rack or less (therefore 4-7 tiles, since our minimum word length is 4). Input should be assumed to be valid based on the standard set of tiles (e.g.: it wont' have something like 3 J's or 4 G's). This would have some practical use for a player in a scrabble game to figure out their next move (though it does not take into account tiles available to them which are already on the board). \$\endgroup\$ – Iszi Dec 18 '13 at 21:14
  • \$\begingroup\$ Alternative mode: Input is a list of tiles, maximum 96 (so that at least 4 are remaining in the set). Output only includes words (minimum 4 letters) which can be created without those tiles. This would be interesting as it provides words that may yet be created (though, again, not taking into account usable tiles on the board) at a given point in the game. \$\endgroup\$ – Iszi Dec 18 '13 at 21:15
  • \$\begingroup\$ Output needs to be decided as either a list of all possible words, or only the highest-scoring word(s). Another enhancement may be to require that the list be sorted descending in order of score (if output is all words), then ascending alphabetically. There's no reason to take each program's output into account for scoring. Since everyone is expected to use the same dictionary, all programs' outputs should be identical (except perhaps in sorting, if that's left out of the spec). So, this should be Code Golf. \$\endgroup\$ – Iszi Dec 18 '13 at 21:15
  • \$\begingroup\$ It's also worth noting that, as currently written, the task could just be to filter the given dictionary down to words which have 4 or more letters. By its very nature, the Scrabble dictionary should already exclude any words that cannot be made with a Scrabble set. \$\endgroup\$ – Iszi Dec 18 '13 at 21:18
  • \$\begingroup\$ @Iszi it's not "what are all the words you can make", it's "what are all the words you can make, where every letter used depletes a tile". There's a max of 25 words if you can use all 100 tiles. \$\endgroup\$ – Rob Dec 19 '13 at 16:40
  • \$\begingroup\$ I think I misunderstood the problem, then. I thought it was "all the words possible using a set of tiles" not "all the words possible, using only one set of tiles". Still, my point about code golf remains. There is an absolute maximum to the number of words (each with 4 or more letters) you can make with a single Scrabble set, and a finite number of permutations which can be used to hit that maximum. Every program written with this goal should end up with the same (or nominally similar) output. \$\endgroup\$ – Iszi Dec 19 '13 at 16:56
0
\$\begingroup\$

Test for Irreducible Complexity (Check for Redundant Characters)

I may need some additional help coming up with the full spec for this competition. As of right now, this is just a concept.

Many interesting questions, such as the "42" question in this sandbox, involve finding the longest program which is not reducible. This means that no set of characters can be removed and still allow the program to function as desired.

The basic idea is that your program will test a Base Program to make sure that it contains no redundant characters. The input will consist of:

  • Base Program (in the same language as your answer)
  • Expected Output

Your program will simply evaluate all possible subsequences of the Base Program and verify that none of them give the Expected Output.

This challenge actually has a utility value to several other challenges. For example, it verifies the results of a "longest non-reducible"-type challenge. In addition, it could make sure that a golfed solution cannot be golfed further.

I assume that the winning criteria will be fastest program, as cycling through all the possibilities takes a long time.

Problems

A sequence of length N has 2^N subsequences. Even if each evaluation is done very quickly, it might be unfeasible to test any program with more than 20 or so characters in a reasonable amount of time.

| |
\$\endgroup\$
  • \$\begingroup\$ Problem: some subsequences of legitimate answers may be pretty dangerous to the environment. You don't want to eval just everything. \$\endgroup\$ – John Dvorak Dec 23 '13 at 16:59
  • \$\begingroup\$ @JanDvorak Yes that actually is a serious problem. To what extent is it possible to fix that? \$\endgroup\$ – PhiNotPi Dec 23 '13 at 17:04
  • 1
    \$\begingroup\$ Forbidding any program with dangerous subsequences? :-) \$\endgroup\$ – John Dvorak Dec 23 '13 at 17:05
  • 1
    \$\begingroup\$ A more reasonable (but very difficult) solution would be the requirement to implement a sandbox. \$\endgroup\$ – John Dvorak Dec 23 '13 at 17:07
  • \$\begingroup\$ Even without dangerous behavior, the halting problem will be an issue: it's hard to tell whether a shortened program will terminate at all, especially for every conceivable input. \$\endgroup\$ – MvG Jan 7 '14 at 23:49
0
\$\begingroup\$

Popularity Contest: Implementation of a Hash Table

Create a class in some OOP language for a hash table that supports getting, setting, and removing values. You can't use the built in hash table/dictionary/map implementation. Highest votes in one week wins.

A key is any valid string. A value is any valid string, number, or boolean.

Example functionality:

hash.set("key","value");
hash.get("key"); // returns "value"
hash.set("key", 1234);
hash.get("key"); // returns 1234
hash.set("key2",hash.get("key"));
hash.get("key2"); // returns 1234
hash.delete("key");
hash.get("key"); // returns null/undefined/none/etc. or throws an error
hash.get("key2"); // still returns 1234

Definition of a hash table (from Wikipedia):

In computing, a hash table (also hash map) is a data structure used to implement an associative array, a structure that can map keys to values. A hash table uses a hash function to compute an index into an array of buckets or slots, from which the correct value can be found.

The hash table cannot be simply an array that is searched in linear time. It must be an actual hash table that uses a hash function to map the keys to the value.

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ Popularity contest and shortest don't mix. That aside, the spec is too vague. What is a "value"? What assumptions can be made about hashcodes? If the language makes all types nullable, should null be permitted as a key? What should the type be in languages which have co- and contravariance? And for that matter, what qualifies as a "hash table", bearing in mind that people will try to exploit any loophole? \$\endgroup\$ – Peter Taylor Jan 2 '14 at 23:16
  • \$\begingroup\$ @PeterTaylor Thank you for the feedback! Please see my edits, and let me know what you think. Could you meant about co/contravaraince? I looked at the wikipedia article about it but I'm not really sure how that has anything to do with this question. \$\endgroup\$ – hkk Jan 2 '14 at 23:37
  • \$\begingroup\$ I think it's still vulnerable to the loophole of "I have a hashtable with one bucket" (i.e. it's really a list of (key, value) pairs which I traverse in linear time). The thing about variance is to do with static typing of the elements of the map. E.g. in Java Map<String, Integer>'s get method has signature public Integer get(Object); in C#, a Dictionary<string, int>'s Get method has signature public int Get(string). The edited version makes it clear enough that the hashtable isn't expected to be genericised. \$\endgroup\$ – Peter Taylor Jan 3 '14 at 0:08
0
\$\begingroup\$

Wordlist detector

You are to write a program which, given a list of words, constructs a regular expression to match all these words but nothing else. Both your program and the constructed regular expressions are to be as short as possible.

Input and Output

Input comes on standard input and consists of one line giving n, the total number of words, followed by n lines with one word each. The number of words will be less than 1000, the length of each word less than 30. Words will consist only of lower case ASCII letters, i.e. a-z. You may choose to ignore the first line and use EOF instead to end the list.

Output shall be written to standard output. It consists of a single line, giving a POSIX extended regular expression to match these words and no others. Since input for this regex is not restricted to letters only, elements like . or [^…] won't make too much sense, which limits the language in a natural way. You may choose whether you want to terminate the line with a newline or not. Programs may choose to print multiple lines of output, in which case only the last one will be used for scoring. So you might print intermediate results and continue searching for improvements.

Test cases

Each submission may be accompanied by one regular expression. When scoring the submissions, I'll use this regular expression to reconstruct a word list from it. The code to do this reconstruction can be found at the end of this post. The reconstructed word list must fit the input specification above in terms of word count and length. It would be nice if your own program would be able to regenerate that regular expression from the word list, but that is not a strict requirement. But please don't paste bogus programs just to submit a challenging regular expression, though.

These test cases will be collected and fed to all programs for scoring.

Scoring

The final score of each program will be the program size plus the size of all its generated regular expressions for the inputs collected from submitted answers, including the example from this question. So short code which produces too long results might get beaten by longer code which generates shorter expressions.

Does this still qualify as ?

Submissions which generate an incorrect regular expression for one of the test cases will be disqualified, as will those which don't terminate in the allotted time. You can use the input reconstruction program below to check whether a produced regular expression does encode the correct word list.

Requirements

All submissions are welcome, but in order to include your submission in the tournament, it must be executable with reasonable effort on my Linux machine. It shouldn't depend on any exotic libraries, or any specialized ones which take too much work away from your own program. It must operate in reasonable time, say no more than five minutes per input. Your output must be reproducible, so if you use randomization at some point, please seed the randomizer, and please don't terminate an improove loop by a timer measuring execution time or some such.

Tournament times

I'll run the first major tournament two weeks after posting this question. I'll include a table of the results in this question. I'll try to run tournaments repeatedly as late submissions arrive, but I'll not promise any regular schedule.

Example

An very simple example application would be in Python 3 (53 chars):

print('|'.join(input() for i in range(int(input()))))

And here is a test case which could be posted along with the program, although this program obviously doesn't generate exactly this concise output:

bann?ana|ap(fel|ple)|s[ou]n|[hs](a|ou)nd

The expansion of that expression could be turned into the following example input, which need not be posted as part of an answer since it can be deduced from the regular expression:

10
banana
bannana
apfel
apple
son
sun
hand
hound
sand
sound

Regex expander program

And here is a program to turn regular expressions into word lists, again written in Python 3.

#!/bin/env python3
concat = set(('',))
altin = set(('',))
altout = set()
prev = None
stack = []
regex = iter(input())
for ch in regex:
    if ch == '(':
        stack.append((concat, altin, altout))
        altin = concat
        altout = set()
        prev = None
    elif ch == ')':
        concat.update(altout)
        prev, altin, altout = stack.pop()
    elif ch == '|':
        altout.update(concat)
        concat = altin
    elif ch == '[':
        ch = regex.__next__()
        cls = []
        while ch != ']':
            if ch == '-':
                crange = range(ord(cls[-1]), ord(regex.__next__()) + 1)
                cls.extend(map(chr, crange))
            else:
                cls.append(ch)
            ch = regex.__next__()
        prev = concat
        concat = set(w + c for w in prev for c in cls)
    elif ch == '?':
        concat.update(prev)
        prev = None
    elif ch >= 'a' and ch <= 'z':
        prev = concat
        concat = set(w + ch for w in prev)
    else:
        raise Exception("Illegal input")
if stack:
    raise Exception("Unclosed group")
concat.update(altout)
words = sorted(concat)
print(len(words))
print('\n'.join(words))

This is restricted to the part of regular expression syntax which I expect for this answer. If you have good reason to use something I did not consider, feel free to do so although I will likely have to update this code to cope with it. If you find a bug, please let me know.

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ This is just Meta regex golf under the constraint that the two lists between them cover all possible words. Given that some people are tackling that existing question on that basis, this would qualify for closing as a duplicate. \$\endgroup\$ – Peter Taylor Jan 8 '14 at 8:45
0
\$\begingroup\$

Code-Golf: Write a number as an expression that's as short as possible

The goal of this code-golf is to create a program that takes a number as input (using STDIN, command line arguments, or prompting for input), and outputs that number, but written as an expression that's as short as possible. So, 10000 should become 10^4. If there is no way to write an expression that's shorter than the number, then output just the number.

Other rules

  1. No network access.
  2. You're not allowed to execute an external program.
  3. Only use the operators +, -, *, / and ^ (that's raising power, not XOR).
  4. Order of operations must be taken in account. Use parentheses if necessary.
  5. This is a code golf, so the code with the smallest amount of characters wins.
  6. The input will always be smaller than 2^32.

Test cases

500000000   -->    5*10^8     or    10^9/2
999999      -->    10^6-1
10          -->    10
4294967295  -->    2^32-1
16384       -->    2^14
| |
\$\endgroup\$
0
\$\begingroup\$

Rhymalator

(at the point, it's just something that came to me before i wake up, so it may need some adjusting, and i'd like some feedback as to if this could be fun)


The code challenge is to write a program that takes as input a calculation in Reverse Polish Notation and outputs the result. It must at least implement + - * /. It So far so easy, but to make it fun and "artistic", the following restriction applies:

  • The source code must rhyme when read. Example in PHP

    $iterator = str_split($a);
    foreach ($iterator as $key=>$value){
        if ($key > 3){
            ++$virtue;
        }
    }
    

    (the rhyme is on value-virtue)

  • Lines whitout readable characters count as whitespace (the two lines with } in the example)

| |
\$\endgroup\$
  • \$\begingroup\$ How does that example rhyme...? \$\endgroup\$ – Doorknob Jan 25 '14 at 12:54
  • \$\begingroup\$ @DoorknobofSnow well, i'm not really a poet, that's why i propose it as a challenge for others :p. if you have a better example i'll replace it \$\endgroup\$ – Einacio Jan 27 '14 at 15:58
0
\$\begingroup\$

Implement Kalah

The game of Kalah is a two-player board game in the Mancala family. Your implementation must:

  • Identify the active player ("Player 1" or "Player 2")
  • Display board state (in format specified below)
  • Accept input to allow that player to move (using index system below)
  • Announce a winner ("Player N wins")

Overview

Each player has a line of six spaces, called houses, and one additional space called a store. Each space holds seeds, which move from house to house in a counter-clockwise direction. The objective is to fill your store with seeds.

You must represent the board in the following two-row format with stores offset, where HH is a house and SS is a store:

SS HH HH HH HH HH HH
   HH HH HH HH HH HH SS

The top row represents the number of seeds in player #1's spaces, and the bottom row represents the seeds in player #2's spaces. The S in each row is the respective player's store (player #1's is top-left, #2's is bottom right). Single-digit values should include a leading space.

In this challenge, user-input will identify each house numerically. Use a left-to-right, indexed-from-one scheme for both sides:

S 1 2 3 4 5 6
  1 2 3 4 5 6 S

Note that the players' stores are not numbered, because seeds placed in the store never move out.

Rules

Wikipedia has a good summary of the game and its rules:

  1. At the beginning of the game, three seeds are placed in each house.

  2. Each player controls the six houses and their seeds on his/her side of the board. His/her score is the number of seeds in the store to his/her right. [Clarification: from our perspective, player 1's store is to the left, player 2's store is to the right.]

  3. Players take turns sowing their seeds. On a turn, the player removes all seeds from one of the houses under his/her control. Moving counter-clockwise, the player drops one seed in each house in turn, including the player's own store but not his/her opponent's.

  4. If the last sown seed lands in the player's store, the player gets an additional move. There is no limit on the number of moves a player can make in his/her turn.

  5. If the last sown seed lands in an empty house owned by the player, and the opposite house contains seeds, both the last seed and the opposite seeds are captured and placed into the player's store. [Clarification: moves that end on an opponent's empty house end normally without a capture.]

  6. When one player no longer has any seeds in any of his/her houses, the game ends. The other player moves all remaining seeds to his/her store, and the player with the most seeds in his/her store wins.

Example

(Parenthetical text should not appear in actual output.)

Player 1
 0  3  3  3  3  3  3
    3  3  3  3  3  3  0
> 2                      (prompt arrow and line break
                          are purely optional)
 Player 2
 1  1  0  3  3  3  3
    4  3  3  3  3  3  0
> 4

Player 2  (P2 gets a bonus turn from rule #4)
 1  0  3  3  3  3  3
    4  3  3  0  4  4  1
> 5

Player 1  
 1  0  3  3  3  4  4
    4  3  3  0  0  5  2
> 4

Player 1  (P1 captures P2's seeds in space 1)
 6  0  4  4  0  4  4
    0  3  3  0  0  5  2
...

Player 2
12  0  0 10  0  1  0
    0  0  0  0  0  1 13
 > 6

Player 1 wins            (because the non-finishing players gets
                          all remaining seeds on their side, it's 23-14)

Meta question: Would this be improved by removing some of the rules?

| |
\$\endgroup\$
  • \$\begingroup\$ Do the players run the game once and then take it in turns to take moves, with the process ending only when the game ends? Or do they run the program once per move? \$\endgroup\$ – Peter Taylor Jan 30 '14 at 10:06
0
\$\begingroup\$

[This is the first time I'm using the sandbox. I want to get feedback/suggestions before posting the question.]

Make a spider web (standard, orb type) that fills frame in the ratio of n:m, where n, m are input integers. You may use the example below as a model (but you don't need to use labels).

spider web

Your web should have multiple radii, at least 4 of which attach directly to the frame. The remaining radii should attach to the outer outline (perimeter) of the web. The web should have at least 15 radii. The mesh spacing should be more or less uniform spacing (although occasional weaving mistakes" or crossings are encouraged and will receive a bonus).

This is code-golf, so the shortest code (minus bonuses) wins.


Bonuses (to be removed from the number of characters in your code). Bonuses are awarded for the following features that reflect the architecture of an actual web (as opposed to a perfectly symmetric rendering). They are somewhat greater than usual as an incentive for attention to detail and realism.

-mesh spiral instead of concentric circles: 40 pts

-assymmetric web: 31 pts. (e.g. height of capture area greater than width)

-irregularly spaced radii: 42 pts

-distinct segments between radii (straight or crooked, but not the arc of a circle): 32 pts

-outer and inner outline clearly distinct from the spiral: 41 pts

-irregular outer outline: 20 pts

-2 or more easily observable reverses in spiral: 40

The accept will be awarded on Feb. 20, 2014.

| |
\$\endgroup\$
  • \$\begingroup\$ If there are bonuses then it isn't code-golf, by definition. It's not clear what output formats are acceptable. I'm not sure what you mean by "distinct segments between radii". "2 or more easily observable reverses" seems problematic: the ease of observing reverses is subjective, and might in addition depend on input and/or on the random numbers obtained. The weighting for the bonuses seems very arbitrary: is there any justification for it? \$\endgroup\$ – Peter Taylor Feb 3 '14 at 11:49
  • \$\begingroup\$ Re: bonuses, I should probably decide on the features I want included in the web, thereby eliminating bonuses altogether. Distinct segments means that there should be 2 straight mesh segments between radius n and radius n+2 (not sure whether this should be required in instructions to be updated.) Will give reverses more thought. \$\endgroup\$ – DavidC Feb 3 '14 at 12:02
0
\$\begingroup\$

Write a PHP Code Golfer

Since my currently daily programming is in PHP, I tend to try the challenges on the site using that language, but frequently I large program because of the verbosity of the language. And then I have to strip it for presentation...

But this is not a tips question, it's an eviscerating challenge.

The objective is to write a program in the language of your choice that takes a PHP file and outputs a golfed valid PHP file with the same functionality.

The scoring will be the average reduction in percent of the result of running the program with 3 selected files (not yet selected, I was thinking of some open source library)

The output file should run on at least 5.4 (so shorthand arrays, function dereference, traits are available)

Since the score is the difference between the ungolfed and golfed files, techniques beyond minifying are encouraged, such as using code subtitution, eval, compression, $$ (variable variables), dereferencing...


Scoring example: The 3 sources have 450, 1200 and 3500 chars respectively

Answer 1
results lenghts: 250, 1000, 3300
reduction: 200, 200, 200 (44%, 17%, 6%) average: 22%

Answer 2
results lenghts: 350, 1050, 3150
reduction: 100, 150, 350 (22%, 13%, 10%) average: 15%

In this case Answer 1 would win, even tough both answers got the same total reduction (-600 chars)

| |
\$\endgroup\$
  • \$\begingroup\$ It's a specialisation of codegolf.stackexchange.com/q/3652/194 , so would likely be closed as a duplicate. \$\endgroup\$ – Peter Taylor Feb 4 '14 at 22:44
  • \$\begingroup\$ @PeterTaylor I saw it. is similar, but I include an objetive goal and score. have any idea on how to make it more unique? \$\endgroup\$ – Einacio Feb 5 '14 at 2:43
  • \$\begingroup\$ "Making it shorter" is too broad, can I just delete some comments? If not, can I only shorten one variable and it's ok. It's not very interesting like this... \$\endgroup\$ – Fabinout Feb 5 '14 at 9:56
  • \$\begingroup\$ @Fabinout the objective is golfing the code. If you only remove some characters, I doubt you'll get a good score \$\endgroup\$ – Einacio Feb 5 '14 at 15:27
  • \$\begingroup\$ Alright, the criterion is the size of the output source code. good clarification. \$\endgroup\$ – Fabinout Feb 5 '14 at 15:55
  • \$\begingroup\$ Sum the bytes with the percents or separately? Also, no matter what sources you choose, make sure to paste the code into your questions; who knows when the code in the library will change? \$\endgroup\$ – Justin Feb 6 '14 at 19:11
  • \$\begingroup\$ i'll edit the bit about scoring (with examples) tomorrow (when i come back to work). I'll post the test sources as a pastebin, but I'll wait to choose them until the question is polished enough and someone consider it interesting enough \$\endgroup\$ – Einacio Feb 6 '14 at 19:34
  • \$\begingroup\$ Is there anyone more with questions? is still possible that it will be marked as a duplicate? or can i choose the sources and publish it? \$\endgroup\$ – Einacio Feb 13 '14 at 19:22
0
\$\begingroup\$

Create diagonal code

Your task is to create a program that outputs d=s*sqrt(2).

Specs:

  • Your program must be at least 4 lines long;

  • d=s*sqrt(2) cannot be hardcoded as is (so using ascii, compression, encoding, etc. is allowed and encouraged);

  • For each line of code n, pick up the nth character. The string obtained this way must be a valid program in a programming language of your choice, that must be different from the one you used for the main program. The obtained program must compile successfully, but it can throw errors, exceptions, etc.;

  • If at the nth line there is no nth character, you can consider that character as a whitespace or a newline. This cannot be done for the first 4 lines, which must be long at least n non-whitespace characters.

  • Your main program must end successfully (no errors, exceptions, etc.);

  • Internet access is forbidden;

  • Most upvoted answer in 2 weeks wins.

Happy coding!


I was unsure about making this a with several bonuses (polyglot answer, secondary program still valid, etc...).


Some bonuses for the code-challenge version:

Your valid answer starts with 0 points. You gain:

+10 if the secondary answer hides a third answer in it;
+15 for any other hidden answer;
+5 for every hidden answer that runs and ends successfully, without any problem;
+10 if your main answer is a polyglot;
+15 for every hidden answer that is a polyglot;


Which version would you prefer? Is there something you would change/improve in this question?

I personally like the one, but the KISS principle (Keep it simple, stupid!) reminds me that I may be wrong.

| |
\$\endgroup\$
  • \$\begingroup\$ It's trivial to make the diagonal program be just whitespace (many scripting languages will accept this as a program) or H (valid program in H9Q+). \$\endgroup\$ – Peter Taylor Feb 26 '14 at 9:26
  • \$\begingroup\$ Nowhere does it say that the diagonal program must output your magic string: it doesn't even have to execute correctly. Your amendment doesn't really fix things: I can now have the second line be #H, the third be #HH, etc. \$\endgroup\$ – Peter Taylor Feb 26 '14 at 9:37
  • \$\begingroup\$ You're right; Don't know why, on a second read I messed up the meaning of your comment. Anyway, I suppose this excludes code-challenge unless I/we don't find a way to avoid such trivial solutions. I guess popularity-contest would still be ok, since more interesting solutions could be found, right? \$\endgroup\$ – Vereos Feb 26 '14 at 9:41
  • \$\begingroup\$ I think my views on popularity-contest in general are well known. On further reflection, there are enough languages in which any string of bytes is a valid program that I don't think this question can work as is. If you want to save it, I think you need to look at doing something like a very difficult double-quine. \$\endgroup\$ – Peter Taylor Feb 26 '14 at 9:49
  • \$\begingroup\$ Thinking about quines and diagonals (which was the "spirit" of the question), what about a sort of mini-quine? The main program would have to display d=s*sqrt(2) only, and its diagonal must reproduce the code used to display the magic string (no comments allowed). It could be tagged code-golf or code-challenge. \$\endgroup\$ – Vereos Feb 26 '14 at 11:04
0
\$\begingroup\$

Create a Karnaugh-map calculator

Given an input of a truth table, generate a corresponding K-map.

Input:

Input will be of the form 10110001 where each bit is a row of a truth table. Count from the left to the right; so that input would be a table of:

i2i1i0 f
0 0 0|1
0 0 1|0
0 1 0|1
0 1 1|1
1 0 0|0
1 0 1|0
1 1 0|0
1 1 1|1

Max 4 variables will be inputted

K-maps (a small explanation):

K-maps are a way of simplifying boolean-algebra expressions.

Let's say we have 4 variables: a, b, c, d. Let the truth-table be 1110101001111111 (and the columns on the truth table be labeled, from left to right: a, b, c, d). Arrange the variables like so:

   cd
ab\   00 01 11 10
   00
   01
   11
   10

Note the grey-code counting scheme.

Fill in the table with the corresponding values from the truth table:

   cd
ab\   00 01 11 10
   00 1  1  0  1
   01 1  0  0  1
   11 0  1  1  1
   10 1  1  1  1

Group the values in rectangles whose dimensions are the largest possible powers of two. Note that this table signifies a torus, so wrap over the left and right edges.

enter image description here

The expression for the truth table is the ors of the and of the unchanging elements. For this, that would be:

Purple group: ¬b ∧ ¬c (for 0's, make them 1 by notting the value)
Green group: ¬a ∧ ¬d
Black group: a ∧ d
Blue group: b ∧ ¬d

Expression: (¬b ∧ ¬c) ∨ (¬a ∧ ¬d) ∨ (a ∧ d) ∨ (b ∧ ¬d)

Output:

  • Generate a 2D K-map (for more variables, add on either side) and show the grouping. K-map must be of the form I used. For less variables, remove rows or columns and change the list on the top left corner.
  • assume alphabetical ordering on the variables, that is, the first variable is a, second: b, third: c, and so on.
  • Also show the expression. Rather than use the unicode characters, the following is permissible:

    ~ instead of ¬
    * instead of ∧
    + instead of ∨
    


Edit: Possible duplicate: More fun with gates: Karnaugh simplification

| |
\$\endgroup\$
  • \$\begingroup\$ I think the grouping is not unique and therefore I might choose the most basic grouping (i.e. none). \$\endgroup\$ – Howard Feb 26 '14 at 9:02
  • 1
    \$\begingroup\$ Although @Howard's concern is partially answered by "rectangles whose dimensions are the largest possible powers of two", it's not obvious to me why you haven't also circled the entire row 10 and the bottom-right quadrant. \$\endgroup\$ – Peter Taylor Feb 26 '14 at 9:29
  • \$\begingroup\$ @PeterTaylor You're right - didn't read that line. But still my main concern is correct: it is not unique. Or as your remark shows it is not optimal if you choose all rectangles. \$\endgroup\$ – Howard Feb 26 '14 at 9:33
  • \$\begingroup\$ Also for higher number of variables you have to either go to n dimensional K-maps or you won't find all possible rectangles (they are no longer adjacent in the matrix). \$\endgroup\$ – Howard Feb 26 '14 at 9:38
  • \$\begingroup\$ @PeterTaylor In priority: Biggest rectangles, then least number. That is a big rectangle, but it is redundant with the others because every 1 in it is already circled. \$\endgroup\$ – Justin Feb 26 '14 at 16:44
  • \$\begingroup\$ @Howard Good point. I'll restrict it to 4 or less variables. \$\endgroup\$ – Justin Feb 26 '14 at 16:47
  • \$\begingroup\$ For the expression: rather than using A and V, why not * and +? That's fairly conventional use of field notation to represent GF(2). \$\endgroup\$ – Peter Taylor Feb 26 '14 at 17:11
  • \$\begingroup\$ Ahem. OR is, of course, not the same as + in GF(2). But * and + is still the conventional notation for operations over the Boolean semiring. \$\endgroup\$ – Peter Taylor Feb 28 '14 at 15:31
0
\$\begingroup\$

Title: Implement ROT-13... in ROT-13

Content:

Challenge: Implement ROT-13 in code that works as both itself and as the ROT-13 version of itself.

Scoring:

Your score is calculated as a percentage of used, ROT-13 eligible bytes in total of both versions of the program divided by total bytes (all characters) of both versions.

A used, ROT-13 eligible byte is any character that is not part of a comment or ignored by the compiler/interpreter. For example, any character in a brainfuck program that is not +-<>[],. is not considered a used byte, and any character in a C program including and after // or inside /* */ is not considered a used byte. All special symbols in APL are not considered used, as are all characters in a Whitespace program (sorry).

Example scoring:

C: 21/32 = 65.625%

main(){printf("Hello World!");}
| |
\$\endgroup\$
  • \$\begingroup\$ Originally this question was ROT-47, not ROT-13. The rules are chosen so that choice of language doesn't easily determine the winner; otherwise, whitespace would easily win. When I changed it to ROT-13 I made only [A-Za-z] count so that a language like golfscript or brainfuck would not automatically score 100%. Looking for thoughts on how to capture the idea without making it too "choice of language" dependent. \$\endgroup\$ – durron597 Mar 3 '14 at 21:13
  • \$\begingroup\$ Just saying, I have a C answer for the 47-version: qp.mniip.com/p/tz pick either of the lines \$\endgroup\$ – mniip Mar 3 '14 at 21:29
  • \$\begingroup\$ @mniip Okay I undeleted it :) \$\endgroup\$ – durron597 Mar 3 '14 at 21:48
0
\$\begingroup\$

Convert input to ASCII Semaphore

With monitor resolutions getting higher and font sizes getting lower, a good programmer has to make efforts to ensure that output is accessible to the visually impaired. This can be problematic when the only display is in text. Toward this end, your assignment (if you choose to accept it) is to write a program that converts text input into ASCII art flag semaphore.

Input

  1. Your program must accept any letter in the ASCII character set from A to Z (case insensitive) and spaces.
  2. The program can accept input in any way that is convenient for the language it is written in (stdin, command line, file, etc.).

Output

  1. The program should output an ASCII art representation of the input string in flag semaphore. Follow this link to see the expected encoding.
  2. Line feeds and carriage returns should be interpreted as spaces.
  3. Numbers and other non-letters in the input may be ignored.
  4. You may use whatever ASCII art representation of the semaphore sender you like, but it must contain a person holding two flags and have distinct arms, legs, head, and flags. It must be at least 10x10 characters.
  5. Output may be either horizontal or vertical.

Example

Input: Hello

Output:

           ###
           ###
            #
 _____########
|  |       ###
|__|      ####
         # ###
        #  ###
       /   # #
      /\   # #
     /  \  # #
     \  /  # #
      \/  ## ##
                    /\
                   /  \
                  /\  /
                 #  \/
           ###  #
           ### #
            # #
          ####
         # ###
         # ###
         # ###
         # ###
         | # #
         |__ #
         |  |#
         |__|#
          ## ##
                    /\
                   /  \
                  /\  /
                 #  \/
           ###  #
           ### #
            # #
           ###
          ####
         # ###
        #  ###
       #   ###
      /    # #
     /\    # #
    /  \   # #
    \  /   # #
     \/   ## ##
                    /\
                   /  \
                  /\  /
                 #  \/
           ###  #
           ### #
            # #
           ###
          ####
         # ###
        #  ###
       #   ###
      /    # #
     /\    # #
    /  \   # #
    \  /   # #
     \/   ## ##
   /\
  /  \
  \  /\
   \/  #
        #  ###
         # ###
          # #
 _____########
|  |       ###
|__|       ###
           ###
           ###
           # #
           # #
           # #
           # #
          ## ##

Scoring

This is code golf. Shortest code wins.

| |
\$\endgroup\$
  • \$\begingroup\$ define "easily recognisable". Would a simple 3x3 compass (say, with a head if not covered) do? say:.o. -|. /|. ; or even: ... xx. x.. (read by lines, dots represent spaces) \$\endgroup\$ – John Dvorak Mar 6 '14 at 20:16
  • \$\begingroup\$ @JanDvorak Good catch. Edited to include distinct items that must be present and a minimum size. I'm not exactly sure how to make that rule more clear. \$\endgroup\$ – Comintern Mar 6 '14 at 20:34
  • \$\begingroup\$ Define "person holding two flags". Is what I drew a person? Is this a (lying, due to formatting issues) person: o--? Are three x's on a vertical line a person? \$\endgroup\$ – John Dvorak Mar 6 '14 at 20:43
  • \$\begingroup\$ @JanDvorak Ack! had to many tabs open and forgot to save my edit. I think number 4 for output should cover that. \$\endgroup\$ – Comintern Mar 6 '14 at 20:47
  • \$\begingroup\$ Define "distinct arms, legs, head, and flags." But I suggest allowing very small figures as well, otherwise this will turn into a kolmogorov-complexity-like question with very little of the code actually involving generating a pair of directions. \$\endgroup\$ – John Dvorak Mar 6 '14 at 20:51
  • 2
    \$\begingroup\$ Very similar to this question. The ascii art is more complex here so perhaps it's not close enough to be called a duplicate... \$\endgroup\$ – Gareth Mar 6 '14 at 22:20
  • 2
    \$\begingroup\$ I disagree with @JanDvorak: I think this would be better with a fixed output spec which must be followed exactly. That way people can golf their code rather than the output. \$\endgroup\$ – Peter Taylor Mar 6 '14 at 23:59
  • \$\begingroup\$ Standard figures seem best to me as well. If you demonstrate a full "clock" of hand positions for the standard figure, then you can require those as output. That's easier to assess than free reign for variations. \$\endgroup\$ – Jonathan Van Matre Mar 7 '14 at 0:14
0
\$\begingroup\$

With its strange choice of 9 different characters (plus space and newline), the ASCII art version of the FreeBSD logo has always looked to me as if it might be nicely formatted, obfuscated code is some programming language. (Is it?)

 ```                        `
s` `.....---.......--.```   -/
+o   .--`         /y:`      +.
 yo`:.            :o      `+-
  y/               -/`   -o/
 .-                  ::/sy+:.
 /                     `--  /
`:                          :`
`:                          :`
 /                          /
 .-                        -.
  --                      -.
   `:`                  `:`
     .--             `--.
        .---.....----.

Therefore I would like to challenge you to make it one: Either specify minimal changes to an existing programming language or minimal changes to this piece of ASCII art (making the artwork look different or significantly changing the character set used are definitely major changes), so that the logo, as source code generates meaningful output.

This should be a challenge, although I wouldn't mind some way of introducing hard scoring and run this as .

| |
\$\endgroup\$
1
49 50
51
52 53
99

You must log in to answer this question.

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