572
\$\begingroup\$

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

Sandbox FAQ

Posting

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

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

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

Discussion

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

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

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

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

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

Other

Search the sandbox / Browse your pending proposals

The sandbox works best if you sort posts by active.

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

\$\endgroup\$
0

4671 Answers 4671

1
87 88
89
90 91
156
1
\$\begingroup\$

Magical BF: BF code that works in two ways


Meta

  • This is basically a resurrection of this closed challenge but with different scoring. It was closed based on the policy about multipart challenges. I believe the most problematic part (copying parts of solutions) is solved by competing for each task separately. I also believe that this challenge is better served as one than five separate challenges, since there are some general techniques that transfer well across tasks (trust me, I solved all five tasks before posting this) and posting five of these would look spammy and unoriginal. Please leave comments if you think this version is off-topic.
\$\endgroup\$
4
  • \$\begingroup\$ Where does tape head start? \$\endgroup\$
    – l4m2
    Mar 7 at 8:34
  • \$\begingroup\$ Tape head (data pointer) starts at the leftmost cell. \$\endgroup\$
    – Bubbler
    Mar 7 at 8:37
  • \$\begingroup\$ Is "Author" you or the source? \$\endgroup\$
    – l4m2
    Mar 7 at 8:38
  • \$\begingroup\$ Those are my best scores. \$\endgroup\$
    – Bubbler
    Mar 7 at 8:40
1
\$\begingroup\$

Can I Clear The Grid?

\$\endgroup\$
4
  • \$\begingroup\$ Suggest case RGRG in case someone click on non-empty cell \$\endgroup\$
    – l4m2
    Mar 18 at 8:37
  • \$\begingroup\$ Provide link to english version instead? \$\endgroup\$ Mar 18 at 13:29
  • \$\begingroup\$ @Mukundan314 didn't realize there was one; thanks \$\endgroup\$
    – hyper-neutrino Mod
    Mar 18 at 13:57
  • \$\begingroup\$ @l4m2 good suggestion, added \$\endgroup\$
    – hyper-neutrino Mod
    Mar 18 at 13:59
1
\$\begingroup\$

Swingin' Four Operations!

Before, I found this song which has no meaning other than to combine all the consonants and vowels in the English alphabet. This challenge is similar, however, instead of outputting the song, your programs should output a modification which is basically addition, subtraction, multiplication and division tables of small integers up to 12, but presented in a format similar to the song.

Your challenge is to write a program that takes no input and outputs the four operation tables, where the operation inputs (first input from 1 to 10, second input from 1 to 12, both inclusive, 1 omitted for both inputs in the tables for multiplication and division) and output are seperated by spaces, the columns are seperated by commas followed by spaces and the rows are separated by dots followed by new lines. For division, non-integer outputs are rounded off to two decimal places. Each table is separated by two newlines.

The last two columns (11 and 12) don't contain the first parameter of the modification and are only separated by spaces. The required output is in this pastebin.

Rules:

  • You are not allowed to use external resources, such as the internet.
  • You cannot use compression algorithms, such as gzip or bzip2, unless you include the full algorithm in your code.
  • Use any language, shortest code in bytes wins.

\$\endgroup\$
4
  • \$\begingroup\$ Great challenge for writing reusable code and formatting numbers. I've got a few questions: 1) You say that it should output the tables for small integers up to 12. Why are the matrices in the pastebin link 10 by 12? 2) Does 'You are not allowed to use external resources, such as the internet' mean you may not do research (which would be a little weird for answering an online question) or you may not use an API (which is generally not allowed for codegolf)? \$\endgroup\$
    – Cactusroot
    Mar 29 at 18:41
  • \$\begingroup\$ @Cactusroot It does not specify that all of the small integer pairs are outputted. Also, 'You are not allowed to use external resources, such as the internet' means you may not use an API. \$\endgroup\$ Mar 29 at 18:49
  • \$\begingroup\$ Sorry, I added the question. Now I got it, but 'the text in this pastebin' may be a little ambiguous. I believe you can define it precisely as "Any of the four modification tables, where the modification inputs and output are separated by spaces, the columns are separated by commas followed by spaces and the rows are separated by dots followed by new lines, with a trailing separation. The last two columns (11 and 12) don't contain the first parameter of the modification and are only separated by spaces" \$\endgroup\$
    – Cactusroot
    Mar 29 at 18:51
  • \$\begingroup\$ @Cactusroot Edited. \$\endgroup\$ Mar 29 at 18:54
