# What is the Sandbox?

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

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

## Get the Sandbox Viewer to view the sandbox more easily

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

# Creative Title about the Moser-de Bruijn

## The Challenge

Calculate the Moser-de Bruijn (A000695) sequence for all integers up to the input value N.

Each term of the sequence is defined as the sum of distinct powers of four arranged in ascending order. This means in base 4 every number of the sequence only has ones or zeroes.

You are to print a list of the sequence where all values are less than N. Output is to be separated by either commas, tabs, or spaces. Trailing/Leading commas or whitespace are not permitted. having a comma followed by whitespace is allowed, but the reverse is not. You must use standard output for your language. You are to take input from your language's standard input. Exclude the sequence's first term of zero as it isn't relevant to the game's rules. You may assume the input will always be a positive non-zero integer.

# Test Cases

5  => 1,4
6  => 1 4 5
22 => 1, 4, 5, 16, 17, 20, 21
1105 => 1, 4, 5, 16, 17, 20, 21, 64, 65, 68, 69, 80, 81, 84, 85, 256, 257, 260, 261, 272, 273, 276, 277, 320, 321, 324, 325, 336, 337, 340, 341, 1024, 1025, 1028, 1029, 1040, 1041, 1044, 1045, 1088, 1089, 1092, 1093, 1104


## Sandbox Notes

This is my first challenge, so input would be greatly appreciated!

• The stuff about "subtract a square" is completely irrelevant and distracting. After reading the introduction I expected the challenge to be finding the best move given the current size of the pile. IMO it would be a notable improvement to remove all mention of the game and just talk about the sequence which the question is actually about. – Peter Taylor Feb 28 '17 at 22:11
• @PeterTaylor Thanks for the input :) – Zavada Mar 1 '17 at 1:37
• Equivalently, this challenge is to find all integers up to N whose base-4 representation contains only 0s and 1s. Include this explicitly? – Greg Martin Mar 5 '17 at 20:01
• @GregMartin Good idea, I'll add that in! – Zavada Mar 5 '17 at 21:25

## Lost in Space: Help me get back to civilisation

To anyone who picks up this transmission, I need help!
the PPCG Planet. I survived the drop from hyperspace,
but now my ship's positioning system is broken. And
worse, I can't seem to access Hyperdrives Stack
Exchange to fix it!

I've tried to triangulate my position using local
satellites. I can send a 'ping' to them, and then the
satellite will report how long the ping took to reach
it. But the results don't make any sense! Some of the
satellites must be broken and are feeding me false
data...

I've attached the read-out of all the satellites I
pinged to this transmission. Can you work out which
ones are faulty?


You examine the data that was attached to the transmission. Your spaceship's computer analyses the data and notes that it is a list of tuples, each tuple which contains:

1. The known position of a satellite as a coordinate pair;
2. The distance from the lost spaceship that that satellite reported.

A majority of satellite data will support the spaceship being at a certain location -- this is the correct location of the lost spaceship. Write a program or function that outputs this location.

Sample Inputs and Outputs

todo

# Battle of the Algorithms, Kruskal vs Prim

This will be a challenge similar to a challenge. There will be two threads each with a winner.

This challenge is about minimum spanning trees. I might include a introduction to the topic, but for now I am working under the assumption that you are at least vaguely familiar with the subject.

Two of the most famous algorithms for finding a minimum spanning tree are Kruskal's Algorithm and Prim's Algorithm.

Explanation of the Algorithms to go here

Now the question is "Which one is golfier"?

In order to figure this out are going to implement each of these two algorithms in as many languages as possible. Each algorithm will have its own thread where it can be implemented in as many languages as possible. Each thread will act as a team scoring points for the algorithm in question. For each language a point will be given to the team with the shorter implementation in that language.

For example if the submissions look like this:

### Kruskal

• Python, 136 bytes

• Bash, 215 bytes

• Brain-Flak, 3144 bytes

### Prim

• Python, 152 bytes

• Bash, 211 bytes

• Perl, 98 bytes

Kruskal would score 2 points, one for having the shortest Python answer and one for the shortest Brain-Flak answer, and Prim would score 2 points one for having the shortest Bash answer and one for having the shortest Perl answer.

At the end of the week two winners will be declared, these will be the two persons that scored the most points for each team. Additionally a winning team will be announced. You can compete for both teams.

## Specifications

You will create a program or function that takes a graph in any reasonable form, implements one of the two algorithms and outputs the minimum spanning tree in any format that uniquely represents the spanning tree.

## Sandbox

• How can I make this clearer?

• What is confusing?

• Would this be fun?

• I/O formats could make a significant difference. – Peter Taylor Mar 7 '17 at 21:33
• @PeterTaylor I don't care about IO any form is fine – Wheat Wizard Mar 7 '17 at 21:37
• Implementing a given algorithm is tricky to define. To what extent can the method deviate from the algorithm? – xnor Mar 9 '17 at 22:23
• @xnor Each of the two algorithms build the trees in a deterministic order. In order for it to match the given algorithm it must add the edges in the same order. I will add this to the question. – Wheat Wizard Mar 9 '17 at 22:26
• @WheatWizard That's a good idea, and I think it can be made into an observable requirement by requiring the algorithm output the correctly-ordered list of edges in the tree. Otherwise, I don't think the internal adding order is necessarily well-defined -- consider for example a functional-language recursive implementation. – xnor Mar 9 '17 at 22:30
• This is basically just two different challenges which happen to be connected. I'd recommend posting it as two challenges, and then adding a snippet to compare the two challenges to see which problem is terser in the most languages. – user62131 Mar 14 '17 at 4:57

# Description

You have to paint N boards of length {A0, A1, A2, A3 … AN-1}. There are K painters available and each painter takes unit time to paint 1 unit of board. You have to get this job done as soon as possible under the constraints that any painter will only paint contiguous sections of board.

# Rules

• 2 painters cannot share a board to paint. That is to say, a board cannot be painted partially by one painter, and partially by another.

• A painter will only paint contiguous boards. Which means a configuration where painter 1 paints board 1 and 3 but not 2 is invalid.

• N boards have length given in integers.

### Input

K : Number of painters

L : A List which will represent length of each board

### Output

Return minimum time to paint all boards

### Sample Input/Output

K = 2

L = [1, 10]

Output = 10

• not sure why painters would only paint contiguous boards. But, without that the problem sounds like knapsack. – John Dvorak Mar 9 '17 at 17:21
• What is the point of T? – Peter Taylor Mar 9 '17 at 17:25
• @JanDvorak Contiguous boards is creating a possibility of a solution other than DP (which is also more optimal). – hashcode55 Mar 9 '17 at 17:27
• @PeterTaylor Actually yes, I should remove it, I'll just make the time cost 1 unit. – hashcode55 Mar 9 '17 at 17:28

## find the set of Sets in a subset of Set.

the Set game is a one-player card game using a deck of 81 cards. Derivatives - primarily those that remove most of the cards - exist. We shall be using one of such derivatives today.

a card in the deck is defined by four properties of the symbol(s) depicted on it. Each of these has one of three values:

• Count (1, 2 or 3); in this version, the count is always 1.
• Color: red, green or blue.
• Fill: hollow, striped or filled.
• shape: a square, a triangle, or a circle.

A card shall be represented as a using those properties: rhs is a red hollow square, while gsc is a green solid circle.

a Set of cards is a triplet of cards such that for each property, the value of that property is either the same for all three cards or different for each of the three cards. For example:

• rhs, gst and bfc form a Set. Each property value is different.
• rss, gss and bss form a Set. They are solid squares of different colors.
• bsc, bhs and bft form a Set. The colors are the same, the fills are different, and the shapes are different.
• gst, bst and bst do not form a set, because there are two blue cards.
• rss, bss and rst do not form a set, because there are two red cards as well as two squares.
• gft, gft and gft do not form a set, because it's not a triplet of cards. It's the same card listed three times.

Your input shall be a set of 9 (distinct) cards from the deck. You may optionally accept a flat string or list of 27 symbols without any separator instead of a list of 9 strings or lists. You may also accept the number of Sets that can be found within this set as a part of your input. You may assume there's at least one Set in your input.

Your output shall be a set of all Sets that can be found among the cards given to you. You may output the Sets in any order, but each Set must only be output once. You may output the cards in each Set in any order as well. You may flatten the output at any level.

How many test cases should I generate? What format is the best? I could provide a test case generator in Ruby, if that's desirable.

In our language, we use language of S for basic encryption for avoid something from children if we do not wish that children know about what we are talking about.

So here is how it works.
Lets take "Hello there" for example. So its encryption using language of S is Hesmello Thesmere

Step to understand

Step 1: take string, in our example its "Hello There"
Step 2: add S and M after first character's vowel and add vowel of that first character after M.
You no need to repeate this for other characters of that word. So in our example, we add SM for he so no need to do that for remain llo.

