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

2871 Answers 2871

1
47 48
49
50 51
96
1
\$\begingroup\$

Posted.

| |
\$\endgroup\$
  • \$\begingroup\$ Duplicate? \$\endgroup\$ – xnor Apr 30 at 4:04
  • \$\begingroup\$ @xnor it's more closely related, as this has the additional source restriction that programs must be a magic square. Also, diagonals don't matter. \$\endgroup\$ – Lyxal Apr 30 at 4:21
  • \$\begingroup\$ @dingledooper here's another example of when source code was required to be a magic square. I think your current scoring method is fine. \$\endgroup\$ – Lyxal Apr 30 at 4:23
  • \$\begingroup\$ Ah, my mistake. I'd suggest using saying other than Magic Square in the title given that the differences are substantial. \$\endgroup\$ – xnor Apr 30 at 4:48
  • \$\begingroup\$ @xnor Ok, I'll think of a better title! \$\endgroup\$ – dingledooper Apr 30 at 4:58
  • \$\begingroup\$ Can I use custom SBCS for the codepoints? Also, I don't see any reason to ban null bytes (and banning it will be banning a random feature in a golfing language). \$\endgroup\$ – Bubbler May 8 at 5:43
  • \$\begingroup\$ @Bubbler Sure, I've edited the question. \$\endgroup\$ – dingledooper May 8 at 6:03
1
\$\begingroup\$

Divide into 2 isosceles triangles

Given the measures of two of the interior angles of a triangle (x and y; the other angle can be easily calculated with 180 - x - y), draw a line segment that cuts this triangle into two isosceles triangles. You need to output the angle measures of both of your triangles.

However, because the base angles are the same, you only need to output the list [apex angle, base angle] of the divided triangles for both of the isosceles triangles. You can output the divided triangles in any order.

An example

Say your input is 100, 60.

Let's take a look at the complete triangle first. The triangle looks approximately like this.

   100

60            20

Now we try to divide one of the angles such that two divided triangles are both isosceles triangles.

       100

(40,20)           20

Now our bottom triangle is an isosceles triangle, since both of the base angles
of the bottom triangle are 20. The angle measures of the bottom triangle
looks approximately like this.

       140
20             20

Now, is the top triangle an isosceles triangle?

    100
          40
40

It is an isosceles triangle, because two of the angle measures are 40.

Therefore, for [100, 60], you need to output [[100, 40], [140, 20]].

Example cases

[20, 40] -> [[140, 20], [120, 40]]
[45, 45] -> [[90, 45], [90, 45]]
[36, 72] -> [[72, 36], [36, 72]]
[108, 36] -> [[108, 36], [36, 72]]
| |
\$\endgroup\$
1
\$\begingroup\$

Complete the landscape

Carcassonne is a tile-based game, where the objective is to construct Roads, Cities and Monasteries, in order to score points. The game works by players taking turns to draw and place tiles to construct a landscape, then claiming roads, cities and monasteries. An example landscape is:

Example Landscape

There are \$19\$ distinct tiles (ignoring rotations), each of which contains at least one feature (Road, City or Monastery):

All tiles

Also, notice that the landscape must be consistent. This means that roads must connect to other roads, city edges must connect to other city edges and fields must connect to fields. Therefore, these tiles are inconsistent:

Inconsistent tiles

To avoid this challenge being about image processing, we can translate each tile into a list containing \$5\$ values, according to this legend:

[North edge, East edge, South edge, West Edge, # of cities]

0: Field
1: Road
2: City

For instance, this tile can be described as [2, 0, 1, 1, 1]. Using this legend, we can describe each tile uniquely, and it's rotations are rotations of the first four elements. The entire grid can be described as a rectangular matrix, with a \$20^\text{th}\$ distinct value for an empty square. Translating the first landscape into this format, we get:

[
 [             [],              [], [1, 1, 0, 0, 0], [1, 1, 2, 1, 1], [0, 1, 0, 1, 0],              [],              []],
 [[1, 0, 1, 0, 0],              [], [0, 0, 0, 0, 0], [2, 0, 2, 0, 2],              [], [0, 2, 2, 2, 1], [0, 0, 0, 2, 1]],
 [[1, 1, 0, 1, 0], [0, 0, 1, 1, 0], [0, 0, 0, 0, 0], [2, 2, 0, 0, 1], [2, 2, 0, 2, 1], [2, 0, 0, 2, 1],              []]
]

using [] to represent an empty square. The complete list of tiles (ignoring rotations) in the same grid as the second image is

[1, 0, 1, 0, 0] [0, 0, 1, 1, 0] [2, 1, 1, 1, 1] [0, 1, 1, 1, 0] [2, 0, 0, 0, 1]
[2, 2, 0, 2, 1] [0, 0, 0, 0, 0] [2, 2, 2, 2, 1] [2, 2, 0, 0, 1] [2, 1, 1, 2, 1]
[2, 2, 0, 0, 2] [0, 0, 1, 0, 0] [2, 0, 1, 1, 1] [2, 1, 1, 0, 1] [0, 2, 0, 2, 1]
[1, 1, 1, 1, 0] [2, 1, 0, 1, 1] [2, 2, 1, 2, 1] [2, 0, 2, 0, 2]

Your task is to take in a rectangular matrix where every element save one is one of the 19 tiles given above. This landscape will be consistent, as defined above. You should take in this input and output the array that would represent the tile(s) which would be able to fill the single empty space in the input matrix, keeping the landscape consistent.

details to be added

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

King+queen vs king checkmate

You are given a chess position, represented either in FEN or as a two-dimensional diagram like this (the example test cases will be using the latter format):

...k....
........
...K....
.....Q..
........
........
........
........

In the examples, K represents the white king, Q represents the white queen, k represents the black king and . represents blank space. You may choose different consistent values instead of these characters. You may also input the diagram as a list of lists or in any other way that is allowed by default for two-dimensional arrays.

It is white's move. The position will always be reachable from the starting position by a sequence of valid moves.

You have to find the minimum number of moves White must do to checkmate Black, assuming perfect play by Black.

Test cases

Incomplete: too many test cases for 1 and no test cases for >1.

...k....
........
...K....
...Q....
........
........
........
........

Output: 1

k.......
........
..K.....
........
........
........
........
.Q......

Output: 1

k.......
..KQ....
........
........
........
........
........
........

Output: 1

| |
\$\endgroup\$
  • \$\begingroup\$ I know it would be a lot different, but have you considered the more general question that allows any (valid) disposition of the three pieces? Then the task would be to find the minimum number of moves to checkmate... Isn't it a bit "tautological" to input a position of which I already know it only takes one move to checkmate? -I most probably know also what this move is- \$\endgroup\$ – Domenico Modica Jun 8 at 16:02
  • \$\begingroup\$ Moreover if it happens to be only 1 move from checkmate (or also, if you want, if the moves can be all determined), with this broader task you could totally ask what this (these) move is (are). \$\endgroup\$ – Domenico Modica Jun 8 at 16:11
  • 1
    \$\begingroup\$ I think asking for the optimal depth to mate in White moves is a better question (far less simple than this, but still much less complicated than a proper chess engine); I'll change the proposal later; it's late here. \$\endgroup\$ – my pronoun is monicareinstate Jun 8 at 16:30
1
\$\begingroup\$

Underfull \hbox (badness 10000)

Every TeX user has been warned many times that their hboxes are terribly underfull or overfull. So much badness! This challenge is to rate how badly underfull or overfull a line of text is for a simplified line wrapper.

Task

You're given a space-separated string or list of words. Output the minimal badness achievable for the first line.

The text needs to be wrapped on a line that's 10 characters wide, but it can only be split on spaces, no in the middle of words. Any letter that spills beyond the width counts for 1000 overfull badness each, and each leftover empty position at the end of the line counts for 1000 underfull badness.

Example

For input "Overfull hbox", we can keep the word "hbox" in the first line for 3000 overfull badness, or wrap it to the second line for 2000 underfull badness which is smaller, so the output is 2000.

0123456789

Overfull hbox
          ^^^
Overfull
hbox    ^^

Note that we don't care about badness of the second line.

Details

The input is a space-separated string or a list of words made of letters a-zA-Z. It won't have any words more than 10 letters long, or be more than 20 characters in total. It won't be empty or have any zero-length words.

Test cases

TODO


Sandbox: Is it OK to have a multiplier of 1000 for theme? Should the underfull and overfull badness penalties be different, like 1000 vs 2000?

| |
\$\endgroup\$
  • \$\begingroup\$ In my opinion, this might be a bit too simple for the big badness theme to be worth it. I feel like most golfing languages might spend nearly half their code multiplying by 1000 (throwing it together in Pyth, I got 1/4 used for multiplying). If it was say, the badness of each of the lines it might feel better. I don't feel terribly strongly about this though. \$\endgroup\$ – FryAmTheEggman Jun 9 at 20:52
  • \$\begingroup\$ @FryAmTheEggman That for the feedback. I'm now thinking the challenge is too simple overall, multiplier or not. What would you think of something like words being able to be broken at certain places in the middle, either explicitly marked or dervied from some property of the letters? \$\endgroup\$ – xnor Jun 9 at 21:14
  • \$\begingroup\$ I think some level of TeX uses hyphens to indicate possible word breaks, but they don't count for the length of words if unused. Adding that may help, while also being on theme? \$\endgroup\$ – FryAmTheEggman Jun 9 at 21:17
1
\$\begingroup\$

Lucky dice rolls

In pen and paper roleplaying games dice are used for various chance calculations. The usual way to describe a roll is \$n\textbf{d}k\$ where \$n\$ is the number of dice and \$k\$ is the number of faces on a die. For example \$3d6\$ means that you need to roll the classical 6-sided die 3 times (or roll 3 dice at the same time). Both \$n\$ and \$k\$ are positive integers.

Usually the values are then summed and they are used for various game mechanics like chance to hit something or damage calculations.

A lucky roll will mean that you have Fortuna's favor on your side (or against you). Luckiness is an integer number that increases (or decreases) the sum in the following way. The roll is modified to \${(n+|luck|)}\textbf{d}{k}\$ and the sum will be the \$n\$ best (or worst) values. Each die is fair, so they will have the same probability for the outcome of the possible values.

The \$luck\$ can be a negative number, in this case you need to get the \$n\$ worst values for the sum.

Input

The integer values for \$n,k,luck\$ in any way.

Output

The expected value for the sum of the (un)lucky roll. The expected value is \$\sum{x_{i} p_{i}}\$ where \$x_{i}\$ is the possible outcome of the sum and \$p_{i}\$ is the probability for \$x_{i}\$ occuring, and \$i\$ indexes all possible outcomes.

Examples

n,k,luck    expected value
1,6,0       3.5
2,6,0       7
2,6,-1      5.541666666666667
2,6,1       8.458333333333334
2,10,-1     8.525
2,10,1      13.475

Scoring

Shortest code in bytes wins.

Good luck! ;)

