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

2922 Answers 2922

1
23 24
25
26 27
98
2
\$\begingroup\$

The Turing Text Tape

Introduction

Ah, INTERCAL...
As much as I'd like encourage everyone to Try it Online sometime, text output is just painful.
According to the docs it uses the "Turing Text Model". While an... interesting concept, using it is about as much fun as shooting yourself in the foot. And what do we do with a task like this? Automate it.

The Turing Text Model

The characters INTERCAL knows are printed on a circular tape that can only be moved in the positive direction. Printing is done by passing tape head movement commands in an array to the READ OUT statement. Every ASCII character is written on the inside of that tape (The outside has the characters for the input on it, duh). This results in the characters' bytes being on the tape in reverse. Also the tape head moves backwards along the character list, because its positioning is based on the outside of the tape.
The head starts at position 0.

Now the magic starts. I'll be using Truttle1's explanation on how to achieve output.

  1. Set up an array with the output length.
  2. Fill the entries in the array with tape head movement values.
    1. Find the current character's ASCII value in binary
    2. Reverse it and convert back a number n.
    3. Subtract n from the current head postion and modulo by 256 if needed, resulting in a value r
    4. r is the value you need to store in the array
    5. The head is now at position n.
  3. DO READ OUT the array.

PLEASE NOTE

  • Array is pre-initialized with 0, first index is 1
  • INTERCAL uses extended 8-bit ASCII characters, hence the tape length of 256.
  • Between 1/3rd and 1/5th of all lines have to start with PLEASE

Challenge

Given an input string, output a valid INTERCAL program that prints that string and terminates.

Examples

Prints "BUZZ"

DO ,1 <- #4
DO ,1 SUB #1 <- #190
DO ,1 SUB #2 <- #152
DO ,1 SUB #3 <- #336
PLEASE READ OUT ,1
PLEASE GIVE UP

Whitespace is optional. The following prints "FIZZ"

DO,1<-#4DO,1SUB#1<-#158DO,1SUB#2<-#208DO,1SUB#3<-#312PLEASEREADOUT,1PLEASEGIVEUP

