577
\$\begingroup\$

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

Sandbox FAQ

Posting

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

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

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

Discussion

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

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

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

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

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

Other

Search the sandbox / Browse your pending proposals

The sandbox works best if you sort posts by active.

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

\$\endgroup\$
2
  • \$\begingroup\$ What if I posted on the sandbox a long time ago and get no response? \$\endgroup\$
    – None1
    Commented May 15 at 14:05
  • \$\begingroup\$ @None1 If you don't get feedback for a while you can ask in the nineteenth byte \$\endgroup\$ Commented May 29 at 13:27

4832 Answers 4832

1
70 71
72
73 74
162
1
\$\begingroup\$

Digit Sum of Sum of Digit Sums

Input: An integer from 1 to 1000 (known as N) Expected behavior: The code will go through the first N integers, and work out the digit sum for each integer, the code will then take these digit sums and add these together. The code will then take this total and work out the digit sum for that number. The final number is the expected output.

Example 1:

Input: 12

Output: 6

Behavior:

1) Numbers
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
2) Digit Sums
1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3
3) Sum of Digit Sums
51
4) Digit Sum of Sum of Digit Sums
6

Example 2:

Input: 20

Output: 3

Behavior:

1) Numbers
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20
2) Digit Sums
1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 2
3) Sum of Digit Sums
102
4) Digit Sum of Sum of Digit Sums
3

There are no restrictions on language type as long as the standard loopholes are avoided. Please demonstrate your code using the last three digits of your current reputation score.

This is code-golf, the shortest number of characters in code will be deemed the winner. In the event of a tie, the one with highest popular answer will be crowned the winner. If both answers are tied in terms of popularity and size, a fight to the death will be used to declare the winner (just kidding...)

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Why would anyone want to do this? Motivation is part of a good question. \$\endgroup\$ Commented Jun 20, 2019 at 8:01
1
\$\begingroup\$

Introduction

When dealing with data in two dimensions, data scientists looove to see straight lines emerge, as they can use a simple linear regression to model it - meaning we assume it is in the form of y=mx+b, and all that's left is to find the best m and b to describe the data.

There are several ways to fit a line to any data (I saw there was a challenge with Ordinary Least Squares once), however one of the most flexible one is gradient descent.

When given vectors X and Y, we start with an initial guess of m and b, then iteratively update them, and hopefully we get a better fit when we're done.

We give a "grade" to our current fitted line with mse (the lower the grade - the better the fit):

loss = mean((y - (m * x + b)) ** 2 for x, y in zip(X, Y))

And in each iteration we change m and b using the gradient of that same grade:

b -= 2 * alpha * mean((m * x + b) - y for x, y in zip(X, Y))
m -= 2 * alpha * mean(((m * x + b) - y) * x for x, y in zip(X, Y))

Here alpha is the learning rate (usually smaller than 1), used to keep the steps small enough to advance towards the minimum grade, rather than overstepping it.

The last question asked is when should we stop these iterations. We (a bit arbitrarily) impose two conditions:

  1. The absolute relative change in the grade between two iterations abs(grade1 - grade2)/grade1 is changed by less than some given epsilon, and/or
  2. A given number of iterations N has been performed already.

p.s. I started by assuming the data is just y(x), however this method may be easily extended to an arbitrary number of free variables and one dependent variable.

Challenge

Write a program that accepts inputs: X, Y, m, b, epsilon, N and returns the updated m and updated b after performing gradient descent as described.

corner cases:

  • X and Y may be empty, in which case m and b are returned unchanged.

This is code golf, so shortest code in bytes wins.

\$\endgroup\$
2
  • \$\begingroup\$ This is in need of a woked example and a fee test cases. \$\endgroup\$
    – Shaggy
    Commented Jun 22, 2019 at 22:17
  • 1
    \$\begingroup\$ What does mean mean? What does zip mean? Those should be made clear, just like you made alpha clear. \$\endgroup\$ Commented Jun 25, 2019 at 12:44
1
\$\begingroup\$

Proposed alternative to this

Golf an H interpreter

H is a text-based, weakly-typed string concatenation language. You task is to run an H script. You may do so by creating an interpreter, a compiler, a transpiler, or by any other reasonable means.

Definitions

Anything not defined herein is undefined behaviour and your implementation does neither have to support it nor does it need to throw an error. This includes unmatched quotes, invalid escapes, usage of variables before definition, etc. All given H scripts will abide by all the rules as stated.

General H syntax

Scripts: One or more lines, each containing zero or more statements, optionally followed by a comment.

White-space: you only have to support spaces in strings (tabs are escaped), plus tabs and/or spaces leading up to a comment.

Operators: There's only one, +, which is string concatenation.

Comments begin with # and continue until the end of the line. # may be prefixed by one or more spaces and/or tabs.

name: a sequence of exactly 4 single-case ASCII letters [A-Z] or [a-z] (you decide the scheme)

value: a +-delimited sequence of one or more strings (see below) and/or previously defined names. The combined value will never exceed 1000 characters.

Strings

Opened and closed by " and support ASCII 32–126 but with the following escape sequences:

\\: the literal backslash character; \

\n: a line break; CR, LF, CRLF, or LFCR (you decide)

\": a quotes symbol; "

\t: a tab character; (HT) or 2, 4, or 8 spaces (you decide)

A string matching the regex 0|-?[1-9]\d?\d? (i.e. look like an integer) may be left unquoted.

Statements

Terminated by ; but may not span multiple lines. There are only three types of H statements:

def name=value; sets the variable name to the given value.

print(value); prints value without trailing line break.

input(value;name); prints value without trailing line break, allows the user to enter a sequence of characters that extend that line, and assigns the characters to name. Any subsequent output begins on the next line.

Test script

The following assumes you have decided on the uppercase variable name scheme:

def HELO="Hello, ";
def HSMO=HELO+"strange"+-1;print("");
input(HSMO+"what is your name?";NAME);         #enter "User A" via stdin
#print(-123)   # nope
print(HELO+"\""+NAME+"\"\n\tthis isn't APL\\"+360+"!");

#done
print(-12+34)	# note the tab before #

Here is the equivalent using a lowercase variable name scheme:

def helo="Hello, ";
def hsmo=helo+"strange"+-1;print("");
input(hsmo+"what is your name?";name);         #enter "User A" via stdin
#print(-123)   # nope
print(helo+"\""+name+"\"\n\tthis isn't APL\\"+360+"!");

#done
print(-12+34)	# note the tab before #

Running the appropriate script, and entering User A should, according to the scheme where \t means ASCII 9 (HT), leave the console/screen/window showing:

Hello, strange-1what is your name?User A
Hello, "User A"
	this isn't APL\360!-1234

If instead you decided that \t means four spaces, it should show:

Hello, strange-1what is your name?User A
Hello, "User A"
    this isn't APL\360!-1234

\$\endgroup\$
5
  • 1
    \$\begingroup\$ You may want to explicitly state that User A is the STDIN-input in the Test script. I must admit I just can't read and read past the explanation of input(value;name); when going through the test script and was thinking: where is def name="User A";. And based on "Anything not defined herein is undefined behaviour and your implementation does neither have to support it nor does it need to throw an error." we can assume all scripts are valid, so no " that are unmatched, and no variable used before it is defined, and stuff like that? \$\endgroup\$ Commented Jun 28, 2019 at 13:45
  • 1
    \$\begingroup\$ @KevinCruijssen How is it now? \$\endgroup\$
    – Adám
    Commented Jun 28, 2019 at 15:50
  • 1
    \$\begingroup\$ Perfect. :) I had already upvoted I see. Everything is clear to me now. \$\endgroup\$ Commented Jun 28, 2019 at 16:40
  • 1
    \$\begingroup\$ @UserA No. There is an overwhelming consensus that one should avoid bonuses in code golf. \$\endgroup\$
    – Adám
    Commented Jul 3, 2019 at 13:23
  • 1
    \$\begingroup\$ @UserA It is very probably that many of the solutions will allow all of those any way. \$\endgroup\$
    – Adám
    Commented Jul 3, 2019 at 13:24
1
\$\begingroup\$

Switch the colour of the largest non-unique connected shape

Given a rectangular grid of square cells, find the non-unique connected shapes with the largest area, and switch their colour

Input

  • A rectangular grid of cells, each of which has 1 of 2 distinct values ("colours")
  • You can choose to accept any of
    • an image with only 2 distinct pixel colours
    • text with only 2 distinct characters (also allowing newlines for forming a rectangle)
    • a 2d array, with each element having 1 of 2 distinct values
    • a 1d array, plus a width and/or height

The 2 distinct values will be referred to as "colours", but the rules apply similarly for all of the permitted formats

Output

  • A rectangular grid of cells in the same format as the input, using the same 2 colours
  • For each shape required to be changed, all of its cells have been switched to the other colour

Rules

  • Each cell is part of a connected shape, which contains all cells of the same colour that can be reached by a path made up only of vertical or horizontal steps to adjacent cells of the same colour (no diagonal steps)
  • The grid does not wrap: a shape cannot be connected across the outer boundary
  • A shape is identical to another if it can be made to coincide exactly with it by any combination of
    • translation
    • rotation by an integer multiple of 90 degrees
    • reflection in any vertical or horizontal line
    • switching its colour
  • A shape is unique if no other shape is identical to it
  • The area of a shape is the number of cells it contains
  • The shapes to be changed are those with the largest area, of those that are non-unique
  • If 2 or more distinct shapes are non-unique and have the largest area, all instances of each distinct shape must be changed
  • If there are no non-unique shapes, the output is the same as the input
  • A grid (input or output) may sometimes contain only 1 of the 2 colours

Test cases

Each test case is an input followed by its unique correct output

.  .

..  ..

.#  #.

.#  .#
..  ..

.#  #.
#.  .#

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

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

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

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

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

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

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

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

The same test cases with colour coding for human reading (click image for larger version):

test cases with colour coding

Scoring

This is . Your score is the number of bytes in your source code. For each language, the code with the lowest score wins


Sandbox thoughts

  • Any important/useful test cases welcome
  • Is there a more useful format for 2d test cases?
  • Are there 2 distinct characters that would make human reading easier?
  • Is this a duplicate?
  • Can anything be made clearer or more succinct?
  • I'm also trying to think of a better name
\$\endgroup\$
2
  • 1
    \$\begingroup\$ I think using "remove" and "change" to mean the same thing is confusing. If I understand correctly, "removing" means to change the colour of, right? That wasn't very intuitive to me on my first reading. \$\endgroup\$ Commented Jun 29, 2019 at 16:52
  • \$\begingroup\$ Ah good point. Thank you. I will try and make that consistent throughout \$\endgroup\$ Commented Jun 29, 2019 at 19:16
1
\$\begingroup\$

Some enchanted avening

(you may see a stranger across a crowded room).

This is one part of a multi-part series inspired by various built-ins in R. Credit goes to digEmAll for suggesting this one.

ave calculates particular grouped values of a list.

For example, we would group x in the following way based on the criteria given in f:

x = [2, 1, 3, 5, 4, 1, 5, 5]
f = [[1, 2, 2, 2, 1, 2, 1, 1], [1, 1, 2, 2, 2, 1, 1, 2]]

     x f1 f2
[1,] 2  1  1    -> group [1,1]
[2,] 1  2  1    -> group [2,1]
[3,] 3  2  2    -> group [2,2]
[4,] 5  2  2    -> group [2,2]
[5,] 4  1  2    -> group [1,2]
[6,] 1  2  1    -> group [2,1]
[7,] 5  1  1    -> group [1,1]
[8,] 5  1  2    -> group [1,2]

Then for each group, we apply a given function (in R, the default is mean), let's say sum:

group [1,1]: 2, 5 -> sum = 7
group [2,1]: 1, 1 -> sum = 2
group [2,2]: 3, 5 -> sum = 8
group [1,2]: 4, 5 -> sum = 9