| |
\$\endgroup\$
  • \$\begingroup\$ Probably worth including a definition of expected value. To what precision should the output be determined? \$\endgroup\$ – Dingus Jun 10 at 12:50
  • \$\begingroup\$ @Dingus Is it now a bit more understandable? \$\endgroup\$ – Gábor Fekete Jun 10 at 13:29
  • 1
    \$\begingroup\$ Yes, that's good, though I'd suggest tweaking the wording a bit: 'The expected value is \$\sum x_ip_i\$ where \$x_i\$ is a possible value for the sum, \$p_i\$ is the probability of that sum occurring, and \$i\$ indexes all possible outcomes.' Perhaps I should rephrase my question about precision - what numeric formats are acceptable for output? Floats are obviously allowed, but do you require a certain number of decimal places? Is it acceptable to output rationals (for languages that support this)? What about 2 integers representing numerator and denominator, respectively? \$\endgroup\$ – Dingus Jun 11 at 12:13
  • \$\begingroup\$ hmm, that's a valid point, but I don't know which one it should be. \$\endgroup\$ – Gábor Fekete Jun 11 at 12:19
1
\$\begingroup\$

Pwning Passwords

Alice decided to improve the security of her website by sending first five characters of an SHA-1 hash to Bob's Leaked Password Detection Service. However, she made two mistakes that let Eve decode the passwords: sending passwords over HTTP and checking the password after each character of a password is typed. Eve asked you for help in decoding the passwords, however she cannot really program, so needs your help in implementing password cracking algorithm as a computer program or function.

Eve eavesdropped the requests for following hashes from Alice.

516B9
379FC
19C2A
9D4E1
08506
F808E
A7F93
5BAA6

How could you decode this password? Well, you can brute-force all lowercase letters. In this case the only letter whose hash starts with 516B9 is p. The hash of letter p is 516B9783FCA517EECBD1D064DA2D165310B19759.

Knowing that the password starts with p, you can brute-force the second character. In this case, the only possible character is a. The hash of pa is 379FC0D5299A71AC0F171FBB5AFB262829B4E765

You can continue to brute-force letters one by one to figure out the password was password (5BAA61E4C9B93F3F0682250B6CF8331B7EE68FD8). Well, that was simple.

Not all passwords are that simple however. Consider the following requests:

4DC7C
A84FD
467D7
BD79D
12D83

First three characters of this password are simple: rxr (467D7856C648A79A096D339A2CE5FC929658967D).

With the fourth character it gets more complicated. BD79D matches for rxrf (BD79DEC8435B8BA509A25F419F31CC2ACDE2FF0A) and rxrp (BD79DC20901B11468F8369B5B0D15894F3D96A5E). There is an ambiguity, but as it turns out, it can be resolved by trying both ways. If you assume the password starts with rxrp there is no valid letters to continue with. However, if you assume the password starts with rxrf, then it's possible to append a, resulting in rxrfa (12D83D3A429CD7D64E9A532C05C2C00C35032A94), which is a valid solution.

All passwords will be composed entirely out of lowercase letters. You can assume all inputs have a solution and there are no inputs that could possibly resolve to multiple passwords (for instance ["4DC7C", "A84FD", "467D7", "BD79D"] is an invalid input because it can match both "rxrf" and "rxrp").

There are no case requirements on the input. Your program is allowed to assume the input is lowercase. Your program is allowed to assume the input is uppercase.

The program must not take longer to execute than 24 hours for a 25 characters long password.

It is allowed to use external libraries or language built-in functions for computation of SHA-1 hash.

Example Input and Output

This is a JSON.

[
  {
    "input": [
      "516B9",
      "379FC",
      "19C2A",
      "9D4E1",
      "08506",
      "F808E",
      "A7F93",
      "5BAA6"
    ],
    "output": "password"
  },
  {
    "input": [
      "07C34",
      "593B7",
      "0262F",
      "CED65",
      "23612",
      "4EF76",
      "B7A87"
    ],
    "output": "letmein"
  },
  {
    "input": [
      "84A51",
      "87DDA",
      "83F67",
      "E6FB0",
      "5157D",
      "82CD7",
      "6F655",
      "43426"
    ],
    "output": "codegolf"
  },
  {
    "input": [
      "7A81A",
      "DB3D4",
      "FE05B",
      "E7280",
      "32726",
      "30AE9",
      "2C61A",
      "A9E46",
      "15D98",
      "F780A",
      "3E949",
      "F4BF2",
      "6A5C4",
      "C4554",
      "FA2EA",
      "48A40",
      "5DD7F",
      "5284E",
      "C0B8D",
      "20D59",
      "9184C",
      "32AD9"
    ],
    "output": "onetwothreefourfivesix"
  },
  {
    "input": [
      "84A51",
      "87DDA",
      "26CA7",
      "9D925",
      "08A23",
      "BE075",
      "3179A",
      "5D904",
      "54C70",
      "47790",
      "5D3B5",
      "0E4CE",
      "004C7",
      "EC8A8",
      "131A6",
      "7F47F",
      "41BC6",
      "FCF07",
      "D62BD",
      "DD14F",
      "6A141",
      "EE184",
      "595F8",
      "9D303",
      "BFD36"
    ],
    "output": "correcthorsebatterystaple"
  },
  {
    "input": [],
    "output": ""
  },
  {
    "input": [
      "4DC7C",
      "A84FD",
      "467D7",
      "BD79D",
      "12D83"
    ],
    "output": "rxrfa"
  },
  {
    "input": [
      "4DC7C",
      "A84FD",
      "467D7",
      "BD79D",
      "7B743"
    ],
    "output": "rxrpa"
  }
]
| |
\$\endgroup\$
  • 1
    \$\begingroup\$ @FryAmTheEggman fixed \$\endgroup\$ – Konrad Borowski Jun 12 at 6:43
  • \$\begingroup\$ I wonder whether MD5 might be preferred over SHA1 - as in, more likely to exist in the language without having to load external libraries? \$\endgroup\$ – streetster Jun 18 at 16:25
  • 1
    \$\begingroup\$ Languages without a hashing builtin or library would have effectively two challenges: implementing the hash and doing the key part of the challenge. There are already challenges for MD5, SHA-1, and SHA-256 e.g. codegolf.stackexchange.com/questions/81195/implement-sha-256. I see two resolutions to this: 1. not count byte count of the hash; or 2. use a simple hash, such as the digits after the decimal point in the square root of the sum of code points \$\endgroup\$ – fireflame241 Jun 18 at 22:19
  • \$\begingroup\$ You could allow a black-box function as input that computes the SHA256 hash to make this more competitive for languages without builtins. \$\endgroup\$ – S.S. Anne Jun 24 at 2:32