(Examples shamelessly stolen from Truttle1's FizzBuzz program from the video.)

You can find an ungolfed reference implementation in python 3 here

Rules

  • No standard loopholes
  • This is , shortest code wins.
  • You can expect input >= 1, ASCII characters only
  • Output optimisation is optional.
  • The program may not throw any errors apart from the RANDOM COMPILER BUG
  • You may not use compiler flags, e.g. to turn off politeness checking

Sandbox stuff

This better not be a duplicate. I didn't find anything though, so it shouldn't be.

  • Is there anything that can be worded better?
  • Are there some edge-cases that need an example?
  • Should I add any rules; if so, which?
| |
\$\endgroup\$
2
\$\begingroup\$

Is this Chessboard Reachable?

The goal of this challenge is to determine, given the state of a chessboard, whether or not that chessboard can actually be reached in the course of standard play. Of course, doing this in general is a rather hard problem, so we'll be simplifying the problem to a set of a few rules which should approximate the "reachability" constraint.

Your input will be a chessboard, specifying what pieces are at what positions on the 8x8 board. At each position, there can be either nothing or a piece. If there is a piece, it is either a pawn, bishop, knight, rook, queen, or king, and it is either white or black. Input can be taken in any reasonable form. Your output should be truthy or falsy, indicating whether all of the below rules are satisfied.

For the below rules, I'll be using standard chess notation to refer to the squares on the board. That is, I'll be referring to squares on the board by their rank (1-8) and their file (a-h), as such

 8........
 7........
 6........
 5........
 4........
 3........
 2........
 1........
  abcdefgh

where the white player starts on ranks 1-2 and the black player starts on ranks 7-8. Obviously, you don't have to use the same notation, and if it's easier for you to take the board input flipped or rotated, that's fine too as long as you specify it in your answer.

For one of the rules, you have to distinguish between white and black squares on the board. The board is layered with a checkerboard pattern, so white squares are always immediately surrounded by black on all four sides, and vice versa. In typical chess, the a1 square is black, but that doesn't really matter for the below criteria.

The Rules

In order for a board to be considered reachable, it must satisfy all of the following rules. This is , so you don't have to tell me which rule an unreachable board violated; all I expect of your output is a "yes" or a "no".

  1. White and black each have exactly one king on the board: no more, no less.

  2. Pawns cannot appear on rank 1 or rank 8.

  3. Each player has a maximum of 16 pieces on the board total. These pieces must be a subset of the following: 2 bishops, 2 rooks, 2 knights, 1 queen, 1 king, and 8 wildcards. The "wildcard" pieces can be any piece they please (since we assume pawns could have been promoted).

  4. For either player, if that player has at least two bishops, and those two bishops cannot have been promoted from pawns (i.e. they must be the "bishops" in rule 3, not the "wildcards"), then that player must have at least one bishop on a white square and at least one bishop on a black square.

  5. All of a player's pawns must be able to reach the square they're occupying. More formally, for each player, there must be an assignment (an injective function) from the set of that player's surviving pawns to the files (a-h) they started on, such that each pawn can reach its current position from its starting position with only forward and forward-diagonal movements.

Pawn Movements

Rule 5 may require some elaboration. Suppose a white pawn is on d5. Then it could have come from the following places (indicated by X)

 8........
 7........
 6........
 5...♙....
 4..XXX...
 3.XXXXX..
 2XXXXXXX.
 1........
  abcdefgh

So it could have started on a2, b2, c2, d2, e2, f2, or g2, but not h2. There must be an assignment of pawns to starting positions such that no two pawns started at the same position and every pawn can reach its current position from where it began. A black pawn follows the same rules but started on rank 7 and moves down rather than up. So a black pawn at the same position could have come from b7, c7, d7, e7, or f7, as follows.

 8........
 7.XXXXX..
 6..XXX...
 5...♟....
 4........
 3........
 2........
 1........
  abcdefgh

Notes

  • Only the rules above apply. Other complexities of a standard game of chess (in particular, castling or en passant) are not part of this problem and should not be considered.
  • This is , so the shortest solution wins.
  • Input can be taken in whatever form is most convenient. Output follows the usual rules, so any two distinct outputs for truthy/falsy are acceptable.
  • This is an oversimplification of the reachability problem in chess. As such, an answer which provably enumerates every chessboard and tests for membership is not correct.

Examples

Reachable chessboards (true):

 8♜♞♝♛♚♝♞♜
 7♟♟♟♟♟♟♟♟
 6........
 5........
 4........
 3........
 2♙♙♙♙♙♙♙♙
 1♖♘♗♕♔♗♘♖
  abcdefgh

 8........
 7........
 6........
 5........
 4........
 3........
 2..♚.....
 1.....♔..
  abcdefgh

 8........
 7.....♚..
 6.♛......
 5...♟....
 4........
 3.....♕..
 2........
 1...♔....
  abcdefgh

 8.....♚..
 7♟♟♟♟♟♟♟♟
 6........
 5........
 4........
 3........
 2♙♙♙♙♙♙♙♙
 1....♔...
  abcdefgh

 8.....♚...
 7♟♟♟♟♟♟♟♟
 6........
 5........
 4........
 3........
 2♙♙♙♙♙♙♙♙
 1....♔...
  abcdefgh

 8........
 7.♚......
 6...♕♕♕♕.
 5..♕....♕
 4..♕..♔.♕
 3.......♕
 2........
 1........
  abcdefgh

 8........
 7...♚.♟.♙
 6.♙.♙..♙.
 5.....♘..
 4.♕..♕♘♗♖
 3.....♘♗♖
 2..♕....♖
 1......♔.
  abcdefgh

 8♜..♛♚♜♜♜
 7♟♟♟♟♟♟..
 6........
 5........
 4........
 3........
 2♙♙♙♙♙♙♙♙
 1♖♘♗♕♔♗♘♖
  abcdefgh

 8♜♞♝♛♚♝♞♜
 7♟♟♟♟♟♟♟♟
 6........
 5........
 4........
 3........
 2♙♙♙♙♙♙♙.
 1♖♗♘♕♔♗♘♖
  abcdefgh

 8♛♛♛♛♛♛.♛
 7........
 6......♚.
 5.♝.♝....
 4.....♟..
 3........
 2..♖♖♖.♔.
 1........
  abcdefgh

 8.....♚..
 7........
 6........
 5........
 4........
 3.♙♙.....
 2..♙♙♙♙♙♙
 1.....♔..
  abcdefgh

 8.....♚..
 7........
 6........
 5........
 4........
 3.....♙..
 2...♙♙♙.♙
 1.....♔..
  abcdefgh

 8.....♚..
 7........
 6.♟♟♟♟...
 5.♟♟.....
 4........
 3........
 2........
 1.....♔..
  abcdefgh

Unreachable chessboards (false):

(Rule 1: Not enough kings)

 8........
 7........
 6........
 5........
 4........
 3........
 2........
 1........
  abcdefgh

(Rule 1: Too many kings)

 8♚♚♚♚♚♚♚♚
 7♚♚♚♚♚♚♚♚
 6♚♚♚♚♚♚♚♚
 5♚♚♚♚♚♚♚♚
 4♚♚♚♚♚♚♚♚
 3........
 2........
 1...♔....
  abcdefgh

(Rule 2: Bad white pawn placement)

 8.....♚..
 7♟♟♟♟♟♟♟♟
 6........
 5........
 4........
 3........
 2.♙♙♙♙♙♙♙
 1♙...♔...
  abcdefgh

(Rule 2: Bad black pawn placement)

 8.♟...♚..
 7♟.♟♟♟♟♟♟
 6........
 5........
 4........
 3........
 2♙♙♙♙♙♙♙♙
 1....♔...
  abcdefgh

(Rule 3: Too many white queens)

 8........
 7.♚......
 6...♕♕♕♕.
 5..♕....♕
 4..♕..♔.♕
 3..♕....♕
 2........
 1........
  abcdefgh

(Rule 3: Too many black pieces)

 8♜♞♝♛♚♝♞♜
 7♟♟♟♟♟♟♟♟
 6......♟.
 5........
 4........
 3........
 2♙♙♙♙♙♙♙♙
 1♖♘♗♕♔♗♘♖
  abcdefgh

(Rule 3: Too many white pieces)

 8........
 7...♚.♙.♙
 6.♙.♙..♙.
 5.....♘..
 4.♕..♕♘♗♖
 3.....♘♗♖
 2..♕....♖
 1......♔.
  abcdefgh

(Rule 3: Too many black rooks)

 8♜..♛♚♜♜♜
 7♟♟♟♟♟♟♟.
 6........
 5........
 4........
 3........
 2♙♙♙♙♙♙♙♙
 1♖♘♗♕♔♗♘♖
  abcdefgh

(Rule 4: White bishops are the same color)

 8♜♞♝♛♚♝♞♜
 7♟♟♟♟♟♟♟♟
 6........
 5........
 4........
 3........
 2♙♙♙♙♙♙♙♙
 1♖♗♘♕♔♗♘♖
  abcdefgh

(Rule 4: Black bishops are the same color)

 8♛♛♛♛♛♛♛♛
 7........
 6......♚.
 5.♝.♝....
 4.....♟..
 3........
 2..♖♖♖.♔.
 1........
  abcdefgh

(Rule 5: White pawn placement is impossible)

 8.....♚..
 7........
 6........
 5........
 4........
 3..♙.....
 2.♙♙♙♙♙♙♙
 1.....♔..
  abcdefgh

(Rule 5: White pawn placement is impossible)

 8.....♚..
 7........
 6........
 5........
 4........
 3.....♙.♙
 2...♙♙♙.♙
 1.....♔..
  abcdefgh

(Rule 5: Black pawn placement is impossible)

 8.....♚..
 7.♟♟♟♟...
 6........
 5.♟♟.....
 4.♟♟.....
 3........
 2........
 1.....♔..
  abcdefgh

Example Implementation (Python 3)

# Takes input from stdin in the form shown above (a grid of Unicode
# chess characters and dots). Prints True if reachable. Prints False
# and the first rule number which is violated if unreachable.

import sys
from collections import defaultdict, namedtuple

Piece = namedtuple('Piece', ['color', 'type'])

# Read in the data from stdin.
data = []
for line in sys.stdin:
    chars = list(filter(lambda x: x in ".♟♙♝♗♞♘♜♖♛♕♚♔", line))
    if chars:
        data.append(chars)
    if len(data) == 8:
        break
assert len(data) == 8
for line in data:
    assert len(line) == 8

# Parse it into a more convenient format.
translation = {
    ".": None,
    "♟": Piece('black', 'pawn'),
    "♙": Piece('white', 'pawn'),
    "♝": Piece('black', 'bishop'),
    "♗": Piece('white', 'bishop'),
    "♞": Piece('black', 'knight'),
    "♘": Piece('white', 'knight'),
    "♜": Piece('black', 'rook'),
    "♖": Piece('white', 'rook'),
    "♛": Piece('black', 'queen'),
    "♕": Piece('white', 'queen'),
    "♚": Piece('black', 'king'),
    "♔": Piece('white', 'king'),
}
for rank in data:
    for i in range(8):
        rank[i] = translation[rank[i]]

# Count the number of each piece that each player has, slotting
# necessary pawn promotions into their own category.
allowed = { 'bishop': 2, 'rook': 2, 'knight': 2, 'king': 999, 'queen': 1, 'pawn': 0 }
pieces = defaultdict(lambda: 0)
for rank in data:
    for piece in rank:
        if piece is None:
            continue
        if pieces[piece] >= allowed[piece.type]:
            # Already have too many; it's a promoted pawn
            pieces[Piece(piece.color, 'pawn')] += 1
        else:
            # Count it normally
            pieces[piece] += 1

# Rule 1: Each color should have exactly one king.
if pieces[Piece('white', 'king')] != 1 or pieces[Piece('black', 'king')] != 1:
    print(False, 1)
    exit(0)

# Rule 2: Pawns cannot appear on rank 1 or rank 8.
for piece in data[0] + data[7]:
    if piece is not None and piece.type == 'pawn':
        print(False, 2)
        exit(0)

# Rule 3: Since we already put any "overflow" pieces at the pawn key,
# we just need to make sure we have at most eight pawns.
for color in ['white', 'black']:
    if pieces[Piece(color, 'pawn')] > 8:
        print(False, 3)
        exit(0)

# Rule 4: If we have both bishops and our pawns are all accounted for,
# then we have to have a bishop in each color.
for color in ['white', 'black']:
    if pieces[Piece(color, 'bishop')] >= 2 and pieces[Piece(color, 'pawn')] >= 8:
        squares = { 'white': False, 'black': False }
        for y, rank in enumerate(data):
            for x, piece in enumerate(rank):
                square_color = 'white' if (x + y) % 2 == 0 else 'black'
                if piece == Piece(color, 'bishop'):
                    squares[square_color] = True
        if not (squares['white'] and squares['black']):
            print(False, 4)
            exit(0)

# Rule 5: All pawns must be able to get to where they are. I solve
# this here by brute force (simply trying every possible permutation),
# which is exponentially inefficient, but it'll do for this example.
def recursive_assign(taken, choices, i):
    if i >= len(choices):
        return True
    current = choices[i]
    for x in current:
        if x not in taken:
            if recursive_assign(taken + [x], choices, i + 1):
                return True
    return False

for color in ['white', 'black']:
    starting_file = 6 if color == 'white' else 1
    choices = []
    for y, rank in enumerate(data):
        for x, piece in enumerate(rank):
            if piece == Piece(color, 'pawn'):
                possibilities = range(8)
                possibilities = filter(lambda i: abs(i - x) <= abs(y - starting_file), possibilities)
                choices.append(list(possibilities))
    if not recursive_assign([], choices, 0):
        print(False, 5)
        exit(0)

print(True)

Proposed Tags

Sandbox Concerns

  • I worry Rules 4 and 5 are still not clear enough. I tried to write them in a way that was as clear as possible while still being mathematically unambiguous.
| |
\$\endgroup\$
  • \$\begingroup\$ too long. try to combine rules or at least don't draw so many of them in a column \$\endgroup\$ – Noone AtAll Aug 4 at 9:06
  • 1
    \$\begingroup\$ If you're going to use unicode chess symbols, use a double-wide filler character instead of .. The alignment in your examples is off, making it very distracting. I'd recommend switching them to ASCII letters using the typical KQRBNP convention. \$\endgroup\$ – Beefster Aug 4 at 16:40
  • 1
    \$\begingroup\$ To add to Beefster's comment, in some fonts the chess symbols are not even double wide, they're somewhere in between. So double-wide fillers won't work either. +1 for ASCII notation. \$\endgroup\$ – Bubbler Aug 4 at 23:43
2
\$\begingroup\$

Stroke Count of a Chinese Numeral

Task

Given an integer \$n\in\left[0,10^{12}\right)\$ in any convenient format, compute the number of strokes needed to write that number in (simplified) Chinese.

Background

Chinese numbers are expressed with a system of digits and places, just like in English, but grouped by powers of 10000 rather than 1000.

At the lowest level, Chinese characters are a collection of strokes, laid out in a certain order and manner. The number of strokes needed to write a certain character is that character's stroke count.

With their English equivalents and stroke count, the (simplified) characters used to write numbers are:

num   char  strokes
0     零*    13
1     一     1
2     二**   2
3     三     3
4     四     5
5     五     4
6     六     4
7     七     2
8     八     2
9     九     2
10    十     2
100   百     6
1000  千     3
10^4  万     3
10^8  亿     3
 * 0 can also be written 〇, but we won't use that here.
** 两 is largely interchangeable with 二, apart from never
   appearing before 十. For simplicity, we won't consider
   it here, but 两 is very common in actual usage.

For example, 987654321 is 九亿八千七百六十五万四千三百二十一: nine hundred-thousand (九 亿), eight thousand seven hundred sixty-five ten-thousand (八千七百六十五 万), four thousand three hundred twenty-one (四千三百二十一). 53 strokes are needed to write this out.

Additionally, there are some special rules involving the digits 0 and 1. These can vary slightly between regional dialects, so we'll choose these:

  • When there are non-trailing 0s in a group of 4 digits, they are combined into a single . No place designation is used.

    (This is because e.g. 一百二 is a common way to say 120. We won't consider that form.)

    • 1020 is 一千二十.
    • 60708 is 六万七百八.
    • 300004005 is 三亿四千五.
    • 0 is 零.
  • If the number would begin with 一十, the is omitted.

    • Powers of 10 are 一, 十, 一百, 一千, 一万, 十万, 一百万, etc.
    • 111 is 一百一十一.

Test Cases

           n  strokes  chinese
           0  13       零
          10  2        十
         236  17       二百三十六
        7041  26       七千零四十一
      100000  5        十万
      860483  42       八十六万零四百八十三
     4941507  52       四百九十四万一千五百零七
    51001924  38       五千一百万一千九百二十四
   105064519  70       一亿零五百零六万四千五百一十九
   300004005  31       三亿四千零五
  1240601851  56       十二亿四千零六十万一千八百五十一
608726402463  79       六千零八十七亿二千六百四十万二千四百六十三

Sandbox notes

How can the organization be improved?

Is anything unclear?

Are there any edge cases I may missed in the test cases, or ambiguities that need explaining?

| |
\$\endgroup\$
  • \$\begingroup\$ Related (not dupe). Stroke count is actually good idea because it avoids the need to hardcode Chinese characters. The description looks clear enough to me. \$\endgroup\$ – Bubbler Aug 5 at 3:11
  • \$\begingroup\$ Might be useful: tio.run/… \$\endgroup\$ – user202729 Aug 5 at 11:45
  • \$\begingroup\$ (to read the test cases) \$\endgroup\$ – user202729 Aug 5 at 11:45
2
\$\begingroup\$

Surround a string with "friendliness pellets"

Input a String and surround it with a ellipse of alternating "friendliness pellets"(0)

Idea originally from Lyxal.

Challenge

Given a single line String of length \$<100\$, print the string with an ellipse of alternating pellets(0) around it. The ellipse must be 11 lines in height.

The first line of the ellipse must have at least 1 pellet.

The middle line of the ellipse must be at least 13 characters long. There must be a padding of one space on each side of the text.

Strings smaller than 9 characters must be padded with spaces equally on both sides to fit the above specification. The right side is allowed to have one extra space if the string is of even length.

The template for the ellipse is as follows:

      00000..... 6 spaces
    0 4 spaces 
  0   2 spaces
 0    1 space
0     no spaces

If the string's length is greater than or equal to 9; the first line must have \$\text{length}-8\$ pellets.

Example Input and Output

Input:

Hello World!

Output:

       0000  
     0      0  
   0          0
  0            0
 0              0
 0 Hello World! 0
 0              0
  0            0
   0          0
     0      0
       0000

Input

0

Output

       0
     0   0  
   0       0
  0         0
 0           0
 0     0     0
 0           0
  0         0
   0       0
     0   0
       0

Input

The quick brown fox

Output

       00000000000 
     0             0  
   0                 0
  0                   0
 0                     0
 0 the quick brown fox 0
 0                     0
  0                   0
   0                 0
     0             0
       00000000000

Input

In this world, it's KILL or BE killed

Output

      00000000000000000000000000000
    0                               0
  0                                   0
 0                                     0
0                                       0
0 In this world, it's KILL or BE killed 0
0                                       0
 0                                     0
  0                                   0
    0                               0
      00000000000000000000000000000

Input

hi there

Output

      0
    0   0
  0       0
 0         0
0           0
0 hi there  0
0           0
 0         0
  0       0
    0   0
      0

Example code

a=[4,2,1,0] # space length to create circle

str=gets.chomp;
l = str.length;
# print first line of pellets
print " "*6
if l<=9 then puts "0" else puts "0"*(l-8) end
    
# initial pattern
for n in a do 
    print " "*n +"0"+" "*(5-n)
    print " " if l<=9
    print " "*(l-8) if l>9
    puts " "*(5-n) +"0"

end
    
# display string with spaces
if l<9 then puts "0"+" "*((11-l)/2).floor + str + " "*((12-l)/2).ceil + "0" else puts "0 #{str} 0" end

#initial pattern but reversed
for n in a.reverse do 
    print " "*n +"0"+" "*(5-n)
    print " " if l<=9
    print " "*(l-8) if l>9
    puts " "*(5-n) +"0"
end
    
# last line(same as first line)
print " "*6
if l<=9 then puts "0" else puts "0"*(l-8) end


| |
New contributor
Raghu Ranganathan is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
\$\endgroup\$
  • \$\begingroup\$ Suggested test case: In this world, it's KILL or BE killed. Also, a reference program would be a good addition. \$\endgroup\$ – Lyxal Aug 5 at 9:11
  • \$\begingroup\$ Done! hysterical Flowey laughter \$\endgroup\$ – Raghu Ranganathan Aug 5 at 10:54
  • \$\begingroup\$ Setting a maximum number of characters would be unambiguous, rather than 'length lesser than your console's width'. \$\endgroup\$ – Dingus Aug 5 at 10:57
  • \$\begingroup\$ I made the threshold to be lesser than 100. \$\endgroup\$ – Raghu Ranganathan Aug 5 at 11:01
  • \$\begingroup\$ This is exactly how I imagined the challenge would look like. Good job! I look forward to seeing you post it when it's time to do so! \$\endgroup\$ – Lyxal Aug 5 at 11:01
  • 1
    \$\begingroup\$ The specific rules that define the ellipses should be described explicitly, not inferred from either the test cases or the example code. For instance, it appears that all ellipses are expected to be 11 lines high, but this is nowhere stated. \$\endgroup\$ – Dingus Aug 5 at 11:23
  • \$\begingroup\$ Ok, I fixed that in the question. \$\endgroup\$ – Raghu Ranganathan Aug 5 at 11:25
  • \$\begingroup\$ (not a problem with the challenge, just a general comment) The circle looks ugly... (you can change the challenge to be "draw an ASCII art of a you circle surrounding something -- with some circle-drawing algorithm or specification -- but I think there's already some similar challenge? Besides, the current version is easier) \$\endgroup\$ – user202729 Aug 5 at 11:38
  • \$\begingroup\$ I'm not sure whether one exists. Bresenham's Algorithm geeksforgeeks.org/bresenhams-circle-drawing-algorithm exists, but I feel like that would be a very different type of question. \$\endgroup\$ – Raghu Ranganathan Aug 5 at 11:45
  • \$\begingroup\$ The ellipse spec is still not detailed enough. It looks like you have set spacing rules for each line - what are they? Is it allowed to make the ellipse wider than the minimum size needed to contain the string? \$\endgroup\$ – Dingus Aug 5 at 13:09
  • 1
    \$\begingroup\$ I added an ellipse template, annd padding rules. \$\endgroup\$ – Raghu Ranganathan Aug 6 at 2:12
  • \$\begingroup\$ Related/dupe. \$\endgroup\$ – Dingus yesterday
  • \$\begingroup\$ Yes, very close, but not exactly the same. \$\endgroup\$ – Raghu Ranganathan 1 hour ago
2
\$\begingroup\$

My smart phone

Introduction

Recently I was trying out one of the more obscure use-cases of a modern smartphone: Calling someone by number. While typing it in, I noticed that some of my phonebook entries were displayed, even though the number I was trying to call was different! After some experiments, I figured out why.

What it does

Every entry in the phone book is examined like this:

  • Split the entry by space into "words".
  • Check every word like so:
    • For every digit in the number...
    • Is the character of the word at the current index on the key with the digit at the current number?
  • If at least one such word exists, display this entry

Challenge

Emulate my smartphone's behaviour!
Take the list of names below and a numeric string as input. The format for the phonebook may be chosen freely. Assume the phone number to always match [0-9]*.

You can expect entries consisting of ASCII characters with values between 32 and 126 (including both). Your program should handle any length of entry and words within, as well as a list of any size.

Output a filtered list.

Use the following phone keyboard:

  1  |  2  |  3   
     | abc | def
-----------------
  4  |  5  |  6   
 ghi | jkl | mno
-----------------
  7  |  8  |  9   
 pqr | tuv | wxy
  s  |     |  z
-----------------
     |  0  |     
     |     |     

Rules

  • This is , shortest code wins
  • No standard loopholes

Phone Book, values comma-seperated.

noodle9, Kevin Cruijssen, Arnauld, RGS, xnor, Bubbler, J42161217, Neil, Third-party 'Chef', fireflame241, Dennis, Martin Ender, Leaky Nun, Lyxal, fireflame241, HighlyRadioactive, Dingus

Test cases

Output: []

Input: 841
Output: []

Input: 532596
Output: []

Input: 53259
Output: [Leaky Nun]

Input: 542
Output: [J42161217]

Input: 27
Output: [Kevin Cruijssen, Arnauld]

Input: 36
Output: [Martin Ender]

Input: 6
Output; [noodle9, Neil, Martin Ender]

Input: 3
Output; [Dennis, Martin Ender, fireflame241, Dingus]

Sandbox questions

This is my first golfing challenge, have mercy :)

  • Is the way the program works clear? I had a lot of trouble formulating this.
  • Are there any rules I have to add?
  • Are there any edge-cases I should add to the test cases?
  • Should I add the * key? (only matches non-digit, non-alphanumeric and non-space characters)
  • Are there any other things I overlooked?

More entry ideas for the phone book are welcome, I'll add them to the test cases when posting.

| |
\$\endgroup\$
  • \$\begingroup\$ I like this idea. Just to make sure I've understood the challenge correctly, given a phone number, are we to find all possible strings that match it within a database of strings? \$\endgroup\$ – Lyxal Jul 24 at 11:45
  • \$\begingroup\$ Not quite. Given a database/list of strings, split these by space into words. Return all database entries that contain a word that matches the number. \$\endgroup\$ – mindoverflow Jul 24 at 13:20
  • \$\begingroup\$ Duplicate? \$\endgroup\$ – fireflame241 Jul 24 at 19:27
  • 1
    \$\begingroup\$ This question only asks return entries consisting of one word, while this asks to check for possibly multiple words per entry and then to return the complete entry. Also, this quesition had unusual and harsh restrictions. This aims to be much more simpler than that, making the puzzle more attractive. While the first reason may be splitting hairs, the second one, combined with the puzzle being ~6 yrs old, is a good reason to post this puzzle, imo. \$\endgroup\$ – mindoverflow Jul 26 at 9:23
  • \$\begingroup\$ Add my name in! \$\endgroup\$ – HighlyRadioactive Aug 2 at 13:44
  • \$\begingroup\$ 'You may only take input in some form of list type, not a string.' Rigid I/O requirements are generally frowned upon. \$\endgroup\$ – Dingus Aug 5 at 1:34
  • \$\begingroup\$ True, no idea why I insisted on that. I'd rather not have this challenge killed because of a probably useless constraint. \$\endgroup\$ – mindoverflow Aug 5 at 12:51
  • \$\begingroup\$ You've probably thought of this, but you could get more names from Users. (I'm chuffed to have already made the cut, by the way!) Is there a mistake in the 34 test case - wouldn't HighlyRadioactive appear under 44? \$\endgroup\$ – Dingus Aug 5 at 13:26
  • \$\begingroup\$ whoops... fixed. I'll add some more people from Users when posting, for the test cases I've just listed some people I see a lot off the top of my head. Also, if you gave some feedback, there's no reason not to put you in there. \$\endgroup\$ – mindoverflow 2 days ago
2
\$\begingroup\$

The Ever-Changing Labyrinth (WIP)

This is a 2-player asymmetric KotH challenge.

  • One player controls the adventurer and must reach the end
  • The other player has the ability to change the maze and tries to keep the adventurer from solving it

Gameplay

At the beginning of the game, the Maze Master creates a \$5 \times 5\$* maze.

Every cell of the maze must always be reachable from every other cell.

The adventurer begins facing east on the northwest corner cell and wins by reaching the southeast corner cell.

The game proceeds in a turn-based fashion, alternating between each player.

  • The adventurer:
    • Observes its surroundings:
      • The wall directly ahead on the current cell is observed
      • If there is no wall directly ahead on the current cell, every wall is observed along each cell ahead in a straight line until a wall obstructs the adventurer's sight
      • The walls on the left and right of the current cell are observed
      • If there is no wall to the left, the wall ahead on the cell to the left can be observed
      • If there is no wall to the right, the wall ahead on the cell to the right can be observed
    • Either moves forward, changes orientation, or waits
  • The maze master, in order:
    • Receives one mana, which can be used to modify the maze
    • Observes the entire maze, including the position and orientation of the adventurer
    • May remove a wall from anywhere in the maze that is not currently visible to the adventurer
    • May add a wall to anywhere in the maze that is not currently visible to the adventurer, provided it does not separate the maze into two unconnected halves.

Illustration of how the adventurer observes the maze: Adventurer vision 1 Adventurer vision 2

The adventurer is facing east and sees all the green cells and walls. The dotted green lines indicate non-walls the adventurer can see.

The cost to modify the maze increases linearly over time. Each edge segment (i.e. slot where a wall can go) of the grid remembers how many times it was added or removed. The first time you add or remove that edge segment, it costs 1 mana, the second time costs 2 mana, the third time costs 3 mana, and so forth. This should make it impossible to trap even the smartest adventurer forever.

The maze master can stockpile an arbitrarily large amount of mana, but can only change two walls per turn (removing one, then adding one)

*Board size might go up or down a size. A 2x2 maze is trivially solvable and provides no opportunities to edit the maze. A 3x3 maze is manageable for human gameplay and is probably too simple for interesting AIs. I suspect 4x4 is still too small. I'm hoping 5x5 strikes a good balance between being big enough for it to be interesting for AIs, but small enough that games can be run quickly and watched turn by turn. 6x6 may be more appropriate, but some preliminary proofing will be needed to determine if this will still be manageable. My best guess is that game duration has an upper bound turn count in \$O(n^4)\$, however, it isn't clear what constants are tied to that.

Coding

  • Both players may retain as much state as they wish for the entire duration of the game.
  • State will not be remembered between games.
  • Players will not be able to access the state of the other player.
  • Players must not use global variables.
  • Each player will receive an isolated RNG state at the beginning of the game. To ensure that all games have the same outcome with a given seed, all non-deterministic behavior must use the provided RNG.
  • Each turn has a time limit of 15ms.

Implementation language will probably be Javascript so that the challenge can be accessed easily without downloading additional language runtimes/compilers.

Scoring

Adventurers compete only with other adventurers, and the same goes for maze masters.

Both roles are scored by the average number of turns it takes for the adventurer to complete the maze over a series of 5 games between each pair of players. If a game lasts for 10,000 turns without the adventurer completing the maze, the score will be 10,000 for that game. If this number turns out to be too small, I reserve the right as the challenge creator to increase it.

The adventurer with the lowest score wins.

The maze master with the highest score wins.

Scores will be updated when a adventurer or maze master is added or updated.


  • Should this be separated into two separate pages when posted?

Ideas I had that might make this more interesting, but also add complexity I'm not sure I want:

  • The maze master has access to 2 portals, each of which can be placed in a wall slot, facing one direction. The portals are linked in space and are indistinguishable from non-walls to the adventurer, adding a sense of disorientation and confusion.
  • To counter this, the adventurer may drop a breadcrumb as part of any turn, which takes place before the action. They are able to observe the count of breadcrumbs for the current cell, and the presence/absence of breadcrumbs on all other visible cells. The adventurer can also choose to eat all breadcrumbs on their current cell.

| |
\$\endgroup\$
  • \$\begingroup\$ Assumes that the maze master will only wait if the adventurer waits, would that always make waiting a bad choice for the adventurer? \$\endgroup\$ – user202729 2 days ago
  • \$\begingroup\$ Does "not visible" mean "not visible at the moment"? \$\endgroup\$ – user202729 2 days ago
  • \$\begingroup\$ Is the "increase over time" by power of 2 or linear? \$\endgroup\$ – user202729 2 days ago
  • \$\begingroup\$ @user202729 waiting is probably never a good idea for the adventurer, yes, and linear. \$\endgroup\$ – Beefster 2 days ago
  • \$\begingroup\$ Would the score of every maze master change whenever an adventurer program is posted, and vice versa? \$\endgroup\$ – user202729 2 days ago
  • \$\begingroup\$ Perhaps "if the game doesn't terminate after X turns then the score will be X", with X large enough such that the optimal adventurer can always achieve a score smaller than X (but small enough so it's practical to compute) \$\endgroup\$ – user202729 2 days ago
  • \$\begingroup\$ Regarding language: if the challenger is implemented in some language that can invoke other programs (such as JavaScript (Node.js)), then it's possible to communicate over standard input/output and let people submit in any language. \$\endgroup\$ – user202729 2 days ago
  • \$\begingroup\$ There should be some time limit for each turn. \$\endgroup\$ – user202729 2 days ago
  • \$\begingroup\$ @user202729 A couple reasons why I probably won't communicate over stdin/stdout: 1. it can be tricky to avoid deadlock; 2. I want the challenge to be accessible to many users without requiring them to download additional language runtimes. \$\endgroup\$ – Beefster yesterday
  • \$\begingroup\$ So the observed information would be [number of free cells to the left, number of free cells to the right, number of free cells in front]? \$\endgroup\$ – user202729 yesterday
  • \$\begingroup\$ "The behavior must be deterministic with a fixed RNG"? (I'm not sure how to phrase this.) \$\endgroup\$ – user202729 yesterday
  • \$\begingroup\$ There exists a maze master algorithm that makes the duration O(n^4) moves regardless of the adventurer algorithm, where n is the side length. \$\endgroup\$ – user202729 yesterday
  • \$\begingroup\$ And I believe that asymptotically it's not possible to do better. \$\endgroup\$ – user202729 yesterday
  • \$\begingroup\$ So the judge program is written in browser JavaScript? \$\endgroup\$ – user202729 16 hours ago
  • \$\begingroup\$ More information: the maze algorithm is to make two long passage from the start to the end, at all point in time at least one of those is open, whenever the adventurer gets close to one end then open the other end and close that end. It can be calculated that the passage length is O(n^2), and the maze master has O(n^2) walls to block/unblock for each round, so the number of rounds is O(n^6) (not n^4). I think the constant factors is pretty small, about 1/2 or 1/4. \$\endgroup\$ – user202729 15 hours ago
1
\$\begingroup\$

I've Got The Key, I've Got The Secret

A cryptography challenge in 2 parts.

Part 1

Implement a pair of programs in any language (the two programs could be in different languages if you wanted) to encode and decode a string of plaintext.

Input and Output

The encoder must take the plaintext (and an optional key) and return an encoded string. The decoder must take the cyphertext (and an optional key) and return the plaintext exactly as it was given to the encoder.

Restrictions

  • The encoding and decoding code must be entirely implemented in the language - no libraries or cryptography functions may be used.
  • The code (encoder+decoder) cannot be longer than 1024 characters.

Part 2

Implement programs (multiple programs per answer, one answer per entrant) which crack your opponents encryption algorithms.

Input

The cyphertext.

Output

The plaintext that generated the ciphertext.

Scoring

I will upvote all answers to part 1 which have working encryption and have obviously made an attempt at golfing their answer.

In order to be eligible to win, an entrant will have to have taken part in both parts of the question. Overall score will be (length of shortest program that cracks your code-(length of encoder+length of decoder)). Highest score wins and winning entrant's entries will be accepted on both questions.

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ The obvious place for this to fall flat on its face is if someone is able to implement AES or something similar within the 1024 character restriction. \$\endgroup\$ – Gareth Jun 13 '12 at 13:06
  • 1
    \$\begingroup\$ Probably better if the methods of the part one programs are disclosed in non-obfuscated language, though with the short length restriction this may not be necessary. \$\endgroup\$ – dmckee --- ex-moderator kitten Jun 13 '12 at 15:23
  • 2
    \$\begingroup\$ Forget AES: RSA is easily doable. That aside, you need to define "crack" in part 2. \$\endgroup\$ – Peter Taylor Jun 13 '12 at 15:35
  • 1
    \$\begingroup\$ Also, it's not clear whether "optional key" means that it's optional to make the algorithm unkeyed (doesn't make much sense, I admit) or optional to supply it, in which case it uses a default key. \$\endgroup\$ – Peter Taylor Jun 13 '12 at 15:42
  • 1
    \$\begingroup\$ @PeterTaylor I just put optional in to leave it up to the implementer whether or not they wanted to have the key input or hard-coded (or use no key). I'd have thought everyone would have the key input into their program, but I didn't want anyone to feel forced into it by the spec. Hmm, if RSA is doable within the character restriction I'll end up with a load of unbreakable codes which would make for a pretty crap part 2. By crack I meant cyphertext goes in, some time later plaintext comes out. Would restricting the character count further help, or is this question beyond help? \$\endgroup\$ – Gareth Jun 13 '12 at 16:05
  • 3
    \$\begingroup\$ On that definition of crack, I can brute force for the length of the decoder plus a few bytes to iterate over all keys of the right length and some heuristics to check plausibility of the plaintext. The brute force cracker might even be shorter than the decoder if the decoder wasn't written in GolfScript... I think this question may be beyond help. \$\endgroup\$ – Peter Taylor Jun 13 '12 at 16:28
  • 3
    \$\begingroup\$ @PeterTaylor Okay, thanks. I like the 'build your own - knock everyone else's down' aspect of this question though. I'll have to find another area where it could apply. \$\endgroup\$ – Gareth Jun 13 '12 at 16:34
  • 2
    \$\begingroup\$ @Gareth I too like the competitive nature of this idea. I'm looking forward to a question with this plan in mind! \$\endgroup\$ – Gaffi Jun 13 '12 at 19:31
  • 1
    \$\begingroup\$ I think it would be better to split this into a "cops" post and a "robbers" post. \$\endgroup\$ – wizzwizz4 Feb 16 '17 at 9:46
  • 1
    \$\begingroup\$ @wizzwizz4 Wow, this is another blast from the past. I think this pre-dates the cops-and-robbers tag. I always seem to be ahead of my time. :-) \$\endgroup\$ – Gareth Feb 16 '17 at 9:49
1
\$\begingroup\$

Countability of Sets of Finite Sets

The aim of this challenge is to code-golf a program which returns an iterator that will iterate over all possible non-empty finite sets of positive integers.

So if running long enough, this iterator should eventually touch on {1}, {2, 5}, {3, 6, 112} (ie none of these should occur "at infinity")

You may choose the order in which you iterate over these sets, but the order must satisfy the following requirement:

Under a particular ordering, if S is the i'th set to be returned by the iterator, then we shall call i the index of set S.

Let a restriction (k,T) be an assertion about a set S that says S has size k and T is a subset of S.

For a given restriction (k,T) and iterator IT, let the restricted iterator be the iterator which takes sets returned by IT and filters out sets that don't satisfy the assertion, iterating only over the ones that do. In other words, if IT iterates over the sequence of all sets, the restricted iterator iterates over the subsequence satisfying (k,T). Now if S is the n'th set returned by the restricted iterator, then we'll call n the restricted index of S with respect to (k,T)

Your ordering must satisfy the property that for any restriction there exists a polynomial P(x) such that for any set satisfying the restriction (with index i and restricted index n), i < P(n)

Note that the following ordering is not acceptable:

{1} {2} {1, 2} {3} {1, 3} {2, 3} {1, 2, 3} {4} {1, 4} {2, 4}...

This is the sequence that comes from counting 1, 2, 3, 4, 5, 6... and listing the set bits in the binary representation of each number.

This is because the restriction (1, {}) satisfies only the sets {1}, {2}, {3}, {4}... whose index i as a function of their restricted index is i=2^(n-1) which is not bounded by any polynomial


Sandbox Questions

The reason for the strange requirement at the end is to disqualify any variants on the most natural ordering which simply counts upwards from 1 and enumerates the set bits in each number. In this ordering, the n'th set of length-one occurs at index 2^n which is non-polynomial.

I posted this problem originally, but didn't think of the obvious solution and so I left out the final restriction. I'd like to re-post it with the extra restriction. But first I'd like to know what people think. Is there a better way I can word that restriction or a more natural restriction I could impose instead?

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ I don't understand the extra restriction, so I can't suggest a rewording, but I can say that it needs one. (In particular: what is k? And what function does T serve? Is it really a parameter of the property?) \$\endgroup\$ – Peter Taylor Jun 18 '12 at 8:25
  • 1
    \$\begingroup\$ I don't understand it either. Maybe a sample of an ordering, satisfying the requirement, and another one, violating it, would help. \$\endgroup\$ – user unknown Jun 18 '12 at 15:31
  • 1
    \$\begingroup\$ I understand the restriction now, although I haven't worked through the full implications. Does allowing T to be non-empty make a significant difference at all? \$\endgroup\$ – Peter Taylor Jun 19 '12 at 6:52
  • 1
    \$\begingroup\$ I don't know. It may not. I guess the size part is the important part. I was just thinking that the ordering should be such that you run into all kinds of sets frequently. \$\endgroup\$ – dspyz Jun 20 '12 at 7:17
1
\$\begingroup\$

The One with Two Parts

The aim of this challenge is to create a pair of functions which scramble and unscramble any given piece of text.

Part 1

In part one you post your scrambling function, along with the length in characters and language of your unscrambling function (but NOT its code). The length of the scrambler does not affect your score so you needn't golf it unless you want to. The two functions may be written in different languages if you wish.

Input/Output

The scrambling function should take one argument only - a string containing the input text - and return a string containing the scrambled text. The unscrambling function should also take only one argument - the scrambled text - and return the original text. The input text will be limited to characters in the ASCII set range from 0 to 127.

Part 2

In part two you try to beat your opponents' scores for their unscrambling functions. You MUST use the language they specify for their unscrambler in part one. Please give just one answer to this question containing all your unscrambling functions making it clear which question in part one each function unscrambles (maybe each answer in part one should give its scrambler a name for identification?).

Once the closing date (TBA) has passed all participants should post their unscrambling functions in their answer to part one to prove the length, language and functionality of their function.

Scoring The participants score will be calculated as follows: (unscrambler length from part one) - (shortest unscrambler length from part two). The participant with the lowest score wins and will have their answers accepted on both parts of the challenge. To be eligible to win a participant must have taken part in both parts of the question.

Example

In part 1:

  • Bob posts a Python answer and says his unscrambler is a 165 character Python function.
  • Fred posts a GolfScript answer and says his unscrambler is a 59 character GolfScript function.
  • Joe posts a JavaScript answer and says his unscrambler is a 180 character PHP function.
  • Jim posts a Ruby answer and says his unscrambler is 163 character Ruby function.

In part 2:

  • Bob posts an 82 character GolfScript function to unscramble Fred's scrambled text. He also posts a 175 character PHP function to unscramble Joe's scrambled text.
  • Fred posts a 181 character PHP function to unscramble Joe's scrambled text.
  • Joe posts a 150 character Python function to unscramble Bob's scrambled text.
  • Jim posts a 156 character Python function to unscramble Bob's scrambled text. He also posts a 91 character GolfScript function to unscramble Fred's scrambled text.

The scores:

  • Bob scores 165 - 150 = 15
  • Fred scores 59 - 82 = -23
  • Joe scores 180 - 175 = 5
  • Jim scores 163 - 0 = 163

so Fred wins.

Miscellaneous

I suggest that the closing date be two weeks after the challenge begins, and that unscramblers be posted to part one within 48 hours of closing date in order to be eligible.

| |
\$\endgroup\$
  • \$\begingroup\$ Are there any rules regarding scrambling? i.e. is "Stockholm"->"Stockhoml" a valid scramble? (it may not matter, but I'm curious. And to be clear, the scoring is the difference between your opponent's unscrambler length and your own for the same language? \$\endgroup\$ – Gaffi Jul 16 '12 at 16:39
  • \$\begingroup\$ @Gaffi No, you scramble however you want. If you want to just output the text as given that's ok, but you probably won't win with that strategy. The aim is to do it in a way that is easy for you to unscramble but difficult for all the others. That way your score will be smaller. Yes, the score is the difference between your score and the score of the best of your opponents' attempts. I'll add an example to make that bit clearer I think. \$\endgroup\$ – Gareth Jul 16 '12 at 21:27
  • \$\begingroup\$ I think this gives an advantage to people who use (relatively) obscure languages. If the scrambler is written in J and the descrambler in GolfScript then only people who know both can realistically attempt a descrambler. (NB the rules don't say how the score works if no-one attempts a particular unscrambler). \$\endgroup\$ – Peter Taylor Jul 17 '12 at 6:59
  • \$\begingroup\$ I did consider saying that programs that had no attempts at beating them were not eligible to win, but then I thought that if they were scored as though the shortest attempt to beat them was 0 then they wouldn't have much of an advantage. I'll add that into the example scoring. What do you think? I want to encourage answers that are clever or well obfuscated rather than written in Malbolge or something like that. \$\endgroup\$ – Gareth Jul 17 '12 at 7:28
  • 1
    \$\begingroup\$ Does it mean that since no one attempts to solve Jim's Ruby challenge his chances are minimal that he'll win? That would discourage complicated scramblers or difficult languages. \$\endgroup\$ – Howard Jul 17 '12 at 17:12
  • \$\begingroup\$ @Howard As it stands, yes that's how it would work. The alternative, as Peter Taylor points out, is that people using obscure languages have an advantage. I'm not sure how else I might score unscramblers that no-one has attempted to beat. Maybe give them a score of 0? Please, if you or anyone else has any suggestions for making the challenge as inclusive as possible, let me know. \$\endgroup\$ – Gareth Jul 17 '12 at 17:51
1
\$\begingroup\$

Compile BF to TM

Your task is to write a compiler accepting a Brainfuck program (previous challenge: Interpret Brainfuck, wikipedia: Brainfuck) as input and outputting a Turing Machine which produces identical output when supplied with the same (correct) input.

You may select the output format from among the various formats accepted by the answers to Turing Machine Simulator.

The following links may also be useful.
An introduction to programming in BF
BF is Turing-complete
Programming a Turing Machine
Programming Praxis: Turing Machine Simulator

Equivalently, you may write a Brainfuck interpreter in TM, or any partial compilation/interpretation which results in a TM program as described above.

If we consider squares of the TM tape to represent bits (blank=0, mark=1) of the BF memory, then eight squares represent a cell. Each BF instruction translates to a minimum of 8 states of the Turing Machine.

'>' "advance" (++ptr) could be implemented by eight states (sixteen transitions):

adv8 _ adv7 R _
adv8 1 adv7 R 1
adv7 _ adv6 R _
adv7 1 adv6 R 1
adv6 _ adv5 R _
adv6 1 adv5 R 1
adv5 _ adv4 R _
adv5 1 adv4 R 1
adv4 _ adv3 R _
adv4 1 adv3 R 1
adv3 _ adv2 R _
adv3 1 adv2 R 1
adv2 _ adv1 R _
adv2 1 adv1 R 1
adv1 _ link R _
adv1 1 link R 1

where 'link' represents the first state of the following instruction.

'<' "rewind" (--ptr) can be implemented similarly by making leftward movements and rewriting the same symbol just read.

'+' "increment" (++*ptr) can be implemented by a ripple-carry from the Least Significant Bit to the Most Significant Bit, borrowing "rewind" states to back-up to normal position. If the LSB is on the left, it would look something like this:

inc8 _ link N 1
inc8 1 inc7 R _
inc7 _ rew1 N 1
inc7 1 inc6 R _
inc6 _ rew2 N 1
inc6 1 inc5 R _
inc5 _ rew3 N 1
inc5 1 inc4 R _
inc4 _ rew4 N 1
inc4 1 inc3 R _
inc3 _ rew5 N 1
inc3 1 inc2 R _
inc2 _ rew6 N 1
inc2 1 inc1 R _
inc1 _ rew7 N 1
inc1 1 overflow N 1

where overflow is a HALT state.

For I/O, the simplest way I can think is to place all input on the tape after the memory area, and expand the alphabet to include a symbol indicating the dividing line between the memory portion and the input portion of the tape. In fact, by expanding the cell size to nine squares, this symbol can serve as an input pointer, advancing as the input is consumed. (So "advance" and "rewind" now need 9 states each.) And another new symbol is written in front of the current memory cell to serve as the memory pointer. Inputting a byte therefore consists of schleping each bit over the entire space between the two tape positions with something like this:

input _ set-memptr L _
input 1 set-memptr L 1
set-memptr _ find-inptr R *
find-inptr _ find-inptr R _
find-inptr 1 find-inptr R 1
find-inptr $ schlep-bit R $
schlep-bit _ schlep-blank L _
schlep-bit 1 schlep-one L 1
schlep-blank $ schlep-blank L $
schlep-blank _ schlep-blank L _
schlep-blank 1 schlep-blank L 1
schlep-blank * deposit-blank R *
schlep-one $ schlep-one L $
schlep-one _ schlep-one L _
schlep-one 1 schlep-one L 1
schlep-one * deposit-one R *
deposit-blank _ etc R _
deposit-blank 1 etc R _
deposit-one _ etc R 1
deposit-one 1 etc R 1

where "etc" represents going to get the next bit in similar fashion.

To perform a loop (all BF loops are "while" loops, so the exit control is at the beginning and the end has a simple goto back to the beginning), we need first to check is the current cell is zero,

zero8 _ zero7 R _
zero8 1 body R 1
zero7 _ zero6 R _
zero7 1 left1 L 1
zero6 _ zero5 R _
zero6 1 left2 L 1
zero5 _ zero4 R _
zero5 1 left3 L 1
zero4 _ zero3 R _
zero4 1 left4 L 1
zero3 _ zero2 R _
zero3 1 left5 L 1
zero2 _ zero1 R _
zero2 1 left6 L 1
zero1 _ exit-loop R _
zero1 1 left7 L 1
left7 _ left6 L _
left7 1 left6 L 1
left6 _ left5 L _
left6 1 left5 L 1
left5 _ left4 L _
left5 1 left4 L 1
left4 _ left3 L _
left4 1 left3 L 1
left4 _ left3 L _
left4 1 left3 L 1
left3 _ left2 L _
left3 1 left2 L 1
left2 _ left1 L _
left2 1 left1 L 1
left2 _ loop-body L _
left2 1 loop-body L 1
...
loop-body-final _ zero8 N _
loop-body-final 1 zero8 N 1

So assuming the machine starts at tape-location 0, and the input is on the tape starting at 0 and going to the right, the "startup code" for this arrangement would be

startup _ place$ L _
startup 1 place$ L 1
place$ _ left270000 L $
left270000 _ left269999 L _
...

Jeez! The output is going to be HUGE! It might be better to treat the BF memory as negative-indexed and reverse all the _L_s and _R_s in 'advance', 'rewind', 'increment', and 'decrement'.


Questions:

Bonuses for optimizations? If I can implement this myself and provide a complete example output, The bonus could be "subtract the difference between your program's output for the example input with the example output". So eliminating states would be far more valuable than shrinking the code. One could possibly achieve a negative score!


Edit: Actually I think this is unreasonable unless the Turing Machine is augmented with non-reading (movement-only or epsilon) transitions. Duplicating every letter of the alphabet just to move over one square is just ridiculously painful. That means this challenge won't link-up nicely with the other one. :(

What about, instead of implementing the compiler, just devise a translation scheme (as above) that leads to a smaller output for a trivial sample program (based on calculating, rather than coding)? "Back of the envelope" compiler.

| |
\$\endgroup\$
  • \$\begingroup\$ "How much detail on BF do I need to supply? Can I simply reference the BF question?" A link to almost any site that describes the language will do. \$\endgroup\$ – dmckee --- ex-moderator kitten Nov 5 '12 at 16:52
  • \$\begingroup\$ Winning condition? \$\endgroup\$ – Peter Taylor Nov 6 '12 at 13:43
  • \$\begingroup\$ "Longest prefix containing syntactically-correct Malbolge!" :) ... I'd say have none at all. Perhaps the questioner should be required to accept their own example answer? \$\endgroup\$ – luser droog Nov 6 '12 at 18:08
  • \$\begingroup\$ @PeterTaylor Apologies for my last comment. I thought we were on my other answer about the [fun] tag. . . . This one would be a golf: shortest code by character count. But I think a clever system of bonuses could make it interesting. \$\endgroup\$ – luser droog Nov 7 '12 at 10:06
  • \$\begingroup\$ The "Equivalently, you may write a Brainfuck interpreter in TM" option doesn't play very well with being a code golf - how are you going to count the length of the TM? \$\endgroup\$ – Peter Taylor Nov 7 '12 at 11:15
  • \$\begingroup\$ @PeterTaylor Since the TM question specified 5-tuples, I think it's sufficient to count the tuples (== transitions). You can reduce states by increasing the alphabet (or vice versa), but the transitions would remain constant, I think. \$\endgroup\$ – luser droog Nov 8 '12 at 5:25
  • \$\begingroup\$ I'd like to adopt (work on and post) this challenge if you don't want to. Would I be able to? If you do not respond to this message within two weeks, by community guidelines, I am allowed to take it over. \$\endgroup\$ – MD XF Aug 18 '17 at 3:23
  • \$\begingroup\$ Yes, please. If you can do something with it, strike while the iron is hot. \$\endgroup\$ – luser droog Aug 18 '17 at 4:19
1
\$\begingroup\$

Polygon prefixes

Polygons are named after the number of sides that they have. A pentagon has 5 sides, an octagon has 8 sides. But how are they named? What's the name for a 248-sided polygon?

All polygons are suffixed with -gon. There are specific prefixes for each polygon depending on the number of sides. Here are the prefixes for the lower numbers:

3 - tri
4 - tetra
5 - penta
6 - hexa
7 - hepta
8 - octa
9 - nona
10 - deca
11 - undeca
12 - dodeca
13 - triskaideca
14 - tetradeca
15 - pentadeca
16 - hexadeca
17 - heptadeca
18 - octadeca
19 - nonadeca
20 - icosa

Polygons with 21 to 99 sides have a different system. Take the prefix for the tens digit (found on the left column), the ones digit (right column below), and then stick a "kai" between them to get (tens)(ones)gon.

20 - icosi       | 1 - hena
30 - triaconta   | 2 - di
40 - tetraconta  | 3 - tri
50 - pentaconta  | 4 - tetra
60 - hexaconta   | 5 - penta
70 - heptaconta  | 6 - hexa
80 - octaconta   | 7 - hepta
90 - nonaconta   | 8 - octa
                 | 9 - nona

The 3-digit sided polygons are named in a similar fashion. A 100-sided polygon is called a hectogon. Take the hundreds digit, find it on the column for ones digits, then stick a "hecta" to its right. Now number off the tens and ones like above: (hundreds)hecta(tens)(ones)gon. If the hundreds place digit is a 1, don't put the prefix behind "hecta".

So, given an integer (3 <= n <= 999), return the name of an n-sided polygon. n-gon is not a valid answer :P

As with all code golf, shortest code wins.


Is the description good? Would it be harder if I instead asked for the number of sides, given a name?

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ What is a 101-sided figure called? "hectahenagon"? Is "hena" from the column for ones digits you mention? If so, then what is a 111-sided figure called? I'd say "hectaundecagon", but then that comes from a column where "hena" is not present. \$\endgroup\$ – Gaffi Feb 11 '13 at 11:15
  • \$\begingroup\$ @Gaffi: Yep, it's hectahenagon, from what Google says. \$\endgroup\$ – beary605 Feb 11 '13 at 16:03
  • \$\begingroup\$ I am going to take this if you allow me or if you don't respond \$\endgroup\$ – Christopher May 30 '17 at 1:13
1
\$\begingroup\$

Self-Golfing Code?

I don't know if I just didn't search hard enough, but I couldn't find any challenge regarding self-golfing code, or rather, any code that can deterministically reduce another set of text code to a much smaller program, yet still compile/run.

For example, take this:

int main() {
std::cout<<"Hello world 1!"<<std::endl;
std::cout<<"Hello world 2!"<<std::endl;
std::cout<<"Hello world 3!"<<std::endl;
std::cout<<"Hello world 4!"<<std::endl;
std::cout<<"Hello world 5!"<<std::endl;
}

And output this (as one possible solution):

#define A std::cout<<"Hello world 
#define B !"<<std::endl;
#define C B A
int main() {
A 1 C 2 C 3 C 4 C 5 B
}

Alternative:

Sub MySub()
Dim aNumber As Integer
Dim someString As String
aNumber = 123
someString = "abc"
MsgBox aNumber
MsgBox someString
End Sub

into (again, as one possible solution)

Sub m()
Dim a As Integer
Dim s As String
a = 123
s = "abc"
MsgBox a
MsgBox s
End Sub

Do we have a challenge for this?

If not, here are some rules I envision:

  • Golfing code need not be in the same language as code to be golfed.
  • Since compilers/running of code varies, newly golfed code must still run under same environment.
  • Possible challenge scoring (multiple options -- thinking code golf):
    • 1: Shortest golfing code wins (not my favorite, since you can minimally shorten the base code, yet still write the shortest program).
    • 2: Shortest output of a set of pre-defined code (potentially limiting if participants are unfamiliar with the options available)
    • 3: Combination of length of golfing code and the output result of the same as input. (Ratio, summation, etc.) -- This I think is my preferred option.
    • 4: Multi-player Ratio of golfed size of other participants' own code versus their original submission. (Similar limitations to that of point #2.)
| |
\$\endgroup\$
  • 1
    \$\begingroup\$ Sounds more like an auto-golfer than obfuscation. Seems like it would be very hard to make it a fair contest unless you pick a language to golf, and even then it had better be a simple language (no platform dependency issues or compiler options). \$\endgroup\$ – Peter Taylor Feb 13 '13 at 15:15
  • \$\begingroup\$ @PeterTaylor My examples are golfing, but either would work. Perhaps golfing would be simpler, then? I agree that the options for usable languages makes this a bit messy... Would one challenge per language be acceptable? (i.e. aligned with most challenges that are language-agnostic) \$\endgroup\$ – Gaffi Feb 13 '13 at 17:36
  • 2
    \$\begingroup\$ Language-agnostic to mean means that you can write a program to do it in any language. Since the language to be golfed can be different from the submitted program, I don't see any incompatibility between making the problem "Write a program to golf Piet" and being language-agnostic. \$\endgroup\$ – Peter Taylor Feb 15 '13 at 0:18
  • \$\begingroup\$ @PeterTaylor So then you see no problem with one question per language on which to operate? Are there any proposed scoring algorithms you particularly like/dislike? \$\endgroup\$ – Gaffi Feb 15 '13 at 12:02
  • \$\begingroup\$ That depends on what you mean. If you're planning to post 10 questions at once, yes, that would be a problem. But I don't see a problem with posting a well-defined "Auto-golf Piet" and following it up two months later with "Auto-golf Perl 5". \$\endgroup\$ – Peter Taylor Feb 16 '13 at 10:19
  • \$\begingroup\$ Scoring is an issue. The halting problem means that it's impossible to write an optimal solution, so the scoring must take into account how good the solution is. I think option 3 is the best, and you'll want a big test set (maybe a few kB taken from a real-world open source project) with coverage of the language features. \$\endgroup\$ – Peter Taylor Feb 16 '13 at 10:22
  • \$\begingroup\$ Btw, your first example doesn't work. You can't have unmatched quotes in preprocessor directives. Don't know why. \$\endgroup\$ – MD XF Jan 13 '18 at 18:03
  • \$\begingroup\$ I honestly think this would be fine if you did something like solely maco-golfing, making it somewhat language agnostic because of gcc -E. \$\endgroup\$ – Zacharý Nov 10 '18 at 14:36
1
\$\begingroup\$

Missile Command

I'm making this CW, because it needs lots of help. I've been toying with this idea for a while. Think "battleship" to get in the right mind-frame. But, instead of ships, what you lay down are tiles which represent a Befunge-style program. This program controls the behavior of guided missiles ejected from the spawn tile. The goal is to program a missile which will obliterate an opponent's program block, as well as guard its own control block.

Haven't nailed-down the board size. 20x20 seems a little cramped.

         1         2
12345678901234567890
____________________1  4x20 program block
____________________2
____________________3
_______@____________4
....................5  12x20 arena
....................6
....................7
....................8
....................9
....................01
....................1
....................2
....................3
....................4
....................5
....................6
___________@________7  4x20 program block
____________________8
____________________9
____________________02

Tiles

@ spawn

Program control.

I'm imagining these to change direction of the code for "boustrophedon" writing.

this,then\
 txen,siht

haven't thought it all though, yet.

/

\

Movement.

F forward move forward one square

B back move back one square

L left turn left 90°

R right turn right 90°

So the submissions would be 4x20 code blocks which compete in a king-of-the-hill style.

| |
\$\endgroup\$
  • \$\begingroup\$ If this is deterministic, won't it be "Last person to submit their program wins"? \$\endgroup\$ – Peter Taylor Jun 7 '13 at 8:39
  • \$\begingroup\$ That is a danger, yes. I'm hoping ways around it can be found. There could be a random operator. And proximity detection, or something. \$\endgroup\$ – luser droog Jun 7 '13 at 8:46
1
\$\begingroup\$

Find all of the Scrabble numbers:

A scrabble number is a number n whose scrabble representation can score n points. As an example consider 12: its English spelling twelve has value 12 when it is placed on a stretch of six blank tiles. Since the highest ever reported 1 word scrabble score barely exceeds 2000 points, that will be the upperbound for this challenge.

Score and quantities for English:

2 blanks |  x1  |  x2  |  x3  |  x4  |  x6  |  x8  |  x9  |  x12 |
    1    |      |      |      | LSU  | NRT  | O    | AI   | E    |
    2    |      |      | G    | D    |      |      |      |      |
    3    |      | BCMP |      |      |      |      |      |      |
    4    |      | FHVWY|      |      |      |      |      |      |
    5    | K    |      |      |      |      |      |      |      |
    8    | JX   |      |      |      |      |      |      |      |
   10    | QZ   |      |      |      |      |      |      |      |

Considerations for either bonus points to scoring or extra requirements:

  • Respect the board, only using gaps between double/triple letter and double/triple word scores that occur on a standard scrabble board.
  • Respect the tile count for each letter.
  • There are non-English versions of scrabble, maybe it should be 'language-agnostic' (lol, but seriously is there a reason to accept only English submissions?).
  • Should the 2 blanks be allowed?
| |
\$\endgroup\$
  • \$\begingroup\$ What about tiles which were already on the board and so wouldn't score anything? As for language: one approach would be to make it take the names of the tiles (and perhaps the values and counts of the letters) as input; this would also prevent the problem from being effectively one of Kolmogorov complexity. \$\endgroup\$ – Peter Taylor Jun 19 '13 at 22:50
  • \$\begingroup\$ I don't believe that tiles on the board already would pose an issue. If you assume that the board may be prepared with any subset of the tiles beforehand (some may be impossible, but checking that is out of scope) all that is relevant to the problem is which are placed to complete the word. All the tiles points are counted, even the earlier placed, but only the new 7 (or less) tiles may qualify for triple/double-word/letter scores. w.r.t. kolmogorov, If I wanted to make it programming challenge instead of codegolf (so that isn't an issue) then there needs to be a scoring system right? \$\endgroup\$ – Kaya Jun 19 '13 at 23:33
  • \$\begingroup\$ Yes, if it isn't codegolf then it needs a scoring system. I'm not sure what you could use as an alternative scoring criterion, though: it's simple enough logic that pretty much any implementation would be IO-bound, so speed doesn't work; and big-O based tends to be less straightforward than you might think. \$\endgroup\$ – Peter Taylor Jun 21 '13 at 11:05
1
\$\begingroup\$

Sort all lines according to their corresponding Levenshtein Distance to the first line.

Shamelessly borrowed from: http://golf.shinh.org/p.rb?Levenshtein+Distance+Sort+FIXED

For a definition of the Levenshtein Distance, look here: http://en.wikipedia.org/wiki/Levenshtein_algorithm

Rules:

Takes input from stdin. Must work for all possible input. Get points for:

Smallest character count. Using Languages that are difficult to golf in. I think character count / the average values from here (http://golf.shinh.org/lranking.rb) might suffice?

| |
\$\endgroup\$
  • \$\begingroup\$ There are a number of ambiguities in the problem description. What is the correct behaviour if the input is empty? In the general case, should the first line be included in the lines which are sorted and output? Should the sort be by ascending or descending edit distance? How should ties be broken? \$\endgroup\$ – Peter Taylor Jun 25 '13 at 20:23
  • \$\begingroup\$ As for handicapping: are you going to prohibit built-in or library-provided edit distance functions? If not then the averages you link are not especially relevant: PHP handily wins the existing edit distance question by virtue of its built-in function. \$\endgroup\$ – Peter Taylor Jun 25 '13 at 20:27
  • \$\begingroup\$ (That existing question does also raise the possibility of yours being closed for not being sufficiently different). \$\endgroup\$ – Peter Taylor Jun 25 '13 at 20:28
1
\$\begingroup\$

Fastest Code: checking if interval pairs overlap

Given an unsorted input of many interval pairs (50+), write the fastest algorithm to determine if they do not overlap.

An interval pair is said to overlap if interval x and interval y are overlapping.

Example input 1:
interval x , interval y

10-25, 50-60
10-15, 25-60

Output:
Can be in any true false format.

false (They overlap)

reasoning:

a.x overlaps b.x
a.y overlaps b.y

Example input 2:

10-25, 50-60
20-30, 25-30

Output:

true (they do not overlap)

reasoning:

a.x overlaps b.x
a.y does not overlap b.y

Scoring:

[not sure...]
brute force gives a worst case n^2 runtime
| |
\$\endgroup\$
  • 1
    \$\begingroup\$ It's hard to understand what the program is supposed to do. It's better to give three separate self-contained test cases than to mix them together with extra identifiers which won't be in the actual input. But if I understand correctly, there's nothing difficult here at all. It's just interval overlap testing (two ifs) done twice for no obvious reason. \$\endgroup\$ – Peter Taylor Jul 5 '13 at 19:45
  • \$\begingroup\$ The problem is that there will be a very large input. I'm thinking > 50 lines. \$\endgroup\$ – EAKAE Jul 5 '13 at 20:50
  • \$\begingroup\$ I'm not sure whether or not to score it based on time, or worst case runtime. \$\endgroup\$ – EAKAE Jul 5 '13 at 20:59
  • 1
    \$\begingroup\$ Instead of asking for overlap, ask for disjoint: "Check if a family of intervals is disjoint". I also think it would be more interesting if you give intervals in interval notation but I you should at least specify whether or not the endpoints are included. \$\endgroup\$ – Justin Dec 21 '13 at 7:41
1
\$\begingroup\$

Countdown: Federal Holidays in the United States

Inspired by this question:

Christmas Countdown

Write a program or script that will countdown to the nearest U.S. federal holiday, at any given time, and will switch the display to an appropriate greeting during each holiday.

The following holidays must be tracked, and announced:

Holiday                         Date                    Greeting
==========================================================================================
New Year's Day                  Jan. 1                  Happy New Year!
Martin Luther King, Jr. Day     3rd Mon. in Jan.        Happy Martin Luther King, Jr. Day!
President's Day                 3rd Mon. in Feb.        Happy President's Day!
Memorial Day                    Last Mon. in May        Happy Memorial Day!
Independence Day                Jul. 4                  Happy Independence Day!
Labor Day                       First Mon. in Sept.     Happy Labor Day!
Columbus Day                    2nd Mon. in Oct.        Happy Columbus Day!
Veterans Day                    Nov. 11                 Happy Veterans Day!
Thanksgiving                    4th Thu. in Nov.        Happy Thanksgiving!
Christmas                       Dec. 25                 Merry Christmas!

The strings listed under "Holiday" and "Greeting" are all free. Shortcuts like "Merry X-mas!" or "Happy 4th of July" will count against you - the full and proper holiday names are free, so there's no good reason not to use them.

The following strings are also free, only when used as a label for time units or in advertising the next upcoming holiday:

days
hours
minutes
seconds
milliseconds
until
time

On any given non-holiday, the program must show a count-down timer which displays time remaining at least down to the second, and updates the display with an accurate value (according to the system clock) at least once per second. Time remaining until a holiday must be counted as the time until midnight (00:00:00) on that day.

How the days, hours, minutes, and seconds (and milliseconds, if you choose) are displayed is up to you, so long as all mandatory items are present and it is clear which numbers represent which value. Again, the strings defining units of time are free so there's no really good reason not to use them. (Though you won't be penalized for not using these strings, so long as it is still unambiguous which time units are which.) The program should also make apparent which holiday is being counted down towards.

On any given holiday, the program must cease displaying the countdown timer and instead display the appropriate greeting for that holiday from 00:00:00 until 23:59:59.

After a holiday is over, at 00:00:00 the next day, the holiday greeting must go away and be replaced with the countdown timer for the next holiday.

Answers must include:

  • Name of language
  • Score (length of golfed code, minus free characters)
  • Golfed code
  • Total length of golfed code
  • Total number of free characters used
  • Un-golfed code, with descriptive comments

The program must be capable of running accurately (according to the system clock) at any time, and must be able to run indefinitely. The only limitations to this should be those imposed by the host computer or the nature of the programming language.


Are there any additions/deletions/modifications that should be made to these rules?

I'm considering changing some of the greetings, but I'm not quite sure what to.

  • "Happy Martin Luther King, Jr. Day!" is just a mouthful and feels awkward, but shortening it to "Happy MLK Day" feels weird too - any other suggestions?
  • I'm not quite sure "Memorial Day" should really be preceded by "Happy" - thoughts?
  • Any others?
| |
\$\endgroup\$
  • \$\begingroup\$ I think it would be more interesting if the strings were not free, but you still required exact match. I would like to see the compression scheme used by contestants. \$\endgroup\$ – John Dvorak Dec 7 '13 at 12:04
  • \$\begingroup\$ @JanDvorak This is meant to be code-golf, not kolmogorov-complexity. \$\endgroup\$ – Iszi Dec 7 '13 at 22:11
  • \$\begingroup\$ This challenge proposal has been inactive for over a month. I would like to take ownership of the challenge and make it ready for posting. Please let me know within the next 14 days if you have any objections and would still like to finish and post this challenge yourself. \$\endgroup\$ – user10766 Nov 3 '14 at 2:01
1
\$\begingroup\$

Quine with syntax highlighting


I don't really have much of an idea how to properly pose a quine challenge, or what the common syntax highlighting rules are (or aren't) for various languages. So, I figured I'd just toss this concept up here for consideration and let the community flesh it out if they think it's a good idea.

| |
\$\endgroup\$
  • \$\begingroup\$ I'm pretty sure some languages don't even have syntax to highlight \$\endgroup\$ – John Dvorak Dec 13 '13 at 20:12
  • \$\begingroup\$ @JanDvorak Perhaps this would not quite be an "all languages" challenge, then - only languages which naturally lend themselves to syntax highlighting would be eligible. \$\endgroup\$ – Iszi Dec 13 '13 at 20:19
  • \$\begingroup\$ You also can't use a language that cannot render any decent GUI. Also, specifying the amount of syntax highlighting the program needs to generate will be hell. \$\endgroup\$ – John Dvorak Dec 13 '13 at 20:36
  • \$\begingroup\$ I don't think this question is feasible, due to the output restrictions and due to the difficulty in defining the minimum required syntax highlighting. \$\endgroup\$ – John Dvorak Dec 13 '13 at 21:09
  • \$\begingroup\$ I like this idea. I think you could specify an adequate level of highlighting with just keywords, strings or characters and numeric literals each having their own color. \$\endgroup\$ – Οurous Feb 28 '18 at 21:13
1
\$\begingroup\$

McDonald's Drive-Thru

Changes from original:

  • Provided some clarification of requirements with regards to impossible ordering quantities.
  • Added specification to include total cost of order.
  • Added specification to prefer lowest cost in case of a tie for number of packages.

TODO:

  • Verify package sizes and pricing to be used for this challenge.
  • Add pricing to output samples.
  • Edit or remove "not have any limitations" rule. As currently written, it may force otherwise unnecessary bloating of code in some languages. (e.g.: PowerShell can handle numbers as uint64 to work with extremely large quantities, but it defaults to int32.)

We want to write a program to help McDonald's Drive-Thru employees assist their customers in ordering Chicken McNuggets. Chicken McNuggets only come in packs of 4, 6, 9, or 20. However, customers may not always be considering this when they pull up to the speaker.

For example, a customer might want to order 50 McNuggets but they really don't care what sort of packaging they come in - they just want to make sure they get 50 McNuggets one way or another. We want to help the customers get the best value out of their order - that is, to compose an order large enough to accommodate their needs in as few packages as possible with little to no excess.

Users will provide a request for n Chicken McNuggets. Your program's task is to provide the user with the sizes and numbers of McNugget packages needed to fulfill the order exactly. If the exact order cannot be fulfilled, the system must output an order which would meet the customer's needs with as little excess as possible. The system must also provide the total cost of the order.

Rules

  • For values of n which can be ordered exactly, output how many of each pack must be ordered to achieve the requested quantity.
  • For impossible orders (1,2,3,5,7,11), print "[requested quantity] is impossible. Have [nearest valid quantity >n]:" followed by the normal output for the nearest possible quantity >n.
  • Impossible orders cannot be hard-coded. The program must be able to determine whether fulfilling an order exactly is possible without being explicitly told that 1,2,3,5,7, and 11 are impossible.
  • Output must exclude any package sizes which do not need to be ordered.
  • Output must be in descending order of package size.
  • Output must include the sum total cost of all the packages. (Tax not included.)
  • Further layout and formatting of the output is up to you, so long as it is unambiguous.
  • Program must not have any limitations beyond those inherent to the system or programming language.
  • If there are multiple ways to assemble the order in the least number of packages, output the method which has the lowest total price.

Examples:

Input: 8
Output:

2x4

Input: 43
Output:

1x20 1x9 1x6 2x4

Input: 11
Output:

11 is impossible. Have 12: 2x6

Relevant Numberphile Link


My main concern is that this problem may be too similar to this thread:

Work out change

Otherwise, are there any changes that should be made to this?

| |
\$\endgroup\$
  • 2
    \$\begingroup\$ My recommendation is to minimize the total cost of the order, rather than the number of packages. Based on these prices: fastfoodmenuprices.com/mcdonalds-prices, the costs are $2.99, $3.89, $4.29, and $5.00. This website lists the "9 piece" as "10 piece", I think that might be an error. \$\endgroup\$ – PhiNotPi Dec 14 '13 at 0:01
  • \$\begingroup\$ Why the restriction #3? \$\endgroup\$ – John Dvorak Dec 14 '13 at 6:12
  • \$\begingroup\$ I agree that it's too similar to the existing question. In addition, "nearest valid quantity" isn't unique, and you don't give any hint as to how to break ties. \$\endgroup\$ – Peter Taylor Dec 14 '13 at 10:17
  • 1
    \$\begingroup\$ @PeterTaylor Tiebreaker is specified as ">n", where "n" is the quantity requested by the user - that is, we want to give the user an option that will have at least as many nuggets as they want to order. \$\endgroup\$ – Iszi Dec 14 '13 at 23:37
  • \$\begingroup\$ @JanDvorak Essentially, to up the difficulty a notch. I figure it's a little trickier to catch the invalid quantities in the process of figuring out the answer if you can't write a simple if statement to match against the known quantities. \$\endgroup\$ – Iszi Dec 14 '13 at 23:42
  • \$\begingroup\$ @PhiNotPi Not sure if that's an error on the site, or a regional difference. The information I posted was based on the linked Numberphile video, which was made in the U.K.. It's also possible they may have changed the menu since then. Presuming that larger packages hold better value in terms of cost-per-nugget than smaller ones, the problem as stated should work itself out to the same goal as you've suggested. However, it might help to differentiate the challenge from the suggested duplicate if we add the total price into the expected output. \$\endgroup\$ – Iszi Dec 14 '13 at 23:45
  • \$\begingroup\$ My question is: how are you going to measure that? How large part of this knowledge are we disallowed from encoding? Can we memorize all but one? Can we special-case 1,2,3? Or, is it that anything goes as long as it either can be generalised to other Frobenius problems, or is inclusive, not exclusive? \$\endgroup\$ – John Dvorak Dec 14 '13 at 23:47
  • \$\begingroup\$ @JanDvorak The program should be able to work out for itself whether or not a given quantity is invalid - that's all there is to it. By its nature, I suppose that means solutions would be able to also handle other Frobenius problems. In fact, I was actually considering a separate "return the largest impossible quantity" problem, where users input several integers and the program outputs the largest quantity that cannot be achieved by adding multiples of those integers. \$\endgroup\$ – Iszi Dec 14 '13 at 23:53
  • \$\begingroup\$ Provided some updates to address comments. \$\endgroup\$ – Iszi Dec 15 '13 at 2:34
  • \$\begingroup\$ @Iszi Minimizing cost should serve as a tiebreaker for when there are multiple solutions with the minimum packaging. For example, look at N=36. The solution {0*4,0*6,4*9,0*20} works, but {1*4,2*6,0*9,1*20} is cheaper. (I used the costs {{4,2.99},{6,3.89},{9,4.29},{20,5.00}}) \$\endgroup\$ – PhiNotPi Dec 15 '13 at 3:07
  • \$\begingroup\$ @PhiNotPi Ah, I think I misunderstood when Peter said there wasn't a specifier for the tiebreaker. For some reason, I was thinking it was not possible for there to be a tie of that sort. Adding the price aspect definitely helps sort that out, then. Thanks. \$\endgroup\$ – Iszi Dec 15 '13 at 3:15
  • \$\begingroup\$ FWIW, it was my misreading. I failed to see the ">n". \$\endgroup\$ – Peter Taylor Dec 21 '13 at 12:01
1
\$\begingroup\$

.... . .-.. .-.. --- .-- --- .-. .-.. -..

Another Hello World challenge, this time with Morse code!

Taking no input, your program must output HELLO WORLD in audible Morse code, printing each letter as it is played. For the purpose of this challenge, the following Morse code guidelines will be followed:

Duration of sounds:

  • Dits are one time-unit long.
  • Dahs are three time-units long.
  • The gap between elements within the same character is equal to one dit.
  • The gap between characters within the same word is equal to one dah.
  • The gap between words is seven time units long.
  • The length of "one time unit" is up to the programmer, so long as it is consistent throughout the message.

Letters:

  • H: ....
  • E: .
  • L: .-..
  • O: ---
  • W: .--
  • R: .-.
  • D: -..


I'm a little iffy on that last bullet regarding duration. Should I set a hard standard, or a minimum? If so, what to?

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ Set a hard minimum for timing. Otherwise, a golfed solution might have 1 unit = 1 millisecond. \$\endgroup\$ – PhiNotPi Dec 16 '13 at 22:23
  • 6
    \$\begingroup\$ Tasks which take input are normally more interesting. \$\endgroup\$ – Peter Taylor Dec 17 '13 at 0:09
  • \$\begingroup\$ I guess that dahs need to be a continuous tone, not just two dits without a gap? \$\endgroup\$ – John Dvorak Dec 17 '13 at 6:32
  • \$\begingroup\$ @JanDvorak Correct. \$\endgroup\$ – Iszi Dec 17 '13 at 6:33
  • \$\begingroup\$ If you don't plan to post this, I would like to modify it and post it. (If you don't reply to this message within two weeks, by community standards, I am allowed to adopt the challenge.) \$\endgroup\$ – MD XF Dec 22 '17 at 2:41
  • \$\begingroup\$ @MDXF What do you suggest for modifications? \$\endgroup\$ – Iszi Jan 2 '18 at 15:18
1
\$\begingroup\$

Code Golf: counting all colors in an image

The goal of this Code Golf is to create a program that counts all colors in an image.

The input

The input will be a path to the image file.

The output

The output should be a number that indicates how much different colors your program found in the image.

The scoring

It's also important that your program supports much image formats, so I'll calculate the score based on this formula:

(character_count * 3) / (number_of_supported_image_formats * 2)

Some other rules

  • The lowest score wins
  • You're not allowed to execute an external program
  • No Internet access
  • A color doesn't just count if it's present in the palette, there really should be pixels of that color in the image.
  • You should also count pixels with 0% opacity.
  • #FFFFFF with 100% opacity is not the same color as #FFFFFF with 50% (of course, this is the same for all other colors).
  • In vector image formats, if there's a red square (for example) with 50% opacity that overlaps a blue square, then this should count as two colors: red and blue.
  • In vector image formats, in case of a gradient, the number of colors depend on which colors are used in the gradient. For example, if there is a red/yellow gradient, then you should count this as two colors: red and yellow.
  • A paletted image format is another image format than the non-paletted variant.
  • SVG 1.0 is another image format than SVG 1.1 (also count for other image formats).
| |
\$\endgroup\$
  • \$\begingroup\$ What counts as a colour? Does a colour count as present if it's in the palette, even if there aren't any pixels of that colour? What about if it's present, but at 0% opacity? On the subject of opacity, are #ffffff at 100% opacity and #ffffff at 50% opacity the same colour? What about vector image formats: does a red square at 50% opacity partially overlapping a blue square count as two colours (red and blue) or three (red, magenta in the overlap, and blue)? What about gradients: does the number of colours depend on the size of the gradient-coloured object? \$\endgroup\$ – Peter Taylor Dec 20 '13 at 15:25
  • 1
    \$\begingroup\$ Also, what counts as an image format? If a program supports paletted PNG but not non-paletted PNG, does that count as 0 formats, 0.5 formats, or 1 format? If a program supports SVG 1.0 and SVG 1.1 does that count as 1 format or 2 formats? Etc. \$\endgroup\$ – Peter Taylor Dec 20 '13 at 15:27
  • \$\begingroup\$ @PeterTaylor: Thanks for your comments! I updated my question. \$\endgroup\$ – ProgramFOX Dec 20 '13 at 19:16
  • \$\begingroup\$ I'm sorry, but I'm afraid the core of this challenge is to be as bold as possible when counting the amount of file formats my language's standard library can handle. \$\endgroup\$ – John Dvorak Dec 20 '13 at 19:33
  • \$\begingroup\$ @JanDvorak: Of course, you should also look whether it's really worth to handle another image format, after you made sure to handle some other. If your score doesn't get lower, then it's not really worth. \$\endgroup\$ – ProgramFOX Dec 20 '13 at 19:35
1
\$\begingroup\$

Since this question is closed, I figured I'd post it here so further issues can be hammered out in Meta instead of the main site.

Known Issues:

  • Some rules seem a bit unclear to some users.
  • Clarification may be needed on what is needed to qualify for the "win percentage" bonus.
  • Win percentage bonus may not be enough to be a real incentive. (This may just depend on the language or implementation.)
  • Perhaps the win percentage bonus should be eliminated entirely, or maybe it should just be made a mandatory part of the spec.
  • It's been suggested to use a simple 1-9 numbering system for the board positions, instead of any sort of X,Y coordinates.
  • May want to allow some flexibility on the input format. (i.e.: Input must still specify the sequence of moves thus far, using whatever addressing scheme is specified in the spec, but leave the delimiters - or lack thereof - up to the developer.)
  • Exactly what is expected of the program, such as how it can figure out whose turn it is or what the output should be, seems to need some clarification.
  • Some test cases should probably be added.
  • Clarification may be needed on the matter of what parts of the game we can assume have followed the guide already.
  • Some flaws exist in the chart. (Two already mentioned in comments on the original post.) These should be identified and addressed so that proper expectations for those conditions are clearly set.
  • Original post said we would not have to account for null input (i.e.: X asking what their first move should be) but this might be a good enhancement to add.

I personally think this is a great challenge. So far, I've had a very hard time finding a lot of room for optimization and got up to probably 400 characters in PowerShell before I gave up (not even half-way through the chart yet) due to some of the above issues. I'd really like to see what some more serious golfers could do with this, once the spec is properly hammered out.


Overview

This is the XKCD tic-tac-toe cheetsheet:

enter image description here

It's rather big, I know. But it's also your most valuable resource in your challenge.

The challenge

Create a program (in your language of choice) that uses the Optimal Move Cheatsheet (henceforth OMC) to output the optimal move when given a sequence of moves.

The input

Your program will be fed a series of moves in the following fashion:

A3 A2 B2 C2 ...

Where the first combination is always X, the second O, and so on. The letter is the Y coordinate (A-C, A at the top) and the number is the X coordinate (1-3, 1 at the left).

You may assume that the given combination is following the OMC's suggestion for each move at least for the player asking for a recommendation. You can also assume that the input will never be null (at least one move has been made). You must:

  1. Figure out whether the next move is for X or O (you don't need to output this)
  2. Use the OMC to decide the next move
  3. Print the next move in the standard format A3

Optional:

You may also include the player's chance of winning (as a percentage) for 50 character discount on your score.

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ I think a 1-9 system would be easier than any XY system, but not by too much. The biggest issue I think is that if you go by the chart (rather than formulating your own algorithm that plays the same way) you have a ton of data to enter (there are several hundred squares in the two charts). Perhaps limit the input to only sequences starting A1 B2 (or 1 5 if you use telephone keypad numbering)? That's the center square in the X chart and the top left square in the O chart. \$\endgroup\$ – Blckknght Dec 23 '13 at 5:14
  • \$\begingroup\$ @Blckknght Limiting the scope of the challenge makes it less interesting. Part of the challenge (if not the entire challenge) here is to find ways to shortcut the flow while still putting out accurate results. As for the 1-9 system, the simplification may be relatively trivial but it does help clear out some otherwise unneeded bloat since everyone will probably build in some conversion to a 1-9 system anyway to shorten the code. It also enables some other shortcuts where the same move suggestion applies to multiple situations which are mathematically related. \$\endgroup\$ – Iszi Dec 23 '13 at 19:47
  • 1
    \$\begingroup\$ My point is that the chart data so dominates the code size that winning answers will pretty much have to ignore the data in the chart and use an AI. So the challenge becomes "write a Tic-Tac-Toe AI that plays exactly like this chart", which seems less interesting to me than "use (part of) this chart to make an AI with trivial code". I already have working code for the problem and bonus in about 200 non-golfed characters of Python, but it will require many 1000s of characters of data, even if I exploit some symmetries. Even if I was willing to type all that data, an AI will beat it, I'm sure. \$\endgroup\$ – Blckknght Dec 23 '13 at 20:55
  • \$\begingroup\$ @Blckknght I'm pretty sure even a fairly straightforward implementation of the chart can be fit within about 5,000 characters - especially in a proper golfing language. IRRC, I'd finished the X portion of the chart in about 400 characters with PowerShell before I gave up on my first go at it. Even then, there was still plenty of room for optimization, and that's in a language which is far from optimal for golfing. Certainly, it's nice when you can bang out a quick answer in 15 minutes. But not every challenge has to fit in 500 characters or less. \$\endgroup\$ – Iszi Dec 23 '13 at 21:12
1
\$\begingroup\$

Implement addition using only division (code golf)

Thought you could implement division using only addition? Well try it the other way around!

Your job is to make a function or equivalent program that accepts 2 numbers and adds them using only division.

Rules

  • No importing libraries
  • You can't use anything dealing with mathematics except / and /=, (and their equivalents)
  • No bitwise operations
  • No string operations except input, output, return, and string concatenation
| |
\$\endgroup\$
  • \$\begingroup\$ Interesting. You might have to close some loopholes, though, as some people will just create a giant lookup table. Also, some people could use string operations use perform addition. Is it going to be code golf? \$\endgroup\$ – PhiNotPi Dec 24 '13 at 16:49
  • \$\begingroup\$ @PhiNotPi I think so, thanks for the tip. \$\endgroup\$ – Timtech Dec 24 '13 at 18:42
  • \$\begingroup\$ Does "no string operations" refer to I/O as well? It's hard to do I/O without string operations of any kind \$\endgroup\$ – John Dvorak Dec 24 '13 at 19:21
  • \$\begingroup\$ @JanDvorak I want to allow I/O - how do I rephrase the question as to allow I/O without allowing math by executing strings? \$\endgroup\$ – Timtech Dec 25 '13 at 16:17
  • \$\begingroup\$ "division using only division" looks like an error... \$\endgroup\$ – Peter Taylor Dec 28 '13 at 10:17
  • \$\begingroup\$ Is this a code golf, code challenge or a popularity contest? \$\endgroup\$ – ProgramFOX Dec 28 '13 at 10:56
  • \$\begingroup\$ @PeterTaylor Thanks :) And @ ProgramFOX, it's code golf. \$\endgroup\$ – Timtech Dec 28 '13 at 14:36
  • \$\begingroup\$ @Timtech Not the number of divisions required? \$\endgroup\$ – Johannes Kuhn Dec 28 '13 at 15:03
  • \$\begingroup\$ @JohannesKuhn What are you talking about? \$\endgroup\$ – Timtech Dec 28 '13 at 15:10
  • 4
    \$\begingroup\$ Tried to calculate 0+0 - the only thing I accomplished was a division by zero ;-) \$\endgroup\$ – Howard Dec 28 '13 at 16:20
  • 2
    \$\begingroup\$ How do you prevent solutions like Array(a).concat(Array(b)).concat([0,0]).length? \$\endgroup\$ – John Dvorak Dec 28 '13 at 19:53
  • \$\begingroup\$ Is eliminating string concatenation too restrictive? Maybe only allow the built in conversions from strings to numeric types. \$\endgroup\$ – Tim Seguine Jan 14 '14 at 11:38
  • \$\begingroup\$ @Tim I guess so, maybe just disallow eval/expr. \$\endgroup\$ – Timtech Jan 14 '14 at 11:50
  • \$\begingroup\$ and would mod be allowed? \$\endgroup\$ – Tim Seguine Jan 14 '14 at 12:07
  • \$\begingroup\$ @Tim As it currently stands, no. Do you think I should add it? \$\endgroup\$ – Timtech Jan 14 '14 at 15:22