Then we replace each value in the group by the group sum, resulting in an output of:

[7, 2, 8, 8, 9, 2, 7, 9]

Inputs:

  • a list x of integers
  • a list of lists f or an arbitrary number of lists, each of length equal to x; these are the factors to group on
  • a black-box function FUN that takes a list of integers and returns a single integer value

Output

  • a list o of length equal to x where each element o[i] is equal to FUN(group(x[i])), or as the documentation says:

    A numeric vector, say y of length length(x). If f is g1, g2, e.g., y[i] is equal to FUN(x[j], for all j with g1[j] == g1[i] and g2[j] == g2[i]).

Rules

  • Input can be in any order and in many flexible output formats.
  • You may assume that the outputs will always result in integers.
  • If your language has a builtin for this for some reason, please also implement your own solution.

Sandbox questions/notes:

  • I've done two of these so far and found a reference to a musical that is somewhat appropriate, any suggestion is appreciated there.
  • Need to add test cases
  • Need to work a bit harder on the explanation of how ave works.
\$\endgroup\$
1
  • 1
    \$\begingroup\$ You could call this something along the lines of "Ave Maria von Trapp"? Aside from that I understood your description well enough to write a (poor) answer. \$\endgroup\$ Commented Jun 26, 2019 at 19:45
1
\$\begingroup\$

Manage a todo list using Cypher (WIP)

Introduction

A list is a common, well-understood data structure. Neo4j's property graph model can represent any data structure. Using the Cypher query language, write a collection of statements for managing a todolist

Challenge

Manage a todo list using parameterized Cypher.

Todo list items are composed of two pieces of information:

  • todo:string - the textual content describing the thing to do
  • completed:boolean - whether this todo has been done

Todo list operations:

  • add new, view, edit, remove, complete, un-complete individual todo list item
  • re-order todo list item
  • view all items
  • view all completed items
  • view all "active" items (items not yet completed)
  • complete all todo list items

Considerations:

  • empty todo list

Out of scope:

  • multiple lists

Answer Format

For each operation, provide a code block of Cypher. Identify the operation with its description. Separate each operation with a --- line. Like this...

  1. Create an empty node:
CREATE ()

  1. Create a generic relationship:
CREATE ()-[:RELATES_TO]->()

Proposed tags

[cypher] [graph-theory]

\$\endgroup\$
1
  • \$\begingroup\$ (1) This is a long way from being self-contained. What's Neo4j? (Sounds like a Java library). What's Cypher? (2) The operations need more explanation, particularly those which rely on properties which haven't been mentioned. (Reorder? But there's no position-in-order property. Operations on individual item: what's its identity?). (3) This site discourages questions which restrict answers to a single language unless there's a good reason for the restriction. I don't see a good reason here. \$\endgroup\$ Commented Jul 6, 2019 at 7:54
1
\$\begingroup\$

Can the cursor reach the bottom?

A cursor position is valid if either of its two sides touches whitespace (i.e. a space or a newline(CR+LF or LF, depending on your OS)). The input will always consist of valid cursor positions.

This takes one input(a character matrix), and for a cursor on the up right corner of the input, can the cursor reach the bottom of the input?

Example input:

 ..... Same, delete text like this in order
 ......
. . . .
.      Same to get normal input
...... Same

The cursor can reach the bottom in this case. This process of moving the cursor will work: down, right(touches spaces on the left), down(touches spaces on the right), down, right(touches spaces on both sides) 6 times, and down(touching spaces and a linefeed).

Notably, this will also work:

  Code Golf deletes trailing whitespace by default
..
. trailing

The cursor starts at the up-right corner. After moving right two times, it can move down (due to touching a newline character). Then, it can move down, which touches the bottom of the line.

This example will not work:

 ...
... Same reason as above

The cursor cannot move down, as there is no sufficient whitespace to be touched.

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

Posted here

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Interesting challenge, but I'm afraid a lot of trivial solutions exist. E.g. 123 which prints 123 in many languages. More interesting would be to require all three/four characters to be unique, and that they be printed in reverse. \$\endgroup\$
    – Adám
    Commented Jul 8, 2019 at 20:04
  • 2
    \$\begingroup\$ now that this has been posted, you can edit it to only include a link to your post and delete it :-) \$\endgroup\$
    – Giuseppe
    Commented Jul 9, 2019 at 18:50
1
\$\begingroup\$

There's an echo in my array... echo in my array... my array...

Posted. Thanks for all of the suggestions and happy golfing!

\$\endgroup\$
11
  • \$\begingroup\$ "0≤n<1000" The input has 0–1000 elements or the elements are in the range 0–1000, or both? \$\endgroup\$
    – Adám
    Commented Jul 8, 2019 at 21:24
  • \$\begingroup\$ Can there not be multiple correct solutions? \$\endgroup\$
    – Adám
    Commented Jul 8, 2019 at 21:26
  • \$\begingroup\$ Will the echo ever begin at the first element? \$\endgroup\$
    – Adám
    Commented Jul 8, 2019 at 21:26
  • \$\begingroup\$ I'm not sure I fully understand how the echo works. Why can [2,4,6] not be [1,2,3] with an echo overlapping at the first element? \$\endgroup\$
    – Adám
    Commented Jul 8, 2019 at 21:31
  • \$\begingroup\$ In fact, would there be one solution for each step, so dividing the input by 2 is always a valid solution? \$\endgroup\$
    – Adám
    Commented Jul 8, 2019 at 21:32
  • \$\begingroup\$ @Adám ah yes, that's why echo cannot begin at the first element. The echo'd version will always be longer than the original un-echoed version. I'll clarify that. \$\endgroup\$
    – 640KB
    Commented Jul 8, 2019 at 21:33
  • \$\begingroup\$ @Adám have updated rules and test cases from your comments. Thanks! \$\endgroup\$
    – 640KB
    Commented Jul 9, 2019 at 18:32
  • \$\begingroup\$ As suggestion: if there is no echo, don't output nothing or false - the challenge is to correct the echo. If there is none, the echo is corrected to be... no different from the input. In a bid for consistency, I would therefore suggest that if there is no echo, they should output the original input, since that is the 'normal' version of the array. \$\endgroup\$ Commented Jul 10, 2019 at 8:09
  • \$\begingroup\$ Also, I'd suggest to make the program return the shortest possible array in the case of multiple solutions, to remove the most possible reverb - i.e choose the one that removes the most values from the input. \$\endgroup\$ Commented Jul 10, 2019 at 13:42
  • \$\begingroup\$ @GezaKerecsenyi I've been trying to come up with a case where there are multiple solutions, and cannot. You can easily have many echo'd versions for a given un-echo'd version, but there seems to only be one or zero un-echo'd versions for an echo'd version. I'm not a mathematician, so I cannot conclusively prove this, and I'm happy to be proven wrong, but I don't see a way that a correctly-constructed echo'd version could produce more than one answer. \$\endgroup\$
    – 640KB
    Commented Jul 10, 2019 at 14:52
  • 1
    \$\begingroup\$ @gwaugh after further consideration, I have come to the conclusion that you're correct. It's like a Fourier transform: every wave function always have a unique value, either in terms of phase or magnitude. Here, the phase is always different, and since the phase is shifted, the 'transform' of these numbers (imagining they are Y values at the X point of their index) must also be unique. So feel free to remove that rule - there can never be two answers. \$\endgroup\$ Commented Jul 10, 2019 at 17:12
1
\$\begingroup\$

Story

I began studying the Collatz Conjecture

And noticed this pattern in the numbers that go to 1 in one odd step, like 5,10,20,21,40,42... and looke in up on OEIS and found this formula.

\$floor(sqrt(4*n + 1)) - 1\$

Which can plot these numbers in their natural order like so;

\$\frac{\left(8\cdot2^{\operatorname{floor}\left(\sqrt{4\operatorname{floor}\left(x\right)+1}\right)}-2^{\left(\operatorname{floor}\left(\sqrt{4\operatorname{floor}\left(x\right)+1}\right)-1-\operatorname{floor}\left(\frac{\left(4\operatorname{floor}\left(x\right)+1-\operatorname{floor}\left(\sqrt{4\operatorname{floor}\left(x\right)+1}\right)^2\right)}{2}\right)\right)}\right)}{3}\$

Then I looked at numbers going to 1 in two steps, like 3,6,12,13,24,26...
Where I found another pattern that I could not find a formula for on OEIS

long nth(int n){if(n>241)return -1;return (((1<<Y[n]+5)-(1<<1+Y[n]-((Z[n]&1)+Z[n]*3)))/3-(1<<Y[n]-2*X[n]-(2*(Z[n]&1)+Z[n]*3)))/3;}

With X[],Y[] and Z[] being these lookup-tables

 int[]X=new int[]{
 0, 
 0, 
 0,  1, 
 0,  1, 
 0,  1,  2, 
 0,  1,  2,                              0,
 0,  1,  2,  3,                          0,                          0, 
 0,  1,  2,  3,                          0,  1,                      0, 
 0,  1,  2,  3,  4,                      0,  1,                      0,  1, 
 0,  1,  2,  3,  4,                      0,  1,  2,                  0,  1, 
 0,  1,  2,  3,  4,  5,                  0,  1,  2,                  0,  1,  2,
 0,  1,  2,  3,  4,  5,                  0,  1,  2,  3,              0,  1,  2,                  0,
 0,  1,  2,  3,  4,  5,  6,              0,  1,  2,  3,              0,  1,  2,  3,              0,              0, 
 0,  1,  2,  3,  4,  5,  6,              0,  1,  2,  3,  4,          0,  1,  2,  3,              0,  1,          0, 
 0,  1,  2,  3,  4,  5,  6,  7,          0,  1,  2,  3,  4,          0,  1,  2,  3,  4,          0,  1,          0,  1, 
 0,  1,  2,  3,  4,  5,  6,  7,          0,  1,  2,  3,  4,  5,      0,  1,  2,  3,  4,          0,  1,  2,      0,  1, 
 0,  1,  2,  3,  4,  5,  6,  7,  8,      0,  1,  2,  3,  4,  5,      0,  1,  2,  3,  4,  5,      0,  1,  2,      0,  1,  2, 
 0,  1,  2,  3,  4,  5,  6,  7,  8,      0,  1,  2,  3,  4,  5,  6,  0,  1,  2,  3,  4,  5,      0,  1,  2,  3,  0,  1,  2,      0, 
 0,  1,  2,  3,  4,  5,  6,  7,  8,  9,  0,  1,  2,  3,  4,  5,  6,  0,  1,  2,  3,  4,  5,  6,  0,  1,  2,  3,  0,  1,  2,  3,  1, 2
 };
 int[]Y=new int[]{
 0, 
 1, 
 2,  2, 
 3,  3, 
 4,  4,  4, 
 5,  5,  5,                              5,
 6,  6,  6,  6,                          6,                          6, 
 7,  7,  7,  7,                          7,  7,                      7, 
 8,  8,  8,  8,  8,                      8,  8,                      8,  8, 
 9,  9,  9,  9,  9,                      9,  9,  9,                  9,  9, 
10, 10, 10, 10, 10, 10,                 10, 10, 10,                 10, 10, 10,
11, 11, 11, 11, 11, 11,                 11, 11, 11, 11,             11, 11, 11,                 11,
12, 12, 12, 12, 12, 12, 12,             12, 12, 12, 12,             12, 12, 12, 12,             12,             12, 
13, 13, 13, 13, 13, 13, 13,             13, 13, 13, 13, 13,         13, 13, 13, 13,             13, 13,         13, 
14, 14, 14, 14, 14, 14, 14, 14,         14, 14, 14, 14, 14,         14, 14, 14, 14, 14,         14, 14,         14, 14, 
15, 15, 15, 15, 15, 15, 15, 15,         15, 15, 15, 15, 15, 15,     15, 15, 15, 15, 15,         15, 15, 15,     15, 15, 
16, 16, 16, 16, 16, 16, 16, 16, 16,     16, 16, 16, 16, 16, 16,     16, 16, 16, 16, 16, 16,     16, 16, 16,     16, 16, 16, 
17, 17, 17, 17, 17, 17, 17, 17, 17,     17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,     17, 17, 17, 17, 17, 17, 17,     17, 
18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18
};
int[]Z=new int[]{
0, 
0, 
0,  0, 
0,  0, 
0,  0,  0, 
0,  0,  0,                              1,
0,  0,  0,  0,                          1,                          2, 
0,  0,  0,  0,                          1,  1,                      2, 
0,  0,  0,  0,  0,                      1,  1,                      2,  2, 
0,  0,  0,  0,  0,                      1,  1,  1,                  2,  2, 
0,  0,  0,  0,  0,  0,                  1,  1,  1,                  2,  2,  2,
0,  0,  0,  0,  0,  0,                  1,  1,  1,  1,              2,  2,  2,                  3,
0,  0,  0,  0,  0,  0,  0,              1,  1,  1,  1,              2,  2,  2,  2,              3,              4, 
0,  0,  0,  0,  0,  0,  0,              1,  1,  1,  1,  1,          2,  2,  2,  2,              3,  3,          4, 
0,  0,  0,  0,  0,  0,  0,  0,          1,  1,  1,  1,  1,          2,  2,  2,  2,  2,          3,  3,          4,  4, 
0,  0,  0,  0,  0,  0,  0,  0,          1,  1,  1,  1,  1,  1,      2,  2,  2,  2,  2,          3,  3,  3,      4,  4, 
0,  0,  0,  0,  0,  0,  0,  0,  0,      1,  1,  1,  1,  1,  1,      2,  2,  2,  2,  2,  2,      3,  3,  3,      4,  4,  4, 
0,  0,  0,  0,  0,  0,  0,  0,  0,      1,  1,  1,  1,  1,  1,  1,  2,  2,  2,  2,  2,  2,      3,  3,  3,  3,  4,  4,  4,      5, 
0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  1,  1,  1,  2,  2,  2,  2,  2,  2,  2,  3,  3,  3,  3,  4,  4,  4,  4,  5, 5
};