1
\$\begingroup\$

Compute the factorial, on both sides of 0

Why, why, why do factorials stop at zero? (Yes there are actual reasons). Make a factorial function (or full program) that doesn't stop at zero!

Your code-golfed program should, given an non-zero integer n (can be positive or negative, the rule still applies), find the product of the range n to -n excluding 0.

Graph that at least works for positive numbers

Sample IO

 Input          | Output
----------------|------------
0               | 1 (product of 0 and -0 without 0 / empty product)
2               | 4 (2*1*-1*-2)
3               | -36 (3*2*1*-1*-2*-3)
4               | 576 (4*3*2*1*-1*-2*-3*-4)
-4              | 576

Probably not a duplicate, but it might not be that much of a challenge.

| |
\$\endgroup\$
  • \$\begingroup\$ Would the input always be positive? Is n=0 a possible input? \$\endgroup\$ – Bubbler Jun 11 at 23:02
  • \$\begingroup\$ @Bubbler For now I'll say 0 is undefined, might change it later before posting if I have a good idea. \$\endgroup\$ – Wezl Jun 12 at 13:53
  • 1
    \$\begingroup\$ As it is, isn't this always the factorial of the absolute value of the input squared, then made negative if the input is odd? - except in the edge case for zero? The sign of the input doesn't really appear to matter, which is an odd feeling. \$\endgroup\$ – FryAmTheEggman Jun 12 at 16:24
  • \$\begingroup\$ @FryAmTheEggman Yes, see this graph of the values. Is that a bad thing? Do you have a better suggestion? \$\endgroup\$ – Wezl Jun 12 at 20:44
  • \$\begingroup\$ "downvotes mean nothing but rudeness" - I downvoted this because I do not think "compute \$|n|!^2 \cdot (-1)^n\$" is a good challenge. I can't see how disagreement is rude. The requirements here seem completely arbitrary to me. This will result in the exact same approaches as were used in the factorial challenge. \$\endgroup\$ – my pronoun is monicareinstate Jun 14 at 8:27
  • 1
    \$\begingroup\$ I think it is a bad thing in that it becomes dangerously close to a dupe of the factorial problem. I probably wouldn't hammer it immediately, but if most of the responses basically worked for both or many others had the same concern I'd probably close it. I'm not sure of a good way to modify this to be better, so unfortunately I don't have any suggestions at the moment. I will let you know if something occurs to me. \$\endgroup\$ – FryAmTheEggman Jun 15 at 20:09
  • \$\begingroup\$ @FryAmTheEggman I wouldn't consider it a dupe but I wouldn't consider it a good question after all based off of what my pronoun is monicareinstate said. \$\endgroup\$ – Wezl Jun 16 at 21:47
  • 1
    \$\begingroup\$ If you consider 0 as a valid input, I suggest that its expected output be 1, which corresponds to the empty product (Wikipedia). \$\endgroup\$ – Bubbler Jun 17 at 3:52
  • \$\begingroup\$ For the interesting-ness, I believe it can be interesting in at least some languages (which IMHO justifies the value of having such a challenge). FWIW, I have two J solutions of equal length, one using the factorial built-in ! and the other not using it. \$\endgroup\$ – Bubbler Jun 17 at 3:53
  • \$\begingroup\$ I'd likewise close this as a duplicate, but I'm known for having much broader standards than the rest of the community about what questions are closeworthy, so make of that what you will. \$\endgroup\$ – pppery Jun 18 at 2:38
  • \$\begingroup\$ I'll just abandon this, but if @Bubbler wants to post it, they can. \$\endgroup\$ – Wezl Jun 18 at 21:17
1
\$\begingroup\$

Iterate diagonally over nxn matrix

Given a matrix of size n, output the matrix into another matrix of size n such that:

  • the outputted matrix, when traversed diagonally,will result in the original matrix.

For example, taking this 3x3 matrix, we arrive at our solution: enter image description here

Which is checked by following the line beginning at 1: enter image description here

Specifications:

  • The matrix will always be square
  • You must output a grid with the same size as you were given (e.g. Not as a triangle)
  • Mark the end of each row with a delimiter such as \n or .

Examples:

Example 1

Input:

1 2 3
4 5 6
7 8 9

Output:

1 3 6
2 5 8
4 7 9

We can check the output by iterating over the array diagonally (follow the arrows for steps 1-5), which will give us the original matrix.

  ↗ ↗ ↗
1 ↗ ↗ ↗
2 ↗ ↗ ↗
3  4 5 

Example 2

Input:

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

Output:

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

We can check this by iterating the array in steps 1-7 which outputs the given array.

  ↗ ↗ ↗ ↗
1 ↗ ↗ ↗ ↗
2 ↗ ↗ ↗ ↗
3 ↗ ↗ ↗ ↗
4  5 6 7