1
\$\begingroup\$
8-bit AVR integer division

Impatience got the better of me

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

Complement of a set of ranges

Consider a shop that exists for a given range of time. At certain times during the shop's existence items can go on sale. These items will be on sale for at least one unit of time.

Challenge

Given such a shop, and the times it has items for sale, find the mutually-exclusive ranges of time when the shop is not selling anything.

Your inputs will be: a two-length array that represents the range of time the shop exists for. An array, where each element is a two-length array that represents a range of time that an item was on sale for.

your output will be: An array, where each element is a two-length array that represents a range of time that no item was on sale for. Where no element's range should overlap another's range.

All values defining a time range will consist of positive integers (or zero).

Example

A shop exists for the time range [0, 10].

An item is put up for sale during the time range [5, 8]. Another item is put up for sale during the time range [2, 3]. Another item is put up for sale during the time range [4, 6].

Thus the shop is selling nothing from time 0 to 2, 3 to 4, and 8 to 10.

Inputs: [0, 10] and [[5, 8], [2, 3], [4, 6]]

Output: [[0, 2], [3, 4], [8, 10]]

Extra info

You may assume that the input time ranges overlap on a common boundary. i.e. items on sale for [1, 3] and [3, 4] is effectively a sale for [1, 4].

No time range (input or output) should span less than one unit of time: i.e. [1, 1] or [7, 7] is not permitted.

In case this seems ambiguous, the input time ranges can be thought of as closed intervals. Whilst the output time ranges can be thought of as open intervals. All the values used are whole numbers, however the ranges they represent are continuous. i.e. the open interval '[1, 2]' which does not contain any integers, still represents a continuous span of time between '1' and '2' (non inclusive on both sides).

Test cases (first array is the time for which the shop exists, second is the times for which items were on sale)


[0, 100] [[3, 7], [2, 5], [17, 54], [99, 100]] -> [[0, 2], [7, 17], [54, 99]]

[7, 20] [[8, 17], [12, 13], [14, 17], [9, 16], [18, 19]] -> [[7, 8], [17, 18], [19, 20]]

[1, 2] [[1, 2]] -> []

\$\endgroup\$
2
  • \$\begingroup\$ “You have written this well” is a compliment. The title should read complement. \$\endgroup\$ Apr 1 at 14:10
  • \$\begingroup\$ @KaiBurghardt Thanks. That explains why I'm always spelling implement incorrectly (impliment). \$\endgroup\$ Apr 2 at 13:45
1
\$\begingroup\$

Odds for second smallest prime factor

\$\endgroup\$
1
\$\begingroup\$
\$\endgroup\$
3
  • 1
    \$\begingroup\$ Maybe add test cases with the words title-cased? And even with mOrE eRrAtIc CaPs, unless it's more to the point to guarantee that the input will always be either all-lower, all-upper, or title. \$\endgroup\$ Mar 29 at 19:31
  • 1
    \$\begingroup\$ @UnrelatedString I am not going to do title case. I've considered it and I think it adds to much complexity, plus there are a bunch of cases where I don't even know what's proper, (m'Ubh, M'ubh, or M'Ubh?) And I definitely am not doing erratic caps. \$\endgroup\$
    – Wheat Wizard Mod
    Mar 31 at 19:01
  • \$\begingroup\$ I had assumed that title casing was expected to be handled from the verbiage about matching the case of the second character, but agree that the added complexity would be out of proportion. \$\endgroup\$ Apr 1 at 0:06
1
\$\begingroup\$

Emulate Jelly's tie-scan

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

Is it a cartesian product?

The cartesian product of two multisets \$A\$ and \$B\$ is multiset list of all ordered pairs consisting of an element of \$A\$ and an element of \$B\$. For example, the cartesian product of \$\{1, 2, 7, 1\}\$ and \$\{4, 6\}\$ is \$\{[1,4],[1,6],[2,4],[2,6],[7,4],[7,6],[1,4],[1,6]\}\$, and the order does not matter.