1
\$\begingroup\$

Recognize spoken numbers of .wav file

The goal of this code golf is to create a program or function that recognizes (and outputs) the spoken numbers of a Waveform Audio File (.wav).
The rules are:

  1. No network access and you are not allowed to run external programs.
  2. The input will be the file path to the WAV file, and the spoken text will only be one of these digits: one, two, three, four or five.
  3. The output must be the recognized spoken number of the WAV file.
  4. You are not allowed to use third-party libraries.
  5. This is a code golf, so the code with the smallest character count wins.
| |
\$\endgroup\$
  • \$\begingroup\$ What do you mean by convert to text? Encode? Recognise spoken text? \$\endgroup\$ – Howard Jan 21 '14 at 18:36
  • \$\begingroup\$ @Howard: Recognize spoken text. I updated my question. \$\endgroup\$ – ProgramFOX Jan 21 '14 at 18:38
  • 1
    \$\begingroup\$ That makes it a very subjective challenge. It is quite debatable if a wav file contains recognisable text or not. I can't think of a safe way to put restrictions on the input without making it to a fixed-input kind of puzzle. \$\endgroup\$ – Howard Jan 21 '14 at 18:41
  • \$\begingroup\$ @Howard: You mean, for example, ensuring that the input will only be spoken text without background music? \$\endgroup\$ – ProgramFOX Jan 21 '14 at 18:43
  • \$\begingroup\$ This needs some explicit restrictions on input. I assume that you're assuming that the text will be English, but even then there is a lot of accent variety. Most speech-to-text programs which U.S. companies release can't handle many (if any) British accents in their first version or two. I think that the only way this can be reasonably objective is either to invert a TTS program (in which case it's boring - no errors to account for) or to specify a training text and a test text, where it gets to hear the training text read n times and then tries to interpret the test text. \$\endgroup\$ – Peter Taylor Jan 21 '14 at 18:58
  • \$\begingroup\$ Maybe it is possible if you restrict the challenge to recognise the spoken digits one, two, three and four. Although still difficult to define clearly spoken there may be small enough variation in the input. \$\endgroup\$ – Howard Jan 21 '14 at 19:09
  • \$\begingroup\$ Maybe you can make a youtube video or something similar that contains all the sound that needs to be recognized; the programs just need to cater to those sounds. \$\endgroup\$ – Justin Jan 21 '14 at 19:32
  • \$\begingroup\$ @Howard: That's a good suggestion. I updated my question. \$\endgroup\$ – ProgramFOX Jan 22 '14 at 14:14
  • \$\begingroup\$ What's a "third-party library"? Can C# programs use MS libraries, Obj-C programs use Apple libraries, etc? \$\endgroup\$ – Peter Taylor Jan 22 '14 at 16:36
  • \$\begingroup\$ @PeterTaylor: Yes, they can. \$\endgroup\$ – ProgramFOX Jan 22 '14 at 17:29
  • \$\begingroup\$ Golfing msdn.microsoft.com/en-us/library/… would make for a rather short and boring answer. \$\endgroup\$ – Peter Taylor Jan 26 '14 at 15:37
  • \$\begingroup\$ @PeterTaylor, ProgramFOX: It would make sense to forbid any libraries or programs designed for speech recognition, whether third-party or not. You might want to take a look at my earlier speech synthesis challenge for some ideas on how to word such challenges (and in the comments for some issues I should've thought of in advance). \$\endgroup\$ – Ilmari Karonen Feb 9 '14 at 10:08
1
\$\begingroup\$

Print Lorem ipsum

The goal of this code golf is to write a program that prints EXACTLY this text:

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

The rules:

  1. No external resources
  2. The shortest code in bytes wins.
| |
\$\endgroup\$
  • 5
    \$\begingroup\$ Is there any reason to expect the answers to be fundamentally different to those to existing kolmogorov-complexity questions? \$\endgroup\$ – Peter Taylor Jan 26 '14 at 15:33
  • \$\begingroup\$ Won't the winner just post something like cout<<"/*text here*/";? This will probably be pretty boring, as the text needs to be hardcoded in. \$\endgroup\$ – user10766 Feb 6 '14 at 1:29
  • \$\begingroup\$ @user2509848: No, I'd expect the winner to be something that packs the text in base 29 or 32 into a raw byte string and decodes it in GolfScript or some similar language. Or possibly some PHP code that starts with <?=gzinflate(. \$\endgroup\$ – Ilmari Karonen Feb 9 '14 at 10:00
  • \$\begingroup\$ OK, but you will need to specify that in the rules. \$\endgroup\$ – user10766 Feb 9 '14 at 15:35
1
\$\begingroup\$

Here's my first proposal. It just occurred to me that it might be a bit difficult testing submissions without a functioning server, but maybe we can manage without? What do you people think?


The web hosting company I use has a jobs page that looks a bit like this:

Screenshot of web page

If you want to work for them, you have to calculate the correct answer and submit it through this form. But you only have a few seconds in which to do this, so you need a script to do it for you. If you submit the correct answer in time, you're then given a hash code and an email address, and are asked to email your source code to this address, using the hash code as the subject line:

Screenshot of next page after a successful submission

Using any language you like, write a script to download and submit this application form with the correct answer and hidden id field, and then email your source code with the hash code provided as the subject line. You can assume that the HTML source of the two pages is as follows:

1. http://jobs.example.com/

<!DOCTYPE html>
<html>
<head>
<title>Job Application</title>
</head>
<body>
<p>Evaluate 943 + 376 - 394 * 573 * 983 , and submit the answer with the following form.</p>
<form method="POST" action="apply.pl">
<input type="text" name="answer" value="" />
<input type="hidden" name="id" value="5d41402abc4b2a76b9719d911017c592" />
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>

2. http://jobs.example.com/apply.pl

<!DOCTYPE html>
<html>
<head>
<title>Job Application</title>
</head>
<body>
<p>Well done, that was the correct answer. Now email your source
code to jobs@example.com with the following text in the Subject
header:</p>
<p><code>1a79a4d60de6718e8e5b326e338ae533</code></p>
<p>But hurry, you only have five seconds!</p>
</body>
</html>

The only variable parts of these pages are:

  1. The sum (up to 6 numbers separated by any combination of +, - and * with spaces on both sides)
  2. The hidden id field that must be submitted with the form.
  3. The hash code on the second page

You may assume that the sum can be calculated without overflow using 32-bit integer arithmetic.

| |
\$\endgroup\$
  • \$\begingroup\$ What's the difficulty with having a functioning server? \$\endgroup\$ – Peter Taylor Jan 28 '14 at 15:53
  • \$\begingroup\$ @PeterTaylor It won't be possible to actually test anyone's script without a server that can process these applications. This probably isn't a problem for sensible languages, but if someone submitted an answer written in Golfscript or Whitespace then I'd have no idea if it would actually work or not. \$\endgroup\$ – r3mainer Jan 28 '14 at 16:07
  • \$\begingroup\$ It won't be possible to test them anyway if you send the e-mail to jobs@example.com. I note that you haven't specified that you're after a program: I would specify that answers should be a full program which takes HTTP URL and e-mail address as command-line arguments or as separate lines on stdin; then each person can test with an e-mail address they control. If you're willing to change the URLs a bit then I can host a couple of PHP pages somewhere under cheddarmonk.org. \$\endgroup\$ – Peter Taylor Jan 28 '14 at 16:34
  • \$\begingroup\$ @PeterTaylor Ah, of course! It didn't occur to me that the email address could be separated out as input data. We'd have to change the background story a bit though. Emailing a job application to yourself seems a bit daft. \$\endgroup\$ – r3mainer Jan 28 '14 at 16:52
  • \$\begingroup\$ I don't see why. If you're allowing people advance knowledge of the full HTML structure, you can assume that they have advance knowledge of the target e-mail, and then it's just a case of promoting testable code. \$\endgroup\$ – Peter Taylor Jan 28 '14 at 17:15
1
\$\begingroup\$

The Poet's Quine:

Write a quine with 1 or more rhyme scheme from http://en.wikipedia.org/wiki/Rhyme_scheme when read. The non-alphanumeric symbols aren't used for rhyming in this scheme (apart from the basic arithmetic signs like plus, minus, times and divided by), neither are comments. Words may be pronounced in any dialect, but it needs to be consistent within the same stanza (no having the first word be pronounced in a Scottish way and the second in a Welsh way).

Contest type would be popularity contest.

Thoughts on this proposal?

| |
\$\endgroup\$
  • \$\begingroup\$ I'm not sure I understand the last two points. Examples? \$\endgroup\$ – John Dvorak Feb 19 '14 at 14:50
  • 2
    \$\begingroup\$ "words are pronounced without a heavy accent or dialect" seems to me to be incompatible with "worked and borked rhyme". \$\endgroup\$ – Peter Taylor Feb 19 '14 at 17:32
  • \$\begingroup\$ That was more intended to be an example of a rhyme in general, rather than a "no heavy accent" example. I'm not a native speaker, so my pronunciation might not be totally accurate. I'll drop that rule (also could make for more interesting interpretations). \$\endgroup\$ – Nzall Feb 20 '14 at 14:53
  • \$\begingroup\$ It seems the scoring scheme actively encourages bad poetry. Maintaining a consistent rhyme scheme throughout is more difficult and better poetically, yet you penalize adjacent repetition of a scheme and give bonuses to unique schemes. Using syllables instead of feet is odd, too. A line of 12 syllables and a line of 8 can work perfectly together if one is anapests and the other iambs. I realize this is a programming site, but if you're going to call it "The Poet's Quine", let's have some real poetry!! \$\endgroup\$ – Jonathan Van Matre Feb 21 '14 at 23:05
  • \$\begingroup\$ I'm not really someone who knows a lot about poetry, but those suggestions seem good. I didn't want to make it too complicated though. you say yourself that this site is for programmers, and I doubt there are many programmers out there that know the different di-, tri- and tetrasyllable feet. maybe having a properly feeted poem can be a bonus objective? \$\endgroup\$ – Nzall Feb 22 '14 at 20:21
  • \$\begingroup\$ The biggest challenge will be finding a proper scoring system which makes sense both poetically and programmatically. It's definitely possible, but it won't be easy. Poetry is such a wide art and relies just as much on format as on content. And I don't want to force a specific kind of meter on the participants, because that's part of the challenge. \$\endgroup\$ – Nzall Feb 22 '14 at 20:35
  • 1
    \$\begingroup\$ We could also make it a popularity contest, since poetry is not about the format and content, but about evoking emotions and feelings. A popularity contest might be suited more for such a puzzle. \$\endgroup\$ – Nzall Feb 22 '14 at 20:37
  • \$\begingroup\$ Yeah, I think popularity contest solves a lot of the issues here. Of course, it also creates issues of its own, like the inexplicable number of "To be or not to be" entries on the aphorism challenge. But...lesser of two evils. :) \$\endgroup\$ – Jonathan Van Matre Feb 28 '14 at 19:32
  • \$\begingroup\$ What issues are you thinking about? maybe some extra rules can make this work. \$\endgroup\$ – Nzall Mar 4 '14 at 8:09
1
\$\begingroup\$

The shortest C program which generates the most instructions

Write a very short C program (length being defined by character count) which generates the most instructions when compiled. Of course, indicate your compiler, the version, and your operating system, and say what your program does. Linked libraries do not count!

Score

  • Base score: 1/(characters) * (instructions)
  • Bonus: if it computes something "useful," +20%

I'm fascinated by C challenges and compiler oddities, but I'm not sure about this question because of the variance you'll get between different compiler versions. Would it be acceptable to ask users to use an online resource which will compile C to assembly? I found two after a cursory search:

| |
\$\endgroup\$
  • \$\begingroup\$ With the chars/instructions formula, the score can approach 0 (e.g. use C macros that, when nested N times, generate 2^N instructions). Also, make it clear that linked libraries don't count. \$\endgroup\$ – ugoren Feb 25 '14 at 14:57
  • \$\begingroup\$ @ugoren I'm confused about what you mean by chars/instructions, maybe I should have written instructions/characters instead of 1/characters * instructions? Noted about the linked libraries. \$\endgroup\$ – 2rs2ts Feb 25 '14 at 15:03
  • \$\begingroup\$ define DUP(x) x x and DUP(DUP(DUP(DUP(DUP(DUP(x++;)))))) - this duplicates x++ 64 times. Add another DUP and you get 128 times. \$\endgroup\$ – ugoren Feb 25 '14 at 15:20
  • 1
    \$\begingroup\$ I caught my mistake. The score can approach infinity, not zero. Still, I think, a problem. \$\endgroup\$ – ugoren Feb 25 '14 at 15:22
  • \$\begingroup\$ @ugoren Probably too many straightforward abuses to bar them all, eh? \$\endgroup\$ – 2rs2ts Feb 25 '14 at 15:29
1
\$\begingroup\$

How many pizzas do I need

Write a program that figures out the minimum number of pizzas I need to order and the amount of left overs I will have.

Requirements

  • Each pizza is 8 slices
  • Each person gets one choice of pizza topping, represented by a letter A-Z
  • Input in the format PVBC 2. Where each letter represents the choice of 1 person (e.g. P=Plain, V=Vegie, etc...), and the number is the amount of slices each person is allowed to eat. Letters can be in any order and do not need to be grouped.
  • If I don't need a full pizza I must be able to do half one topping and half another topping, the output for a half and half pizza will be denoted by X/Y where X and Y are different toppings
  • If I need multiple of a certain type of pizza they must be shown on one line (e.g. 2 x V Pizza). If there are different combinations the both result in the same, least, amount of pizzas, either output works
  • Output must match the format below of one type of pizza per line and a comma separated list of left overs. The output must show the minimum amount of pizzas and leftover possible.

Extra Credit

  • -20 - Take a 3rd argument that allows you to input the number of slices in a pizza, assume it will be an even number such that you can split it in half

Sample Input/Output

PCPVCB 3              (6 slices P, 3 slices V,  6 slices C, 3 slices B)
1 x P Pizza
1 x V/B Pizza
1 x C Pizza
2 slices P, 2 slices C, 1 slice V, 1 slice B left over

VBBCBBB 2             (10 slices B, 2 slices C, 2 slices V)
1 x C/V Pizza
2 x B Pizza
6 slices B, 2 slices C, 2 slices V left over

The 2nd example has many other combinations that could result in only 3 pizzas, this is just an example of what an output might be.

The shortest code wins.

| |
\$\endgroup\$
  • \$\begingroup\$ I can't say for sure, but I may have seen a similar challenge before. If not, it seems good to me. \$\endgroup\$ – user10766 Feb 18 '14 at 19:20
  • \$\begingroup\$ The use of the word "preferences" is confusing to me, because it suggests some kind of optimisation problem where people might get their second preference and you have to optimise for overall satisfaction. In addition, I don't find either the input or the output specification sufficiently clear. For the input, is there any guarantee that the letters are grouped (i.e. that PVP 1 will never be given as input)? And are the 4 letters given the only ones which may be used, or could there potentially be 26 different preferences? How much flexibility is there in the output? \$\endgroup\$ – Peter Taylor Feb 18 '14 at 21:12
  • \$\begingroup\$ @Danny, the one problem with this question is that because of my voracious appetite, there would be no left over pizza... ;) \$\endgroup\$ – WallyWest Feb 18 '14 at 21:15
  • \$\begingroup\$ @PeterTaylor I made edits to hopefully address all of the parts you saw that were possibly confusing. Can you look at the question again and let me know what you think. \$\endgroup\$ – Danny Feb 19 '14 at 13:44
  • \$\begingroup\$ @Danny You might want to add that you want the minimum amount of ordered pizzas/left overs - otherwise there exists a trivial solution where each person gets his own pizza (provided slices<=8). \$\endgroup\$ – Howard Feb 26 '14 at 8:19
  • \$\begingroup\$ Hello! This looks like a good but abandoned meta post, would you be willing to offer it for adoption? (If you want to, you can still post to main.) \$\endgroup\$ – programmer5000 Jun 9 '17 at 16:07