Challenge

The challenge is to write a "reasonably fast" function or expression that replaces and extends these lookup tables.
Think of the lookup tables as a 3D structure. Pictured is the top 720 boxes of this structure.

challenge

Input

An integer which is the index of a cube in the structure. You can assume the input will be in the range 0 to 719 inclusive.

Output

The x,y,z coordinates for the given index. Assuming the input is between 0 and 719 the output ranges are x, 0 to 13 y, 0 to 27 z, 0 to 8

It's fine to accept and return larger indexes correctly just not required.

Examples

    i  ->   x   y   z
    0  ->   0,  0,  0
   12  ->   0,  5,  1
   30  ->   4,  8,  0
   65  ->   2, 11,  1
  100  ->   0, 13,  2
  270  ->   1, 19,  3
  321  ->   1, 20,  6
  719  ->   1, 27,  8

If you collapse the z-coordinate, then the structure is indexed top-down left right like shown below; Examples are marked in square brackets []

Y,Z 0,
 0   | [0]  
 1   |  1 
 2   |  2   3 
 3   |  4   5 
 4   |  6   7   8                                1,
 5   |  9  10  11                                 |[12]                           2,
 6   | 13  14  15  16                             | 17                             | 18 
 7   | 19  20  21  22                             | 23  24                         | 25 
 8   | 26  27  28  29 [30]                        | 31  32                         | 33  34 
 9   | 35  36  37  38  39                         | 40  41  42                     | 43  44 
10   | 45  46  47  48  49  50                     | 51  52  53                     | 54  55  56                    3,
11   | 57  58  59  60  61  62                     | 63  64 [65] 66                 | 67  68  69                     | 70                4,
12   | 71  72  73  74  75  76  77                 | 78  79  80  81                 | 82  83  84  85                 | 86                 | 87 
13   | 88  89  90  91  92  93  94                 | 95  96  97  98  99             [100] 101 102 103                |104 105             |106 
14   |107 108 109 110 111 112 113 114             |115 116 117 118 119             |120 121 122 123 124             |125 126             |127 128 
15   |129 130 131 132 133 134 135 136             |137 138 139 140 141 142         |143 144 145 146 147             |148 149 150         |151 152 
16   |153 154 155 156 157 158 159 160 161         |162 163 164 165 166 167         |168 169 170 171 172 173         |174 175 176         |177 178 179        5,
17   |180 181 182 183 184 185 186 187 188         |189 190 191 192 193 194 195     |196 197 198 199 200 201         |202 203 204 205     |206 207 208         |209    6, 
18   |210 211 212 213 214 215 216 217 218 219     |220 221 222 223 224 225 226     |227 228 229 230 231 232 233     |234 235 236 237     |238 239 240 241     |242     |243 
19   |244 245 246 247 248 249 250 251 252 253     |254 255 256 257 258 259 260 261 |262 263 264 265 266 267 268     |269[270]271 272 273 |274 275 276 277     |278 279 |280
20   |281 282 283 284 285 286 287 288 289 290 291 |292 293 294 295 296 297 298 299 |300 301 302 303 304 305 306 307 |308 309 310 311 312 |313 314 315 316 317 |318 319 |320[321]
  X->|  0   1   2   3   4   5   6   7   8   9  10 |  0   1   2   3   4   5   6   7 |  0   1   2   3   4   5   6   7 |  0   1   2   3   4 |  0   1   2   3   4 |  0   1 |  0   1  

Note that at even y-coordinates the structure expands in the x-direction, and at 0 and 5 mod 6 in the z-direction. Expect for the very top block.

Rules

This is code-golf, the shortest code in bytes wins.

Reasonably fast As an additional requirement although not a competition of fastest code,
the code must still be shown to compute coordinates in a reasonable amount of time. You may for example use try it online and run a loop through all coordinates under 720 without exceeding the time limit of a minute, printing is optional.

If you fail this rule, mark your answer with non competing

"storing information as you go" is forbidden. For example executing f(100) should not depend on having computed f(99) previously.

Lookup tables are allowed but included in bytecount so aim to make them sparse if you choose to use them.

Example code

non-competing

coord coords(int index){
int a=0,b=0,c=0;
int x=0,y=0,z=0;
long n,k,one;  
n = k = 3;
int t=0;
while(t<index){
int s=0;k++;n=k;
while(n>1 && s<4){ n/=n&-n;n=n*3+1; n/=n&-n;s++;}
if(s==2)t++;
}
n=k; 
one=n&-n;k = one;while(k>1){k>>=1;c++;} n=3*n+one;
one=n&-n;k = one;while(k>1){k>>=1;b++;} n=3*n+one;
one=n&-n;k = one;while(k>1){k>>=1;a++;} 
coord r;
r.x = (b-c-1)>>1;
r.y = a-5;
r.z = (a-b-2)/6 +(a-b-4)/6;
return r;
}

Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ Will the input always be between 0 and 321 (inclusive)? \$\endgroup\$
    – mkst
    Commented Jul 10, 2019 at 6:27
  • \$\begingroup\$ Good question, let's go with 797 @streetster \$\endgroup\$ Commented Jul 10, 2019 at 10:59
  • \$\begingroup\$ @streetster 719.. i counted the boxes wrong, good thing I began in the sandbox \$\endgroup\$ Commented Jul 11, 2019 at 17:58
1
\$\begingroup\$

Decode a RISC-V J-type immediate

RISC-V is an open processor instruction set, which defines a somewhat typical RISC instruction set. However, in order to make decoding simpler in hardware, the encoding for immediate values tends to be quite complex, with the bits essentially shuffled around. And the worst offender for that is without a doubt the type J (jump) instruction type.

So, the challenge is, given a (non-compressed) RISC-V instruction word, decode and output its type J immediate part.

A type J instruction has the following format:

   31      30-21     20       19-12   11-7  6-0
|imm[20]|imm[10:1]|imm[11]|imm[19:12]| rd |opcode|

The only fields we are interested in are the imm fields. The immediate is sign extended, and its least significant bit is always 0, so the immediate (in term of instruction bits) is:

    31-20       19-12       11        10-1     0
|...inst[31]|inst[19:12]|inst[20]|inst[30:21]| 0 |

Sample pseudocode: 0xFFF00000 * ((instr >> 31) & 1) | (instr & 0x000FF000) | ((instr & 0x100000) >> 9) | ((instr & 0x7FE00000) >> 20).

Test cases

I: 0x4DFAB06F (j 0xABCDE)
O: 0x000ABCDE

I: 0xFD9FF0EF (jal ra, -0x28)
O: 0xFFFFFFD8

I: 0x8000006F (j -0x100000)
O: 0xFFF00000