Your challenge is to, given a nonempty multiset of pairs of positive integers in some order, determine whether it is a cartesian product of two lists - that is, there exist two multisets of positive integers such that their cartesian product is that list. The input may contain duplicate pairs, may be in any order and may be a cartesian product of two multisets in more than one way.

This is , shortest wins!

Testcases

Truthy

[[1,1]]
[[1,1],[1,2]]
[[1,1],[1,1],[2,1]]
[[1,4],[1,6],[2,4],[7,4],[7,6],[2,6]]
[[4,7],[4,6],[4,5],[4,4]]
[[1,1],[1,1],[1,2],[1,2],[2,1],[2,1],[2,2],[2,2]]

Falsy

[[1,2],[3,4]]
[[1,2],[2,2],[3,2],[1,3],[2,3]]
[[1,1],[1,1],[1,2],[2,1],[2,2]]
[[1,4],[7,4],[9,6]]
[[6,1],[1,6]]
\$\endgroup\$
8
  • \$\begingroup\$ Without order maybe better called multiset \$\endgroup\$
    – l4m2
    Apr 6 at 8:45
  • \$\begingroup\$ Diff set and multiset, [1,1][1,1][1,2][2,1][2,2] \$\endgroup\$
    – l4m2
    Apr 6 at 8:45
  • \$\begingroup\$ Is this equivalent to the matrix counting appearances of pairs being of rank 1? \$\endgroup\$ Apr 7 at 6:16
  • \$\begingroup\$ Can the input list be empty? Can it be taken as a matrix, counting the number of appearances of each pair? \$\endgroup\$ Apr 7 at 6:16
  • \$\begingroup\$ @CommandMaster I specified "nonempty". Taking it as a matrix seems a bit too different from the input format I have here, so I'll say no on that one. I'm not sure whether it's equivalent to that problem. \$\endgroup\$
    – emanresu A
    Apr 7 at 6:24
  • \$\begingroup\$ @l4m2 I'm trying to keep things somewhat simple, so I'll stick with list. I'll add that testcase \$\endgroup\$
    – emanresu A
    Apr 7 at 6:25
  • \$\begingroup\$ If it's list then [[1,4],[1,6],[2,4],[7,4],[7,6],[2,6]] would be false, [1,2,7]x[4,6] should be [[1,4],[1,6],[2,4],[2,6],[7,4],[7,6]] \$\endgroup\$
    – l4m2
    Apr 7 at 6:31
  • \$\begingroup\$ @l4m2 I guess you're right that changing everything to multiset is the easiest way to show that order doesn't matter, I've also clarified that elements can be repeated. \$\endgroup\$
    – emanresu A
    Apr 7 at 6:35
1
\$\begingroup\$

Bitwise and on 2-adic number

TODO: Explain 2-adic number

E.g. 0b...001001001 * 0b111 = 0b...1111111 = -1, so 0b...001001001 = -1/7.

Given two 2-adic numbers in fraction form, output their bitand result.

Test cases:

1 & 2 => 0
1/3 & 2/3 => 2

  • Should I require decimal support (1/2 = 0b0.1)?
\$\endgroup\$
1
\$\begingroup\$

You're to create a file using a hex editor. Unluckily most of keys on your keyboard are broken. You can:

  • Add a byte you can press at the end of file
  • Add a byte such that, the upper 4 bits hex is a character you can press, and lower 4 bits hex is 0
  • Modify upper/lower 4 bits of a byte hex to a character you can press.

Here, character 0x30-0x39 map char 0-9, and 0x41-0x46, 0x61-0x66 map A-F for hex edit purpose.


Given the set of characters you can press, return all chars you can type in. IO can be integers or chars, and all in [0,255].

Test Cases

  • 3 (space and three) => #03
  • 8A => 8:AHJ\x81\x88\x8A\xA1\xA8\xAA
  • \xBA => \xBA
\$\endgroup\$
1
  • 1
    \$\begingroup\$ I think it would be helpful to have "Given the set of characters you can press, return all chars you can type in." closer to the top, with the "rules" below that. The rules are a bit confusing otherwise until I get further down. \$\endgroup\$
    – mbomb007
    Apr 10 at 18:30