So as per our example for "Hello There" is Hesmello thesmere

What you have to do
1. User add input (or pre defined string in variable) and its output should be as per Output String below

Input : Hello World
Output: Hesmello Wosmorld

This is so lowest number of bytes wins!

Consider these as vowels:A, E, I, O, U, Y

• This isn't encryption. It's obfuscation. – John Dvorak Mar 10 '17 at 9:52
• Welcome to PPCG! This would probably make for an interesting challenge, but I would suggest removing the "pre-defined string in variable" option: our standard ways of taking input are STDIN or an argument to a function. Also, what characters can be part of a word? A-Z and a-z only? – ETHproductions Mar 10 '17 at 15:26

# Find a basis for each eigenspace!

Related

The challenge is just as it seems; you are to find a basis for each eigenspace of a matrix. If you have taken Linear Algebra 1, you'll understand what this means, but this is an attempted full explanation of eigenvalues, eigenvectors, eigenspaces, what a basis is, and how to obtain all of these.

This is the challenge; the explanations are below so you can skip them if you already know how to do this.

# Input

The input will be a single matrix given in any reasonable format according to PPCG conventions.

# Output

The output will be an array of bases. There will be one basis for each eigenspace. You can choose whether or not to repeat eigenvalues with an arithmetic multiplicity of more than 1. This can be output in any reasonable format, probably a 3D array.

# Vectors

In Computer Science terms, a vector is an array of values. For the purposes of this, we are assuming that all of these values are in Q; that is, they are all rational numbers. Wikipedia: Vector space

# Matrices

In Computer Science terms, a matrix is a 2D array of values. For the purposes of this, we are assuming that all of these values are in Q; that is, they are all rational numbers. Wikipedia: Matrix

# Terminology

Let A be an m x n matrix (with m rows and n columns) and let x be a size-k vector. Then, Aij is the element in the i-th row in the j-th column of A with 0 < i <= m and 0 < j <= n (they are 1-indexed). Also, xi is the i-th element of the vector x with 0 < i <= k.

# The Zero Vector and the Zero Matrix

The zero vector is the vector containing all zeros. Similarly, the zero matrix is the matrix containing all zeros. It is important to note that the size still needs to be considered.

# Scalar Multiplication

Scalar multiplication by a value s (again we are assuming it is rational) is quite easy to understand; simply multiply each element by s. Thus, we say that x is a scalar multiple of y if and only if x = sy. Note that the zero-vector is a scalar multiple of any vector but all non-zero vectors are not scalar multiples of the zero vector.

# Matrix-Vector Multiplication (MathInsight)

Let A be an m x n matrix (with m rows and n columns) and let x be a size-n vector. Then, Ax = y where y is a size-m vector defined as such:

yi = Ai1*x1 + Ai2*x2 + ... + Ain*xn


That is, the i-th element in the result is the dot product of the i-th row of A and x.

# Eigenvalues and Eigenvectors

Let λ != 0 be any real number, A be an m x n matrix, and x != 0 be a size-n vector (not the number 0, but the 0-vector, which contains all zeros). Then, if Ax = λx, we say that x is an eigenvector of A corresponding to λ, and similarly, we say that λ is an eigenvalue of A corresponding to x.

# Determining Eigenvectors

It's easy to determine if x is an eigenvector of A. Simply check if Ax is a scalar multiple of x, which also gives us the corresponding eigenvalue λ. However, it is harder to find eigenvectors than to check it a vector is one.

# Finding Eigenvalues

Conversely, it's easier to find the eigenvalues but harder to check if a value is one, which is fortunate for this challenge. Firstly, we must look at determinants.

# Determinants

The determinant of a 2 x 2 matrix [[a, b], [c, d]] is ad - bc. This is a specific definition of the determinant, so in order to explain the recursive definition of a determinant, I will say that the determinant of a 1 x 1 matrix is that value. Note that only square matrices have a determinant.

## The recursive definition of a determinant

In order to give the recursive definition of a determinant, I first need to explain what A(i,j) means. A(i,j) is the matrix formed by removing the i-th row and the j-th column from A; thus, if A is an n x n matrix, A(i,j) is an n-1 x n-1 matrix. Thus, we recursively define the determinant of an n x n matrix A, which we call det A, as sum x=1->n (-1)^(x+1)*(det A(1,n)). In other words, we go down the left-most column and take the values obtained from multiplying this value with the matrix formed by taking out the row and column it is in, and then alternate adding and subtracting those values. See the Wikipedia link for more information. This definition is recursive.

Also note that we do not have to expand on the left-most column, we can also expand on any column or any row.

So, how do determinants help us?

Well, I'm not going to prove it, but if we have C(λ) = 0, then λ is an eigenvalue of A. C is the characteristic polynomial function, which is gives the determinant of A - λI, where λI is scalar-multiplication between scalar λ and the Identity Matrix I, which has all 1s on its main diagonal and 0s everywhere else.

So, given an eigenvalue λ, we can find the RREF of A - λI. Let this matrix be M. Then, the eigenspace of λ corresponding to A is the set of all vectors x such that Mx is the zero-vector.

We have finally arrived at the task. Your task is to output, for each eigenvalue, a basis of the corresponding eigenspace.

# Linear Combination

A linear combinations of vectors x1, x2, ..., xn with scalars s1, s2, ..., sn is s1x1 + ... + snxn. When adding vectors, you add each individual element.

# Spanning Set

S is a spanning set of B if and only if every vector in B can be written as a linear combination of S with any real numbers as scalars.

# Linearly Independent Set

L is a linearly independent set if and only if no vector is a linear combination of the other vectors (thus L cannot contain the zero-vector), and it is linearly dependent otherwise.

# Basis: a linearly independent spanning set

A basis is simply a spanning set that's linearly independent. All possible bases will have the same number of vectors (proof omitted).

# The Challenge

Now that you hopefully understood my explanations, we arrive at the following challenge:

Given an n x n matrix with 0 < n <= 20, for each eigenvalue (there will be at most n distinct ones), output a basis for the eigenspace of the eigenvalue. You can choose whether or not to output duplicates. You can choose the format for input and output within reasonable conditions. My recommendation is a 2D array for input and a 3D array for output. The input matrix is guaranteed to have only real eigenvalues, and is guaranteed to be square.

# Find all the triples!

Your task is, given a number n, find all the Pythagorean triples containing that number, and output a list of the terms in each Pythagorean triple which is not n, without repeats and in ascending order.

For example, given 8 as an input, there are two Pythagorean triples which contain 8:

6 8 10
8 15 17


The terms in each Pythagorean triple (without 8) are:

6 10 15 17


Because this set doesn't have repeats and is in ascending order, we can output just that.

You must write a program or function that takes one input, and your output can either be your language's representation of a list, or a string with any delimiter. So these outputs for 8 are all valid:

[6 10 15 17]    (Clojure list)
[6, 10, 15, 17] (Python list)
6 10 15 17      (uses space delimiter)
6#10#15#17      (uses "#" delimiter)


## Rules and Specs:

• You are guaranteed that the input is a positive integer.
• Your program must return the correct output for 3600 in 60 seconds. This is the same amount of time as TIO timing out. The output for 3600 should be:

147 380 425 660 810 1008 1050 1204 1342 1500 1755 1920 2160 2240 2415 2700 2880 2886 3190 3250 3456 3570 3603 3620 3625 3660 3690 3750 3780 3796 3842 3900 4005 4080 4125 4240 4335 4352 4500 4559 4614 4800 4810 4850 5049 5070 5220 5460 5475 5648 5809 5980 6000 6201 6270 6540 6750 6980 7068 7230 7595 7650 7700 7932 8265 8405 8500 8640 9015 9360 9676 9805 10324 10445 10500 10962 11100 11538 11730 12270 12710 13210 13260 13740 14175 14625 14784 15216 16000 16400 16683 17067 17820 18180 19838 20090 20162 20410 21450 21750 22356 22644 23865 24135 25795 26045 26880 27120 29892 30108 32300 32500 33654 33846 35910 36090 39919 40081 40420 40580 43125 43275 44928 45072 50561 50689 53940 54060 59946 60054 64750 64850 67452 67548 71955 72045 80960 81040 89964 90036 101218 101282 107970 108030 119973 120027 129575 129625 134976 135024 161980 162020 179982 180018 202484 202516 215985 216015 269988 270012 323990 324010 359991 360009 404992 405008 539994 540006 647995 648005 809996 810004 1079997 1080003 1619998 1620002 3239999 3240001


This is , so shortest code in bytes wins!