1
\$\begingroup\$

Resurrect Adobe SubScript.

In an obscure conference procedings volume of forgotton lore, there's a quaint little paper which describes an early effort to implement a published subset of Adobe Postscript. There a line in the bibliography! :) But it cannot be found Nobody's ever heard of it. :(

Adobe Systems, "SubScript Specification", 1984.

But there's obvious utility in such a thing. So this is a hypothetical Micro-Manual Postscript, and its name shall be ASS[*]. :)

ASS is a dynamically-typed stack-based programming language with powerful graphics primitives. It has support for floating-point arithmetic, arrays and dictionaries.

The scanner reads white-space delimited tokens and attempts to interpret the token as a decimal floating-point number with optional sign (+/-). The program may (but is not required to) support exponential notation. Failing to recognize a valid number, the token becomes a name object, an atomic symbol type which is identified by the name (an "interned" string).

Types

As suggested by the scanner behavior and the operator list , there are the following object types:

  • floating-point numbers (coerced to integer where appropriate)
  • names (usually an index into a string table, for easy comparisons)
  • arrays (an indexable sequence of objects)
  • dictionaries (a key-value map of objects)
  • operators (a pointer to a built-in function)

Operators

Operators are the basic actions predefined in the dynamic name space.

Stack Manipulation

  • any   pop   -
    pop an object from the operand stack

  • any1 any2   exch   any2 any1
    exchange top two elements

  • anyN anyN-1 ... any0 N   index   anyN anyN-1 ... any0 anyN
    retrieve object from stack by position

where N is treated as an integer.

Arrays.

  • N   array   array
    create a new array of length N

  • any0 any1 ... anyN-1 array   astore   array
    fill array with objects from stack

  • array   aload   any0 any1 ... anyN-1 array
    spill contents of array onto stack

  • [   any0 any1 ... anyN-1   ]   array
    construct an array

  • array index any   put   -
    put a value into array

  • array index   get   any
    retrieve value from array

where index is treated as an integer.

The typical way to implement the array syntax is using an auxiliary type, the marktype object, and an operator counttomark. This is an implementation detail and is not strictly required but may be found to be convenient.

  • -   [   mark
    produce marktype object as a sentinel on the stack

  • mark anyN anyN-1 ... any1   counttomark   mark anyN anyN-1 ... any1 N
    count objects up to mark

Then the ] operator may be implemented in terms of the other array operators.

  • mark anyN anyN-1 ... any1   ]   array
    { counttomark array astore exch pop }