1
\$\begingroup\$

Lost is a 2-D programming language where the start position and direction of the ip are entirely random.

Today we will be writing a Lost program which uses this randomness to simulate a coin flip.

A coin flip can have 3 outcomes:

  • It lands on "heads"
  • It lands on "tails"
  • It lands perfectly balanced on the side

To simulate these outcomes your program should output:

  • "Heads!"
  • "Tails!"
  • "Side?!"

Heads and tails are equally likely while landing on the side is extremely unlikely, so your program should output "Heads!" about as often as it outputs "Tails!", specifically of all the possible start states the number of heads and tails should differ by at most 1. The side is extremely unlikely so of all the possible start conditions exactly 1 should output "Side?!" when run.

No other output should occur, and your program should deterministically halt.

Answers must be in Lost. To simulate all the outputs you should run your program with the -Q flag.

You may assume no input is passed to the program.

This is , so the goal is to minimize the size of your program as measured in bytes.

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

Split cell and duplicate content

Input a strict subset of HTML <table> string representation as defined below. Output parsed table, while any cells who span multiple rows or columns get splitted and duplicated.

Supported HTML Syntax

Table: '<table>' '\n' Row Row* '</table>'
Row: '<tr>' Cell* '</tr>' '\n'
Cell: '<td' (' colspan="' ColSpan '"')? (' rowspan="' RowSpan '"')? '>' Content '</td>'
Colspan: Integer
RowSpan: Integer
Content: /[a-z]+/
Integer: /[1-9][0-9]*/

Notes:

  • Text in quotes 'text' will be provided as-is.
  • Text in slashes /text/ is regular expression
  • ? means optional, zero or one
  • * means any number of repeat, may be zero
  • You may assume the table is well-formed, and is rectangle
  • You may assume the table is non-empty (has at least one cell).

If you cannot read / parse the syntax define, don't worry. Just checkout the testcases which are well explained.

Rules

  • Input is a string with HTML (XHTML) syntax define above
  • Output can be in any reasonable format who represent the 2d string array. If you choose to output a single string (or display on screen, write to file), you may use any delimiter you want. But you need use different delimiters between rows, and between cells in a single row.
  • This question is about , so you are not allowed to input pre-parsed HTML / XML document.
  • This is as usual.

Testcases

Testcase 1: The simple example without colspan, rowspan

Input

<table>
<tr><td>a</td><td>b</td><td>c</td></tr>
<tr><td>x</td><td>y</td><td>z</td></tr>
</table>

Output

[['a', 'b', 'c']
 ['x', 'y', 'z']]

Explain

    1   2   3
  +---+---+---+
1 | a | b | c |
  +---+---+---+
2 | x | y | z |
  +---+---+---+

Testcase 2: An example with colspan

Input:

<table>
<tr><td colspan="2">a</td><td>c</td></tr>
<tr><td>x</td><td colspan="2">y</td></tr>
</table>

Output:

[['a', 'a', 'c'],
 ['x', 'y', 'y']]

Explain:

    1   2   3
  +---+---+---+
1 | a     | c |
  +---+---+---+
2 | x | y     |
  +---+---+---+

Testcase 3: An example with rowspan

Input:

<table>
<tr><td rowspan="2">a</td><td>b</td><td rowspan="2">c</td></tr>
<tr><td>y</td></tr>
</table>

Output:

[['a', 'b', 'c'],
 ['a', 'y', 'c']]

Explain:

    1   2   3
  +---+---+---+
1 | a | b | c |
  +   +---+   +
2 |   | y |   |
  +---+---+---+

Testcase 4: An example with both colspan and rowspan

Input:

<table>
<tr><td colspan="2" rowspan="2">a</td><td>c</td></tr>
<tr><td>z</td></tr>
</table>

Output:

[['a', 'a', 'c'],
 ['a', 'a', 'z']]
    1   2   3
  +---+---+---+
1 | a     | c |
  +       +---+
2 |       | z |
  +---+---+---+

Testcase 5: A complex example

Input:

<table>
<tr><td rowspan="2">a</td><td rowspan="2">b</td><td rowspan="2">c</td><td rowspan="3">d</td></tr>
<tr></tr>
<tr><td colspan="2">e</td><td rowspan="2">g</td></tr>
<tr><td>i</td><td>j</td><td rowspan="2">l</td></tr>
<tr><td colspan="3">m</td></tr>
<tr><td>long</td><td colspan="3" rowspan="2">text</td></tr>
<tr><td>here</td></tr>
</table>

Output:

[['a', 'b', 'c', 'd'],
 ['a', 'b', 'c', 'd'],
 ['e', 'e', 'g', 'd'],
 ['i', 'j', 'g', 'l'],
 ['m', 'm', 'm', 'l'],
 ['long', 'text', 'text', 'text'],
 ['here', 'text', 'text', 'text']]

Explain:

      1    2   3   4
  +------+---+---+---+
1 | a    | b | c | d |
  +      +   +   +   +
2 |      |   |   |   |
  +------+---+---+   +
3 | e        | g |   |
  +------+---+   +---+
4 | i    | j |   | l |
  +------+---+---+   +
5 | m            |   |
  +------+---+---+---+
6 | long | text      |
  +------+           +
7 | here |           |
  +------+---+---+---+
\$\endgroup\$
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\$
8
  • \$\begingroup\$ Problem: some subsequences of legitimate answers may be pretty dangerous to the environment. You don't want to eval just everything. \$\endgroup\$ Dec 23, 2013 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, 2013 at 17:04
  • 1
    \$\begingroup\$ Forbidding any program with dangerous subsequences? :-) \$\endgroup\$ Dec 23, 2013 at 17:05
  • 1
    \$\begingroup\$ A more reasonable (but very difficult) solution would be the requirement to implement a sandbox. \$\endgroup\$ Dec 23, 2013 at 17:07
  • 2
    \$\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, 2014 at 23:49
  • \$\begingroup\$ Are you sure this is possible? The problem of testing if two functions/programs/turing-complete things are equivalent is undecidable - I'm fairly sure it's reasonable easy to constract a brainfuck program that you can't tell if you can remove even a single character. \$\endgroup\$ May 16, 2021 at 4:44
  • \$\begingroup\$ Extending on my previous comment - Let's assume you have a solution to this. Take a brainfuck program you want to test if halts. Let it reduce it, now you have an equivalent irreducible program. Add +. in the end of it, and then try to reduce it again. If the code never halts, that +. is reducible and when you'll run it again it will be removed. Otherwise it's important, so it will be kept. The halting problem is undecidable, therefor this is undecidable. \$\endgroup\$ May 16, 2021 at 4:54
  • \$\begingroup\$ You can also get its undecidablility from that in Unary it will tell you if a given program is minimal, which is known to be undecidable as well \$\endgroup\$ May 16, 2021 at 5:25
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
  • 2
    \$\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\$ Jan 8, 2014 at 8:45
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\$
2
  • \$\begingroup\$ How does that example rhyme...? \$\endgroup\$
    – Doorknob
    Jan 25, 2014 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, 2014 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\$
1
  • \$\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\$ Jan 30, 2014 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\$
2
  • \$\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\$ Feb 3, 2014 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, 2014 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\$
8
  • \$\begingroup\$ It's a specialisation of codegolf.stackexchange.com/q/3652/194 , so would likely be closed as a duplicate. \$\endgroup\$ Feb 4, 2014 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, 2014 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, 2014 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, 2014 at 15:27
  • \$\begingroup\$ Alright, the criterion is the size of the output source code. good clarification. \$\endgroup\$
    – Fabinout
    Feb 5, 2014 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, 2014 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, 2014 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, 2014 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\$
5
  • \$\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\$ Feb 26, 2014 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\$ Feb 26, 2014 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, 2014 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\$ Feb 26, 2014 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, 2014 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\$
8
  • \$\begingroup\$ I think the grouping is not unique and therefore I might choose the most basic grouping (i.e. none). \$\endgroup\$
    – Howard
    Feb 26, 2014 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\$ Feb 26, 2014 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, 2014 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, 2014 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, 2014 at 16:44
  • \$\begingroup\$ @Howard Good point. I'll restrict it to 4 or less variables. \$\endgroup\$
    – Justin
    Feb 26, 2014 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\$ Feb 26, 2014 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\$ Feb 28, 2014 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\$