Hint:

Looking at the coordinates, we can see a pattern:

(0,0) -> (0, 1) -> (1, 0) -> (0, 2) -> (1, 1) -> (2, 0) -> (1, 2) -> (2, 1) -> (2,2)
| |
\$\endgroup\$
  • \$\begingroup\$ Do the matrices always consist of one character per cell? \$\endgroup\$ – Trebor Jun 19 at 0:45
  • \$\begingroup\$ they don't have to, but that can be a specification. Thoughts? \$\endgroup\$ – Peter S Jun 19 at 1:20
  • \$\begingroup\$ Perhaps the title could be a bit more descriptive, like "put the contents of a matrix into its antidiagonals". Then you could add a definition of the antidiagonals, and then a description of how you traverse the matrix to get the ordering for the antidiagonalization. \$\endgroup\$ – Giuseppe Jun 19 at 17:42
1
\$\begingroup\$

I am surely the fastest!... asymptotically

Posted.

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

Posted.

| |
\$\endgroup\$
  • \$\begingroup\$ It would ease readability if all of the test cases were in a single code block, with empty lines in between. Then you can add the explanations afterward for cases that really need it. \$\endgroup\$ – fireflame241 Jun 23 at 17:43
  • \$\begingroup\$ Is there a limit to the depth of the tree? \$\endgroup\$ – fireflame241 Jun 23 at 17:44
  • \$\begingroup\$ The problem statement involves a bunch of high-level math terms, which can deter some people. If possible, the challenge would be more approachable if you add an alternate definition, e.g. relating isomorphism to permutations (kinda) of the underlying set. For the explanation of the first case, it would be good to rewrite each line using normal infix notation, e.g. (x+y)+z = x+(y+z) and x+(-x) = 0. \$\endgroup\$ – fireflame241 Jun 23 at 17:49
  • \$\begingroup\$ @fireflame241 I hid the technical details. And could you please explain why I should put a limit to the depth? In what ways does that make the challenge better? ;) \$\endgroup\$ – Trebor Jun 24 at 1:25
  • \$\begingroup\$ I was just wondering. A golfer might be able to optimize for a limit depth of 2, but it's more interesting to have an arbitrary rank \$\endgroup\$ – fireflame241 Jun 24 at 1:29
  • \$\begingroup\$ @fireflame241 After some thoughts, it is clear that every theory can be translated to one that has a limit depth of 2 ;) Also every practically interesting case happens at depth 2. So I think I'll add that. \$\endgroup\$ – Trebor Jun 24 at 1:53
1
\$\begingroup\$

Write an expect program

If you're not already familiar, expect is a Tcl extension that makes it easier to script interactions with programs. It allows you to spawn a process, send lines to it, and wait for expected output before continuing.

Challenge

The aim of this challenge is to write a very simple implementation of expect in as few bytes as possible (code golf). It should parse a script, with commands separated by newlines. Then it should use this script to interact with a program.

Here are the commands for this implementation:

  • spawn <cmd>: spawn a process.
  • write <line>: write a line into the process' input.
  • expect <line>: expect a substring from the process' output. No timeout is necessary, if the line never appears it is OK for the program to hang.
  • print <line>: print something to stdout.

You can assume that only one spawn will be found in the script, and that it will appear before any write or expect. If your language of choice doesn't have the ability to spawn processes, you can write a helper program in a different language that can pipe input and output through your main program. How you do this is left up to you.

Example script:

spawn /bin/bash
write whoami
expect root
write uname -a
expect Linux
print i am root on Linux

Output:

this is Linux

or

spawn /bin/bash
write uname -a
expect Windows
print this is Windows

(no output.)

Restrictions

In order to keep things fresh, the use of the standard expect utility or any libraries that emulate expect functionality (such as pexpect on Python or jest on Node) are not allowed. The idea is that the bulk of the functionality should be written in the program and not handled in a library.

| |
New contributor
nununoisy is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
\$\endgroup\$
  • \$\begingroup\$ Will the script always have 4 commands, namely those 4 in that order? \$\endgroup\$ – Adám Jun 30 at 3:52
  • \$\begingroup\$ While prohibiting the standard expect utility is probably unambiguous, prohibiting expect-like libraries could potentially be problematic because there's no objective way to judge if any given feature is expect-like. I could claim that addition is expect-like, and you'd be hard pressed to counter that. \$\endgroup\$ – Adám Jun 30 at 3:55
  • \$\begingroup\$ The script could have more commands. I will update the examples to reflect that change. As far as the library restrictions, I could remove them - I do see where it could lead to being a problem. Perhaps I could make it more unambiguous by mentioning specific libraries (one that comes to mind is python-pexpect.) \$\endgroup\$ – nununoisy Jun 30 at 16:10
  • \$\begingroup\$ Can we make any assumptions about the order of the commands? \$\endgroup\$ – Adám Jun 30 at 18:06
  • \$\begingroup\$ Yes, I forgot to mention that spawn will come before any command that needs the process. It should be updated now. \$\endgroup\$ – nununoisy Jun 30 at 20:23
1
\$\begingroup\$

Verify Tents and Trees solution

Background

Tents and Trees (try here) is a puzzle played on a square (or rectangular) grid, where the objective is to place tents horizontally or vertically adjacent to each of the trees, so that no two tents touch each other in 8 directions (horizontally, vertically, and diagonally) and the number of tents on each row/column matches the given clues.

Example puzzle and solution

In these examples, trees are T and tents are A.

Puzzle
  2 0 2 0 2 1
2 . T . T . .
1 . . . . T .
1 T . T . . .
2 . . . . . T
1 T . . . . .
0 . . . . . .