Dictionaries.

  • N   dict   dict
    create a new dictionary, an associative container with room for N name-value pairs

  • dict   begin   -
    push dictionary on dictionary stack, making names part of the dynamic name space

  • -   currentdict   dict
    push copy of topmost dictionary on dictionary stack to the operand stack

  • -   end   -
    pop and discard the topmost dictionary on the dictionary stack

  • name any   def   -
    associate name with any value in topmost dictionary

  • name   load   any
    lookup name in each dictionary in the dictionary stack from the top-down, returning the first match, or error if not found

Matrices and transformations.

A matrix is a 6-number array [a b c d e f] which represent a left-multiplying affine transformation matrix with the constant right-most column omitted.

 a b 0
 c d 0  =>  [a b c d e f]
 e f 1
  • -   matrix   matrix
    returns a new identity matrix [1 0 0 1 0 0]

  • matrix   setmatrix   -
    make matrix the current transform in the graphics state

  • -   currentmatrix   matrix
    return current transform from the graphics state

  • x y   transform   x′ y′
    transform (x,y) pair by current transformation matrix

Transforming a point involves multiplying the homogeneous vector through the transformation matrix:

          [a b 0]
[x y 1] * [c d 0] => [x' y' 1]
          [e f 1]

or, equivalently

x' = a*x + c*y + e
y' = b*x + d*y + f