3
  • \$\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, 2014 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, 2014 at 21:29
  • \$\begingroup\$ @mniip Okay I undeleted it :) \$\endgroup\$
    – durron597
    Mar 3, 2014 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\$
8
  • \$\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\$ Mar 6, 2014 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, 2014 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\$ Mar 6, 2014 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, 2014 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\$ Mar 6, 2014 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, 2014 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\$ Mar 6, 2014 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\$ Mar 7, 2014 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\$
0
\$\begingroup\$

King of the Hill Fighting

In this game, a player controls 5 bots that attack the other players 5 bots. Each bot has life points, and has to reduce the other playres lifepoints to zero. This post is program that tests the controllers. It is in literate haskell.

> import Data.Set as S
> import Data.Map as M

Here is the arena:

    D---G
   /|   |\
  B |   | J
 /|\|   |/|\
A | E---H | L
 \|/|   |\|/
  C |   | K
   \|   |/
    F---I
20  12    4
  16    8   0

Positions are denoted by letters

> data Positions = A | B | C | D | E | F | G | H | I | J | K | L deriving (Show, Read, Eq, Ord)

Each player is presented a map in which their side is the one with A. Here is code that will reflect it so each player sees their own view.

> pairFlip = (\(x, y)->[(x,y), (y,x)])
> reflect = M.fromList $ [(A,L), (B,J), (D,G), (C, K), (E, H), (F, I)] >>= pairFlip

Lines denote connections.

> connections=S.fromList $
>   [(A,B), (A,C), (B,D), (C, F), (E, D), (E, F), (D, G), (E, H), (F, I)]
>   >>= pairFlip
>   >>= (\(x,y)->[(x,y), (reflect ! x, reflect ! y)])
> 
> connected x y=(x, y) `S.member` connections

The numbers below are the number of life points of generation that each bot.

> regen = M.fromList $
>   [ (A, 20), (B, 16), (C, 16), (D, 12), (E, 12), (F, 12)
>   , (G, 8), (H, 8), (I, 8), (J, 4), (K, 4), (L, 0)]
\$\endgroup\$
4
  • \$\begingroup\$ Is there supposed to be a specification hidden in here somewhere? \$\endgroup\$ Mar 14, 2014 at 16:30
  • \$\begingroup\$ @Peter Taylor Just not done yet. \$\endgroup\$ Mar 14, 2014 at 16:44
  • \$\begingroup\$ You won't get lots of answers if it's limited to Haskell. \$\endgroup\$
    – ugoren
    Mar 14, 2014 at 17:57
  • \$\begingroup\$ No no no, the above post is also a program for testing it. I will add in code that can take arbitrary programs and use them. \$\endgroup\$ Mar 14, 2014 at 21:17
0
\$\begingroup\$

Create the perfect CSS reset stylesheet

Your job is to create a CSS reset stylesheet, That is, a stylesheet that you can apply to any HTML file, and the result will look the same in all webbrowsers. Because we all know that cross-browser interoperability is very important these days, and you want to make your website look pixel perfect everywhere.

The rules:

  1. You must be able to throw any valid HTML5 document at it and the result will look the same in the main browsers.
    For simplicity, you can assume that the HTML document does not contain any styles of its own or Javascript that changes anything. Just pure, static HTML that is valid HTML5.
  2. The main browsers are Firefox >= 22, Chrome >= 28 and IE >= 10.
  3. To avoid solutions like *{display:none} (which do indeed make all documents look the same in all browsers, yes) the result must be identical to the document without the stylesheet in one of the browsers.
    In other words, take your browser of choice and make the document look like that in the other browsers.

The winner is the stylesheet that works the best, again, on any HTML file that is valid HTML5 and uses no other styles. I'm not looking at efficiency. If you come up with a 100K stylesheet or one that slows the site down considerably, that doesn't matter, as long as the end result looks good.


That's the question so far. Now I have a bit of a problem with "any HTML5 document"; I know I could provide a test document that people can work with, but then you'll get answers that cater to only that particular test case, and that's not what I want. Not sure how to handle this. Ideas?
Also, I want to include Safari as a main browsers, but as I don't have a Mac, I can't test the results on it. Not sure how to handle that.