The answer with the smallest byte count wins, standard loopholes apply, etc... Your program may take input and write output in any format it requires.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ It took a bit of puzzling to figure out the second code block. The ... notation is liable to misunderstanding (I'm not sure whether JS developers would find it more or less confusing), and there's no clear reason for 10-5 and 4-1 to be split up. This is one case where a reference implementation in generic C-like pseudocode could help: I think 0xfff00000 * ((imm >> 31 & 1)) | (imm & 0x000ff000) | ((imm & 0x00100000) >> 9) | ((imm & 0x7fe00000) >> 20) is correct and fairly generic. (In particular, I've deliberately avoided making assumptions about how the sign bit is treated under >>). \$\endgroup\$ Commented Jul 16, 2019 at 8:10
  • 1
    \$\begingroup\$ @PeterTaylor I copied the instruction format diagram from the RISC-V specification and I didn't realize the 10-5 and 4-1 parts could be merged. Oops. And I added a pseudocode for the decoding. \$\endgroup\$ Commented Jul 16, 2019 at 11:38
1
\$\begingroup\$

Alphanumeric Line and Curve Counting

Posted here.

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

Bits and Bytes constant generation

In this challenge, you have to generate the shortest Bits and Bytes program that outputs an integer input. For the simplicity of the challenge, you only have to search with ! and <.

Bits and Bytes quick reference

Bits and Bytes operates on a one-byte accumulator. There are 4 operations (only 2 are neccecary for this challenge):

  • ! : Invert all of the bits in the accumulator
  • < : Shifts all bits in the accumulator one bit to the right. The leftmost bit becomes a 0 and the rightmost bit is discarded.
  • > : Shift right
  • @ : Swap nybbles

Input / Output

Input will be two integers. The first integer sets the accumulator to the value of that integer. The second integer indicates the resulting value. Your program should output the shortest program in Bits and Bytes that sets the accumulator to that value.

Examples

0
255
!
0
4
!<!<!<

This is a contest; the shortest program wins.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ I'd recommend having the question be self contained and explaining what the instructions actually do \$\endgroup\$
    – Jo King Mod
    Commented Jul 21, 2019 at 11:34
  • 2
    \$\begingroup\$ This is similar enough to some previous challenges that I wouldn't be surprised if someone finds a dupe. Also, should there be a second input for the starting value of the accumulator? \$\endgroup\$ Commented Jul 21, 2019 at 23:04
1
\$\begingroup\$

WANTEDM?VEMENTANDACALMCOURSE?FE???UENCE

Challenge

Inspired by puzzles appearing on my website's chat, your job (should you choose to accept it) is to accept a string (say (?@Nbgkx¨¾ÃÐÕã÷øĆĊċĎďěĨīĺŏšŴŹǣǩǮ˘͵ΖΫΰξρφ) and:

  • Find the Unicode points for the string: [40, 63, 64, 78, 98, 103, 107, 120, 168, 190, 195, 208, 213, 227, 247, 248, 262, 266, 267, 270, 271, 283, 296, 299, 314, 335, 353, 372, 377, 483, 489, 494, 728, 885, 918, 939, 944, 958, 961, 966]
  • Find the differences between elements: [23, 1, 14, 20, 5, 4, 13, 48, 22, 5, 13, 5, 14, 20, 1, 14, 4, 1, 3, 1, 12, 13, 3, 15, 21, 18, 19, 5, 106, 6, 5, 234, 157, 33, 21, 5, 14, 3, 5]
  • For every element in the differences between elements:
    • If the element is less than 27, add it by 64 and output it converted to a Unicode character (e.g. 1 -> "A", 2 -> "B", \$\ldots\$ ).
    • If the element is greater than or equal to 27, output a non-alphabet character ([^A-Za-z])

Test Cases

The test cases output in uppercase and use the question mark for the non-alphabet character.

(?@Nbgkx¨¾ÃÐÕã÷øĆĊċĎďěĨīĺŏšŴŹǣǩǮ˘͵ΖΫΰξρφ --> WANTEDM?VEMENTANDACALMCOURSE?FE???UENCE
!1CRYkly¤´ÉãýĉĎġĢİĴķņŊŏŖťűŷ --> PROGRAM?PUZZLESANDCODEGOLF
!$37<CR^deswz¤«®¶·ÃÏÔâéîā --> CODEGOLFANDC?GCHALLENGES
!5=BShqt¢¹ÇÍÜôþēĠİĵĹňŞţŵƉƑƖƢƣƽǖǚǩǰȃ -> THEQUIC?WNFOXJUMPEDOVERTHELAZYDOGS

Notes

  • The difference between the Unicode points for the string will always be greater than 0.
  • The input's Unicode points will be strictly increasing.
  • You may output in lowercase.
  • The non-alphabet character does not need to be consistent.
\$\endgroup\$
4
  • \$\begingroup\$ I suggest using less than or equal to 26, so that Z can be represented \$\endgroup\$
    – wastl
    Commented Aug 1, 2019 at 12:59
  • \$\begingroup\$ @wastl Yeah, done \$\endgroup\$
    – MilkyWay90
    Commented Aug 1, 2019 at 16:07
  • 1
    \$\begingroup\$ What stops us from just adding 97 to all the differences, since outside that range is non-alphabetical? \$\endgroup\$
    – Jo King Mod
    Commented Aug 2, 2019 at 4:09
  • 1
    \$\begingroup\$ @JoKing Nothing stops you from doing that. \$\endgroup\$
    – MilkyWay90
    Commented Aug 2, 2019 at 4:54
1
\$\begingroup\$

I've had an idea for a coding challenge, but I'm a). not 100% certain it's not already been done, and b) not sure if some of the golfing specific languages will trivialise it too much.

Basically the premise is thus:

The scoring for your question is achieved in the following fashion:

  1. All comments are removed from your script
  2. +1 point per character in your script
  3. +1 point per character in your output
  4. The following algorithm applied to the concatonation of your script and your output:
    • +1 point the first time a character shows up
    • -1 point the second time a character shows up
    • -2 points the third time
    • -4 points the fourth time
    • -8 points the fifth
    • double ad infinitum
  5. The scores for character repetition above are cumulative. So, a would yield 2 points (1 for length, 1 for first occurance of character). aa would yield 2 points (2 for length, +1 for first instance, -1 for second instance). aaa would yield 1 point (3 for length, +1 for 1st, -1 for 2nd, -2 for third)

Rules:

  • No standard loopholes

I'm also not even sure what I would tag this question as.

\$\endgroup\$
11
  • 2
    \$\begingroup\$ As far as tagging goes: code-challenge. \$\endgroup\$
    – Wheat Wizard Mod
    Commented Aug 2, 2019 at 14:12
  • 1
    \$\begingroup\$ One issue is I could just write a comment with 65,000 unicode characters in it. \$\endgroup\$
    – rydwolf
    Commented Aug 2, 2019 at 14:45
  • \$\begingroup\$ @RedwolfPrograms ah so there needs to be a rule excluding comments \$\endgroup\$
    – Scoots
    Commented Aug 2, 2019 at 14:49
  • \$\begingroup\$ Hmm and I also need a creative way to say “script cannot simply be print ‘abcdefg...’ \$\endgroup\$
    – Scoots
    Commented Aug 2, 2019 at 14:51
  • 2
    \$\begingroup\$ @Scoots Well, that's where it gets complicated. This could also be considered a code-bowling challenge in a way, since the goal is to make the longest source code (or output) possible. The issue with code bowling questions is that they often have exploitable loopholes like comments, regexes, variable names, etc. I'd find a way to work this into the scoring, such as reducing points for source code lengths and adding points for output length \$\endgroup\$
    – rydwolf
    Commented Aug 2, 2019 at 14:52
  • \$\begingroup\$ @RedwolfPrograms that falls afoul of a for loop and a given language’s chr function. This will take some thinking. \$\endgroup\$
    – Scoots
    Commented Aug 2, 2019 at 14:57
  • \$\begingroup\$ @Scoots Maybe base it on some other element, like execution time? \$\endgroup\$
    – rydwolf
    Commented Aug 2, 2019 at 14:59
  • 1
    \$\begingroup\$ @RedwolfPrograms Nah that's too contingent on circumstances outside our control (how busy is the server when it runs the script etc)... I'm going to think on this for a while. Maybe something creative with exclusives between script and output \$\endgroup\$
    – Scoots
    Commented Aug 2, 2019 at 15:45
  • 1
    \$\begingroup\$ @Scoots I haven't seen too many good posts based on getting the longest source code/output, and I'll be excited to see something new. Good luck! \$\endgroup\$
    – rydwolf
    Commented Aug 2, 2019 at 16:00
  • 1
    \$\begingroup\$ I only see a scoring system, but no challenge. Also, in languages like Unary or Whitespace it would be trivial to get arbitrarily large negative scores - and in most languages you can add effective no-ops. I think this kind of thing has been tried before, but it may not have made it past the sandbox because it has big problems which can't really be fixed. \$\endgroup\$ Commented Aug 5, 2019 at 7:53
  • 1
    \$\begingroup\$ @PeterTaylor The challenge would be to get the highest possible positive score of course, but sadly my thinking has led me to concur with the rest of your statement. Sandbox being the filter it is supposed to be :) \$\endgroup\$
    – Scoots
    Commented Aug 5, 2019 at 16:58
1
\$\begingroup\$

This puzzle is based on this Math.SE post.

Assume I have some number of black shirts and some number of white shirts, both at least 1. Both colors of shirt have a non-zero durability. All shirts of a given color start with the same durability.

Every day, I pick out a clean shirt to wear, and it becomes dirty. Once I run out of all clean black shirts or all clean white shirts, I wash all my dirty shirts of both colors and start over. Clean shirts do not get washed. Whenever a shirt gets washed, its durability goes down by one. Immediately after washing, if the durability of a shirt reaches 0, it must be thrown out.

When picking which shirt to wear of a particular color, I always choose a shirt with the highest durability of that color to ensure even wear and tear among shirts.

Challenge:

Take in a sequence of two characters of arbitrary length (eg. b b b w b w w b...) representing my choice of shirt to wear on that day. Continue execution until either my last black shirt or my last white shirt is thrown out. Once this occurs, stop consuming input and halt execution immediately. Note that the program must not consume any more input than is required before halting.

Inputs:

Number of black shirts, number of white shirts, durability of black shirts, durability of white shirts, and an arbitrary number of two single characters, your choice (eg. b and w)

Output

None. The program must simply halt when the last shirt of either color is thrown away.

Test cases

1 1 1 1 b

1 999 1 999 b

1 999 1 999 w w w w w w w w b

2 999 1 999 b w w w b

2 999 2 999 b w w w b w b w w w b

5 3 6 1 w w w w w b b b b b b b b b b b b b b w

General rules:

  • This is , so shortest answer in bytes wins.
  • Default input rules apply for the first four arguments. For the arbitrarily long input sequence after the first four arguments, input must come from a source which can provide input one character or byte at a time, of theoretically infinite length, such as STDIN or some other stream.
\$\endgroup\$
2
  • 1
    \$\begingroup\$ How exactly are you going to test that only a certain amount of input has been used? \$\endgroup\$
    – Jo King Mod
    Commented Aug 8, 2019 at 5:04
  • 2
    \$\begingroup\$ Typically you should address concerns made in Sandbox before posting to main. \$\endgroup\$
    – Jo King Mod
    Commented Aug 8, 2019 at 5:31
1
\$\begingroup\$

Calculate mobile data coverage

Background

You've been hired by the HQ of Vodafizon - a relatively new mobile network provider interested in spreading to the global market. In particular, your job description involves working as a marketing rep to produce ads for each country, where you give a figure of the data coverage, as a percentage, in that country. You get this data from the data scientists, but you've started to notice a pattern: the number always seems to be 98%, 99% or 100% (which, in your experience, seems to be far too high). Despite your trust in Vodafizon, you seem to find this suspicious, so you write your own program to investigate, ensuring maximum precision, even implementing your own floating-point and circle rasterization algorithm to minimize error. You end up making a 112KB monster of a program, but the result confirms your suspicions: these figures are, for the most part, made up by the data scientists, to try and exaggerate their claims.

When you mention this discovery to a coworker, they act surprised at first, but later tell you to keep quiet: upper management probably know about the forgery, and in fact endorse it. Telling them that you know their dirty secret could will result in losing your job.

But here's the thing: you know that advertising these fake numbers could result in massive lawsuits to Vodafizon, the effects of which could result in you getting laid off. You know you can't risk getting fired, but just using the data scientists' figures could be disastrous in the long term.

After consulting Workplace SE, you come up with a plan: keep using your program, but hide it from your superiors. The only issue is, that the data scientists responsible for providing you the data also happen to be the makeshift sysadmins in Vodafizon HQ, so your program can't attract too much attention to itself. 112KB is far more than Vodafizon uses on average (they prefer to split code into lots of tiny files), so when filtering through by file type, the sysadmins will easily see this file as potentially twenty times larger than all the others. So clearly, you need to compress it, without sacrificing the accuracy.

Input

The input will consist of a nested array of form [[x, y], [x, y]] (or alternatively an object of form [{"x":x, "y":y}, {"x":x, "y":y}]) of line segments, in clockwise order, defining the border of a country.

The input will also contain a nested array of form [[x, y, strength], [x, y, strength]] (or an object of form [{"x":x, "y":y, "s":strength}, {"x":x, "y":y, "s":strength}]), which will describe the location of the mobile data towers, and the strength: the radius (or diameter, you can request either in your answer (but not both)) of the circle in which that given tower provides mobile data.

Output

Your program should output an approximation of the mobile data coverage of the input given. Of course, this is impossible to get perfect (unless you live in Indiana, that is), so you need to provide an approximation, but while reducing your byte count as much as possible. Note that your program must halt by itself before 5 seconds of runtime (for any test where the number of towers is less than or equal to 500, and the number of edges is less than 100), or alternatively continuously provide output such that once it is stopped after 5 seconds, the last output will be taken as the result.

Scoring

Like I mentioned, my program also needs to be small, therefore size will factor into the equation. So, to score your program:

  • Get the number of bytes, B
  • Run your code with the randomly-generated test cases provided by tests.py in this repo, and save the ref outputted.
  • Run your outputs through score.py, providing the ref at the start. The last input you will be asked for will be B.

Get the score outputted by score.py, and post it in your answer.

Sandbox

  • Is my background too long?
  • Is my scoring system too long-winded? I intend to use a complex algorithm (which I have mentally worked out, but not coded yet) which essentially creates a weighted average of all of the scores as a percentage of a value which is correct to 16 decimal places. Is referring people to some code, instead of telling them the algorithm, standard practice? I don't want to spend ages describing a confusing algorithm, when I could just write a program to do it.
  • Is this challenge not a duplicate? Is is unclear in any way?
\$\endgroup\$
1
\$\begingroup\$

Broken mouse

This is just an idea, I have not elaborated it.

My mouse accidentally fell to the ground, and now there is a double click for each of my single click(which makes window-closing very hard to do). :(

Most computer screens have a higher resolution ratio than 16x12, but let's assume that my computer screen has a 16x12 resolution ratio.

Example: A Window looks like this:

0-----OX
|      |
--------

The number 0 is the indicator of the window. O is a dragging button that allows windows to be moved. X is a closing button that closes the window. (You can not resize windows.) Assume that there is a window below that window looking like this:

1-----OX
|      |
--------

If I click X, I will close both windows. However, what should(or must, if appropriate) I do if I only want to close the first window?

I can move my mouse to the O tab and drag the window around by using mousedown. After 1 drag to the right:

10-----OX
||      |
---------

Now I can click the X to close the window 0 after I click the O button again to remove the dragging effect. (Note that there is the window "1" below that window.)

Wait, I changed my mind and wanted to close the window 1. What should I do?

I should click the number 1; then, the window 1 goes to the top and the X button shows. Now I can click the X button to close the 1 window.

For reference, this is the TUI commands I used(when the mouse starts at 0x0):

0-----O
>>>>>>.>.<<<<<<<.>>>>>>.

What should I do if I want to close the windows that I specified? (Output the TUI instructions.) (Your score is -(code length + output); you want to keep your score as high as possible.)

TUI Instructions

  • ^v<>: Move the mouse up, down, left, or right
  • .: Mouse down+mouse up (i.e. click)
\$\endgroup\$
7
  • 3
    \$\begingroup\$ What does the input look like? \$\endgroup\$ Commented Aug 12, 2019 at 21:35
  • \$\begingroup\$ I have no idea. \$\endgroup\$
    – user85052
    Commented Aug 13, 2019 at 4:36
  • \$\begingroup\$ Output for what (set of) input? \$\endgroup\$
    – user202729
    Commented Aug 16, 2019 at 4:49
  • \$\begingroup\$ @The Obviously a list of coordinates of the input windows... \$\endgroup\$
    – user202729
    Commented Aug 16, 2019 at 4:49
  • \$\begingroup\$ Is this always possible? If the frontmost window is as large as the screen, by dragging the "O" you cannot make the lower-leftmost cell appear. What if the "X" of the desired window is there? \$\endgroup\$
    – user202729
    Commented Aug 16, 2019 at 4:51
  • \$\begingroup\$ I guess I will make the windows draggable for at least 1 direction and at most 4 directions. (The window is always smaller than the screen.) \$\endgroup\$
    – user85052
    Commented Aug 16, 2019 at 4:59
  • \$\begingroup\$ Oh I see, otherwise output impossible to avoid this situation. \$\endgroup\$
    – user85052
    Commented Aug 16, 2019 at 7:00
1
\$\begingroup\$

tags: "code-golf", "ellipse", "geometry"

Sandbox Questions

Is this a proper code-golf question?

A major challenge is: How to verify the computed shape? Numerical verification is impossible, since there are infinitely many possible solutions. Is there an easy way to plot xy-data online, or should I provide a script myself? Your suggestions are greatly appreciated.

edit:

after 3 days of being posted here in the sandbox, I still have no clear answer to the above question. I therefore propose to ask participants to include their own plot in the answer, which they can make with whatever plotting tool they wish. If people feel inclined to cheating, they only fool themselves, don't they?

Introduction

To create a circle you can stick a nail in a piece of board, put a loop of string around it and hold it taut with a pencil at the other end. Move the pencil and you get a circle. If you put the loop of string around two nails and move your pencil, you create an ellipse. But what happens if you use three nails, or four, or ten perhaps? It's gonna get ugly soon if you try this in real life, and that's where computers come in handy.

Challenge

Your task is to write a program or function that accepts two inputs:

  • A list of (x,y) coordinates (viz. the nails), of arbitrary length>2.
  • The length of the rope.

And produces the following output:

  • A list of coordinates of the poly-oval, which could be fed to a plotting-tool. Plotting the output does not need to be part of your program!

References

Details:

  • You may assume that the input coordinates form a convex shape (no inner points on which your program could crash).

  • As coordinates, you can use tuples, pairs, complex numbers or even two separate scalars if you like.

  • The output resolution (ie. the length of the list) is not so important, but is should give a fair representation of the real curve. In my experience, you'll need between 100 and 1000 points. For smaller rope lengths, you need an even higher resolution.

Rules and scoring:

  • This is code-golf, so shortest answer in bytes for each language wins.
  • Standard rules and default I/O rules apply.
  • Loopholes forbidden (of course).

Example Input and Output

Provide at least one example input and output. Make sure they match your own description of what the input should look like.

Input can be any of the following:

P = [2+0j, -2+1j, -2-1j]

P = [(2,0),(-2,1),(-2,-1)]

X = [2,-2,-2] and Y = [0,1,-1]

Output should be in one of the following forms:

[0.862+1.591j, 0.703+1.668j, 0.527+1.729j, ...]

[(0.862,1.591), (0.703,1.668), (0.527,1.729), ...]

X = [0.862, 0.703, 0.527, ...], Y = [1.591, 1.668, 1.729, ...]

\$\endgroup\$
4
  • \$\begingroup\$ "You may assume that the input coordinates form a concave shape" I think you mean convex. This is a very helpful assumption though, as you would otherwise need to calculate the convex hull before doing anything interesting. \$\endgroup\$
    – Beefster
    Commented Aug 13, 2019 at 22:05
  • 2
    \$\begingroup\$ "How to verify the computed shape?" - Two possibilities: 1. don't worry about it and make this a graphical output challenge ; 2. specify a starting angle and angle step and require accuracy to within 2 decimal points. ... I personally would go with #1 \$\endgroup\$
    – Beefster
    Commented Aug 13, 2019 at 22:11
  • \$\begingroup\$ @Beefster Thank you, I did indeed mean convex. As per your second comment, frankly I am not interested in how to write short plotting code, I am interested in the calculation itself. But thanks a lot for your help, I think I will post in a couple of days:) \$\endgroup\$
    – Hermen
    Commented Aug 14, 2019 at 16:28
  • \$\begingroup\$ One solution would be to specify a pixel resolution and require that the density of output points should be sufficient that the maximum separation between the curve and the piecewise linear output should be half a pixel. Then you can compare the output with the output of a reference implementation by looking for separations of more than one pixel. \$\endgroup\$ Commented Aug 20, 2019 at 15:55
1
\$\begingroup\$

I mainly need help with scoring as I want to encourage use of esolangs.

I also would like to know how to improve the answer-ability of this question in languages that don't specifically have defined functions


Church booleans

A church boolean is a function that returns x for true and y for false where x is the first argument to the function and y is the second argument to the function. Further functions can be composed from these functions which represent the and not or and xor logical operations.

Challange

Construct the church booleans and and not or and xor church gates in a language of your choice.

Scoring

The total length of all of the code required to make church true and false in your language and the and not or and xor church gates excluding the functions name. (for example, false=lambda x,y:y in python would be 12 bytes). You can reuse these names later in your code.

Pseudo code Examples:

true(x, y) -> x
false(x, y) -> y
and(true, true)(x, y) -> x
and(true, false)(x, y) -> y
# ... etc
\$\endgroup\$
6
  • \$\begingroup\$ instead of functions, you should also accept full programs. I also don't understand what your examples represent(is and supposed to be a curried function?) \$\endgroup\$ Commented Aug 16, 2019 at 20:43
  • \$\begingroup\$ @SuperStormer and returns a church boolean which is a function which is then called with variables x and y and returns x or y based on whether that function is the true or false church boolean. In the examples I was just trying to get across the nature of church gates and church booleans without answering the question. I wanted to break it up into discrete functions for readability and to ensure that the question is actually being answered correctly \$\endgroup\$ Commented Aug 16, 2019 at 20:46
  • \$\begingroup\$ I'm not really sure it's possible to make this work for all languages, except by just operating on lambda calculus expressions with no actual significance within the language, but that aside you definitely don't need anything additional to encourage esolangs on this site! \$\endgroup\$ Commented Aug 16, 2019 at 20:55
  • 1
    \$\begingroup\$ @UnrelatedString as far as fit for this site goes do you think there is anything I should add to improve the question? \$\endgroup\$ Commented Aug 16, 2019 at 20:58
  • 2
    \$\begingroup\$ Esoteric languages usually don't support function as first-order object very well, but they usually have eval so it may work using some "function" representation. \$\endgroup\$
    – user202729
    Commented Aug 17, 2019 at 6:46
  • \$\begingroup\$ Otherwise I don't think there is a problem. \$\endgroup\$
    – user202729
    Commented Aug 17, 2019 at 6:46
1
\$\begingroup\$

Distant Programs

Create a program that, when run, prints "Do you still love me?" with or without a newline at the end.

Your score is the Levenshtein distance to the closest non-erroring program (the non-erroring program doesn't have to do anything, although it might), and you want the largest score. Ties are broken by whichever code is shorter, in bytes.

Your program can read it's own source code, through the filesystem or otherwise. If your program must have a specific name, the length of that name should be included in your byte count.

Notes:

  • Compiler warnings are not counted as errors for this challenge.
  • An erroring program can output, frobricate, do anything as long as it eventually errors.

Notes for the sandbox:

  • Is the specification clear?
  • Is it possible to create a solution that can simply be repeated to get any arbitrary score? If so it would pretty much ruin the challenge as it is, and I think it should be possible but I can't get it to work.
  • What tags would this use?
\$\endgroup\$
3
  • \$\begingroup\$ I think it should be possible to get arbitrary scores using quining techniques and cryptographic hash verification. \$\endgroup\$ Commented Aug 20, 2019 at 15:41
  • 1
    \$\begingroup\$ In addition to what Peter said, I think there is a clarity problem in defining precisely what counts as an error. \$\endgroup\$ Commented Aug 20, 2019 at 19:33
  • \$\begingroup\$ @FryAmTheEggman I was going top copy my definition of "error" from codegolf.stackexchange.com/questions/63433 but to my surprise there isn't one. Honestly I'm not sure how exactly to define "error". \$\endgroup\$
    – Shelvacu
    Commented Aug 23, 2019 at 23:03
1
\$\begingroup\$

Solve All the Rubik's Cubes!

I want to solve a Rubik's Cube. Unfortunately, I am blind, and my friend doesn't know how to solve a Rubik's Cube, so I just make one move at a time and ask my friend if it is solved. This generally doesn't work very well, so I would like to know a specific thing I could do to increase my chances of eventually fixing it. Also, I don't like memorizing things, so please keep your solution as short and simple as possible.

Rules

  • I cannot see the cube or anything about it.
  • The only thing my friend will tell me about the cube is whether or not it is solved.
  • My friend and I are fully willing to wait until the heat death of the universe to solve this, if necessary.
  • I don't have a great memory, so keep your instructions as short as possible.
  • I can feel around the cube enough to turn whatever face you tell me to turn in whatever direction.
  • I can turn the cube in my hands.
  • I can memorize anything you give me, but I won't like it.

Solution Format

Give me a description of turns to do on my Rubik's Cube, to be repeated endlessly (or until I solve it).

F: Turn the front face clockwise
B: Turn the back face clockwise
R: Turn the right face clockwise
L: Turn the left face clockwise
U: Turn the top face clockwise
D: Turn the top face clockwise

x: Turn the cube so the top face becomes the front
y: Turn the cube so the left face becomes the front
z: Turn the cube so the left face becomes the top

' can be appended to any of these commands to make them go in the opposite direction.

Also, to make things easier, you can give me inner repetitions. Write these as

{...commands...}*4

where 4 is the number of times it is repeated. Inner repetitions can be nested.

Scoring

Non-memorability:

  • Each turn gives one point.
  • For nested repetitions, double the point value of everything inside the repetition and add the number of times I do it.

Effectiveness:

  • Any sequence of moves on a Rubik's cube will eventually return to the initial state. The effectiveness is how many turns are required before this happens (roughly equivalent to how many states it passes through).

Total score = non-memorability / effectiveness

Solutions that are easier to remember are probably better than solutions that are hard to remember but will be solved.

Lowest total score wins.

Questions:

  • Will people actually answer this question?
  • Is the specification clear enough?
  • This is my first question. Is there anything else I need to consider before posting?
\$\endgroup\$
4
  • \$\begingroup\$ This sounds like an interesting question, however it may actually be a better fit for puzzling.stackexchange.com. Either way, it's not entirely clear what the end goal is; Am I trying to find the series of moves that will make it likely for the cube to be solved quickly (on heatdeath timescale), or am I looking for a series of moves that garuntees it will be solved eventually? Also see (similar but not duplicates I'm pretty sure) math.stackexchange.com/questions/1694536 and math.stackexchange.com/questions/184760 \$\endgroup\$
    – Shelvacu
    Commented Aug 19, 2019 at 10:36
  • \$\begingroup\$ I'm looking for something easy to remember, with a reasonable chance of eventually solving it. This doesn't have a definite answer and should focus more on space optimization (golfing) (the existing Hamiltonian Circuit is probably very difficult to remember and would score poorly), so it might not fit as well on Puzzling. \$\endgroup\$
    – Hiatsu
    Commented Aug 19, 2019 at 20:48
  • \$\begingroup\$ As written, I agree with Shelvacu that this is for puzzling. This is still a programming site, so here it would be better to ask for a program to output the solution. But that's probably necessary anyway, given that the fully expanded solution will have at least 43.252.003.274.489.855.999 moves. \$\endgroup\$ Commented Aug 20, 2019 at 15:38
  • \$\begingroup\$ @PeterTaylor Actually, it would most likely be between 34,326,986,725,785,600 and 43,251,683,287,486,463,996. This is basically the Devil's Algorithm: a set of moves that when applied, repeatedly if necessary, will eventually return a Rubik's Cube to a solved state regardless of the starting configuration. \$\endgroup\$ Commented Aug 27, 2019 at 9:35
1
\$\begingroup\$

Talk interpreter

"Talk" is a baroquified accumulator-based language that is created in order to make it difficult to put on Try It Online. The "Talk" language has 4 commands:

  • 00 If the accumulator is 0, set the accumulator to 0.
  • 01 If the accumulator is 0, set the accumulator to 1.
  • 10 If the accumulator is 1, set the accumulator to 0.
  • 11 If the accumulator is 1, set the accumulator to 1.

Input:

  • The input can be taken via any acceptable input method by our standard I/O rules.

  • The input will always be a sequence of the commands above.

  • The program will take an input that is either 1 or 0 to set the accumulator to.

Output:

  • On the end of a command execution, the accumulator is outputted implicitly.

Rules:

  • The input has to be a single string or character list, and splitting it in parts of size 2 is part of the challenge.
  • As this is , the shortest answer, in bytes, wins.
\$\endgroup\$
8
  • 2
    \$\begingroup\$ So we take two inputs? The starting 0/1, and the sequence of commands? Since you state I/O is flexible, would for the commands a list of 2-character strings be allowed (i.e. ["00","01","11","11","01"])? Or does the input have to be a single string or character list, and splitting it in parts of size 2 is part of the challenge? \$\endgroup\$ Commented Aug 19, 2019 at 8:02
  • 4
    \$\begingroup\$ Um, commands 00 and 11 don't seem to do anything, while the other two seem to be just 'set the accumulator to 0/1' \$\endgroup\$
    – Jo King Mod
    Commented Aug 19, 2019 at 8:07
  • \$\begingroup\$ The commands 00 and 11 was added in order to avoid uninteresting abuses like directly printing the last character of the code. \$\endgroup\$
    – user85052
    Commented Aug 19, 2019 at 13:42
  • 3
    \$\begingroup\$ Why would this be difficult to put on Try It Online? Does the accumulator ever do any accumulating? \$\endgroup\$
    – Shelvacu
    Commented Aug 19, 2019 at 19:21
  • \$\begingroup\$ This will overlap with the existing talk.tryitonline.net. \$\endgroup\$
    – user85052
    Commented Aug 20, 2019 at 0:16
  • \$\begingroup\$ Um, it's not that hard to change the name slightly. Languages like ><>, /// and ??? already have url friendly names \$\endgroup\$
    – Jo King Mod
    Commented Aug 21, 2019 at 6:49
  • \$\begingroup\$ Do you know how to change the name "Talk" slightly? \$\endgroup\$
    – user85052
    Commented Aug 21, 2019 at 7:04
  • 3
    \$\begingroup\$ @Shelvacu, I imagine that it would be difficult to persuade Dennis that a "language" this useless is worth space on his server. \$\endgroup\$ Commented Aug 23, 2019 at 7:45
1
\$\begingroup\$

Normalized Malbolge to Malbolge translator

In this task, you will write a program/function that takes a Normalized Malbolge program and outputs the resulting Malbolge program. (This is a secret tool that all Malbolge programmers are using!)

Input

A data structure that (somehow) represents a Normalized Malbolge program.

Output

A data structure that represents the resulting Malbolge program.

Examples

jpoo*pjoooop*ojoopoo*ojoooooppjoivvvo/i<ivivi<vvvvvvvvvvvvvoji:
(=BA#9"=<;:3y7x54-21q/p-,+*)"!h%B0/.~P<<:(8&66#"!~}|{zyxwvugJ%

jjjj*<jjjj*<v
('&%#^"!~}{XE

jjjjjjjjjjjjjjjjjjjjjjj*<jjjjjjjjjjjjjjjjjjjjjjjj*<v
('&%$#"!~}|{zyxwvutsrqpnKmlkjihgfedcba`_^]\[ZYXWVT1|

How to convert

This is a placeholder for the convertion process.

def normal_to_malbolge(prog):
    pos = 0
    malbolge = ""
    for i in prog:
        char = ord("' ( > D Q b c u".split()["*jpovi</".find(i)]) - pos
        while char < 33:
            char += ord("~")-32
        malbolge += chr(char)
        pos += 1
    return malbolge

Explanation

Iterate over the normalized Malbolge program, and then convert all "*jpovi</"'s to a character in "'", '(', '>', 'D', 'Q', 'b', 'c', 'u'. Then, minus the position.

While the temporary Malbolge representations' ASCII code is less than 33, increment the char by the ASCII code of "~" minus 32.

Append the resulting character to the output.

Rules

  • This is a contest; the shortest answer wins.
  • No standard loopholes please.
  • The default I/O methods are allowed.

    Sandbox

  • Is it a duplicate? This probably is.

  • Is the challenge well-written?
\$\endgroup\$
3
  • 2
    \$\begingroup\$ You need to include the instructions for converting normalized malbolge to malbolge (will give later) \$\endgroup\$
    – MilkyWay90
    Commented Aug 21, 2019 at 1:18
  • 2
    \$\begingroup\$ ^ Check my code to convert and make an explanation out of that. Some people don't know python, and my code is very ugly \$\endgroup\$
    – MilkyWay90
    Commented Aug 21, 2019 at 4:18
  • 1
    \$\begingroup\$ You could include a link to the standard loopholes, and put in that default I/O methods are allowed. Other than that I /support \$\endgroup\$
    – MilkyWay90
    Commented Aug 21, 2019 at 15:33
1
\$\begingroup\$

I need help rewording the prompt.

I learned from last time about having convoluted scoring and having too broad of a focus from my last question. I hope this one is more clear.

Church Subtraction

Lambda calculus has always been a fascination of mine and the emergent behaviors of passing functions into each other is delightfully complex. Church numerals are representations of natural numbers contructed from the repeated application of a function (normally the unary addition of a constant). For example, the number zero returns and "ignores" the input function, one is f(x), two is f(f(x)) and so on:

ident = lambda x: x
zero = lambda f: ident
succ = lambda n: lambda f: lambda x: f(n(f)(x))
one = succ(zero)
add1 = lambda x: x + 1
to_int = lambda f: f(add1)(0)
print(to_int(one))
>>> 1

From this we can easily see that addition is accomplished by applying the first function to x then applying the second function to x:

add = lambda m: lambda n: lambda f: lambda x: n(f)(m(f)(x))
print(to_int(add(one)(two)))
>>> 3

Addition is relatively easy to understand. However, to a newcomer it might be inconceivable to think of what subtraction looks like in a Church encoded number system. What could it possibly mean to un-apply a function?

Challenge

Implement the subtraction function in a Church encoded numeral system. Where subtraction performs the monus operation and unapplies a function n times if the result will be greater than zero or zero otherwise. This is code-golf so shortest code wins.

Input

Two Church numerals that have been encoded in your choice of language. The input can be positional or curried. To prove these are true Church numerals they will have to take in any function and apply them repeatedly (add1 is given in the examples but it could be add25, mult7, or any other unary function.)

Output

A Church numeral. It should be noted that if m < n then m - n is always the same as the identity function.

Examples:

minus(two)(one) = one
minus(one)(two) = zero
...

also acceptable:

minus(two, one) = one
minus(one, two) = zero

Credit:

This github gist for giving me a python implementation of Church Numerals.

\$\endgroup\$
4
  • \$\begingroup\$ 1. I'm not sure how to parse "the number zero is a cat function Church encoding". Perhaps it would be better expressed as "the Church encoding of the number zero is the identity function"? 2. Explaining multiplication is an unnecessary distraction (unlike addition, which is relevant context). You've got a link to Wikipedia for people who want to learn more. 3. There is a technical term, monus, which describes the truncated subtraction. The truncation at zero should be described in the Challenge section, not the Output, and you might want to introduce this term there. \$\endgroup\$ Commented Aug 23, 2019 at 7:31
  • \$\begingroup\$ 1. I missed an "in" and a cat function is pretty known in esolangs (esolangs.org/wiki/Cat_program), thank you for catching this. 2. I could explain exponentiation as well and maybe that might make a more compelling story. Or should I just stick with addition? 3. Thanks for the suggestion. \$\endgroup\$ Commented Aug 23, 2019 at 12:04
  • 1
    \$\begingroup\$ 1. cat is well known in POSIX too, and in both cases it does I/O. I think it's misleading and confusing to call ident a cat function. And the word order of the edited version is ambiguous, and IMO tends to the parse "(the number zero) (is) (a cat function in Church encoding)". \$\endgroup\$ Commented Aug 23, 2019 at 12:29
  • \$\begingroup\$ @PeterTaylor that work better? \$\endgroup\$ Commented Aug 23, 2019 at 13:22
1
\$\begingroup\$

Determine the minimal indices needed to cover all queries

This challenge is based on Mongo's handling of compound indices and index intersection, inspired by a problem that came up at work, but I'll restate the relevant details here.

Background

In any database, relational or not, the primary purpose of indices is to optimize data lookup.

For example, if the task of finding all questions on this site had to be accomplished by looping through all posts and looking for the code-golf tag, it would be unusably slow. An index, however, organizes this data in a way that enables fast and efficient lookup of the data we want, which drastically reduces the resource cost of queries in exchange for some more work and space in maintaining the index.

However, the cost of maintaining indices is not negligible, so it quickly becomes untenable to create 2^N indices for N fields. (Databases designed for this purpose do exist and are the better choice when this functionality is actually needed. I'm ignoring this fact because it's a more interesting challenge this way.) Thus, careful index construction and selection is important to get the most bang for your buck.

Details

A simple index only organizes data based on one field but Mongo provides two ways to efficiently query on more than one field: compound indices and index intersection.

Compound Indices

Compound indices organize data based on a sequence of fields, e.g. [A, B, C]. Here, order matters. If data is sorted by A then B then C, then doing a lookup based on C first cannot be done efficiently since there are no guarantees on where the desired data might be located within the index (whereas one could do e.g. a binary search based on A).

Note: compound indices enable efficient queries on prefixes of that index as well. That is, a compound index on [A, B, C] enables efficient queries that have [A], [A, B], or [A, B, C]. However, as previously mentioned, it does not support queries that have [B], [C], [A, C], or [B, C].

Index Intersection

Exactly two indices can be used to optimize a query if there does not already exist a compound index for the desired fields. That is, if there is an index on [A] and an index on [B], then a query on [A, B] can be executed fairly efficiently (though not as efficiently as if there was a compound index, but let's ignore that). This also applies to prefixes of indices, so an index on [A, B, C] and an index on [C] can be intersected to support a query with [A, C].

Problem

Given N fields, determine the minimal indices needed to make all possible queries on those fields efficient. That is, minimize the total number of fields indexed. There may be more than one minimal set.

Note: the order of fields in the query doesn't matter since the query analyzer can reorder these fields to be as optimal as possible before running the query.

Input/Output

Input is a single positive integer and the output should consist of clearly-delimited sequences.

Examples

A variety of output formats are shown here to demonstrate what I mean by "clearly-delimited sequences".

N: 1

[0]

N: 2

AB
B

N: 3

[['A', 'B', 'C'], ['B', 'C'], ['C']]

['AB', 'BC', 'CA']

To elaborate on the first example in this N=3 case, the first index covers a query with all three fields, index intersections cover all choices of two fields, and index prefixes cover all queries with one field.

Note: for N=5, the obvious pattern does not hold; the indices ABCDE BCDE CDE DE E do not enable an efficient query on A, C, E.


Meta

I am really hoping this doesn't boil down to [A, B, ..., X], [B, ..., X], [C, ..., X], ... [X]. I haven't taken a look at the N=4 case yet though so I don't know if this pattern holds.

Thankfully, the pattern breaks down for N=5.

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

N-bonacci from a Seed

Tags:

An N-bonacci sequence is a Fibonacci-like sequence where the N previous terms are added to get the next term. The Fibonacci series is a 2-bonacci sequence.

Given a list of integers L of length l and an integer n, output the first n digits of the l-bonacci sequence starting with the sequence L.

Input

Input is a list, array, delimited string, stream, etc of integers, and an integer. Input is flexible, provided L and n are separable. It is guaranteed that n >= 0, and l >= 1.

Output

Output the first n digits of the l-bonacci sequence starting with L. Output is flexible here also: a list, array, string, stream, etc.

Samples:

[1,1], 5       --> 1, 1, 2, 3, 5
[0,1,2], 1     --> 0
[10,1,-1], 10  --> 10, 1, -1, 10, 10, 19, 39, 68, 126, 233
[-1,0,1], 0    --> //no output, or empty output
[-1], 3        --> -1, -1, -1
[-1,-2,1,0], 9 --> -1, -2, 1, 0, -2, -3, -4, -9, -15

This is , so smallest in bytes wins.

Related

\$\endgroup\$
4
  • 1
    \$\begingroup\$ You'd probably need to explain what an l-bonacci sequence is. That said I'm not sure this isn't a dupe of the related challenge you posted since at least some answers (including mine) would be able to be reposted with [1]*n replaced with L and n replaced with len(L). \$\endgroup\$ Commented Aug 27, 2019 at 14:42
  • 3
    \$\begingroup\$ Closely related: codegolf.stackexchange.com/q/70476/31716 \$\endgroup\$
    – DJMcMayhem Mod
    Commented Aug 27, 2019 at 14:58
  • \$\begingroup\$ n <= l seems like an odd restriction, which your test cases don't always follow. If that is an actual requirement, this would be L[:n] in Python, which I don't think you want. \$\endgroup\$
    – Hiatsu
    Commented Aug 28, 2019 at 13:56
  • \$\begingroup\$ Hmm. I'll axe n <= l then and change it to n >= 0. \$\endgroup\$
    – bigyihsuan
    Commented Aug 28, 2019 at 17:37
1
\$\begingroup\$

Solve a cubic equation

(Is this really not a duplicate?)

\$\endgroup\$
10
  • \$\begingroup\$ Apparently not. I can find multiple quadratic equation challenges: 1; 2; 3, but there doesn't seem to be any cubic equation challenges yet. \$\endgroup\$ Commented Sep 13, 2019 at 9:35
  • 1
    \$\begingroup\$ Sounds like it might be a dupe of either codegolf.stackexchange.com/q/154001/194 or codegolf.stackexchange.com/q/11694/194 \$\endgroup\$ Commented Sep 13, 2019 at 10:58
  • 1
    \$\begingroup\$ @PeterTaylor The first challenge only asks for integer solutions, while yours has some constraints that this challenge might not have. \$\endgroup\$ Commented Sep 13, 2019 at 13:48
  • \$\begingroup\$ @EriktheOutgolfer, I said "might" because "solve" is so vague that there's no way of knowing what the challenge is. And I don't think my challenge has constraints so much as licence to not have to be accurate to 1ulp. It's true that cubics can't be as ill-conditioned as higher-order polynomials, but there are still some nasty cases. \$\endgroup\$ Commented Sep 14, 2019 at 8:48
  • \$\begingroup\$ @PeterTaylor I think there's a lot of subtleties in specifying challenges like this. I'd really like to push solvers to do something like the cubic formula rather than some generic method to solve or brute-force a polynomial equation. It's also fair that it's hard to judge anything from just a title. I'll try writing something up later and would be happy to hear your thoughts. \$\endgroup\$
    – xnor
    Commented Sep 14, 2019 at 8:53
  • \$\begingroup\$ Regarding Peter's comment about the ambiguity of not including the description, one important thing to include is whether we must at least find one solution, the real solutions, or all solutions (I'm in favor of the last option). Also, "pushing solvers to do work" can be as simple as encouraging them to implement an algorithm that's more than just a built-in solving function (including the built-in solution for reference doesn't hurt, if it exists). \$\endgroup\$ Commented Sep 14, 2019 at 15:38
  • \$\begingroup\$ @EriktheOutgolfer Can you explain why you like the last option of requiring all solutions? I had thought a bit about this and was leaning pretty heavily to only asking for one solution because it gives less advantage to generic solvers (even non built-ins) over writing a formula, and it means one never has to output a complex solution for languages that don't support them natively. \$\endgroup\$
    – xnor
    Commented Sep 14, 2019 at 19:47
  • \$\begingroup\$ The "less advantage" restricting the output to one solution gives is simply a need for the answer to just pick one of the solutions it has found, in the worst case. Also, there are some cases where there are only complex solutions. If you want to account for such languages, you will need to add a guarantee that the equation will have at least one real solution, and none of the aforementioned cases will ever be input (there's some ambiguity about this currently). \$\endgroup\$ Commented Sep 14, 2019 at 19:53
  • \$\begingroup\$ @EriktheOutgolfer Doesn't every cubic equation have a real solution? I'm not intending to include ones where the leading coeff is zero so it's really quadratic. \$\endgroup\$
    – xnor
    Commented Sep 14, 2019 at 19:55
  • \$\begingroup\$ Hm, must've been thinking of something else (I'm currently doing other stuff). And yeah, a cubic equation \$ax^3+bx^2+cx+d=0\$ is cubic precisely because \$a\ne0\$. \$\endgroup\$ Commented Sep 14, 2019 at 19:58
1
\$\begingroup\$

Randomize \$SL_n(\mathbb R)\$

Given a positive integer \$n > 1\$, return a random element from \$SL_n(\mathbb R)\$.

Details

  • \$SL_n(\mathbb R)\$ is the set of \$n \times n\$ matrices with determinant \$1\$.
  • In theory the output must cover the whole \$SL_n(\mathbb R)\$ (that is, if the RNG you're using was perfect and we could actually represent real numbers).
  • We don't require an uniform distribution.
  • Instead of real numbers it is sufficient to work with floating point numbers.
\$\endgroup\$
9
  • \$\begingroup\$ I suspect the interesting solution you have in mind is to start with the identity and do random row operations. But maybe it's shorter to just generate a random matrix and divide the first row by its determinant, even if your language means you need to implement det yourself? \$\endgroup\$
    – xnor
    Commented Sep 14, 2019 at 7:30
  • 3
    \$\begingroup\$ On second thought, random row operations is probably shorter to golf. And there's probably niftier ways to it like generating the LU decomposition, or taking the exponential of a trace-zero matrix. So this definitely seems like an interesting challenge to golf, at least for languages that don't make it too easy. A technical issue that might be worth addressing is whether it's OK to never be able to generate some probability-zero subset. For instance, what if the method only generates matrices with distinct eigenvalues? I think this should be allowed since floats can't reach everything either. \$\endgroup\$
    – xnor
    Commented Sep 14, 2019 at 7:43
  • \$\begingroup\$ @xnor Thanks for you input! This task actually came up when I was trying to test a function I've written and I ended up using the random matirx/scale by determinant solution. I see your point about the zero-probability sets. The only problem I see is that it is hard to define it in a way that cannot be abused: As matrices with floats have only rational entries you could argue that we can only represent a zero-probability set in the first place. (If we use this exact wording.) So I'm not actually sure how to specify this. \$\endgroup\$
    – flawr
    Commented Sep 14, 2019 at 17:49
  • \$\begingroup\$ I think it would be OK to say that in theory, the output must cover cover the whole space except for some probability-zero subset of it. I see what you're saying about floats being measure zero, but I think this wrinkle is already present and covered by you saying "in theory" and that floating points suffice for reals, so I don't see the change making it more abusable. I also realized that the code probably should be allowed to fail with theoretical probability zero, like if you go the determinant-scaling route, you could get det zero. Maybe defaults cover this already, I'm not sure. \$\endgroup\$
    – xnor
    Commented Sep 14, 2019 at 19:53
  • \$\begingroup\$ As a side thought, it could be possible to avoid these annoying real-representation issues by changing the challenge to generating integer examples or ones over F_2, but I suspect this won't allow as wide a variety of solutions. \$\endgroup\$
    – xnor
    Commented Sep 14, 2019 at 20:01
  • \$\begingroup\$ "We don't require an uniform distribution." -- would a Dirichlet distribution be allowed? \$\endgroup\$ Commented Sep 17, 2019 at 7:38
  • \$\begingroup\$ @xnor Even though \$\mathbb{F}_2\$ allows the possibility for bit-fiddling in solutions, possibly being interesting in their own rights. \$\endgroup\$ Commented Sep 17, 2019 at 7:43
  • \$\begingroup\$ @JonathanFrech Can you elaborate how you'd define a Dirichlet distribution over \$SL_n(\mathbb R)\$? I'm not familiar with this distribution and I don't quite see how we can apply it as the support seems to be defined as \$(x_1,\ldots,x_n)\in \mathbb R^n\$ with \$\sum_i x_i =1\$. \$\endgroup\$
    – flawr
    Commented Sep 17, 2019 at 7:43
  • \$\begingroup\$ I though of something along the lines of \$P[X\neq\mathrm{id}]<\epsilon\$, where \$X\$ models the output and \$\epsilon\$ represents machine accuracy, however on second thought this case is covered by your theoretical surjectivity requirement. \$\endgroup\$ Commented Sep 17, 2019 at 7:50
1
\$\begingroup\$

Battleships TDM

In this (not so simple) game of commanding a battleship, you are tasked to defeat the opposing team. Cooperation is essential in order to win the battle.

Each ship starts with $${500\cdot\bigg\lfloor\frac{10}{\log{\frac{n}{3}}}}\bigg\rfloor$$ health (rounded down), where n is a number of players. At 30 players, it is 5000.

Setup

The game starts with a square map of length 50+3n. On top and bottom there is 15% of the width, in which the players' ships will spawn. The rest of the map will be prodedurally generated with islands.

The sample map looks like this: Map

Phase 1: Issuing commands

On your turn, your program will be given a file input.txt located in the program's directory, with following format:

TURN=(turn number)
SIZE=(size of the map)
YOUR_SHIP=(first 6 chars from SHA1 hash of your ship's name; in case of conflicts a random one will be generated)
YOUR_TEAM=(your team's id)
HEALTH=(your ship's health)
POS=(position of your ship in 0,0 format)
SPEED=(your ship's speed)
DIR=(your ship's direction)
TERRAIN:
(21x21 square of characters, centered on the ship)
PROXIMITY:
(line-separated list of ships within 10 squares, with its properties separeated by semicolon)
CHAT:
(line-separated history of text sent by teammates from the last and current round)

For example:

TURN=21
SIZE=110
YOUR_SHIP=acf44a
YOUR_TEAM=1
HEALTH=3231
POS=64,121
SPEED=3
DIR=NW
TERRAIN:
.....................
###.............x....
##.................##
(etc.)
PROXIMITY:
bd439a=1;69,132;S;3 (ship's id, team, position, direction, speed)
43351f=2;78,112;NE;4
(etc.)
CHAT:
58ab38@21: ENEMY_SHIP 582af2 @ 142,62 NE 3
902dd1@20: 033b2c 4 92,62 SW 1
(etc.)

The map shows . for water, # for land, x for wrecks, 1 and 2 for ships belonging to particular team.

Your program is allowed 3 actions per turn. The actions are:

NONE - do nothing
TURN_LEFT - rotates ship counterclockwise by 45 degrees
TURN_RIGHT - rotates ship clockwise by 45 degrees
SPEED_UP - increases speed by 1. At speed 5 it is ignored.
SPEED_DOWN - decreases speed by 1. At speed -1 it is ignored. 
MESSAGE=message - sends a message to chat
FIRE=x,y - fire a projectile in specified location. Can be done only once per turn. 
           The cannon has range of 25. Issuing a command which exceeds it is ignored.

For example:

TURN_LEFT
SPEED_UP
FIRE=62,69

must be written to output.txt. After each round the file is cleared.

Phase 2: Movement phase

All ships in random order move forward defined by their speed.

  • If ship hits the land or wreck during movement, the ship stops and takes damage worth 50x of ship's speed.

  • If ship hits the map border, same situation applies.

  • If ship hits other ship, it is considered ramming:

    • If rammed from the front, both ships receive damage worth 100x sum of ships' speeds. Both ships stop.

    • If rammed from the back, rammed ship receives damage worth 20x difference of ships' speeds. Rammed ship moves one step forward and ramming ship ends its movement.

    • If rammed from the side, rammed ship receives damage worth 100x speed of ramming ship, while the ramming one receives 50x. Ramming ship stops.

    • If rammed at the angle, rammed ship receives damage worth 50x speed of ramming ship, while the ramming one receives 20x. Ramming ship stops.

    • If the rammed ship is friendly, ramming ship receives 1 point of friendly fire.

Phase 3: Firing phase

In the same order ships fire from the cannons (if any). If the cannon hits a target:

  • That is within range 10: Shots deal 500 + 0-99 damage

  • That is beyond range 10: Shots deal 500 + 0-99 damage + 0-99 damage for each unit beyond 10th (up to 2084 total damage at range 25)

  • If the target is friendly, the damage is 0 and shooting ship receives 1 point of friendly fire.

  • There is 5% chance to make a hit critical: The total damage is tripled and shooter recieves 1 critical point.

  • If it is a fatal blow, it is considered a destruction:

    • The fatal blow dealer receives a fatal point.

    • Attacker with most dealt damage receives a kill point (it may be the same ship as the dealer).

    • Everyone else with a hit receives an assist point.

    • If it is a solo kill, the dealer receives 2 of each points instead.

Phase 4: Checking conditions

Each ship is considered a wreck if:

  • Health reaches below 0 HP,

  • Ship gains 5 friendly fire points.

Wrecks remain on the map, but they are removed from the queue and program of such ships is being not executed.

Game ends whenever entire team gets destroyed or after 1000 turns, in which the points are being calculated as follows:

  • 1 point for each 10 damage dealt

  • 500 points for each kill

  • 200 points for each fatal blow

  • 100 points for each assist

  • 150 points for each critical hit

  • -250 points for each friendly fire hit

  • 1000 points for each winning team member

  • Points for achievements (names are just for decoration):

500 (awarded once) Beyond the horizon - Hit on enemy from 13 sq or more
500 (awarded once) Maximum range - Hit on enemy from 23 sq or more
500 (awarded once per participant) Coordinated attack - 3 or more ships attacking the same target
500 (awarded once) Hammer - Ram a ship on full speed
500 (awarded each time) - Survive a critical hit
1000 (awarded once per participant) Anihilation - Both ships getting destroyed in headfront ramming

The ship with most points after 10 games wins.

Code

The controller code is here.

Rules

Your program can:

  • store data in files within its own directory

  • communicate with teammates through the team's chat

Your program cannot:

  • read files outside its scope

  • disrupt the communications

  • Attack friendly ships on purpose

  • Copy other competitors' functionality (No duplicates)

  • Use standard loopholes

Sandbox questions

  • I'm not sure whether to allow the challenge in any usual language or require one specific (in this case Java 8)?
  • Wouldn't be achievements unnecessary? If not, could be any added/modified/removed?
  • Are there some rules that require clarification?
\$\endgroup\$
14
  • \$\begingroup\$ What does "procedurally generated with islands" mean? Could you provide a small example map? What does "15% of the width where players' ships spawn" mean? Are they distributed randomly, or packed into a corner (or do they have a choice)? \$\endgroup\$ Commented Sep 7, 2019 at 15:18
  • \$\begingroup\$ @someone 1. "Procedurally generated islands" I meant. 2. Added. 3. Area reserved for ships to spawn. 4. Randomly across the spawn area. \$\endgroup\$ Commented Sep 7, 2019 at 18:48
  • 2
    \$\begingroup\$ a) Ship health and particularly map size, in my opinion, scale in a weird way with participant count. b) I would highly recommend avoiding file I/O in favor of sending data to programs via STDIN and reading their actions via STDOUT. c) Additionally, I would recommend using a ubiquitous I/O format, like JSON or XML. This will reduce the amount of boilerplate code that the participants will have to write. Moreover, it would prevent d) the problem of newlines in chat. e) What order are the programs asked for output in? This is important for chat, for example. \$\endgroup\$
    – Alion
    Commented Sep 7, 2019 at 22:32
  • \$\begingroup\$ f) Does the damaging behavior differ depending on whether the ramming ship hit the front-right/left or the back-right/left? g) Does ramming a friendly ship deal damage to it? Please make that clear. h) Does solo-killing also provide 2 assist points? I'm guessing it doesn't, but it's not clear either. i) Shooting right at the current position of an enemy ship seems ridiculously effective. You've got a 50% chance to hit by definition, while all the other methods necessarily have less, since the ship can dodge. I can see very few edge cases. That's just my opinion, however. \$\endgroup\$
    – Alion
    Commented Sep 7, 2019 at 22:47
  • \$\begingroup\$ j) I misunderstood the "1000 points for each winning team member" the first 2 times I read it. "1000 points for member of the the winning team" is clearer in my opinion. k) Coordinated attack achievement is perhaps a bit unclear, but I can't seem to put into words why that is. l) 10 games is not an awful lot. While I understand that you don't want to run this for too long, this game does seem to be a bit random. m) Attacking friendly ships "on purpose" is difficult to define rigorously, and is already punished by the game, which makes it Emo Wolf-y. All in all I find the rule unnecessary. \$\endgroup\$
    – Alion
    Commented Sep 7, 2019 at 23:03
  • \$\begingroup\$ n) It would be lovely if the challenge was available for all standard languages. I would definitely not participate if it was Java-only. p) How are teams chosen? Randomly every game? r) I strongly recommend making a dedicated chat room for participants once the challenge hits main - you seem to be looking forward to coordinated plays, and I don't think they're possible without an agreed-upon communication format, which in turn is unlikely to develop without any group discussion amongst players. \$\endgroup\$
    – Alion
    Commented Sep 7, 2019 at 23:19
  • \$\begingroup\$ Correction for j) - I meant "1000 points for each member of the winning team". There's also a general problem of weird English present in all parts of the spec, but as long as it's understandable (which it is), there shouldn't be any problems here. Anyway, looking forward to the updated spec, and of course to the challenge itself. Good luck! \$\endgroup\$
    – Alion
    Commented Sep 7, 2019 at 23:26
  • \$\begingroup\$ @Alion The main issue is that I have no idea how can I run programs from multiple languages, so my controller could capture it and interpret all actions within reasonable time (since I'd have to run each program thousands of times to make an action). I don't want to end up copying/pasting/calculating everything by hand each turn, which could take a week or more to finish the game. The further points will refer to this one as I go \$\endgroup\$ Commented Sep 8, 2019 at 5:32
  • \$\begingroup\$ a) True, but the ship health has at least been addressing the time constraints. I could end up with some long functions for both of those anyway. b) STDIN/OUT capture issue. c) Haven't thought of this. d) Oh? e) What order? I'm not sure what do you mean. f) FL/R and BL/R deal the same damage. g) Uh, yes. h) Would have to think about it. i) Do you suggest any alternatives? l) Time constraints, again. n) Here we go back to the issue with multiple languages. p) Random every game. r) I would if I had the power to do so. Currently I don't. (BTW English is not my first language) \$\endgroup\$ Commented Sep 8, 2019 at 5:48
  • \$\begingroup\$ I've cobbled together a simple demo of how a language-agnostic controller could work. As I don't write Java, I used C# instead, but the code should be mostly readable for a Java developer as well. You will certainly need to find the Java equivalents of the methods and classes used, but I would be very surprised if Java doesn't support something akin to what I've done in C# at all. I also assumed Windows all throughout. Here's a demo.. Contains the C# controller and the files required for a sample Python entry. \$\endgroup\$
    – Alion
    Commented Sep 8, 2019 at 12:27
  • \$\begingroup\$ a) After understanding what the ship health function does, I don't have a problem with it anymore. The map size, however, grows quadratically with the ship count. d) You've defined chat as a line-separated history of messages. But what happens if an entry decides to put a newline into its message? e) Are the programs queried for actions in a consistent order? If so, what is the initial order? Random? Additionally, being early in the call order is a huge disadvantage, since most of the messages received will be from the previous turn, as I understand it. \$\endgroup\$
    – Alion
    Commented Sep 8, 2019 at 12:36
  • \$\begingroup\$ i) It's really difficult to come up with any alternatives from my position. I don't have access to your vision of the game. Inevitably I end up overhauling the battle system one way or another and remain unsatisfied with it. Considering previous challenges, however, I can't say for sure if this really is a notable flaw. \$\endgroup\$
    – Alion
    Commented Sep 8, 2019 at 12:42
  • \$\begingroup\$ Alion's point (b) is addressed at the execution speed issue you raise. See github.com/pjt33/ppcg36515 (linked from the KotH tag wiki) for an example which supports Java submissions natively and other languages by stdin/stdout communication. Another issue which Alion has touched on briefly is the team business: it needs to be clear how the teams will be assigned. \$\endgroup\$ Commented Sep 9, 2019 at 8:34
  • \$\begingroup\$ I have slightly edited your equation, feel free to roll back if you disagree. \$\endgroup\$ Commented Sep 17, 2019 at 8:03
1
70 71
72
73 74
162

You must log in to answer this question.

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