Path description.

  • -   newpath   -
  • x y   moveto   -
  • x y   lineto   -
  • -   closepath   -

Clipping.

  • -   clip   -
  • -   clippath   -

Painting.

  • -   erasepage   -
  • -   fill   -
  • -   showpage   -

The fill operator is where the magic happens. This operator is responsible for performing all of the graphics algorithms in sequence:

  • Shape Mapping
    Tranform the coordinates of the path from user space to device space using the current transformation matrix.

  • Shape Clipping
    Clip the portions of the path that lie outside the clipping path.

  • Filling
    *Perform a scan-line rasterization of the (may assumed closed-) polygon described by the path into the output frame buffer.

And showpage copies the contents of the framebuffer to the actual output mechanism (window or file as described above).

... need to fill this out a little more. Math, graphics state, errors. Describing stroked lines is too much, I think. I'm not sure if it needs the forall operators for iterating through arrays and dicts. I'd like to avoid any need for overloading different types under the same operator name, and calling back to user code from an operator.

Output may be to a window, or to a file in a simple format, like pgm or even a text-file of hashes and spaces for rough bitmaps. No half-toning. Only bi-level filling of convex polygons will be required. But a program may handle more colors if desired.

This is CW in case anybody wants to help me type-in the basic operators.

Questions