\$\endgroup\$
7
  • \$\begingroup\$ necolas.github.io/normalize.css ? \$\endgroup\$ Mar 14, 2014 at 12:59
  • \$\begingroup\$ @PeterTaylor That breaks rule #3. \$\endgroup\$
    – Mr Lister
    Mar 14, 2014 at 13:05
  • \$\begingroup\$ The result must be identical to the document without the stylesheet in one of the browsers. I assume you have loaded a webpage without a stylesheet before? If you mean that it can have the main stylesheets, and we just need to create a modification stylesheet, you should specify that. \$\endgroup\$
    – user10766
    Mar 14, 2014 at 16:17
  • \$\begingroup\$ @hosch250 What I mean is that I want the document to retain its basic HTML-ness, so it shouldn't look like plain text. Take this fiddle for example; open it in all browsers, and then add CSS to it so that it looks like (your favourite browser) in all other browsers. If the name of such is "modification stylesheet" rather than "reset stylesheet", I apologise. \$\endgroup\$
    – Mr Lister
    Mar 14, 2014 at 19:32
  • \$\begingroup\$ OK, I was thinking about how most HTML pages rely on CSS stylesheets to even be legible. If you took the CSS sheet off any webpage, it would not look the same; in fact, if the HTML wasn't laid out good using accessibility techniques, it wouldn't be legible. \$\endgroup\$
    – user10766
    Mar 14, 2014 at 20:01
  • 2
    \$\begingroup\$ Pixel perfect isn't going to happen because of issues around anti-aliasing: CSS doesn't let you do things like enable ClearType on Safari/OS X or disable it on IE/Win. So the best anyone can do is somehow obtain the default stylesheets for the listed browsers (e.g. iecss.com but updated) and then find a minimal diff. \$\endgroup\$ Mar 14, 2014 at 20:09
  • \$\begingroup\$ Guys, I'm not interested in solutions to the question right now. I want to know if the question is OK! Specifically if I can get away with not posting a testcase like the fiddle above. \$\endgroup\$
    – Mr Lister
    Mar 14, 2014 at 20:38
0
\$\begingroup\$

music theory challenge

Create a program that takes some input in the form of frequency, waveform, and duration that generates an audio stream based on the input.

You can take input parameters however you choose, but if I input (translated to your method) 440Hz, sin(x), 3 seconds, your program should play or create a file for a sound 3 seconds long at 440 hertz on a sine wave.

Also, any output should be musically correct as far as frequency is concerned. See http://www.phy.mtu.edu/~suits/notefreqs.html for example frequencies

Since this is a popularity contest, the rest is up to you. I bid you Good programming!

Oh, and any use of external functions or APIs is ok, as long as they weren't developed specifically for this contest.

\$\endgroup\$
4
  • \$\begingroup\$ If the program takes "input in the form of frequency, waveform and duration" then where do linear functions fit? What do you mean "output should be musically correct as far as frequency is concerned" given that the input is frequency? Is it supposed to correct the input: "You said 494Hz but you must mean 493.88Hz"? And simple synth has been done before in various guises: see music. To differentiate this and make it non-trivial you could perhaps specify a set of basic synth operations which need to be configurable (e.g. input specifies generators, envelopes, filters, mixers). \$\endgroup\$ Mar 14, 2014 at 8:39
  • \$\begingroup\$ On second thoughts, that would probably work better as a Code Review Code Challenge \$\endgroup\$ Mar 14, 2014 at 9:23
  • \$\begingroup\$ @PeterTaylor I didn't even know about Code Review Code Challenges <intrigued>. Linear isn't the right word...and I think that statement is redundant anyway, so I'll nix it. \$\endgroup\$ Mar 14, 2014 at 12:44
  • \$\begingroup\$ Actually, I'm going to re-write this challenge...I don't know yet whether it'll be here of on CR \$\endgroup\$ Mar 14, 2014 at 13:07
0
\$\begingroup\$

Calculate pi using a unique method

Your task is to calculate or approximate pi using the most interesting method you know. Well-known things such as using inverse trig functions (asin, acos, atan) or commonly used convergent series are considered uninteresting.