Solution
  2 0 2 0 2 1
2 . T A T A .
1 A . . . T .
1 T . T . A .
2 A . A . . T
1 T . . . . A
0 . . . . . .

Challenge

Given a grid with some tents and trees, determine whether the tents are placed correctly. Ignore the number clues in this challenge. In particular, your program should check the following:

  • The number of tents equals the number of trees,
  • The tents do not touch each other in 8 directions, and
  • There is at least one way to associate every tent with an adjacent tree in 4 directions, so that every tree is used exactly once.

If all of the above are satisfied, output a truthy value; otherwise, output a falsy value. You can choose to follow your language's convention of truthy/falsy, or use two distinct values for true/false respectively.

You may take the input in any reasonable way to represent a matrix containing three distinct values to represent a tree, a tent, and an empty space respectively.

Standard rules apply. The shortest code in bytes wins.

Test cases

This uses the same notation as the above example; T for trees, A for tents, and . for empty spaces.

Truthy

T A

A T A
. . T

A T A
T . T
A T A
(note that there are two ways to associate tents with trees)

A . .
T T A
A T T
. . A

. T A .
A . . T
T T . A
. A . .

Falsy

(The number of Ts and As don't match)
T

A

T A T

(Two A's touch each other)
T A T
A . .

A . . A
T T T T
. A A .

(Some T's are not associated with an A)
A T A
T T .
A T A

A . T
T T A
A . .
| |
\$\endgroup\$
1
\$\begingroup\$

Implement 1-dimensional version of Multi-Take

Background

Adám and I were once discussing a way to properly extend some features in Dyalog APL. I came up with the following extension to Take, a function that takes some front or back elements (and an analogous extension to Drop). We agreed that it was a good idea, but it was incredibly hard to come up with a piece of code that imitates the behavior.

While the original proposal operates on multi-dimensional arrays, this challenge's scope is limited to 1D arrays of numbers. Whenever I mention "array", it implies a 1D array.

The Take function

takes two arguments. One is the array A (of length L), and the other is a single integer N (which can be 0, positive, or negative).

The behavior depends on the value of N:

  • If 0 ≤ N ≤ L, takes first N elements of A from the start.
  • If -L ≤ N < 0, takes last -N elements of A from the end.
  • If N > L or N < -L, performs "overtake", appending (for positive N) or prepending (for negative N) zeros until the array's length becomes abs(N).

It can be thought of applying a Boolean mask to an infinitely zero-padded version of A:

For all cases, A = [1, 2, 3, 4, 5]

For N = 3: (positive simple take)
A     :  ... 0 0 1 2 3 4 5 0 0 ...
Mask  :  ... 0 0 1 1 1 0 0 0 0 ...  # Fill 1s from the start of the array
Result:          1 2 3              # Elements at 0 mask are removed from the array

For N = -4: (negative simple take)
A     :  ... 0 0 1 2 3 4 5 0 0 ...
Mask  :  ... 0 0 0 1 1 1 1 0 0 ...  # Fill 1s from the end of the array
Result:            2 3 4 5

For N = 7: (positive overtake)
A     :  ... 0 0 1 2 3 4 5 0 0 0 ...
Mask  :  ... 0 0 1 1 1 1 1 1 1 0 ...  # The mask overflows the input array
Result:          1 2 3 4 5 0 0

For N = -8: (negative overtake)
A     :  ... 0 0 0 0 1 2 3 4 5 0 0 ...
Mask  :  ... 0 1 1 1 1 1 1 1 1 0 0 ...  # The mask is filled from the end,
                                        # overflowing through the start
Result:        0 0 0 1 2 3 4 5

The proposed extension ("Multi-Take")

The extension allows N to be an array of integers [N1, N2, N3, ..., Nn]. It conceptually generates all the masks to apply to A using each of Ni, and combines all of them by logical OR. Then the mask is applied to A in the same sense as above, giving the resulting array (which may have some contiguous middle elements removed, or have padding in both directions).

Because the identity element for OR is 0, empty N gives all-zero mask, resulting in an empty array (which is equivalent to giving a single zero as N).

For all cases, A = [1, 2, 3, 4, 5]

For N = [1, -2]: (removing a contiguous region)
A        :  1 2 3 4 5
Mask (1) :  1 0 0 0 0  # Taking from start
Mask (-2):  0 0 0 1 1  # Taking from end
OR       :  1 0 0 1 1
Result   :  1     4 5  # [1, 4, 5]

For N = [8, -7]: (padding in both direction)
A        :      1 2 3 4 5
Mask (8) :  0 0 1 1 1 1 1 1 1 1  # Overtaking from start
Mask (-7):  1 1 1 1 1 1 1 0 0 0  # Overtaking from end
OR       :  1 1 1 1 1 1 1 1 1 1
Result   :  0 0 1 2 3 4 5 0 0 0  # [0, 0, 1, 2, 3, 4, 5, 0, 0, 0]

For N = [2, 4, 7]: (for multiple values of same sign, some are simply shadowed)
A        :  1 2 3 4 5
Mask (2) :  1 1 0 0 0 0 0
Mask (4) :  1 1 1 1 0 0 0
Mask (7) :  1 1 1 1 1 1 1
OR       :  1 1 1 1 1 1 1  # Same as simply N = 7 or [7]
Result   :  1 2 3 4 5 0 0  # [1, 2, 3, 4, 5, 0, 0]

For N = []: (empty N gives empty result)
A     :  1 2 3 4 5
Mask  :  (None)     # No mask to apply
OR    :  0 0 0 0 0  # Identity element of OR
Result:  (Empty)    # []

Challenge

Implement the extension, i.e. a program or function that takes an array of numbers A and an array of take amounts N, and outputs the modified array using the mechanism described above.

The "array" can be any sequential container type in your language of choice.

You can assume the elements of A are given in any common number type in your language of choice (or, if you're doing string I/O, represented in the most natural format for your language). Your program should be able to handle empty A and A containing zeros or duplicate elements.

Standard rules apply. The shortest code in bytes wins.

Test cases

Coming soon.

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

Find me a Tinder date!

Ah, Tinder... the app that takes the code golf approach to online dating. With just a few well-chosen right swipes and a bit of luck (or a cute puppy), you too could have more matches than /(?!)/.

This is a Tinder dating challenge of a different kind. Given a Tinder version number as input, hook me up with the date on which that version was released. Use this table*:

+-------------+--------------+
| Version no. | Release date |
+-------------+--------------+
|   11.18.0   |  2020-06-18  |
|   11.17.0   |  2020-06-04  |
|   11.16.0   |  2020-05-26  |
|   11.15.0   |  2020-05-11  |
|   11.14.0   |  2020-04-27  |
|   11.13.0   |  2020-04-13  |
|   11.12.0   |  2020-03-27  |
|   11.11.1   |  2020-03-21  |
|   11.11.0   |  2020-03-20  |
|   11.10.4   |  2020-03-06  |
|   11.10.3   |  2020-03-02  |
|   11.10.2   |  2020-02-29  |
|   11.10.1   |  2020-02-28  |
|   11.9.0    |  2020-02-13  |
|   11.8.0    |  2020-01-30  |
|   11.7.2    |  2020-01-24  |
|   11.7.1    |  2020-01-20  |
|   11.7.0    |  2020-01-19  |
|   11.6.1    |  2020-01-04  |
|   11.6.0    |  2019-12-16  |
|   11.5.0    |  2019-12-06  |
|   11.4.0    |  2019-11-22  |
|   11.3.0    |  2019-11-10  |
|   11.2.1    |  2019-11-01  |
|   11.1.1    |  2019-10-16  |
|   11.1.0    |  2019-10-11  |
|   11.0.2    |  2019-10-09  |
|   11.0.1    |  2019-09-27  |
|   11.0.0    |  2019-09-20  |
|   10.20.0   |  2019-09-10  |
|   10.19.1   |  2019-09-03  |
|   10.19.0   |  2019-08-28  |
|   10.18.0   |  2019-08-15  |
|   10.17.0   |  2019-07-24  |
|   10.16.0   |  2019-06-24  |
|   10.15.1   |  2019-06-08  |
|   10.15.0   |  2019-06-05  |
|   10.14.0   |  2019-06-04  |
|   10.13.0   |  2019-05-16  |
|   10.12.1   |  2019-05-02  |
|   10.12.0   |  2019-04-28  |
|   10.11.0   |  2019-04-13  |
|   10.10.1   |  2019-04-10  |
|   10.10.0   |  2019-04-02  |
|   10.9.1    |  2019-03-23  |
|   10.9.0    |  2019-03-18  |
|   10.8.1    |  2019-03-15  |
|   10.8.0    |  2019-03-06  |
|   10.7.0    |  2019-02-16  |
|   10.6.0    |  2019-02-12  |
|   10.5.0    |  2019-01-22  |
|   10.4.1    |  2019-01-08  |
|   10.4.0    |  2018-12-17  |
|   10.3.0    |  2018-11-29  |
|   10.2.1    |  2018-11-20  |
|   10.2.0    |  2018-11-15  |
|   10.1.1    |  2018-11-02  |
|   10.1.0    |  2018-10-31  |
|   10.0.2    |  2018-10-25  |
|   10.0.1    |  2018-10-19  |
|   10.0.0    |  2018-10-17  |
|    9.9.2    |  2018-10-12  |
|    9.9.1    |  2018-10-11  |
|    9.9.0    |  2018-10-09  |
|    9.8.1    |  2018-10-03  |
|    9.8.0    |  2018-09-21  |
|    9.7.2    |  2018-09-14  |
|    9.7.1    |  2018-09-06  |
|    9.7.0    |  2018-08-29  |
|    9.6.1    |  2018-08-23  |
|    9.6.0    |  2018-08-21  |
|    9.5.0    |  2018-08-06  |
|    9.4.1    |  2018-08-03  |
|    9.4.0    |  2018-07-24  |
|    9.3.0    |  2018-06-22  |
|    9.2.0    |  2018-06-11  |
|    9.1.0    |  2018-05-29  |
|    9.0.1    |  2018-05-17  |
|    9.0.0    |  2018-05-14  |
|    8.13.0   |  2018-05-03  |
|    8.12.1   |  2018-04-28  |
|    8.12.0   |  2018-04-26  |
|    8.11.0   |  2018-04-12  |
|    8.10.0   |  2018-04-05  |
|    8.9.0    |  2018-03-15  |
|    8.8.0    |  2018-02-28  |
|    8.7.0    |  2018-02-16  |
|    8.6.0    |  2018-02-05  |
|    8.5.0    |  2018-01-22  |
|    8.4.1    |  2018-01-02  |
|    8.4.0    |  2017-12-15  |
|    8.3.1    |  2017-12-08  |
|    8.3.0    |  2017-11-29  |
|    8.2.0    |  2017-11-03  |
|    8.1.0    |  2017-10-17  |
|    8.0.1    |  2017-10-09  |
|    8.0.0    |  2017-09-25  |
|    7.8.1    |  2017-09-08  |
|    7.8.0    |  2017-09-05  |
|    7.7.2    |  2017-08-23  |
|    7.7.1    |  2017-08-15  |
|    7.7.0    |  2017-08-14  |
|    7.6.1    |  2017-07-24  |
|    7.6.0    |  2017-07-14  |
|    7.5.3    |  2017-06-22  |
|    7.5.2    |  2017-06-09  |
|    7.5.1    |  2017-06-02  |
|    7.5.0    |  2017-05-30  |
|    7.4.1    |  2017-05-17  |
|    7.4.0    |  2017-05-09  |
|    7.3.1    |  2017-04-19  |
|    7.3.0    |  2017-04-13  |
|    7.2.2    |  2017-04-03  |
|    7.2.1    |  2017-04-01  |
|    7.2.0    |  2017-03-30  |
|    7.1.1    |  2017-03-16  |
|    7.1.0    |  2017-03-06  |
|    7.0.1    |  2017-02-19  |
|    7.0.0    |  2017-02-16  |
|    6.9.4    |  2017-02-06  |
|    6.9.3    |  2017-01-27  |
|    6.9.2    |  2017-01-25  |
|    6.9.1    |  2017-01-17  |
|    6.9.0    |  2017-01-12  |
|    6.8.1    |  2017-01-03  |
|    6.8.0    |  2016-12-19  |
|    6.7.0    |  2016-11-30  |
|    6.6.1    |  2016-11-18  |
|    6.6.0    |  2016-11-16  |
|    6.5.0    |  2016-11-07  |
|    6.4.1    |  2016-11-01  |
|    6.4.0    |  2016-10-26  |
|    6.3.2    |  2016-10-19  |
|    6.3.1    |  2016-10-12  |
|    6.3.0    |  2016-10-04  |
|    6.2.0    |  2016-09-27  |
|    6.1.0    |  2016-09-20  |
|    5.5.3    |  2016-09-12  |
|    5.5.2    |  2016-09-08  |
|    5.5.1    |  2016-09-03  |
|    5.5.0    |  2016-08-31  |
|    5.4.1    |  2016-08-25  |
|    5.4.0    |  2016-08-18  |
|    5.3.2    |  2016-07-29  |
|    5.3.1    |  2016-07-21  |
|    5.3.0    |  2016-07-19  |
|    5.2.0    |  2016-06-27  |
|    5.1.1    |  2016-06-07  |
|    5.1.0    |  2016-06-06  |
|    5.0.2    |  2016-05-13  |
|    5.0.1    |  2016-04-29  |
|    5.0.0    |  2016-04-21  |
|    4.8.2    |  2016-03-02  |
|    4.8.1    |  2016-01-30  |
|    4.8.0    |  2016-01-27  |
|    4.7.2    |  2015-12-17  |
|    4.7.1    |  2015-11-13  |
|    4.7.0    |  2015-11-11  |
|    4.6.1    |  2015-09-23  |
|    4.6.0    |  2015-09-04  |
|    4.5.0    |  2015-07-07  |
|    4.4.6    |  2015-05-18  |
|    4.4.5    |  2015-05-12  |
|    4.4.4    |  2015-05-05  |
|    4.4.3    |  2015-04-28  |
|    4.4.1    |  2015-04-16  |
|    4.4.0    |  2015-04-15  |
|    4.3.0    |  2015-03-02  |
|    4.1.4    |  2015-02-13  |
|    4.1.3    |  2015-02-06  |
|    4.1.1    |  2015-02-02  |
|    4.0.9    |  2014-10-09  |
|    4.0.8    |  2014-09-27  |
|    4.0.7    |  2014-09-19  |
|    4.0.6    |  2014-09-18  |
|    4.0.4    |  2014-07-17  |
|    4.0.3    |  2014-06-26  |
|    4.0.2    |  2014-06-17  |
|    4.0.1    |  2014-06-06  |
|    4.0.0    |  2014-06-05  |
|    3.0.4    |  2014-03-12  |
|    3.0.3    |  2014-02-26  |
|    3.0.2    |  2013-12-19  |
|    3.0.1    |  2013-11-28  |
|    3.0.0    |  2013-11-21  |
|    2.2.3    |  2013-11-20  |
|    2.2.2    |  2013-09-25  |
|    2.2.1    |  2013-09-24  |
|    2.2.0    |  2013-09-14  |
|    2.1.1    |  2013-06-07  |
|    2.1.0    |  2013-05-23  |
|    2.0.3    |  2013-04-01  |
|    2.0.2    |  2013-03-29  |
|    2.0.1    |  2013-03-28  |
|    1.1.4    |  2013-02-08  |
|    1.1.3    |  2013-02-06  |
|    1.1.2    |  2013-01-21  |
|    1.1.1    |  2013-01-11  |
|    1.1.0    |  2013-01-08  |
|    1.0.6    |  2012-11-24  |
|    1.0.5    |  2012-11-16  |
|    1.0.4    |  2012-11-06  |
|    1.0.3    |  2012-09-20  |
|    1.0.2    |  2012-08-29  |
|    1.0.1    |  2012-08-15  |
|    1.0.0    |  2012-08-03  |
+-------------+--------------+

*Source, with four modifications to unify the version number format (1.03 -> 1.0.3, 4.3 -> 4.3.0, 4.4 -> 4.4.0, iOS 8.4.0 -> 8.4.0).

Input and output may be in any convenient format. This is : the shortest answer (in bytes) in each language wins.

| |
New contributor
Dingus is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
\$\endgroup\$
  • \$\begingroup\$ haha, I love this. Great challenge! \$\endgroup\$ – Krzysztof Szewczyk 12 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
  • \$\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
47 48
49
50 51
96

You must log in to answer this question.

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