• 1) What should be returned for numbers which don't show up in any Pythagorean triple? 2) I'm not sure the sorting adds anything to the challenge. 3) You didn't state a winning criterion yet. – Laikoni Mar 12 '17 at 18:38
• @Laikoni 1) All numbers (except for 1 and 2) should have Pythagorean triples. 2) I can get rid of it, if you want. 3) Fixed. – clismique Mar 13 '17 at 8:43
• What about 0? With the current spec I think it should be in every output. – Peter Taylor Mar 13 '17 at 13:58

# Make a 'Logical' interpreter

'Logical' is an esoteric language I am working on.

It involves 4 logic gates, AND(&), OR(|), NOT(!) and XOR(^).

Since only having 4 logic gates, the IO is only true or false (We are not discussing Qubits here :P)

It will have some lines in the format [input 1] [(not included in not gates) input 2] [output] [gate], showing which node is connected to which logic gate. For example, 1 2 3 & would mean node 1 and 2 are connected to an AND gate, and the output goes to node 3.

During the interpretation, it should get the status of the input nodes(nodes which are only connected to an input of a logic gate) as an array of tuples. For example, [[1,true][2,true]] is a valid input for the program 1 2 3 &.

Then the interpreter should output the result of the output nodes(nodes which are only connected to an output of a logic gate), also as an array of tuples. For example, [[3,true]] is the output for 1 2 3 when given the input [[1,true],[2,true]].

# Examples

[Too long, pastebin coming soon]

# Rules

• No logic gates will be given one or more input nodes as same as their output nodes.
• A blank program is invalid, thus will not be given.

## OP's note

I have clearly made this esolang for fun, but I hope it will be on some challenges, or make people understand more on logic gates.

• The language is missing quite some specification. You give syntax for a program consisting of one gate, but how do programs with multiple gates look? – Laikoni Mar 13 '17 at 12:52
• 1 2 3 & 3 2 ! doesn't violate the constraint "No logic gates will be given one or more input nodes as same as their output nodes" but it does give an unstable circuit. – Peter Taylor Mar 13 '17 at 14:51
• @PeterTaylor Is that a flip-flop? – fəˈnɛtɪk Mar 13 '17 at 15:41
• @fəˈnɛtɪk, no. A flip-flop settles into a stable state, whereas an AND whose output feeds via a NOT into one of its inputs can only settle into a stable state when the other input is 0. – Peter Taylor Mar 13 '17 at 16:08

This is

The Address Resolution Protocol is used to associate IP addresses on the local network with hardware addresses (aka MAC addresses). In its most basic form, ARP can be very insecure in the sense that your computer will believe anyone on the local network that says "Hey, this IP and this MAC go together!". This can be used maliciously, so we want to keep an eye on our ARP caches.

Write a program that does the following:

• On initial execution, reads in the operating system's ARP table.
• With a frequency between once per second and once per ten seconds (inclusive), checks the operating system's ARP table for changes and prints something, as described immediately below:

-- If there is no change, print this exact string (with one or two trailing new lines):

No Change

-- If a new entry has appeared in the cache, print the string (with one or two trailing new lines):

New Entry: <IP ADDRESS> --> <MAC ADDRESS>

where <IP ADDRESS> is the IP address of the new entry (formatted as described below) and <MAC ADDRESS> is the MAC of the new entry (formatted as described below).

-- If any entry has changed to a new MAC (meaning an IP address is now being associated with a different MAC address) print the string (with one or two trailing new lines):

!!! Possible Malicious Change: <IP ADDRESS> --> <NEW MAC ADDRESS> from <OLD MAC ADDRESS>

where <IP ADDRESS> is the IP whose entry has changed (formatted as below), <NEW MAC ADDRESS> is the new MAC (formatted as below), and <OLD MAC ADDRESS> is the old MAC (formatted as below)

-- If any entry has changed to a to <incomplete> (meaning an IP address is now being associated with nothing) print the string (with one or two trailing new lines):

Entry incomplete: <IP ADDRESS> --> <incomplete> from <OLD MAC ADDRESS>

where <incomplete> is a literal.

--- If an entry is now missing, print the string (with one or two trailing new lines):

Entry for <IP ADDRESS> (<MAC ADDRESS>) is gone.

• The program repeats until terminated.

Formatting

IP addresses have 4 octets that are dot separated. They may be formatted in either of the following fashions:

• in hex: e.g. 02.22.DC.FD, leading zeros MUST be included, alphabetical digits may be capital or lowercase, as long as cases are not mixed within a single IP address.
• in decimal: e.g. 22.54.198.9, leading zeros MUST NOT be included.

MAC addresses have 6 octets that are colon separated and must be formatted in the following fashion:

• in hex: e.g. 0F:CD:12:44:22:F1, leading zeros must be included, alphabetical digits may be capital or lowercase, as long as cases are not mixed within a single IP address.

A MAC address can also be a string literal to the effect of "incomplete" or "unknown" if that is what is in your arp cache. If it is, this should be used literally instead of an actual MAC address.

Operating System Differences

The three major operating systems (Mac, Linux, Windows) all use ARP and I'm fairly certain that all other modern OS's do as well. Your program need only run on a SINGLE operating system, to be specified in your submission header by its main type (e.g. Linux) and in your submission body by a fuller identifier (e.g. Centos 6.5). We will view each OS as it's own competition.

Testing things

The following commands will change your ARP table on Linux (and Mac?).

Add a (static) entry or overwrite an existing entry: arp -s <IP> <MAC>, e.g. arp -s 2.2.2.2 ab:cd:ef:12:34:56

Delete an entry: arp -d <IP>, e.g. arp -d 2.2.2.2

Flush all: ip neighbor flush all

• Is there an easier way to test submissions than building a local network with multiple devices? – Laikoni Mar 12 '17 at 18:48
• @Laikoni yes (at least on linux), static entries can be added to the table using arp -s. I'm sure there is something similar on other OS's. – Liam Mar 12 '17 at 18:51
• That's good to know. You could add a test script which triggers the different outputs to make the challenge a bit more accessible. – Laikoni Mar 12 '17 at 18:58

# Introduction

Although quines are interesting on their own, they've been explored to death. Quines with strange properties, such as palindromic quines, are also pretty interesting, but each of those challenges are basically one-shots. How about a challenge to create a program that creates quines?

# Instructions

Let's call an N-quine a program that prints its source code N times. The program is allowed to print newlines between each copy of the program. For example, any normal quine is a 1-quine. In python 3,

s='s=%r;print(s%%s);print(s%%s);';print(s%s);print(s%s)


is a 2-quine.

The challenge is to write a program that takes a number as input (call it N) and outputs the source code for an N-quine in the same language.

Programs will be scored by their length plus the length of the output when you put in 1. This is , so the shortest program wins.

# Example

One virtually ungolfed Python 3 answer (69 characters):

n=int(input());print("s='s=%r;"+"print(s%%s);"*n+"'"+";print(s%s)"*n)


If you input 1, it prints (32 characters):

s='s=%r;print(s%%s);';print(s%s)


So the final score is 69+32=101.

## Nearly-match a string

Our near miss algorithm is too slow. The boss is blaming the Levenshtein distance builtin for being overkill for our purpose as we're only interested in a distance of 1. Please code something leaner.

Input: Two different strings, in any reasonable format. At least 36 different characters should be supported.

Output: A truthy/falsy value which distinguishes between strings with a Levenshtein distance of 1 or more than 1.

This is , so the shortest program or function that breaks no standard loopholes wins! Builtins that calculate the Levenshtein distance are not allowed.

• What's the rationale for choosing 36 in "at least 36 different characters"? – DLosc Mar 18 '17 at 20:29
• [a-z0-9], perhaps? – Greg Martin Mar 18 '17 at 22:01
• The back story actively contradicts the scoring criterion. Golfed answers are likely to be much slower than the builtin. – Peter Taylor Mar 22 '17 at 14:52
• @PeterTaylor Surely that depends on the language. I suspect a C answer for the specific challenge would outspeed any generic library. – Neil Mar 22 '17 at 16:41

# Shh... Can you Split a Secret? cryptographycode-golf

In Applied Cryptography by Bruce Schnieier (which I have been reading quite a lot recently), a protocol for splitting secrets is discussed. Here is a brief description:

1. Trent generates a random string, R, the same length as the message, M.
2. Trent XORS M with R to make S.
3. He gives R to Alice and S to Bob.

Your task is to, given an input, split the input into the two outputs. One output should contain the random string; the other should contain the original input XOR'd with the random string. Input and output may be to/from files or to/from STDIN/STDOUT. Outputting to STDERR is also allowed.
There are a few restrictions, however:

1. Your program must take 3 inputs, and output the random string and the original string XOR'd with that random string into the other.
2. Your program must be cryptographically secure. All random number generators must be cryptographically secure. For example, /dev/random is fine, but the Mersenne Twister (usually randint(number,number) is not. Any random number generator must be explicitly cryptographically secure.
• If you want to know anything more about what "cryptographically secure" means, check here.
3. Standard rules and loopholes apply.

This is , so the code with the fewest bytes will win.
May the best coder prosper...

• Is there a reason you are requiring input/output to be file-based? That removes a lot of languages out of the challenge. – Nathan Merrill Mar 18 '17 at 17:47
• @NathanMerrill What should I change? – ckjbgames Mar 18 '17 at 17:48
• @NathanMerrill I did kind of have file I/O in mind... – ckjbgames Mar 18 '17 at 17:48
• Simply take in a single string as input (M), and have it output two strings (R and S). Writing/reading from a file is trivial in most languages, but in others its literally impossible. – Nathan Merrill Mar 18 '17 at 17:49
• @NathanMerrill Thanks – ckjbgames Mar 18 '17 at 17:49
• Also, I'm not very good at cryptography, so I may be wrong here, but I think that "cryptographically secure" is a bit too broad. Explaining to use /dev/random is great, but what other steps need to be taken to ensure it's cryptographically secure? – Nathan Merrill Mar 18 '17 at 17:52
• @NathanMerrill See this. – ckjbgames Mar 18 '17 at 17:56

In an effort to improve things, I have split this challenge into two parts, both currently listed in this question for the sake of keeping them together.

NOTE: "Run a game of Flood" has now been posted.

# Solve a game of Flood

This is a Code Challenge with Code Golf aspects.

Flood is a game in which the player is presented with a game board such as this:

On each turn, you choose a colour (on the link above, by clicking a square containing that colour), and the cell in the top-left corner is filled with that colour - this colour will absorb all adjacent cells with the same colour. So, for example, the first turn might be Blue, which will cause the yellow cell in the top corner to turn blue, and merge with the existing blue cell. The next turn might be Purple, which will fill both of the first two cells purple, merging them with the two-cell purple area attached to them. Then you might go Red, then Orange. With this sequence, the board will end up as:

Your task is to write code that acts as a "solver" program/code, which reads in the initial/current state of the board, and determines the next move or the remaining moves. This code should make an effort to produce an efficient path to the solution, but you must balance this search for efficiency with the golfing effort.

Your code may make use of a simulator code (such as may be used in the "Run a game of Flood" challenge) that takes input of the current state of the board and a sequence of moves, and outputs the resulting state of the board after these moves - these must be the only inputs/outputs used by your code.

Your code must produce a solution for any initial board (not just the test boards, see below), and must be deterministic - that is, it must produce the same solution every time the same initial board is input (fixed-seed pseudorandom numbers are acceptable).

## Scoring

As noted above, this is a combination Code Golf challenge. Your goal is to minimise your score, much of which is determined by the length of your code in bytes.

Your final score is b+2sum(n_i)+sum(d_i), where b is the total bytes of your code (simulator code does not count towards this value, but the call to simulator code does), n_i is the number of steps used by your solver program to solve each of the test boards (see below), and d_i is the maximal depth to which your code searches for each of the test boards before selecting a step.

The d_i value, here, is intended to punish those who use brute force to find the optimal solution. You need to find efficient solutions, cheaply.

## Rules and Assumptions

Standard Loopholes are forbidden.

Code must be able to handle non-square boards, with each dimension being anywhere between 6 and 30 cells (more is fine, it must handle this range). It must be able to handle between 3 and 9 distinct colours or "colour" labels (numbers are fine).

You may assume that input is in simplest form - that is, if there are four colours, they will be labelled 1-4, or a-d, or any other similar system as appropriate. You will not need to handle situations such as incorrect inputs, unsimplified inputs (you won't have the numbers 1, 3, 6, and 9, without the others in between, unless it suits your code).

Your code may take input indicating details of the board such as dimensions and the set of valid "colours".

Code cannot treat the test boards as special cases - that is, you cannot have the code detect which test board it is, and if it doesn't match a test board, use a generic, low-quality code for solving.

Request: If you believe you have identified a non-standard loophole, and it's definitely a loophole and not in the spirit of the question, please comment to have the loophole closed, rather than posting an answer using it. This is not a rule, per se, but an effort to keep the challenge interesting.

## Test Boards

7x6, 6 colours

12x12, 6 colours

12x12, 3 colours

16x16, 9 colours

Tags: Code-Challenge, Code-Golf, Optimization, Game

Not sure whether this should be labelled as Code-Challenge, Code-Golf, or both

• The game itself is a nice challenge but I don't think it's a good idea to put both the simulation and the solver into the same challenge. They'd make perfectly decent separate challenges, especially since the scoring is mostly based on the solver, apart from the simulators byte count being added in. – Martin Ender Dec 13 '16 at 12:11
• Also, there's this: codegolf.stackexchange.com/q/26232/8478 – Martin Ender Dec 13 '16 at 12:12
• @MartinEnder - I'd considered having two separate challenges, but I realised that the solver code would likely require the simulation code or a variant of it, anyway. Or at least, there would be a lot of duplication between the two. Also, thanks for finding that past question - I did a quick search, but I didn't spot that particular question, for some reason (maybe I included the word "golf" in the search, I'm not sure) – Glen O Dec 13 '16 at 13:52
• Given the issue with overlap between the two parts, what do you think - split them, leave the challenge as-is, or modify the question to merge the parts into a single code (so the code has to be able to take input, but will auto-solve for some input?) – Glen O Dec 13 '16 at 13:54
• I'm definitely in favour of splitting. Especially since we've already done a solver challenge, I think just the simulation could be a really fun (and well-scoped) challenge. It could be as simple as "here is a grid and a list of moves, return whether the moves solve the grid". – Martin Ender Dec 13 '16 at 13:55
• @GlenO I made the edit I did because as the challenge has already been posted, it shouldn't take up vertical space for no reason. – Okx Mar 20 '17 at 10:36
• @Okx - I understood why you made the edit, but the thing is, there were two challenges, and only one had been posted. So I reverted, then removed the one I'd already posted and replaced it with a link. What remains is the unposted one. – Glen O Mar 20 '17 at 15:18

# MCDI: Make and Change Directory into

Input: A string consisting of only alphanumeric characters, whose length does not exceed 255. It is given as string input, through STDIN on a single line, through ARGV, etc.

Effect: If a directory with the given name does not exist in the current directory, create it. Then, change the current directory to that directory. You can assume that no file with the given name exists.

Here is an example Batch script that does this (ungolfed, of course):

@ECHO OFF
IF NOT EXIST %1 MKDIR %1
CD %1

• if it's possible but not normal to create directory names containing "/" or "\" in your environment, what should the script do when it encounters those? – Sparr Mar 24 '17 at 0:25
• @Sparr A string consisting of only alphanumeric characters – Dennis Mar 24 '17 at 0:37
• @Sparr Yeah, I didn't want to get into the nitty-gritty of file system's allowed characters (especially window's), so I restricted the domain to alphanumeric characters (as seen by the first sentence) – Conor O'Brien Mar 24 '17 at 0:40
• Can we assume that there is no file with the same name? – Dennis Mar 24 '17 at 1:07
• Also, what about full programs? I don't know how this works on Windows, but in Linux, you can only change the directory for the program itself. Once it finishes, you'll be back where you started. – Dennis Mar 24 '17 at 1:11
• @Dennis Oh, hm. I suppose the batch script only works like that because it's windows. Perhaps I should add some sort of requirement, like, copy the original file to the location. Thoughts? – Conor O'Brien Mar 24 '17 at 1:19
• @Dennis: that's not quite true. "/bin/cd" is a bit of a running joke in the esolangs community, because it's a fun absurd concept; it is possible to write, but it isn't possible to write in any sort of sane way. (When I wrote it myself, I had it attach a debugger to the parent process to change the current directory inside that process directly.) Without using debugger tricks, the program would need to run inside the parent process directly, which would basically limit the choice of language to sourced shellscripts (including the batch in the OP; that's a sourced language). – user62131 Mar 24 '17 at 14:27
• Point taken, but I doubt the OP was expecting us to write something like that. – Dennis Mar 24 '17 at 14:30

# Meta Code Golf kolmogorov-complexitycode-challenge

Late new year resolution: I'm finally cleaning up all my input and output files I used for code golf previously. Only problem is, I don't know which input and output files go to which code golf question on this site.

All problems used in this question should be posted on or before 31st December 2016 23:59:59 (GMT).

Input format:

The input would consist of an input and a correct output for the code golf question.

Each file can be accepted as an input file with a hardcoded filename, in the standard input, or as a function argument. The output can be a function return value, written to a file, or to standard output.

In the case both files are in standard input, you are allowed to define any arbitrary separator as long as it is consistent for all input files, and the separator is less than 16 bytes long.

You may assume that the separator is neither in the input file or in the output files. (All possible input files/output files with the separator in it are not used for scoring purposes.)

Output format:

Your code is required to output the ID of the question. Your code is allowed to have other non-numerical output.

For example, for this question:

https://codegolf.stackexchange.com/questions/64449/rearrangement-inequality


You can output any one of the following:

https://codegolf.stackexchange.com/questions/64449/rearrangement-inequality
64449
The question ID is 64449.
Just look at question 64449. You can find the question there.


## Sandbox Meta: Scoring definitions

For each input-output pair, it may correspond to multiple questions. In that case, you may choose to output multiple answers, or only one answer. An input-output pair is considered to be correctly classified if it has at least one correct answer, and all provided answers are correct.

A question is considered correctly classified only if all input-output pairs corresponding to the question are correctly classified and the question ID is in the output for at least one of the input-output pairs corresponding to the question.

## Sandbox Meta: Alternative definition

A question is considered correctly classified only if all input-output pairs with the question ID in the output are actual input-output pairs to the question, and all input-output pairs which do not correspond to the question do not have the question ID in the output.

Your score is the length of your code divided by the square of the number of correctly classified questions.

In the case the total number of questions you correctly classify is zero, you score positive infinity. Why am I even saying this? Of course it should work on at least one question.

In the case that there are many ways the input and output for the question can be formatted, you are allowed to choose any one of them in the question, which is clearly allowed before 31st December 2016 23:59:59 GMT. You are allowed to choose different input/output formats for different questions.

It is guaranteed that none of the input-output pairs have infinite input or output. It is guaranteed that none of the input-output pairs have

## I have some concerns:

As I may not have online access all the time, your code should not rely on looking at StackExchange to find the questions.

## Finally:

This is , and the winner will be the person with the lowest score, in case of a tie, it would be tiebroken by submission time.

## Sandbox Meta:

Lots of these questions might be difficult to encode the input, for example questions where the input is to a function.

• What exactly is the input? A single test case, and the program should output a question for which the test case would pass? – Peter Taylor Mar 24 '17 at 11:38
• @PeterTaylor The input consists of an input file, and a correct output for that question. The output would be the ID of the question. (Sorry if it wasn't clear.) – Element118 Mar 24 '17 at 11:40

# Many Happy Returns!

I'm not sure whether to make this or .

Write a function that when it returns, it returns an extra frame up the stack. In other words, functions usually return directly to their callers; however, here the function should return directly to its caller's caller. To illustrate, consider this program:

#include <stdio.h>

int b(void) {
int rc = 3;
printf("%s(): returning from b()\n", __FUNCTION__);
return rc;
}

int a(void) {
int rc;
rc = b();
printf("%s(): returned from b()=%d\n", __FUNCTION__, rc);
return 2;
}

int main(int argc, char *argv) {
int rc;
rc = a();
printf("%s(): returned from a()=%d\n", __FUNCTION__, rc);
return 0;
}


The output from this program is:

b(): returning from b()
a(): returned from b()=3
main(): returned from a()=2


An entry to this challenge would return from the innermost function c() in a special way such that the output is:

b(): returning from b()
main(): returned from a()=3


Note that the flow of execution goes directly from the return of b() back to the next line after where main() called a(). The returned from b() message is not output as this code never executes. It is not sufficient just to put this message in a conditional.

### Rules

Assuming a template similar to this sample - i.e. main() calls a() calls b():

• Entries are scored by the size of function b() in bytes - smallest wins.
• Functions main() and a() must be provided, but are not included in the score
• There must be no special logic in main() and a() that help. If the call to b() were replaced with a call to b1() (a normal function that returns normally), with no other modifications, then the returned from b() message would be observed.
• You may assume that the return types of a() and b() are the same

I am aware that there are languages which make this very easy, but it is significantly more challenging (or maybe impossible) in other languages. I don't want to explicitly ban any languages, but I am most interested in the answers where the solution is non-trivial.

• Your example is much longer and verbose than it needs to be, to the point that I think it's harder to follow than a minimal example would be. – Sparr Mar 24 '17 at 0:07
• @Sparr I've shortened the example somewhat – Digital Trauma Mar 24 '17 at 5:31
• What can be assumed about a(), particularly in terms of how many elements and of what type it will allocate on the stack? – Peter Taylor Mar 24 '17 at 11:40

# Secret Santa

Goal: Given a list of names with public keys, assign each person a name, encrypt it with their public key and print the list of gifters with their encoded giftees.

## Introduction

My family wanted to get a head start on Secret Santa (so they can shop sales though out the year). The problem was "how do we do this remotely?" Pubic key encryption, of course! My family is not very tech-savvy (or math-savvy). So after a several hours of phone calls, I was able to get everyone to generate public+private keys (by hand) and chat them to the group. Now I need to message back a gifter/giftee list.

## Specification

• Input
• Flexible
• A list of First Name, Last Name, Piece One of Key, Piece Two of Key tuples
• So [ John, Smith, 351, 174 ] is an example tuple
• n would be 351
• e would be 174
• Each name will be nonempty, capital and lowercase letters
• Initials will be unique
• Algorithm
• For each tuple (i.e. gifter)
• Randomly assign a giftee such that giftee != gifter
• [NOTE] Each giftee should be assigned to exactly one gifter
• Get the giftee's first initial and last initial
• A or a = 1, B or b = 2, ..., Z or z = 26
• Encrypt each initial
• Encryption
• The encryption of a number x is x^e % n
• Output
• Flexible
• A list of gifters (first and last name) with the encrypted first and last initial of their giftee
• Score
• Shortest code in bytes wins

## Test Cases

Input                         Middle Step                   Output
-----                         -----------                   ------
[Sherlock Holmes,1363,3]      Irene Adler => IA             [Sherlock Holmes,729,1]
[John Watson,1763,11]         Mycroft Holmes => MH          [John Watson,281,935]
[Mary Watson,1927,3]          John Watson => JW             [Mary Watson,1000,605]
[Mycroft Holmes,1271,7]       Peter Jones => PJ             [Mycroft Holmes,256,1043]
[Peter Jones,1073,5]          Sherlock Holmes => SH         [Peter Jones,688,578]

• "Assign a giftee such that giftee != gifter" seems to be lacking a constraint that each person should be giftee of exactly one gifter. – Peter Taylor Mar 23 '17 at 23:03
• @PeterTaylor Good catch! I clarified that "Each giftee should be assigned to exactly one gifter" – NonlinearFruit Mar 24 '17 at 15:26

# Simplify Brainf**k

We'll call a language BF equivalent if it emits a context-free substitution mapping to and from BF. For example, consider the hypothetical language SimpleBrain which is identical to BF except that it does not include + or >, but instead has }. It emits the following mapping to BF:

}: +>
<: <
-: -
.: .
,: ,
[: [
]: ]


And the following mapping from BF:

+: }<
>: -}
<: <
-: -
.: .
,: ,
[: [
]: ]


# Challenge

Design a BF equivalent language. The language with the fewest commands wins (SimpleBrain, for example, has 7). In the event of a tie (which is likely) the language with the shortest representation with the mapping you provide of the following BF program wins:

++++++++++[>+++++++>++++++++++>+++>+<<<<-]>
++.>+.+++++++..+++.>++.<<+++++++++++++++.>.
+++.------.--------.>+.>.


# Sandbox Notes

There have been many efforts to "simplify" BF, but most of them shift complexity from the language to the interpreter. I've tried to formulate the rules in such a way that this cannot happen.

Are there interesting solutions to this challenge? I can only think of a few. I'd love to seem some creative answers to this problem. I am also looking for ways to better define context-free substitution mapping as what I have in mind clearly excludes trivial reductions like Braincrash because there is not a context-free mapping from Braincrash to BF, but I don't know if that's totally clear from the wording. By context-free substitution mapping, I mean substitution rules of the form:

a := b_1 b_2 ... b_n


where a is a single command in the source language and the RHS is any finite number of commands in the language we're mapping to (the LHS consists of a single symbol which is why I described it as context-free).

I also question whether this is exactly a programming puzzle per say. I am open to reformulating the challenge to make it better suited for the site if there is opposition.

• esolangs seems to be down but if memory serves, there are 2-command or 1-command equivalents/analogs (Unary might count but I can't reference how it works) which already exist. Also I think an implication of Turing completeness implies that you can create a mapping to commands in another Turing complete language but I have not taken enough CS theory to back up that intuition. – cole Mar 25 '17 at 2:19
• Yeah, Braincrash is the first 2-command example that comes to mind. There are also trivial equivalents that claim to reduce BF to two characters by using what amounts to a different encoding. But, as far as I can tell there isn't a mapping like the one I am trying to describe from any of these languages to BF (thus, they would not qualify). If you can find an example do let me know :) – Orby Mar 25 '17 at 4:05
• Also, I agree with your intuition that there exist mappings between any two turing-complete languages, though I think they are usually not context-free. – Orby Mar 25 '17 at 4:07
• One more comment: context-free is probably not the right word to use. I mean that the substitution rules are in the form A -> B_1B_2...B_n where LHS is a single command and RHS is any finite number of commands. – Orby Mar 25 '17 at 4:11
• This is a code-challenge with metagolf as the tiebreak, so I'd say it's reasonable here. Also, it's going in a different direction from the typical BF minimizations on Esolang (although I've seen similar minimizations for other languages, like Underload); I like the requirement for the language to be compilable to and from BF by replacing each single character with a specific string, which puts hard limits on what sorts of cheating are allowed. I'd recommend that the equivalence be in terms of I/O behaviour, not values stored on the tape (so that the tape format can be changed). – user62131 Mar 26 '17 at 18:08
• I like this challenge, but the simplest would only need two symbols a la Ook. – wizzwizz4 Dec 16 '17 at 19:53

# Make a generated MIDI sound better

Being a crazy man, I sometimes listen to music made to midi trough a filter that makes it MIDI. It is a great experience, but I need to work a lot on it, because MIDI has a lot of instruments, and not every one sound good with every track

## Challenge

Write a program that that finds which instrument represents the song the best

## Input

A single .mid file

## Output

A number representing MIDI instrument

## Scoring

Score=Similarity/length by characters

Similarity is defined by executing Fourier transform and finding the percent of similarity between original and output sounds

## Meta

Is this any good? and is scoring not exploitable?

• You need to provide a lot more details on what task exactly is needed to perform. Also on how many test cases is the similarity mentioned in the scoring computed? Do you already have a program to measure similarity? – Laikoni Mar 26 '17 at 0:07
• @Laikoni It's the part I'm working on now, so it may change a lot. I don't already have a program to measure similarity, but looks like it's preety easily done in Audacity. For test cases, i have some, but i don't have enough rep to add them. – Ignas Kiela Mar 26 '17 at 18:34
• @ais523 I'm sure that it's difficult, it would already been done by now :) . For anti-brute-force restriction, i can't find a way to solve this puzzle that wouldn't be brute-forcing, so maybe adding a speed requirement would help? Or something that would require effective brute-forcing. – Ignas Kiela Mar 26 '17 at 18:38
• restricted-complexity is probably the best way to add a speed requirement here (if you restrict it to quadratic, that means that doubling the length of the music to analyse can increase the runtime by no more than a factor of 4). That would allow pretty much all legitimate solutions, but disallow pretty much all brute force solutions – user62131 Mar 26 '17 at 22:14