You may calculate pi to any precision desired, but the more precision you can achieve, the better.

\$\endgroup\$
5
  • \$\begingroup\$ I couldn't find an exact duplicate of this, but I'd like to know if this overlaps too strongly with an existing question. \$\endgroup\$ Mar 14, 2014 at 18:51
  • \$\begingroup\$ If you rule out convergent series, what's left? \$\endgroup\$ Mar 14, 2014 at 20:02
  • \$\begingroup\$ @PeterTaylor If someone knows of a convergent series that isn't on Wikipedia, that would make a good answer. I know of an answer that does not use trigonometry or an approximation, but calculates the digits directly. \$\endgroup\$ Mar 14, 2014 at 20:08
  • \$\begingroup\$ Is it in mathworld.wolfram.com/PiFormulas.html ? I've got some ancient code which uses a spigot hypergeometric evaluator to compute pi as 3*F(1/2, 1, 1, 8/5 ; 3/5, 4/3, 5/3 | 2/27), but I would expect that to count as well-known. \$\endgroup\$ Mar 14, 2014 at 20:11
  • \$\begingroup\$ @PeterTaylor I'm familiar with it in layman's terms only, but I don't see it there. It could be related to some of them, but I don't see more than a small resemblance. It isn't original with me, BTW. \$\endgroup\$ Mar 14, 2014 at 20:22
0
\$\begingroup\$

I like trees

...so this is a challenge to make me a tree.

Produce a program called tree which takes a single integer argument, N and draws a randomly-generated tree N levels deep, where level 0 is just the trunk.

  • Your program must produce visibly different results for at least N=0..5
  • The tree ought to not be symmetrical in any axis.
  • The tree should be an image
  • Tree(5) should mostly fill dimensions of at least 200w*250h
  • I should be able to run your tree from a bash prompt, eg. '$ python tree.py 3'

I also accept ferns.

Optionally your tree may be 3d, iterate forever, be colourful, have leaves at level 5, or be lit according to the time of day. However, this is code-golf, so the smallest file wins.

Tags: code-golf

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

Implement multi-line lambdas in Python.

Guido van Rossum said it couldn't be done, prove him wrong. Your solution should allow multi-line anonymous functions, like:

>>> f = multilinelamba("hour", """
...     if hour > 20 or hour < 6:
...         print "Good night"
...     else:
...         print "Hello world"
...     """)
>>> f(10)
... 'Hello world'

Your solution should be as close as possible to the behavior of real def or lambda. The actual syntax doesn't matter. E.g. you may choose to pass the code as a string as above, or you may find a way to avoid it. The implementation is also open, you may for example define a function, write a preprocessor, or edit the python source, but keep in mind that the solution should fit in the answer, so the last option probably won't work.

Your solution must allow arbitrary python code inside, except the following which is optional:

  • recursive use of the multilinelambda "statement" inside of the multilinelambda
  • calling the function recursively, i.e. using f inside the multilinelambda in the above function
  • defining classes and
  • importing modules (these two might be too hard)

You must also be able to use a multilinelambda as a parameter when calling a function.

You get bonus points:

  • If your solution captures outside variables in a closure, like real def does
  • For correct handling of exceptions in the multilinelambda. They should display similarly to when using def, and include line number relative to the file.
  • For allowing default parameters
  • For allowing *args and **kwargs
  • If the solution admits any kind of consistent indentation. Two options must be considered:

    • All lines have a common indentation (like in the example above) that can be stipped away.
    • The first line of the body is given on the same line as the multilinelambda statement. In this case, all the remaining lines must be checked for consistency. It makes a difference whether the first line starts a block or not. Example:

      multilinelambda("x", """print "Hello"
                              print "World" """)
      
      multilinelambda("x, y", """if x > y:
                                     print "case 1" 
                                 else:
                                     print "case 2"
                              """)
      

    In both cases, I may add or remove the same number of spaces to/from each of the lines following multilinelambda.


Any ideas for additional criteria? I personally don't really care much about picking a winner, this is more about tinkering and proving that it can be done. But in any way, more "unit tests" will only benefit the question.

Btw., I asked about this kind of question here on meta.

\$\endgroup\$
1
87 88
89
90 91
156

You must log in to answer this question.

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