Does it need anything more? Should something be removed as unnecessary? Does anyone have the spec??

Perusing my ps implementations of the graphics portions linked in the comments, I've noticed the following needed operators:

length
sub
roll
add
eq
array copy
mul
div
ne

I think it needs loops, too. It's possible to do with just recursion, of course, but loops are nice. And length, I think, needs to be polymorphic, operating on array or dict to retrieve the size for making copies and calculating indices. Add sin and cos, too.


And this would be a .

[*] The moniker "ASS" is not intended as a disparagement of Adobe Systems nor any of their stupendous intellectual property. Rather it is merely intended to express frustration at the encountered difficulty in locating this document.

| |
\$\endgroup\$
  • \$\begingroup\$ So this is intended to be a subset of PostScript: are you going to point people at a PS spec for the nitty-gritty details about things like the precise implementation of path filling? Also, if the idea is to be minimalistic, why have both mark and [? \$\endgroup\$ – Peter Taylor Jan 11 '14 at 13:19
  • \$\begingroup\$ I'm hoping I can concisely specify everything so it's self-contained and not need to refer to a PS spec. ... Good point about mark. I suppose I can require [ and ] and suggest mark ... counttomark as a possible way to implement it. \$\endgroup\$ – luser droog Jan 11 '14 at 13:22
  • \$\begingroup\$ oh. I see what you mean now. removed mark as a separate entity. It isn't needed. \$\endgroup\$ – luser droog Jan 11 '14 at 13:32
  • \$\begingroup\$ My idea is to follow the most basic part of the original Warnock paper which is the basis of the Adobe Image Model. I've got some excerpts here. \$\endgroup\$ – luser droog Jan 11 '14 at 13:46
  • \$\begingroup\$ I don't see any way to create a non-identity matrix. \$\endgroup\$ – Peter Taylor Jan 24 '14 at 9:20
  • \$\begingroup\$ You can construct any matrix using the array notation. There should also be user space transforms: rotate, scale and translate. They're usually part of the graphics state, so I didn't put them under matrices. \$\endgroup\$ – luser droog Jan 24 '14 at 9:25
  • \$\begingroup\$ This spec from the 80s would be gold for implementing postscript. Offering a glimpse at the intermediate stage between the Warnock/Wyatt paper (which describes the image model in the syntax of the Xerox Mesa language) and the PLRM 1ed. Warnock/Wyatt has been described as "smuggling" the ideas out of Xerox. ... Ugh. I forgot to add some control structures. \$\endgroup\$ – luser droog Mar 1 '14 at 10:22
  • \$\begingroup\$ I've got implementations of paths, matrices, clipping, and filling in postscript. Perhaps I should wrap these up and just require the data structures and scanning to load and use them. \$\endgroup\$ – luser droog Mar 1 '14 at 11:33
  • \$\begingroup\$ Hello! This looks like a good but abandoned meta post, would you be willing to offer it for adoption? (If you want to, you can still post to main.) \$\endgroup\$ – programmer5000 Jun 9 '17 at 16:08
  • \$\begingroup\$ Thanks! ... Done. \$\endgroup\$ – luser droog Jun 11 '17 at 10:00
1
23 24
25
26 27
98

You must log in to answer this question.

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