# Goodstein Sequences

From Wikipedia:

The Goodstein sequence G(m) of a number m is a sequence of natural numbers. The first element in the sequence G(m) is m itself. To get the second, G(m)(2), write m in hereditary base-2 notation, change all the 2s to 3s, and then subtract 1 from the result. In general, the (n + 1)-st term G(m)(n + 1) of the Goodstein sequence of m is as follows:

1. Take the hereditary base-n + 1 representation of G(m)(n).
2. Replace each occurrence of the base-n + 1 with n + 2.
3. Subtract one. (Note that the next term depends both on the previous term and on the index n.)
4. Continue until the result is zero, at which point the sequence terminates.

Example: The Goodstein sequence for 13 is:

1. 2^(2+1)+2^2+2^0 = 13
2. 3^(3+1)+3^3+3^0-1 = 3^(3+1)+3^3 = 108
3. 4^(4+1)+4^4-1 = 4^(4+1)+3*4^3+3*4^2+3*4^1+3*4^0 = 1279
4. 5^(5+1)+3*5^3+3*5^2+3*5^1+3*5^0-1 = 5^(5+1)+3*5^3+3*5^2+3*5^1+2*5^0 = 16092
5. 6^(6+1)+3*6^3+3*6^2+3*6^1+2*6^0-1 = 6^(6+1)+3*6^3+3*6^2+3*6^1+6^0 = 280711

And so on

Print the first 3 terms of the Goodstein sequence that starts on the input. If there are fewer than 3 terms, print out all the terms in the sequence (e.g. for input 1).

Example inputs and outputs:

Input: 1, Output: 1, 0

Input: 2, Output: 2, 2, 1

Input: 3, Output: 3, 3, 3

Input: 4, Output: 4, 26, 41

You may assume that the input will be a natural number from 1-200. Note that one of the challenges of this challenge is to support integers over 2^500.

# Winning Criterion

This is , so shortest code wins! Answers from all languages are encouraged. The speed of the solution does not matter, as long as it eventually prints out the desired answer.

# Fun Fact

All Goodstein sequences eventually converge to 0.

Tags: code-golf, math, sequence, number-theory, base-conversion

# Darwin Fights

(code-challenge)

You are fighting a swarm of evolving enemies. Your goal is to outsmart them by turning evolution on its head.

The game consists of multiple rounds, starting with round 0. Every round n contains 5(n+1) enemies, so it starts out with 5, then 10, and so on. Each enemy has a couple statistics:

1. Health -- the amount of health the enemy has left

2. Attack -- the damage that the enemy can do

3. Defense -- reduces damage done

4. Reproduction -- controls the rate (chance) of reproduction

5. Blur -- Makes the enemy seem weaker than it actually is.

The starting values for these numbers are taken from the previous round (details below), or if it is the first round, a mutated form of the enemy with health 1, attack 0, defense 0, reproduction 1, and blur 0. The player also has similar stats: health, attack, defense, and regeneration (how much health recovered per turn). You start off with 100 health, and the only condition on attack, defense, and regeneration is that their sum must be less than or equal to 10.

Details of turn order:

1. All the enemies attack you, you lose health according to the damage formula below.

2. You choose 3 enemies to attack or you nuke them (see below). It is advised to choose the 3 most powerful enemies to stop them from reproducing.

3. All surviving enemies have the chance to reproduce. If r is their reproduction coefficient, their chance of reproducing is r/n where n is the total number of enemies. Thus, the expected number of new enemies is the average value of all the enemies' r-values.

4. If there are no surviving enemies, the round is over. The next round starts and is populated with 5(n+1) enemies. Your health is restored. The next round's enemies' stats are determined by a weighted average of all the dead enemies' stats of the current round. They are weighted by the number of steps they survived in that round. Thus, it is important to eliminate strong enemies early in the round.

Damage: If the attacker has attack a and defender has defense d, the amount of health lost by the defender is a*(1-d/25). The minimum amount of damage is capped at a/4, so the value of d is essentially capped at 18.75 (it can be higher, but it wouldn't do any good).

Input You will get input in the following manner: a list of lists, each list containing the data for one enemy, in the order [health, attack, defense, reproduction]. Each of these values is reduced by a number uniformly chosen between 0 and blur. You will return the indices of the enemies you want to attack. If you return anything other than a list of 3 nonnegative integers (so e.g. an empty list), you choose to nuke the enemies.

Nuke: Nuking is just the ability to attack every enemy in a single turn. After nuking, you must wait 10 turns before being able to nuke again. Warning: since nuking attacks all enemies, it is common that a nuke will leave only strong enemies behind. Thus if there are survivors that reproduce, they will be the strongest. Use nukes carefully!

Reproduction: If an enemy is able to reproduce, it will choose a mate to mate with. The chance of being chosen as a mate is proportional to the attack power. It is possible the enemy's mate is itself (asexual), or that there is only one enemy left, in which case it is forced to reproduce asexually. The new enemy's traits is based on the average of the parents' traits, added to a mutation

Mutations: As soon as an organism is created, whether at the beginning of the round or from parents, its values are mutated. A normally distributed random number with mean 0 and standard deviation 0.3 is added to each one. A mutation will never cause the starting health or reproduction coefficient to go below 1, and will never cause the attack or defense to go below zero.

Score: Your score is the number of rounds you survive. Ties are broken by the amount of least health you had left at the end of any round before the last round. Scoring will be based off of taking your median run after running your code for a large number of times (to be determined, on the order of 100).

Controller: Currently written in python, available here: https://gist.github.com/prakol16/f0a306efd63a977a95c034b4b6e00ef1#file-darwin_main-py. To write your own class, extend the class Player and override the methods __init__ and get_attack

class ExamplePlayer(Player):
def __init__(self):
# Should add up to 10
super().__init__(attack=3, defense=0, regeneration=7)

def get_attack(self, enemies, round_num, nuke_recharge):
if self.get_health() < 50 and nuke_recharge == 0:
return [0]  # Nuke it!
return [0, 1, 2]


## Linear Chemistry

Input is a string representing a skeletal formula of a molecule, in a format similar to O=C-O-H. However as a lot of formulas contain carbon and hydrogen atoms, it is customary to skip them from the description and just signal their presence by only displaying the used bonds. We will call these atoms implicit atoms, while the ones that are shown explicitly in the formula explicit atoms.

Your job is to calculate the number of different atoms a specific skeletal formula contains.

The input is a one line string containing the following tokens:

• -, =, ≡ symbolizing the bonds between the atoms
• Any uppercase character followed by a number of lowercased characters symbolizing an atom of some sort (e.g. O, H, Br, Uub, etc.)

You have to output the number of different atoms this molecule contains in any sensible format.

Notes:

• You can omit specifying the number of atoms if there is only one in the molecule
• You may or may not merge the number of implicit and explicit atoms of C and H molecules (e.g. you can treat them as separate types).
• You can output the atoms in any order

For example for the input string -OH valid output can be:

• CH₃OH (preferred output)
• CH3OH
• CH4O
• H4O1C1
• {C:1,H:4,O:1}

Invalid outputs:

• CHHHOH (you have to merge the same type of atoms into one)
• CH2OH2 (you have to maintain the numbers for explicit and implicit C and H atoms properly if you didn't merge them)

You can use the following rules to parse the input:

• For every explicit atom present in the input there will be one atom in the output. E.g. OOHOBrUub is O₃H₁Br₁Uub₁
• Every bond token between two explicit atom tokens can be ignored. E.g. O-O, OO and O=O all mean the same thing: O₂
• Two bond tokens following each other, or a bond token at any end of the string means an implicit C molecule and some amount of H molecules. The amount of H molecules will be 4 minus the amount of dashes in the bond tokens (1 for -, 2 for = and 3 for ≡). E.g. O--O means O₂CH₂, O-=O means O₂CH and O==O/O-≡O both mean CO₂.
• You can always assume that there will be no invalid inputs where the number of implicit hydrogen atoms would be negative (e.g. ≡=, ≡≡, or =≡)

Examples:

-: C₂H₆
≡: C₂H₂
--: C₃H₈
==: C₃H₄
O==O: CO₂
-OH: CH₃OH (or CH₄O)
--OH: C₂H₅OH (or C₂H₆O)
-=-: C₄H₈
≡-≡: C₄H₂
=O≡-≡O=: C₄O₂H₄
Br-O-C-=Uub: BrOCCUubH (or BrOC₂UubH)


This is code golf, so shortest submission wins.

• 1. The last test case seems to be missing two hydrogens from the explicit carbon. 2. I think that the detailed explanation of how implicit atoms work needs to be earlier. Most of the spec assumes that you understand it, but it comes right at the end. 3. I find it rather confusing that sometimes the bonds are omitted completely in the explanations (e.g. in OOHOBrUub), and even more so that none of the test cases cover this. – Peter Taylor Mar 28 '17 at 13:49
• 1. You don't need to add hydrogens for the explicit atoms, I probably have to add this. 2. I wasn't sure where to put it exactly, I could swap the output spec with the input parsing 3. They're okay by the spec, and there are some examples (OH), but you are right I might need to add some more – SztupY Mar 28 '17 at 14:28

# Let's play hide and seek.

The objective of this game is for the user to pick a spot on a grid (size given by user). For example, here is a 5x5 grid below.

--------------------------
| A1 |    |    |    |    |
|    |    |    |    |    | A
--------------------------
|    |    |    |    | B5 |
|    |    |    |    |    | B
--------------------------
|    | ME |    |    |    |
|    |    |    |    |    | C
--------------------------
|    | D2 |    |    |    |
|    |    |    |    |    | D
--------------------------
|    |    |    |    |    |
|    |    |    |    |    | E
--------------------------
1    2    3     4    5


Each tile is identified by its cross section of letters and numbers, A1, D2, and B5 are shown above.

The user picks a random tile to hide in. I picked C2.

Now, you must build a program that will guess tiles.

If you are in the tile, you will respond with Y meaning the computer won.

Otherwise, you will give the direction from the guessed tile (N, NE, E, SE, S, SW, W, NW). So if the computer guesses D3, you would input NW.

Let me show you an example of what the program should look like.

Grid?
5x5


Pick: E2

Guess: C3?
SW
Guess: D2?
S
Guess: E2?
Y


The scoring for this program: The program will be tested for three different scenarios using the grid sizes: 5x5, 10x10, 20x10

The program should be able to guess the correct square in the minimum number of guesses.

Then, lowest bytes wins.

• With your four scenarios I can get it in an average of 1.75. This is also an incredibly poor scoring system. – fəˈnɛtɪk Mar 30 '17 at 15:29
• @fəˈnɛtɪk Should I make it a requirement to get the correct answer in the minimum number of guesses (and specify for each case)... and then just lowest bytes wins? – JKonowitz Mar 30 '17 at 15:33
• Welcome to PPCG and thanks for posting in the sandbox! I like the premise of this challenge but as fəˈnɛtɪk has pointed out in the current form the scoring system is poorly defined. Also allowing larger board sizes might make for a harder challenge. – Laikoni Mar 30 '17 at 15:34
• As a code challenge, this scoring system is incredibly bad because it will essentially allow you to pick and choose which answer will win. It would be better if you just made it a Code-golf challenge for code that will use the least moves on average to cover the entire board. – fəˈnɛtɪk Mar 30 '17 at 15:49

# How far is this list from sorted?

Input: sequence of whitespace-separated base-10 integers (on stdin).

Output: minimal count (base-10 integer) of numbers which have to be moved to a different position in order to sort the list (to stdout).

### Example

Input

0 1 2 4 5 6 3 9 7 8

becomes sorted by moving at least two numbers ‒ 3 and 9.

0 1 2 3 4 5 6 7 8 9

so the output would be 2.

• For already sorted (including constant) or empty lists, the result is 0.
• Shortest entry wins.
• Can the input be a string or literary a list of numbers? – Anthony Pham Apr 2 '17 at 0:56
• Seems like a duplicate of this, if I understand the task correctly. – Zgarb Apr 3 '17 at 7:47
• @Zgarb No, that's something different. For sequence 1 7 2 2 4, the result of the task you linked would be 2 (the longest strictly increasing subsequence). In my task, it's 1 (you have to move 7 to the end to make it sorted). I think my task would be a bit more difficult than the other one. – kyrill Apr 3 '17 at 11:21
• @kyrill, the result of the task Zgarb linked would be 3 because the longest strictly increasing subsequence is 1 2 4. Relax the strictly and it's asking for the length of the list minus the answer to your proposed question. I agree with Zgarb that it's a dupe. – Peter Taylor Apr 3 '17 at 11:30
• @PeterTaylor Right, I didn't realize that. Duplicate it is. – kyrill Apr 3 '17 at 11:41

# Route the phone calls

The challenge is to take the 3 ascii cities with 3 zones and (meta: in progress) and two phone numbers, you will return the cities with the phone lines that are used to connect the two calls replaced with a symbol of you choosing that is not used in the cities. (I will provide the cities at the end of this challenge post so you know).

# Rules and notes

Everything must be the same except the phone lines (they will be the letter L)

Standard rules

The cities will be top down

# Input

The cities shown as is without newlines (the cities will be connected together with phone lines :)

Two phone numbers (will be valid)in the format (xxxxxxxxxx)

# Output

The cities with the connected calls

# Meta

This is going to be a big project. I am not done writing the challenge for sure. I need cities and will start to make some but if anyone has cities or makes any I would be happy, a website with cities would also be pretty chill.

Also I am posting in sandbox as I have to get off the computer :P

# Given a list of words, find which word follows Zipf's Law the least.

For each distinct word w in this list, we know the following two properties of w in this list:

• Its frequency in the list (that is, the number of occurrences of it divided by the number of elements in the list), and
• Its frequency rank; that is, the number of words that occur more often than it.

In the case that two words have the same frequency, we assume the one that comes first when sorted by lexicographical order is first.

If we plot a large list of words with regular natural language distribution on a logarithmic graph with these two properties as the x and y values, we see that the points form nearly a straight line with slope of approximately -1. This is known as Zipf's Law.

# The Challenge

You will be given a list of words l. Imagine each distinct word being plotted this way on a logarithmic graph. Then, the line k is the Linear Regression Line for the data set. Then, for every point p except the top-most ranking and most frequent point, find the vertical distance to the line k, and let this distance be d. Then, we scale the vertical distance so that points in the middle of the line will be the most heavily weighted. We do this by the following. We find the x coordinate of the mid-point of the line (let this be x). Then, half of the horizontal span of the line is w, the width. If we let px be the x coordinate of the point p, then we multiply d by 1 - (x - px) / w. This value is the score.

# Input

The input will be an unordered list of words in any reasonable format you wish.

# Output

The output will be a single word indicating which word conforms the least to the "standard".

# Test Case

Input: a a a a a a a a a a b b b b b b b c c c c c d d
Output: b
See an explanation here

• 1. "Normal distribution" is a technical term: anyone who's studied statistics in English will immediately think of the distribution also known as Gaussian. IMO you should just call it Zipf's law. 2. The description given for the score is a) ambiguous and b) very odd. It's ambiguous because the question in general implies that the absolute difference should be what matters, but nothing explicitly says this. It's very odd because comparing gradients gives a massive bias towards the more frequent values. Why not vertical distance from the line? (And why not use the line of best fit?) – Peter Taylor Apr 4 '17 at 8:34
• @PeterTaylor Thanks for the suggestions. Yes, I forgot that Normal Distribution is actually something. And yes, I should explicitly state absolute difference. The reason that I compare gradients is because vertical distance makes a larger difference near the ends of the line. So I will change the specs to compare vertical distance, but with a specific weighting. By the way, how is line of best fit calculated exactly? I can only find definitions where you draw a line that looks like it fits the system best. – user42649 Apr 4 '17 at 13:20
• en.wikipedia.org/wiki/Linear_regression – Peter Taylor Apr 4 '17 at 13:31
• @PeterTaylor Okay, thanks. I've adjusted the specs to include all of your suggestions. – user42649 Apr 4 '17 at 13:39

# Lock the Language!

This is a challenge.

### Challenge:

• Write a program that given two arbitrary integers adds those and prints them to STDOUT
• In this Thread you post the fully working solution including language
• The robbers will try to find any other language where an anagram of your source code will also add two integers
• The language has to be a different one then yours
• Different versions of the same language don't count as different languages
• After 5 days you're code is safe and can't be cracked any more

### Winning criteria:

• The shortest safe program (in bytes) wins.

• The cops wrote an addition program you want to steal
• Since the cops encrypted it so you can't use the same language as the cop you stole the program from used, so you have to use an different language
• Different versions of the same language are count as the same language
• You may use the cops character set in any order (anagram)

### Winning criteria:

• The robber with the most cracked answers wins.
• Does it need to be a "proper" anagram or can I crack an answer by finding a language in which the solution is a polyglot? – Martin Ender Apr 4 '17 at 14:24
• "After 5 days you're code is safe and can't be cracked any more." We usually require the cops to reveal their solution (after the period has passed) before they are considered safe. – Martin Ender Apr 4 '17 at 14:25
• How does it work with languages using different encodings? Is it the actual characters that should be used for the anagram or the byte-values? – Emigna Apr 4 '17 at 14:26
• Related. (Same idea, different task) – ETHproductions Apr 4 '17 at 14:27

# Comment polyglot

From an original idea by Digital Trauma

### The challenge

This challenge requires you to write a polyglot which contains a comment in as many languages as possible.

The comment must say This is a polyglot comment.

The program must do nothing at all.

The winner is whoever writes the polyglot with most languages!

### The rules

Your submission should consist of a full program whose source contains the text "This is a polyglot comment".

For each language of the polyglot, your code executed in that language should:

• Take no input
• Generate no errors.
• Produce either no output or the same output produced by the empty program in this language.
• Still comply to the previous rules if any part of This is a polyglot comment is removed.

Addictionally, there can be no superflous code. This means that it should not be possible to remove a subset of characters (outside of the comment) and still have a submission that complies to the previous rules for all the languages of the polyglot.

Ok? Ok. Now please wait a minute before running to see how many languages you can find that use # for comments, because we have one more rule:

We define a character of your source as required for a language if removing that character makes the program change its behavior for that language (this could mean for example changing its output or producing an error). The sets of required characters for each language must all be distinct.

### Example submission

#This is a polyglot comment


A polyglot in Python and Brainfuck for a score of 2.

The set of required characters for Brainfuck is empty. This is perfectly valid, as long as no other set is empty.

The set of required characters for Python is composed of just the first #. We can't add Bash to this submission because it would share the same set.

That's all, good luck and have fun!

Sandbox question:

• Do you see any potential loopholes in the rules?
• Should I add some other factors to the score (like code length for example) or is the number of languages enough?
• Anything else I've missed?
• I'm unsure about the definition of required. If I write ///This is a polyglot comment in a language which uses // for comments, is / a required character? If I remove one / nothing changes, but if I remove two then I get an error. Similarly, if my language has both # and // as comments, what is the required set for #///This is a polyglot comment ? – Peter Taylor Apr 5 '17 at 10:53
• a character has to be required for at least one language I think it says – Destructible Lemon Apr 7 '17 at 3:12
• @PeterTaylor you're right, this definition doesn't work. I'm having a hard time to come up with a correct one, I'll update this proposal if something suitable comes to my mind. – Leo Apr 8 '17 at 12:52

# Operation Permutations code-golfdecision-problem

We're likely all familiar with the order of operations; the precedence rules that we use to govern basic arithmatic. Most schoolchildren are taught this order using an acronym such as "BODMAS", "BIDMAS", or "PEMDAS". There's no common consensus on the 'right' acronym to use, with the one that you learnt depending on the country you went to school in, or even the teacher who taught you. Your challenge is to determine the validity of an order of operations acronym (O3A), even if it's so unpronounceable that no-one would ever actually use it.

## Challenge Specification

Input

Input for this program is guaranteed to be exactly six characters. Your program can require upper-case, require lower-case, or be case agnostic. You may accept this input in any manner that you please.

Each character is guaranteed to be one of the following: (B, P, I, O, E, D, M, A, S). Furthermore, each character is guaranteed to appear at most only once in the input.

The following characters correspond to the following operations:

| Characters | Operation      |
| ---------- | -------------- |
| (B, P)     | Brackets       |
| (I, O, E)  | Exponentiation |
| D          | Division       |
| M          | Multiplication |
| S          | Subtraction    |


Output

Your program must yield a truthy value for a valid O3A, and a falsy value for an invalid one. Your program is not expected to handle input not matching the above specification.

O3A Validity

The first character in a valid O3A must correspond to 'Brackets'. Likewise, the second character in a valid O3A must correspond to 'Exponentiation'. The next two characters must correspond to 'Division' and 'Multiplication', but either order is valid as these operations are on the same precedence level. The final two characters must correspond to 'Addition' and 'Subtraction', but again, either order is valid. Any other O3As are invalid.

## Testing

Reference Implementation

The following Python 3 reference implementation is given for guidance. Note that while this reference implementation is case-agnostic, your program does not need to be.

def validate(acronym):
acronym = acronym.upper()

if acronym[0] not in {"B", "P"}:
return False

if acronym[1] not in {"I", "O", "E"}:
return False

if set(acronym[2:4]) != {"D", "M"}:
return False

if set(acronym[4:6]) != {"A", "S"}:
return False

return True


Test Input

BIDMAS => True
PEMDAS => True
PIDMSA => True
BOMDAS => True
BMIDAS => False
IBMDAS => False
BODAMS => False


## Rules

• This is , so the shortest code wins counted in bytes.
• Standard rules and loopholes apply
• Check meta for consensus

## Sandbox Notes

My worry with this challenge is that it would be so trivially regex-able in something like Retina that it wouldn't be fun. I'd like feedback from others about this before going live.

• So: test whether an input which is known to match [BPIOEDMAS]{6} also matches [BP][IOE](DM|MD)(AS|SA)? It's possible that there's a hash function which would be shorter than an actual check, but... If you're worried about boring answers then I suggest trying to find a solution which beats the boring regex in a language you know before posting. – Peter Taylor Apr 5 '17 at 11:53
• @fəˈnɛtɪk I just checked, and no, it doesn't fail. – FourOhFour Apr 5 '17 at 12:09
• @PeterTaylor I do believe that a shorter solution than a naive regex exists, but I also don't think I'm good enough at golfing to find it. Hence I posted on sandbox in the hope that more experienced golfers would be able to better judge the golf-ability of the challenge. – FourOhFour Apr 5 '17 at 12:10
• @PeterTaylor You can actually shorten it slightly to ...[AS]+ since the input characters are also guaranteed to be unique (making it even harder to beat the regex solution). – Martin Ender Apr 5 '17 at 12:16
• @MartinEnder, in fact that becomes [BP][IOE][MD]+[AS]+ applying the same reasoning. – Peter Taylor Apr 5 '17 at 14:58
• @PeterTaylor Oh right, good catch. – Martin Ender Apr 5 '17 at 15:00
• I've found a trick which lets me golf 3 chars off the regex-inspired solution in CJam (which doesn't have regexes). Perl will still beat it, but there's some non-trivial interest to the question. – Peter Taylor Apr 5 '17 at 15:19
• @PeterTaylor I was hoping that it would still be an interesting challenge for CJam golfers etc... I might put it up live tomorrow on the basis that it's not completely trivial (so long as it's seen as an per-language challenge). – FourOhFour Apr 6 '17 at 0:08