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]

Find the smallest number bigger than the input whose digital sum is the input

"Digital sum" refers to the sum of all the digits in a number.

For example, the digital sum of 1324 is 10, because 1+3+2+4 = 10.

The challenge is to write a program/function to calculate the smallest number bigger than the input whose digital sum is the input.

Example with walkthrough

As an example, take the number 9 as the input:

9 = 1+8 -> 18
9 = 2+7 -> 27
9 = 3+6 -> 36
...
9 = 8+1 -> 81
9 = 9+0 -> 90


The valid output would be the smallest number above, which is 18.

Specs

Note that 9 is not the valid output for this example, because the reversed number must be greater than the original number.

Note that the input will be positive.

Test-Cases:

 2 => 11
8 => 17
12 => 39
16 => 79
24 => 699
32 => 5999


References:

This is OEIS A161561.

• As far as I know it's either 2 or there is none – user31373 May 23 '16 at 14:14
• I see what you mean, let me specify this a little better – user31373 May 23 '16 at 14:17
• I edited the question to include the additional rule and changed the term digital root with digital sum – user31373 May 23 '16 at 14:38
• Do you mean I should remove the mentioned part? – user31373 May 23 '16 at 14:44
• Could I edit the question for you? You can rollback the edit afterwards if you don't like it. – Leaky Nun May 23 '16 at 14:47
• You are welcome to. This is my first Challenge I post here – user31373 May 23 '16 at 14:49
• Done. How's it now? – Leaky Nun May 23 '16 at 15:01
• Also, you are welcome to join our chat. – Leaky Nun May 23 '16 at 15:01
• Yes thats exactly what I meant. thank you – user31373 May 23 '16 at 15:04
• "because the reversed number must be greater than the original number." I don't know what you mean by this. Do you mean the output number must be greater than the input number? – AdmBorkBork May 23 '16 at 16:39
• Yes it has to be greater. If you look at the examples you can see it: input 9 and output has to be a number which has at least two numbers which have 9 as its sum. – user31373 May 23 '16 at 16:47
• Can I post this abandoned proposal? – programmer5000 Jun 9 '17 at 13:03

Light the Way!

This is based on the Lights Out game. There is a grid of tiles, and clicking on a tile (performing a "move") toggles the state of the clicked tile as well as the (orthogonally) adjacent tiles. This variation will also toggle the diagonally adjacent tiles.

It is helpful to note that (on a board with only two states) all moves commute, so the order in which they are performed is not important. It follows that performing a collection of moves a second time will undo what was done the first time.

There are a few ways to present this challenge, so I'll describe some possibilities. Let me know what you think. The challenge could be one of the below:

• Given a board size n (optional) and the initial state of the n-by-n board, determine an optimal collection of moves that will toggle every lit ("on") tile into its dark ("off") state.
• Given n and a sequence of moves performed on an initially dark board of size n, provide the resulting matrix of states.
• A variation on the above involving graphical output.

Input format would be flexible. n >= 1.

Snippet to show how the game works:

The board size may be adjusted in the first input field. The second field (functionality added by Conor O'Brien) will take a list of coordinates ([[0,0],[1,2],[3,0],...]) and perform the moves for you.

var table;
var color1 = "aqua",
color2 = "yellow";
var moveList = [];

table = document.getElementById("lightGame");
buildTable();

var updateButton = document.getElementById("updateButton");
if (updateButton) {
updateButton.onclick = buildTable;
}

var toPerf = JSON.parse(document.getElementById("moves").value);
//console.log(toPerf);
function rec(arr) {
var m = arr.shift();
var x = m[0],
y = m[1];
var cell = table.rows[y].cells[x];
update(cell);
if (arr.length) {
setTimeout(rec, 500, arr);
}
}
rec(toPerf);
});
};

function buildTable() {
// get size
var input = document.getElementById("size");
var size = new Number(input && input.value || 5);

var rows = size,
cols = size;

// clear moves
moveList = [];
moveHolder.innerHTML = "[]";

// remove existing rows
while (table.lastChild) {
table.removeChild(table.lastChild);
}

// create new rows
for (var y = 0; y < rows; y++) {
var row = document.createElement("tr");

for (var x = 0; x < cols; x++) {
var cell = document.createElement("td");
cell.style.backgroundColor = color1;
cell.x = x;
cell.y = y;
cell.onclick = function () {
update(this);
};
row.appendChild(cell);
}
table.appendChild(row);
}
}

function update(cell) {
var x = cell.x;
var y = cell.y;

var xMax = table.rows[0].cells.length;
var yMax = table.rows.length;

// update cell
changeColor(cell);

if (x > 0) changeColor(table.rows[y].cells[x - 1]);
if (x + 1 < xMax) changeColor(table.rows[y].cells[x + 1]);
if (y > 0) changeColor(table.rows[y - 1].cells[x]);
if (y + 1 < yMax) changeColor(table.rows[y + 1].cells[x]);

if (x > 0 && y > 0) changeColor(table.rows[y - 1].cells[x - 1]);
if (x > 0 && y + 1 < yMax) changeColor(table.rows[y + 1].cells[x - 1]);
if (x + 1 < xMax && y > 0) changeColor(table.rows[y - 1].cells[x + 1]);
if (x + 1 < xMax && y + 1 < yMax) changeColor(table.rows[y + 1].cells[x + 1]);

// update moves
moveList.push([x, y]);
moveHolder.innerHTML = JSON.stringify(moveList);
}

function changeColor(cell) {
cell.style.backgroundColor = cell.style.backgroundColor === color1 ? color2 : color1;
}

function getStyle(elt, styleProp) {
if (elt.currentStyle)
return elt.currentStyle[styleProp];
return document.defaultView.getComputedStyle(elt, null)[styleProp];
}
body {
background-color: darkslategray;
color: white;
}
#gameDiv {
text-align: center;
}
margin: 25px;
}
h2, h4 {
color: red;
}

#lightGame {
border: 1px solid white;
margin: auto;
}
#lightGame td {
/*background-color: aqua;*/
height: 25px;
width: 25px;
}
#updateDiv {
margin: 25px;
}
button {
margin-left: 10px;
}

#autoMoveDiv {
margin-top: 10px;
}

footer {
position: fixed;
bottom: 0px;
width: 100%;
}
footer small {
color: cyan;
position: absolute;
bottom: 0px;
}
img {
float: right;
}
<div id="gameDiv">
<h2>Light Game</h2>
<div>
<table id="lightGame">
</table>
</div>
<div id="updateDiv">
<input id="size" name="size" type="number" min="1" max="20" pattern="\d{1,2}" value="5" required />
<button id="updateButton" type="button">Update</button>
</div>
<div>
</div>
<div id="autoMoveDiv">
Auto move:
<input id="moves" />
<button id="perform" type="button">Do Moves</button>
</div>
</div>

Related Questions

JsFiddle of the snippet I made.

• Option 1 would be a duplicate IMO. I do like option 2, though. – Nathan Merrill May 24 '16 at 17:36
• I agree with Nathan Merrill. – El'endia Starman May 24 '16 at 17:37
• @NathanMerrill This does include diagonals too, so it's different. But I don't know how different that'd be programmatically. – mbomb007 May 24 '16 at 17:40
• Does the board wrap? – trichoplax May 24 '16 at 17:43
• Option two sounds like it's pretty much a duplicate of this one, though. Except for the initial board state and diagonals, that is. – Geobits May 24 '16 at 17:44
• Does it need further variation? Hexagonal board? 3d? Broader effect? Random effect? Context dependent effect? – trichoplax May 24 '16 at 17:48
• I'd definitely make diagonals bold. I completely missed that when reading. I think diagonals make either 1 or 2 unique. – Nathan Merrill May 24 '16 at 17:50
• @trichoplax The board does not wrap. – mbomb007 May 24 '16 at 20:01
• "Given a board size n (optional) and the initial state of the n-by-n board, determine an optimal collection of moves that will toggle every lit ('on') tile into its dark ('off') state." Or you can have "determine an optimal collection of moves that will toggle every lit tile into its dark state and vice versa". – msh210 Jun 15 '16 at 22:53
• @msh210 If the goal is to toggle every tile, the solution is trivial. If the goal is merely to end with all light, then with all dark, getting from one to the other is also trivial (it's the set of all moves minus the set from the first answer). – mbomb007 Jun 16 '16 at 13:25

Version Comparator

Given two version strings, return a positive, negative or zero value depending on which one is earlier. Version strings consist of one or more non-negative integers separated by full stops, optionally suffixed by a lowercase letter and a final non-negative integer. Examples of versions:

1.5a2
1.5b1
1.5
2.19
2.20b
2.20 or 2.20.0 (these should compare equal)
8.1a
8.1
9
10


When comparing versions the integers should of course be compared numerically, not lexically. Missing components should compare as zero against numbers, but they compare after letters. You should then be able to recognise that the above versions are in version order, but you can choose whether this should be a positive or negative result. Reversing the parameters should obviously negate the sign of the result, but you can return a different absolute value if you prefer.

Builtins that compare versions are disallowed, but things like regexes are OK.

This is , so the shortest program or function wins.

• How do letters compare numerically? – Leaky Nun Jun 2 '16 at 12:40
• It should never be necessary. – Neil Jun 2 '16 at 13:10
• Test-cases please. Especially 1a1 vs 1a vs 1. – Leaky Nun Jun 2 '16 at 13:52
• @LeakyNun Added some more examples. 1a should compare as if it was 1a0 so less than 1a1 which is less than 1. – Neil Jun 2 '16 at 15:49
• How do 1a and 1b compare? – Leaky Nun Jun 2 '16 at 15:56
• @LeakyNun Well, you already know that 1.5a2 compares before 1.5b1... – Neil Jun 2 '16 at 16:16

Find the duration of a worst-case brute-force attack

Given the following information about a 7-bit ASCII-encoded password and the computer that will crack it with a brute-force attack:

• Length of the password in characters
• Charset size (i.e total count of the possible characters one character in the password can be)
• Number of passwords the computer can test in one second millisecond (rounded down)

Write the shortest program that finds out how long the attack will take in the worst-case scenario where the computer tries all possible passwords.

• The output is the duration in this format: years months days hours minutes seconds milliseconds
• One "month" is 30 days long.
• Fractions of milliseconds are rounded up.
• You can assume that the cracking finishes immediately if it takes less than 50 milliseconds, and make the program print out Instant in such cases.
• Similarly, the cracking can be considered Neverending if it takes more than 292 billion years.
• The program can output using any method, from merely printing to STDOUT to causing a kernel panic/bluescreen with the duration as the error message.
• The input method to get the info about the password/the machine can be anything, as well. Don't use standard loopholes though.
• It's not enforced, but strongly encouraged to write a standalone program.

Here's how to calculate the charset size:

• If there's a lowercase letter, add 26.
• If there's an uppercase letter, add another 26.
• If there's punctuation, add 32 (7-bit ASCII has this many punctuation characters).
• If there's a whitespace character, add 2. Whitespace characters are horizontal tab (0x09) and space (0x20).
• Any other character counts as non-printable (including backspace (0x08), DEL (0x7F), line feed (0x0A) and carriage return (0x0D)). Add 29 if there's any of them.

Here are some applicable-in-real-life cases you can test your program with (let's assume the computer that will crack them can test 1 billion passwords per second, which equals to 1,000,000 passwords/millisecond):

• 4 characters, charset size 10 (PIN) - 10,000 passwords, output is 0 0 0 0 0 0 1 or Instant
• 8 characters, charset size 94 (at least one uppercase letter, one lowercase letter, one digit and one punctuation) - 6,095,689,385,410,816 passwords, output is 0 2 10 13 14 49 386
• 10 characters, charset size 2 (weakest valid Discourse password, contains whitespace only) - 1024 passwords, output is 0 0 0 0 0 0 1 or Instant
• 25 characters, charset size 26 (correcthorsebatterystaple) - 236,773,830,007,967,588,876,795,164,938,469,376 passwords, output is 7612327353651221350 2 14 0 26 4 939 or Neverending
• 127 characters, charset size 96 (strongest password on newer Windows releases) - written below
• 1024 characters, charset size 36 (4096-bit PGP key represented as a hexadecimal number) - written below

These are the stats of the maximum-strength Windows password:

Passwords: 560,333,510,486,846,899,384,847,242,571,130,277,659,458,884,466,874,695,582,912,274,460,529,559,443,783,341,570,989,525,270,653,136,186,432,110,439,597,936,820,880,106,519,625,601,191,574,799,863,912,148,304,962,133,852,037,202,160,056,511,510,962,873,278,300,126,526,144,267,006,137,180,032,492,751,016,171,207,701,495,935,943,049,216
Output: 18014837657113133339276210216407223432981574217685014647084370963880194169360318337544673523362047845500003550655797865897637169483847774934889398916928636347805229296463546812516445182705545212838429981490065783731353925307067135133992 5 15 19 58 55 944
Alternate output: Neverending


And these are the stats of the PGP key:

Passwords: 4,505,684,579,918,576,285,346,738,866,335,056,898,110,301,685,668,199,078,230,938,179,212,682,315,156,231,410,185,391,761,603,272,976,014,035,539,665,517,248,679,228,261,440,294,129,198,036,262,705,242,310,399,830,546,082,361,923,420,737,260,766,677,891,361,176,003,624,143,368,380,527,062,643,297,677,246,518,686,688,642,023,537,863,317,793,178,302,508,440,097,154,593,959,832,175,055,427,351,149,410,096,495,695,380,712,810,868,774,475,142,767,054,868,274,802,269,522,299,482,066,464,842,097,715,922,988,138,315,118,067,288,670,934,735,264,524,936,706,249,961,394,413,647,964,221,767,703,673,264,468,419,121,528,644,906,680,808,060,759,817,669,970,046,776,525,266,199,099,671,937,918,801,013,826,958,891,378,841,908,663,991,372,649,027,188,879,525,186,690,599,345,723,173,064,252,017,258,129,131,786,488,462,307,158,861,824,049,980,863,991,149,295,162,169,512,952,373,415,599,734,988,691,348,925,488,351,712,593,858,837,027,205,238,618,188,975,201,320,681,214,515,875,812,195,250,605,867,622,987,451,763,883,339,709,733,502,125,838,221,788,546,339,051,347,360,900,518,381,976,167,289,930,943,228,024,924,785,158,428,496,314,937,921,503,359,298,542,415,845,218,449,360,806,235,379,253,546,728,753,218,950,843,742,471,105,739,555,344,908,900,309,982,913,223,331,321,839,212,821,903,239,320,600,564,890,951,140,667,647,680,682,245,252,370,183,758,578,065,733,075,207,856,432,661,797,090,351,101,165,469,273,829,754,476,555,209,675,613,232,875,323,406,611,257,057,059,099,019,633,298,079,410,970,345,108,939,943,042,100,267,260,413,671,556,828,411,902,575,269,208,445,279,433,655,878,082,023,068,697,154,581,711,817,787,688,949,105,583,339,471,599,190,831,084,304,744,483,799,555,478,063,729,574,297,623,870,804,763,558,027,580,772,927,971,329,879,231,979,556,301,616,929,595,576,646,883,067,201,999,872,899,862,889,211,861,332,535,050,455,387,251,034,043,732,447,006,164,551,883,918,733,705,027,099,846,583,024,013,092,062,384,703,436,459,115,108,358,829,136,251,317,699,709,899,140,949,893,425,335,769,021,022,912,434,045,643,544,474,460,899,799,213,759,568,795,794,758,914,390,056,283,305,470,380,859,003,818,724,678,434,816
Output: 144858686339974803412639495445442930108998896787172038266169565946909796654971431654622934722327449074525319562291578211137739886840732034401886018044055761311424449664413690224320369299057721231224396352345948448015131278860508182828147139982752631922511354755096078964028889980704480936709984283352948061204198196785328857204061945957268141550998891534834171375541476907019128991072373909056348731183618329634024763694746476776233417623704464804027405450152026906721990999895827471385353870130056140660354679074035526421905828555132520211676677361401337091034117370453939870215183392876069255694823382473711006907851853458746913295694931911314073828877816349504523255816791677974298928074750103049081088894521647398444396729546431174466495229648516324713327536964168664025148591452750098101445502202880078966283755495859954505040675103796820824907455740718188735077328268047865426806174561044520100917915500979652319301547868727504821981520811835192875926630119576922600465887060849654310721522802609638109522185755307201898676461606130734024600227278608209698963323356340446015796148617903068964091403666193996894642822309315198786075754477250953946657292049336910661279747924178751224344877465829301109562043071275369906871767991229129085786546569052197642684662087651029574035646976531236521763373563846425925268656816387911380422031991615290633773786744123323731112880994579065426763237282889858685438654794679302568796507941872848896038602862540480809810919146613018187362072374644736799940064590439265446053422181856817801562474722208358918298576208528044087753034364036 10 24 22 32 4 679
Alternate output: Neverending

• Is there any wrong information? – dorukayhan Jun 4 '16 at 20:43
• Please provide proper test cases, i.e. with all input parameters (speed of computer is missing) and solutions, so that we can verify our programs. – nimi Jun 4 '16 at 22:36
• Unless there's a good reason you should should go with our defaults and allow functions and programs . Don't allow loopholes. – nimi Jun 4 '16 at 22:42
• IMO this challenge would be better if it allowed simply returning/outputting an integer number of milliseconds. As it is, the mixed-base conversion will be trivial for languages that have a builtin for it, and nearly as long as the code to compute the length of time (if not longer) for languages that don't. – user45941 Jun 6 '16 at 8:51
• You can see how many people agree with Mego's suggestion in the discussion on meta. – trichoplax Jun 6 '16 at 13:40
• In response to "It's not enforced, but strongly encouraged to write a standalone program.": Elsewhere in the same discussion it recommends avoiding saying "ideally your code will.... That will just be ignored anyway (otherwise the code won't be competitive). Make a definite decision one way or the other rather than a recommendation. – trichoplax Jun 6 '16 at 13:46

Maximal root multiplicity of integer polynomials

Given a non constant polynomial with integer coefficients, determine the maximal multiplicity of it's (perhaps complex) roots.

Definitions

Multiplicity: Let p be a polynomial with complex coefficients and x0 some complex number. If x0 is a root, it is said to have multiplicity n if p(x) = a(x) * (x-x0)^n where a is another (complex) polynomial such that (x-x0) does not divide a. If x0 is not a root it is defined to have multiplicity 0. Note that the polynomials we consider do only have integral coefficients (consider the integers as a subset of the complex numbers).

Maximal Multiplicity: Let x0,...,xk be the roots of of p,then the maximal multiplicity of p is defined as the maximal multiplicity of xi for i=0,...,k.

I/O

For the input and output, the polynomials can be written in any convenient format, e.g. also as a (variable length) list of coefficients.

Hints

A polynomial has a root of multiplicity greater than one if and only if it shares a root with it's derivative. This can e.g. be checked with the discriminant.

Examples

polynomial     maximal multiplicity
1              0
x^7-1          1
x^8-x^7-x-1    2
x^3-3x^2+3x-1  3

• What sorts of builtins are allowed/banned? Root finding? Polynomial GCD? – Sp3000 Jun 7 '16 at 9:19
• I did not plan to ban anything, would you suggest banning these? – flawr Jun 7 '16 at 9:22
• Not really, it's fine if nothing's banned. Just making sure it was considered :) – Sp3000 Jun 7 '16 at 9:47
• Do you have any test cases for roots which repeat in different irreducible factors and thus demonstrate that it can't be done by counting multiplicity of irreducible factors? – Peter Taylor Jun 7 '16 at 10:49
• Answering my own question: it can be done by counting multiplicity of irreducible factors, because the minimal polynomial of an algebraic number is a factor of any polynomial of which that number is a root. So factor to irreducibles is worth mentioning as related, although it's far more than needed. – Peter Taylor Jun 7 '16 at 14:01
• I considered factoring as the obvious approach but I think most languages do not have the means to calculate with exact complex numbers (except some CAS' like Mathematica), so the method via resultants/discriminants should just provide another way, which surprisingly only needs integer arithmetic. – flawr Jun 7 '16 at 14:31
• The line on maximal multiplicity ends rather abruptly, I'd assume that that was an accident? Anyway, I'm not sure the terminology "does not divide" is correct here. It's been a while for me, but I think you should say something like: "does not divide a(x) such that the quotient is a polynomial"? – FryAmTheEggman Jun 7 '16 at 14:40
• Right, I think I wanted to add something regarding the constant polynomials, but now I excluded those too for the sake of simplicity. Statements about divisibility usually only make sense in the context of rings, and is defined as: A divides B if there is a C such that B = AC. As soon as you consider a field (in your example the field of rational functions) the divisibility becomes trivial, as any nonzero element divides every element of the field. – flawr Jun 7 '16 at 14:59
• The method via factoring only requires integer arithmetic. I don't find it at all surprising that an approach with resultants only needs integer arithmetic, because subresultants are the standard efficient way to do polynomial GCD. – Peter Taylor Jun 7 '16 at 16:12
• @PeterTaylor I agree, the "surprisingness" is subjective, as far as I know the resultants are usually defined via the product of the differences of the zeros. From that perspective it isn't really obvious that this might result in something even real=) Regarding the factoring we probably did not have the same thing in mind or I do not understand what you mean. I thought about factoring into linear factors, which generally results in general algebraic numbers, far from integers. What did you have in mind? – flawr Jun 7 '16 at 16:38
• Factoring to polynomials which are irreducible over the integers, as in the linked question. Equivalently, as I realised between my first and second comment, factoring to the minimal polynomials of the roots. Edit: ah, but wait. Can the minimal polynomial contain the root multiple times? – Peter Taylor Jun 7 '16 at 19:10
• I'm not sure in general, I think this might fail for some fields with finite characteristic, but for algebraic numbers (=elements of finite field extensions of the rational numbers) the minimal polynomials have distinct roots in the corresponding splitting field. – flawr Jun 7 '16 at 20:11

Array of Integers to Array of Digits

Given an array of arbitrary length containing only integers, output an array of integers of each digit of each integer in the array.

Notes

• The input array will only consist of integers in base 10

• The integers will be in the range of [0, MAX_INT] where MAX_INT is the greatest value an integer can have in your language

• Assume that all integers will be positive, however you can interpret the integers as signed or unsigned

• String manipulation and the use of any regex is banned by default

• The outputted array must be exactly 1 deep and contain only integers

• The order of the digits in the outputted array must be exactly as they were in the inputted array

• Leading zeros are to be stripped, as they should be when parsed as an integer

Examples

[2, 3, 5, 7, 11, 13] -> [2, 3, 5, 7, 1, 1, 1, 3]
[1, 2, 3, 4, 5] -> [1, 2, 3, 4, 5]
[123, 456, 789, 101112] -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 0, 1, 1, 1, 2]
[0, 000, 000123] -> [0, 0, 1, 2, 3] //'000' is treated as '0' and '000123' is treated as '123'

• Seems pretty straightforward, but pretty trivial in most languages. (Trivial does not mean off topic, but you will likely get lots of answers, as well as some downvotes). You should specify that the integers are in base 10. – Nathan Merrill May 25 '16 at 14:19
• Will the input array contain 0 or negative integers? – Leaky Nun May 25 '16 at 19:30
• You say integers, but I take it you mean positive integers? – xnor May 25 '16 at 22:19
• I updated the specification – MrPublic May 26 '16 at 12:22
• You should clarify that leading zeros are stripped, so that people don't need to infer that from the last test case. – AdmBorkBork May 26 '16 at 18:51
• What leading zeroes? Numbers can't have them if they are not strings. Is it an array of numbers or array of strings? – Qwertiy May 29 '16 at 23:12
• It may be interesting to ban the use of string manipulation. This would change the challenge a lot, but it will force the answers to be less trivial. (also note that such a challenge may be frowned upon: meta.codegolf.stackexchange.com/a/8079/31203) – MegaTom Jun 1 '16 at 15:19
• You mention signed integers, but none of your examples contain negative numbers. Do we only need to support non-negative numbers? If not you should specify how negative numbers should be handled and add an example to the test cases. – Martin Ender Jun 3 '16 at 11:33
• Personally, I doubt that string manipulation is the easiest way to do this in most languages? I don't think banning it improves the question. It just seems to make a bunch of languages unusuable, and the rest just entirely ignore it? – FryAmTheEggman Jun 9 '16 at 20:08

Ping Pong

The Challenge

This challenge is to make a program that prints a text ping-pong animation. Your program is to display a string of tildes with a PING on it moving to the right. Each tick, the text PING moves one to the right one character, reducing the number of tildes on the right by one and increasing the amount on the left by one. Once the PING reaches the right side of the string, it changes to a PONG and the reverse happens (i.e it moves to the left instead).

Rules

• The number of tildes must always be the same
• The number of tildes must be at least 30
• The number of milliseconds between ticks must be at least 10 ms and at most 1 s
• The PING must start at the left hand of the string

Scoring

Your score is the number of bytes plus/minus the following (all that apply):

• -10 bytes for browser implementation using the ping after the hash
• +10 bytes if your implementation does not clear previously outputted frames
• More suggestions welcome

Lowest score wins.

Example Implementation (JS, Ungolfed)

i=0;b=false;len=50;td=40;function urlPong(){location.hash=new Array(i+1).join("~")+(!b?"PING":"PONG")+new Array(len-4-i+1).join("~");if(!b){if(len-4-i<=0){b=true;}else{i++;}}else{if(i<=0){b=false;}else{i--;};}setTimeout(urlPong,td);}urlPong();

• Why do you restrict this to be in a browser? That seems to add an unnecessary limitation on which languages can reasonably participate. – FryAmTheEggman Jun 9 '16 at 13:06
• Okay, I made it less browser dependant – takra Jun 10 '16 at 0:57

Implement this cipher

(I'm not sure what to call this cipher)

Goal

Use the algorithm (explained in the Algorithm section) to implement a certain cipher.

The program must read input from STDIN or the closest available equivalent, use the algorithm to generate the ciphertext and a key.

The ciphertext and the key will be written to STDOUT or the closest available equivalent, preferably with the format (ciphertext)\n(key).

Algorithm

Convert the characters in the string into the respective ASCII values. For example:

Hello -> 72 101 108 108 111

Next, you will need to generate a key as long as the string with random numbers in the range of 0-9.

Hello -> 62841

Add the integers in the random number sequence to the ASCII values of the string. In the above examples, 72 would become 78, and 101 would become 104.

72 + 6 = 78, 101 + 2 = 104, 108 + 8 = 116, etc

Next, convert the new ASCII values back to characters. In the above examples, the text Hello has become Nhttp.

Examples

(These are simply examples of what the output might look like. The output can and will vary.)

Hello, World!

Hgqqu/$\\p{ni$
0255634519253


This will be encoded

Zhjs$~koo gj$iuhofgj
60104723305544750226


Rules

• Submissions must be full programs.
• Languages newer than the challenge are allowed.
• Submissions will be scored in bytes.
• Standard loopholes are forbidden.
• This is code-golf, so the shortest code wins.

I'm sure this challenge needs a little tidying up and making it look and sound a bit nicer. I'm not very good at writing challenges, so I'd like some advice.

• This is an actual cipher (though not usually with ASCII codes). I don't remember the name right now. But seeing that, it might be a dupe. – Rɪᴋᴇʀ Jun 12 '16 at 15:13
• @EᴀsᴛᴇʀʟʏIʀᴋ Oh, I didn't know that. I thought it was original. – m654 Jun 12 '16 at 15:32
• Yeah, it's called something like a key cipher. – Rɪᴋᴇʀ Jun 12 '16 at 15:34
• @EᴀsᴛᴇʀʟʏIʀᴋ What do you think of this challenge? Do you have any advice for making it... better? – m654 Jun 12 '16 at 16:16
• If properly implemented (i.e. with a pre-shared key which covers the full range of symbols rather than just 0-9) this would be a one-time pad, which is (in some sense) the limit case of the Vigenère cipher. It's not quite a dupe of the Caesar cipher question, but it's barely more complicated. – Peter Taylor Jun 12 '16 at 21:57
• @PeterTaylor The Caesar cipher shifts the characters up the alphabet, but this one shifts the up the whole character range. – m654 Jun 13 '16 at 7:49
• How does this handle overflow? It's easy to imagine a scenario where z (122) gets a number >=5 added to it. – AdmBorkBork Jun 14 '16 at 15:03
• @TimmyD I hadn't thought about that... Maybe it could display an \x code? That's what my Python implementation does, but I'm not sure if that will work in some other languages. – m654 Jun 14 '16 at 15:07

Latin vs Greek vs Cyrillic / Battle of the Alphabets

Meta: This is just a rough draft, the challenge is still under development, feel free to add suggestions as comments or via chat pinging @flawr

Points that are unclear so far:

• Is there one fixed typeface for all three?
• Will the image always be provided in the exact horizontal orientation?
• How long will the provided text be, just single words? A single line? A multiline piece of text?

These three alphabets are relatively similar and even have some letters in common, but also a lot of distinct letters. In this challenge, you have to write a classifier that can distinguish these three alphabets, when presented with a raster image of a corresponding text.

This is an image from Wikipedia that shows the differences in the capital letters:

This challenge was inspired by this message.

• What about ambiguity? Expected output for POTATO, COMA, or TAXONOMY? – Geobits Jun 15 '16 at 14:03
• Good point, then all outputs are correct. But I had longer pieces of texts in mind, like multiple lines, but now I'm thinking perhaps just single words would be easier. What would you say? – flawr Jun 15 '16 at 15:39
• I'd prefer the input to be a single letter, and the correct output to list all alphabets where it belongs, with score being number of correctly classified letters in a test battery (secondary goal is byte count). That may be vulnerable to hashing tricks though. Maybe the letters could also be randomly scaled to, say, 90% to 110%? – Zgarb Jun 16 '16 at 7:53
• @Zgarb it's still easy to get 100% with computer vision classifiers if there is only one nicely cropped letter as input and all test images have the same exact font as the one used in training – Fatalize Jun 17 '16 at 8:09
• I agree, thats why I'd use at least full words or lines. – flawr Jun 17 '16 at 8:36

Don't let those functions get away

Introduction

My imaginary language, PremOpt discourages the use of functions. They are the source of every performance problem. Your task today is to fix beginner PremOpt programmer's code.

Every statement's and loop's (if, switch, while, for) content is enclosed in brackets:

<if/switch/while/for> <statement here> {
<stuff>
}


Switch cases are one liners:

switch <value> {
case <val1>: <statement1>;
case <val2>: <statement2>;
case <val2>: <statement2>;
}


Functions look like these:

function <name>(arg1, arg2, arg3) {
// Stuff here
}

// Calling a function:
<name>(arg1, arg2, arg3);


Other lines end with a semi-colon.

Variables don't need to be declared, they're already initialized to null, you can set a variable to a value with

variableName = value;


Outputting a value is done by doing

out-><value>


Input

Your input is a string with a piece of code. Each row is separated with a line-feed. The input may or may not contain functions.

Output

You need to remove the functions from the code, and put their content to the where they were called.

Examples:

function hello() {
sayHello1();
sayHello2();
}
hello();


becomes

sayHello1();
sayHello2();


Multiple function calls:

function func() {
doStuff1();
doStuff2();
}
func();
func();


becomes

doStuff1();
doStuff2();
doStuff1();
doStuff2();


If the function takes in arguments:

function argFunc(arg1, arg2) {
doStuffWithArg(arg1);
doStuffWithArg2(arg2);
}
argFunc(myVar1, myVar2);
argFunc(myVar3, myVar4);


then you need to change the arguments inside the function to match with the calling arguments

doStuffWithArg(myVar1);
doStuffWithArg2(myVar2);
doStuffWithArg(myVar3);
doStuffWithArg2(myVar4);


Test cases

fibonacci sequence:

a = 1;
b = 1;
function getNextNumber(num1, num2) {
return num1 + num2;
}

while(true) {
a = getNextNumber(a, b);
out->a;
b = getNextNumber(a, b);
out->b;
}


Should become

a = 1;
b = 1;

while(true) {
a = a + b;
out->a;
b = a + b;
out->b;
}


FizzBuzz:

for (counter = 0; counter <= 100; counter++) {
checkNumber(counter);
}

function checkNumber(num) {
if (num % 3 == 0  num % 5 == 0) {
out->"Fizz Buzz";
} else if (num % 3 == 0) {
out->"Fizz"
} else if (num % 5 == 0) {
out->"Buzz"
} else {
out->num;
}
out->newLine;
}


Becomes:

for (counter = 0; counter <= 100; counter++) {
if (counter % 3 == 0  counter % 5 == 0) {
out->"Fizz Buzz";
} else if (counter % 3 == 0) {
out->"Fizz"
} else if (counter % 5 == 0) {
out->"Buzz"
} else {
out->counter;
}
out->newLine;
}


Rules

• There'll be no recursive functions in the input
• Standard loopholes are forbidden
• This grammar doesn't seem to be well defined enough for this to not be too broad. What about functions in functions? What kinds of literals are expected to be supported? Can functions have the same name but different arguments? What operators have to be supported (specifically w.r.t. functions, like myFun(++foo)++)? What about functions that return things but have more than one operations, but are in a heavily nested statement? This is all just from the top of my head, there are likely more such problems. I think you would need to heavily simplify the language for this to be a good question. – FryAmTheEggman Jun 28 '16 at 12:58

fix show

Your task is given n, you must print first n character returned from Haskell expression fix show.

Let me explain how fix show produces the "magic" string.

show is just escaping the string and then add quote. Since the resulting string consists only double quotes and backslash, show then essentially just put backslash before every character then quote the resulting string.

show str = '"' : concat ( zipWith (\x y->[x,y]) (repeat '\\') str ) ++ "\"" -- Well, this is not what prelude give, but


fix is, well, fixpoint combinator. But thanks for laziness, it won't do a infinite loop first.

The string is equivalent to the string defined below:

Assuming there is a series of string. The first string is "" and the next series is just application of show to previous string:

"" "\"\"" "\"\\"\\"\"" "\"\\"\\\\"\\\\"\\"\"" "\"\\"\\\\"\\\\\\\\"\\\\\\\\"\\\\"\\"\""

For all n, there is k so that for all l above k, n-th character of l-th string from series is same. That character is the n-th character of fix show

TODO: I hate the sentence above, please fix it.

The first 100 character in resulting string

"\"\\\"\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\


So, another implementation is

fixshow = '"' : zip (repeat '\') fixshow ++ "\""


Rules

1. You are not allowed to use function fix, show, and the equivalent functions.

Sandbox question

Is there another way to prevent answer like flip take$fix show, or without importing f k=k$f k;j n=take n$f show. And how about array programming language like APL, J and Jelly? • Your construction doesn't work because zip doesn't intersperse the characters, but creates a list of tuples. I think the backslashes also need escaping. It would be helpful to explain that the number of backslashes in sequence goes 1,3,7,15,... with numbers one less than powers of two. It would be a shame to eliminate all languages with lazy evaluation or generators. It's also vague. Python has generators but they are totally useless here. Even Haskell needs a costly import to get fix. – xnor Jun 1 '16 at 3:52 • The output should start "\"\\\"\\\\\\\"\\\\\\\\\\\\\\\". – xnor Jun 1 '16 at 3:58 • Language-specific questions are not likely to make much challenge acceptors. – Erik the Outgolfer Jun 3 '16 at 7:25 • @EʀɪᴋᴛʜᴇGᴏʟғᴇʀ This question isn't language specific, it just involves implementing a particular Haskell program in any other language. That said, it was a bit hard to figure out what was going on as someone who doesn't really know Haskell. – FryAmTheEggman Jun 3 '16 at 13:18 • @FryAmTheEggman This should be closed as "unclear what you're asking". – Erik the Outgolfer Jun 3 '16 at 13:55 • seems like a cool challenge, but instead of trying to explain lazy evaluation, just define show rigorously, and then say the challenge is to output the limit of applying show n times on the empty string. also, your output is wrong. – proud haskeller Jun 3 '16 at 18:46 • @proudhaskeller when you say the limit of applying show n times, do you mean result of applying show infinite times on ""? – Xwtek Jun 4 '16 at 15:21 • @xnor 1. I just hate the answer flip take$fix show. How do I avoid it? 2. Fixed. – Xwtek Jun 4 '16 at 15:24
• @ChristianIrwan no, because there is no such thing, applying infinite times. instead, if you have a series of strings, first the empty string, then applying once, then twice, and so on, and at each string look at the ith character, from some point on it will be identical in all the strings of the series, and the ith character of the limit will be this character. – proud haskeller Jun 4 '16 at 15:29
• @proudhaskeller Oh, I see. Thanks. – Xwtek Jun 4 '16 at 16:04
• The implementation with zipWith. Maybe you could just ban the command show and equivalents? I think implementing it and a a pseudo-fix would be interesting and not definitely better than concatenating powers-of-2-sized blocks. – xnor Jun 5 '16 at 2:54
• *The implementation with zipWith doesn't work. – xnor Jun 5 '16 at 21:58

Golfing with ultrasound

Within medical physics, the percentage of ultrasound reflected between material boundaries can be calculated using two pieces of data: the density(p) and the speed(c) at which sound travels through the material.

To calculated the percentage reflection the following equation can be used

(Z1-Z2)^2 / (Z1+Z2)^2

Where Z1 and Z2 are the acoustic impedances(Z) of the two materials. Z is calculated such that Z=pc That is density * speed of sound in the material

This is where the issue lies

I have two ways of asking the question

1:

Given the acoustic impedance for two materials, calculate the percentage reflection.

2:

Given the density and speed of sound in two materials, calculate the percentage reflection

Reason

The first method will be much simpler, in the way you are just plugging values into a formula. However I feel that method 2 is heavy on the inputs, and I understand that four inputs is a large number of inputs in golfing challenges

On posting the question I will also add a number of test cases

• Firstly, I think you should add test cases while it's still in the sandbox. I find it's easy to miss important ones. In your formula you say Z=pc. What is c? I think you should add some formatting to your formulas, as they are a bit hard to read. You could also consider using some TeX service to generate an image of the formula for you. Also, density is usually denoted by ρ. – FryAmTheEggman Jun 29 '16 at 19:38
• I was going to use rho, but I didn't know where to find one. In hind sight I could have copied and pasted from Wikipedia. Speed should have been given as c not v. But I will make clear what I mean by Z=pc. What is TeX? I've not heard of it before? – george Jun 29 '16 at 19:41
• TeX is a very popular typesetting program, most of your textbooks were probably made using some variant of it. For example, go to this site and enter \frac{(Z_1-Z_2)^2}{(Z_1+Z_2)^2} as the text. You should see a much easier to read version of your formula as an image. – FryAmTheEggman Jun 29 '16 at 19:45
• @FryAmTheEggman Wow that's a really cool website, thanks! I will edit the question soon and hopefully it will be better – george Jun 29 '16 at 19:50
• With either option, it looks like there's a direct mathematical formula that leaves little to golf. – xnor Jun 29 '16 at 22:45

Write a BF to Hexagony Converter!

According to community moderator Martin Ender ♦:

Hexagony is Turing-complete as any brainfuck program can be translated to Hexagony with some effort. (Source)

Your program's job is simple: take a valid brainfuck program, and convert it to an equivalent Hexagony program. For completeness, here are all the relavant commands in both BrainFuck and Hexaongy (taken from esolangs.org).

brainfuck

brainfuck operates on an array of memory cells, also referred to as the tape, each initially set to zero. There is a pointer, initially pointing to the first memory cell. The commands are:

• > Move the pointer to the right
• < Move the pointer to the left
• + Increment the memory cell under the pointer
• - Decrement the memory cell under the pointer
• . Output the character signified by the cell at the pointer
• , Input a character and store it in the cell at the pointer (-1 for EOF)
• [ Jump past the matching ] if the cell under the pointer is less than or equal to 0
• ] Jump back to the matching [ if the cell under the pointer is nonzero

All characters other than ><+-.,[] should be considered comments and ignored.

Modifications:

• Infinite tape in both directions
• Arbitrary precision integers (like hexagony)
• No overflow/underflow
• [ acts the same for negative numbers as it does for 0

Source code

The source code consists of printable ASCII characters and line feeds and is interpreted as a pointy-topped hexagonal grid, where each cell holds a single-character command.

Because of this restriction, the number of commands in the source code will always be a centered hexagonal number. For reference, the first 10 centered hexagonal numbers are:

1, 7, 19, 37, 61, 91, 127, 169, 217, 271

When reading a source file, Hexagony first strips all whitespace characters. Then the remaining source code is padded to the next centered hexagonal number with no-ops and rearranged it into a regular hexagon. This means that the spaces in the examples above were only inserted for cosmetic reasons but don't have to be included in the source code. The following three programs are identical:

   a b c
d e f g
h . . . .
. . . .
. . .

abcdefgh...........

abcdefgh


But note that

abcdefg

would instead be the short form of

   a b
c d e
f g


Control flow

Hexagony has 6 instruction pointers (IPs). They start out in the corners of the source code, pointing along the edge in the clockwise direction. Only one IP is active at any given time, initially the one in the top left corner (moving to the right). There are commands which let you switch to another IP, in which case the current IP will make another move (but not execute the next command), and then the new IP will start by executing its current command before making its first move. Each IP has an index from 0 to 5:

   0 . 1
. . . .
5 . . . 2
. . . .
4 . 3


The direction of an IP can be changed via several commands which resemble mirrors and branches.

The edges of the hexagon wrap around to the opposite edge. In all of the following grids, if an IP starts out on the a moving towards the b, the letters will be executed in order before returning to a:

   . . . .          . a . .          . . k .          . g . .
a b c d e        . . b . .        . . j . .        . h . . a
. . . . . .      g . . c . .      . . i . . e      . i . . b .
. . . . . . .    . h . . d . .    . . h . . d .    . j . . c . .
f g h i j k      . i . . e .      . g . . c .      k . . d . .
. . . . .        . j . . f        f . . b .        . . e . .
. . . .          . k . .          . . a .          . f . .


If the IP leaves the grid through corner in the direction of the corner there are two possibilities:

-> . . . .
. . . . .
. . . . . .
. . . . . . . ->
. . . . . .
. . . . .
-> . . . .


If the current memory cell (see below) is positive, the IP will continue on the bottom row. If it's zero or negative, the IP will continue on the top row. For the other 5 corners, just rotate the picture. Note that if the IP leaves the grid in a corner but doesn't point at a corner, the wrapping happens normally. This means that there are two paths that lead to each corner:

      . . . . ->
. . . . .
. . . . . .
-> . . . . . . .
. . . . . .
. . . . .
. . . . ->


Special characters

. is a no-op: the IP will simply pass through.
@ terminates the program.

Arithmetic

) increments the current memory edge.
( decrements the current memory edge.

I/O

, reads a single byte from STDIN and sets the current memory edge to its value, or -1 if EOF is reached.
; takes the current memory edge modulo 256 (positive) and writes the corresponding byte to STDOUT.

Control flow

$ is a jump. When executed, the IP completely ignores the next command in its current direction. This is like Befunge's #. _, |, /, \ are mirrors. They reflect the IP in the direction you'd expect. For completeness, the following table shows how they deflect an incoming IP. The top row corresponds to the current direction of the IP, the left column to the mirror, and the table cell shows the outgoing direction of the IP:  cmd │ E SE SW W NW NE ──────┼──────────────────── / │ NW W SW SE E NE \ │ SW SE E NE NW W _ │ E NE NW W SW SE | │ W SW SE E NE NW  < and > act as either mirrors or branches, depending on the incoming direction. The cells indicated as ?? are where they act as branches. In these cases, if the current memory edge is positive, the IP takes a 60° right turn (e.g. < turns E into SE). If the current memory edge is zero or negative, the IP takes a 60° left turn (e.g. < turns E into NE).  cmd │ E SE SW W NW NE ──────┼──────────────────── < │ ?? NW W E W SW > │ W E NE ?? SE E  [ switches to the previous IP (wrapping around from 0 to 5). ] switches to the next IP (wrapping around from 5 to 0). # takes the current memory edge modulo 6 and switches to the IP with that index. Memory manipulation { moves the MP to the left neighbour. } moves the MP to the right neighbour. " moves the MP backwards and to the left. This is equivalent to =}=. ' moves the MP backwards and to the right. This is equivalent to ={=. = reverses the direction of the MP. (This doesn't affect the current memory edge, but changes which edges are considered the left and right neighbour.) Some commands/description omitted for conciseness, full list here. Other rules: • Input/Output may be done however is most natural for your language • Output does not have to be formatted like a hexagon • Must run in a reasonable amount of time • Minimal brute-force • No brute-forcing the entire program • You can only use Hexagony commands specified in this challenge. • This is , so shortest code wins • {META NOTE: I know this challenge is hard, is there a better way to score?} • As usual, standard loopholes are prohibited. Test Cases: Input: (cat) ,.[,.] Output: (example) \ . . < _ . . . _ ; . . . . > , . @ . Input: ("123") +++++++++++++++++++++++++++++++++++++++++++++++++.+.+. Output: (example) ) ) ) ) ) ) ) ; ) ; / ) ) ) ) ) ) / ) ) ) ) ) ) ) / ) ) ) ) ) ) ) ) / ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) . . @ ; < Input: (@primo's infinite Fibonacci) +[[<+>->+>+<<]>] Output: (example) ) \ . . . . | . | . / { } < . . . . . > [ . / > . . . . . . . . . . . . . . . . @ . . . . / . ] < . > < . ] . . . _ > " ' / | . > < . . . . _ / . . . / . . [ . . . . / . . . . . . ) . . . . . . . . . . ] . . . . [ . . . . | . . [ . . . . ( . \ ) ] ) ] <  • I am quite sure that the outputs are not unique, are they? – flawr Jul 4 '16 at 16:18 • @flawr The outputs do not have to be unique as long as the inputted BF programs do the exact same thing, under all circumstances. – Blue Jul 4 '16 at 16:22 • I think Hexagony's padding rules would be important, especially if you don't require the output to be formatted like a hexagon. I predict most answers to generate tons of no-ops at the end, which can't be omitted without messing up the layout. – Martin Ender Jul 4 '16 at 16:26 • I don't think it's a good idea to mask brainfuck in the question body, since it hurts searchability. You're going to need the brainfuck tag anyway. – Dennis Jul 4 '16 at 16:36 • @Dennis Should I change the title as well? – Blue Jul 4 '16 at 16:48 • No, the title cannot contain fuck due to network-wide rules. – Dennis Jul 4 '16 at 16:51 • I think this challenge is actually rather easy except for translating [] loops: everything else is a simple mapping. I think the most likely type of answer will just generate the code mostly linearly while keeping track of a "stack" of loops and then figuring out what size hexagon to put it in. – FryAmTheEggman Jul 4 '16 at 18:34 • @FryAmTheEggman Should I make this challenge metagolf to encourage less linear output? – Blue Jul 4 '16 at 20:29 • @Blue That would certainly be interesting, but I have doubts you'd get a lot of participation in that case. – Martin Ender Jul 4 '16 at 20:41 • I agree with Martin, I may not have worded my last comment very well, as the [] translations will actually be rather time consuming, if not difficult. Further increasing the complexity of the challenge will make it more interesting, but it might be too much to expect more than an answer or two at that point. – FryAmTheEggman Jul 4 '16 at 21:11 Platformer game Write a platformer game. Rules: • Keyboard input, minimum three commands: left, right and jump; • Real-time. Screen should update (and the game iterate) on timer. Update speed should not depend on CPU speed. FPS should be between 2 and 120; • It should be possible both to win and to lose (the game can although be very hard and require preparing a special bot to win or to lose); • Playing field should have at lest 64 positions, minimum width is 6, minimum height is 5. • Player may move left, right or jump. Player moves down automatically unless on a platform. Jumping means moving up for some limited time (not higher than 67% of playing field's height), then falling down like usual. • Falling down outside playing field is losing the game. Stepping on 6 distinct platforms is a win. • Player, platforms and borders of area should be visible on playing field. If output method is ASCII art, it may looks like this: .....----... ............ ...@....---- ..---....... .......---.. ............  • Platforms may be horizontal, vertical, diagonal. Platforms should not overlap (except of differently oriented). Platform's projection to horizontal and vertical axes should not overlap for at least 4 platforms. Example of too projection-overlapping playing field: ............ ....@....... .--.--..--.. ............ .--.--..--.. ............  • Platforms may move. Overlapping rules apply only to initial positions. • The game should track losing and winning conditions and stop the game, outputting distinct messages in case of lose or win. • I feel like this spec is much too broad. Different answers will vary so much that I don't think they will be comparable. I think you need to specify each interaction precisely. – FryAmTheEggman Jul 4 '16 at 19:43 • @FryAmTheEggman, The idea was to just implement a platformer game, with rules only to prevent "degenerate", uninteresting cases (like 1x1 field with 0 platforms and unconditional lose in the first turn). Do you think it would be more interesting if each answer's game would basically be the same? – Vi. Jul 4 '16 at 21:06 • I think it is a much more interesting golfing problem if all the games are the same, as otherwise what is the point of golfing? I don't think this is a good site to try to get interesting platforming games, as I don't think this will work with either a pop-con or code-challenge either. – FryAmTheEggman Jul 4 '16 at 21:09 • I though it would be interesting if main point were to design the game to be compactly implementable, not just to implement already designed game in a compact way... – Vi. Jul 4 '16 at 21:22 Compute h-index of PPCG users Thanks to @Suever for his help refining this challenge. Background The h-index is a commonly used metric that measures the amount and quality of publications of a given scholar or researcher. It is defined as follows: A scholar with an h-index of n has published n papers each of which has been cited at least n times. Adaptation for PPCG In this challenge I propose to compute the h-index of PPCG users based on the analogy • paperanswer; • paper's citations → answer's vote count, defined as upvotes minus downvotes. The following examples illustrate the computation of h-index. The array to the left is the vote count of answers in descending order for a hypothetical user, and the number to the right is the resulting h-index: [5 3 2 1 1] 2 [1 1 1] 1 [] 0 [-1 -2] 0 [0] 0 [9 4 3 ...] 3  Referring to the last example, note that we don't need to know the array entries after the 3. The challenge Given a user identification, output their h-index. Rules User identification can be defined as anything reasonable, such as user number, user name, or user name without spaces. The result must be based on actual data from the PPCG site. You may want to take a look at the StackExchange API, for example here. Note that some users have a lot of answers. For one such user the API may not give all the results, or may only give them split across several chunks. However, if you ask the API to provide the results with an appropriate sorting you may not need all of them to compute the h-index (see last example above). Also, you may assume that the h-index of any user will be less than 100. If the answer can't be tested in an online compiler (for example due to restrictions to read web content), you are encouraged (although not required) to post some evidence that the answer works, such as a screen capture. This is code golf. Fewest bytes wins. Table of h-indices After submitting your answer, you may optionally edit the table below to include your own h-index, in the indicated format. Please keep the table in decreasing order, so that users with higher h-indices appear higher on the table. I will remove the dummy user names when the table has some actual content. Example user name: 5 Another example: 3 Yet another user: 3  • @FryAmTheEggman Having 1000 answers is irrelevant only if you ask the API for the answers in descending order of votes. The note is intended to make it clear that asking for the answers in that order is probably a good idea. I've rephrased a little, I hope it's clearer now. As for how many results the API provides in the same chunk, I think the limit is 100, but I'm not sure – Luis Mendo Jul 4 '16 at 23:45 • Yes, I think that is much clearer now. Also, Yet another user? I hate that guy... – FryAmTheEggman Jul 5 '16 at 0:13 • We've had a challenge to find the h index. With that done, this mostly looks like a question to query the SE API. – xnor Jul 5 '16 at 10:28 • @xnor Oh. Pity. I didn't see that challenge. I guess this is mostly a duplicate then – Luis Mendo Jul 5 '16 at 11:11 What is closer? Tags: , Inputs: a, b (Both integer and positive) .Output: Integer, in natural numbers sequence. We have one single atom which has a electrons, we ionize the atom with b positive charges (take b electrons out). The output is the sum of the orbital quantum numbers (n,l,ml) which is nearest to the atom shell. EXAMPLE: We take 3 electrons from 26Fe, Now we have 26Fe3+. We need to get the sum of the nearest remained orbitals quantum numbers to the shell. We have this configuration for Fe3+: [Ar], 3d3, 4s2 The nearest orbital to shell has these numbers: n = 4 l = 0 ml = 0  In this case: a => 26 b => 3 output => 4  My 3rd grade chemistry teacher asked me once to create such a program, but I didn't success, I found the paper that my teacher wrote these descriptions on it and I typed it here because I believe that someone might create an interesting code-golf for this. • You can't create the atoms and electrons tags right now (2/150 rep). Even then, we're not going to need them. – user48538 Jul 6 '16 at 9:03 • This is a long way from being self-contained. I don't know whether someone who knows quantum chemistry would find the question clear, but I need a link to some background material to even start trying to work out what I'm supposed to do. – Peter Taylor Jul 6 '16 at 16:59 KotH Chess Warriors. This game will be based on fairy chess, but really could be imagined to be anything else. Submissions will include both: A function that determines the moves of the piece (as in, how the piece can move), called at the start, and a function that determines how it moves each turn, called each turn, of course. Bot's move simultaneously; strategy is needed. A piece may make 5 moves in a row before it must rest. Bot's will be able to do any valid move they choose, and the input they will get when deciding what to do will be: a value that can be 2, 1, 0, or -1, for each possible move. 2 denotes that an ally is in that square, 1 denotes that an enemy is in that space. 0 denotes an empty space which could be moved to, -1 represents an illegal move, which may result from the board ending or another piece in the way. If a piece attempts to move into it's ally, the following things could happen; A) ally stays still; Piece stays where it is. B) ally moves; Piece moves where it wishes. C) ally is captured; Piece recaptures See below for early stage point spending system Sandbox I don't have the experience to host this challenge, so someone who can program these kind of things will need to help. I have sketched out some movement point system, but I need to figure out how large the board is, and so how valuable riders (pieces that move continously, like a rook), would be, compared to leapers, before i could finalise it Here is the quick system done, which could clearly be improved (for one thing, the multiple move thing probably needs to be a bit more expensive): Point buying system Points: each piece receives (to be decided) points base move: points spent on a move are as so. Largest dimension + floor(small dimension/2). There are no riders in this mode; Only repeated movement Repeated movement by x cost:*ceil(x^1.25) make move-only=/2 It is possible to have a leaping attack and sliding attack on the same square; it is also possible to have only one of these able to attack; How this is sorted is that both moves get their own value, and so you can attack if the attack move by itself can reach there. Examples for base move costs: • Any king move: 1 • any knight move: 2 • Zebra move:4 • Camel move:3 PLEASE NOTE: These move values on their own are not representative of how powerful a piece with that move actually is; A knight is better than a camel or zebra. However, when paired with other moves, the zebra and camel moves may become effective. Example of moves that can be purchased:  1 7 2 3 6 @55555 4  • move 1=(2+floor(0/2)):2 points • move 2=(1+floor(1/2)):1 point • move 3=(2+floor(1/2)):2 points • move 4=(1+floor(0/2)): 1 point • move 5=((1+floor(0/2))*ceil(5^1.25))=8 points • move 6=(5+floor(0/2))=5 points • move 7=(5+floor(1/2))=5 points in total, this piece costs: (2+2+1+1+8+5+5) 24 points. Considerations: • How large the board is. I'm fairly sure of having a cylindrical board; the left wraps to the right and vice versa. • how exactly turns work. So far, I have thought that the way it works is this: Everyone moves simultaneously. When you move, you deplete your remaining moves, which tops and starts at 5. You can choose to not move, and replenish your moves at any point. However, this could induce stale games which don't end properly. • I think you should add a hyperlink to the Wikipedia page on Fairy Chess for users to refer to. Also, if you're interested, there's a great game online that involves unique fairy chess pieces. It's called Chess Evolved Online. Not only are there different pieces, but you build your setup ahead of time and don't know what setup your opponent will have. – mbomb007 Jul 22 '16 at 19:34 Calculate my total hours I record the work I do for one of my customers using a flat file in the following format: 0000-00-00 0000-0000 0.0 code0000 free text  The 0.0 represents the amount of time spent on the task identified by code0000, where 0000 is an optional numeric task ID and code is a project code (and does not contain digits or spaces). Because I'm lazy, I need as short a program as possible to calculate subtotals of my total time for each project, plus a grand total. If you are using plain text output it should show the hours first and then the project code on the same line, and then the grand total on a line on its own with no code. You don't need to use a specific numeric format but you should be capable of dealing with half hours (0.5) in both the input and output. • Are the beginning strings (presumably a date, and something else?) and the free text ever relevant? If not, I'd consider omitting them. Is any order for the subtotals acceptable? – FryAmTheEggman Jul 11 '16 at 14:35 • @FryAmTheEggman Sorry, but that's my actual input format. The good news is that the subtotals can be in any order. – Neil Jul 11 '16 at 16:26 • It's obviously up to you, but I think that input makes it a chameleon challenge. I wrote a preliminary Pyth answer to do this, and only 16 of the 36 bytes were related to summing and grouping, the other 20 were used for processing. (Surely it can't be that hard to preprocess away the first two fields and the free text? :P ) – FryAmTheEggman Jul 11 '16 at 17:07 • If I didn't have to preprocess them away I could just open the file in Excel and be done with it... – Neil Jul 11 '16 at 18:41 Undone Mathematics Definitions I define the following: nᵗʰ Undone Addition of A Let +ᵣ A denotes the nᵗʰ Redacted Addition of A; the sum of the elements of A after n layers have been removed in every dimension:  ²+ᵣ [1,2,3,4,5,6,7] = ∑ [3,4,5] = 12 // 1D: remove leading and trailing elements [[1,1,3] ¹+ᵣ [4,2,5] = ∑ [2] = 2 // 2D: remove leading and trailing rows and columns [3,4,1]]  Then +ᵤ A denotes the nᵗʰ Undone Addition of A; the nᵗʰ Redacted Addition of A plus the sum of the elements of A:  ²+ᵤ [1,2,3,4,5,6,7] = ²+ᵣ [1,2,3,4,5,6,7] + ∑ [1,2,3,4,5,6,7] [[1,1,3] [[1,1,3] [[1,1,3] ¹+ᵤ [4,2,5] = ¹+ᵣ [4,2,5] + ∑ [4,2,5] [3,4,1]] [3,4,1]] [3,4,1]]  nᵗʰ Undone Multiplication of A Let ×ᵣ A denotes the nᵗʰ Redacted Multiplication of A; the product of the elements of A after n layers have been removed in every dimension:  ³×ᵣ [3,2,1,1,2,3,1,1] = ∏ [1,2] = 2 // 1D: remove leading and trailing elements  Then +ᵤ A denotes the nᵗʰ Undone Multiplication of A; the nᵗʰ Redacted Multiplication of A times the product of the elements of A:  ³×ᵤ [3,2,1,1,2,3,1,1] = ³×ᵣ [3,2,1,1,2,3,1,1] × ∏ [3,2,1,1,2,3,1,1]  nᵗʰ Undone Average of A Let μ denote the average (arithmetic mean), i.e. μA = (∑A)N and μᵣA denote the nᵗʰ Redacted Average of A; the average of the elements of A after n layers have been removed in every dimension:  ³μᵣ [3,2,1,1,2,3,1,1] = μ [1,2] = 1.5  Then μᵤ A denotes the average of the nᵗʰ Redacted Average of A and the average of the elements of A:  ³μᵣ [3,2,1,1,2,3,1,1] + μ [3,2,1,1,2,3,1,1] ³μᵤ [3,2,1,1,2,3,1,1] = ───────────────────────────────────────────── 2  Task With all this in mind, create an interpreter that will evaluate expressions that use the below operations (numbers are just examples). Alternatively, extend the language of your choice to include the notation. 1 + 2 Addition 3 × 4 Multiplication μ [5,6] Average 7 +u [8,9] Undone Addition 9 ×u [1,2] Undone Multiplication 2 μu [3,4] Undone Average  Note that you do not need to implement redacted operations. They were only defined above to facilitate the definitions of the undone operations. You may substitute any ASCII or Unicode symbol for +, ×, and μ as long as you stay consistent: You may not choose * with ×u. Each undone operator has a higher order precedence than their normal counterpart. Test cases: 2+u [1,2,3,4,5,6,7]40 1+u [[1,1,3][4,2,5][3,4,1]]26 3×u [3,2,1,1,2,3,1,1]72 3μu [3,2,1,1,2,3,1,1]1.625 0.1 × 2+u [1,2,3,4,5,6,7]4 2+u [1,2,3,4,5,6,7] × 0.14 0+u [[[1,1][3,2]][[1,3][3,1]]]15 1+u [[[0,1,1][2,1,1][1,0,0]][[2,2,2][2,2,0][1,0,2]][[1,2,0][2,1,1][2,1,2]]]34 1×u [[[1,1,2][1,1,1][1,2,1]][[1,2,2][2,2,1][2,2,1]][[1,1,1][1,1,2][2,1,1]]]2048 1μu [[[2,2,3][3,2,1][3,3,3]][[1,3,3][2,1,1][2,1,3]][[2,3,3][3,2,3][3,2,1]]]3.259 • I find the structure of the definitions very confusing. It would help to a) define terms before you use them; and b) be explicit about the domain and range of the operators. I also, possibly as a result of b), fail to understand the examples: ITSM that ²+ᵣ [1,2,3,4,5,6,7] should be a sum over zero elements because by the time you've removed the first two rows and the last two rows you're left with -3 rows. And the test cases are even more confusing: what is [[1,1][3,2]][[1,3][3,1]]? It looks like two matrices side by side, but I didn't see any mention of implicit operators. – Peter Taylor Jul 12 '16 at 20:57 • @PeterTaylor a) I originally had redacteds before undones, but I wanted to put the focus on the undones. I'll swap again. b) Notice that the input can be n-dimensional, so as [1,2,3,4,5,6,7] is one-dimensional, only the first and last elements in that only dimension need to be stripped off, giving [3,4,5]. The later examples are missing outer brackets, to indicate that they are 3D. Thanks for your feedback! – Adám Jul 13 '16 at 6:01 • 1. There's no way visually to distinguish the 1D examples from the 2D ones. Now that you've added some [] to the test cases, they're better. Why not do the same for the 2D examples: add a [ before the first row and a ] after the last one, as a cue to distinguish them from the 1D cases? 2. If you think that the redacted distract from the undones, you could rephrase undone addition in terms of a convolution with an n-dimensional "matrix" with elements 1 or 2 according to distance from the exterior; then introduce redacted addition as an alternative way of understanding it. – Peter Taylor Jul 13 '16 at 7:40 • @PeterTaylor 1. is done. I'm not sure how to formulate 2). – Adám Jul 13 '16 at 11:02 Family Tree, Folder Tree Given a simple family tree in a format reasonably similar to the format outlined below, create a file tree to match it, as explained below. Input An ascii family tree in a similar format to the following:  Grandpa Jim = Grandma Jane | ------------------------------------------------------- | | | | Bill Bob Jim Jane Sam Sammyson = Aunt Jimbo Daddy McDad = Mommy McMom | | ----------- Me | | Cousin One Cousin Two  The scheme can be changed within reason, however the test cases provided will meet the following specs: 1. = Symbolizes a marriage 2. If there are any children from a marriage, there will be a | one line below the = symbolizing the marriage. 3. A - character that is below a |, or connected (by adjacency) to a - that is immediately below a | are used to signify multiple children. Below any of these - there may be a |, which will have a the first word of a name immediately below it. This full name is the name of a child. 4. The initial line of the family tree will only contain two people. This spec maybe should be cleaned up more. Note that there won't be any relationships more complicated than = marriage or | child linking two names. This means that more complicated relationships, such as divorce or step-children, will not appear in the tree. Output There will be no output as such, instead the program/function will create a directory structure matching the input. For example, the above example would lead to the following directory tree: $ tree family_tree/
family_tree/
├── Grandma Jane
│   ├── children
│   │   ├── Bill Bob
│   │   │   └── parents
│   │   │       ├── Grandma Jane -> ../../../../Grandma Jane/
│   │   │       └── Grandpa Jim -> ../../../../Grandpa Jim/
│   │   │   ├── children
│   │   │   │   └── Me
│   │   │   ├── parents -> ../Jim Jane/parents
│   │   │   └── spouse
│   │   │       └── Mommy McMom
│   │   │           ├── children -> ../../children/
│   │   │           └── spouse
│   │   ├── Jim Jane
│   │   │   └── parents -> ../Bill Bob/parents/
│   │   └── Sam Sammyson
│   │       ├── children
│   │       │   ├── Cousin One
│   │       │   └── Cousin Two
│   │       ├── parents -> ../Jim Jane/parents
│   │       └── spouse
│   │           └── Aunt Jimbo
│   │               ├── children -> ../../children/
│   │               └── spouse
│   │                   └── Sam Sammyson -> ../../../../Sam Sammyson/
│   └── spouse
│       └── Grandpa Jim -> ../../Grandpa Jim/
└── Grandpa Jim
├── children -> ../Grandma Jane/children/
└── spouse
└── Grandma Jane -> ../Grandma Jane/


The directory tree must satisfy the following:

1. Create a directory called family_tree that will contain the entire family tree.
2. Inside family_tree/ there will be exactly two directories, these are the two people at the top of the family tree.
3. For every person in the tree, do the following in their directory:
1. If they have a spouse, create a spouse directory. If the spouse already has a directory named after them, create a link to that directory within the spouse directory. Otherwise, create a directory in the spouse directory with the name of the spouse.
2. If they have children, then they must have a spouse. If the spouse already has a directory named children, then create a link to that directory and name the link children. If their spouse doesn't already have this directory, create the children directory and add a directory corresponding to each child.

Again, this is a rough draft. The spec needs to be cleaned. I welcome comments

Note that, in all cases, it does not matter where the true directory and where the link is, as long as the link is properly setup. Also, it is okay to create links to other links.

This is

The French Farmer in the Dell

I used to work with kids and The Farmer in the Dell was a popular song among them. Also, I like challenge like 99 bottles of beer or Polar Bear, Polar Bear, what do you hear?. Try them too!

Goal

In your programming language of choice, write the smallest program possible which will output the following text. Output should match exactly, including case, spacing, and punctuation. A trailing linefeed is fine but specify it in your answer. We will play with the french version of the song because I find it more interesting than the english version (also I am french so more memories for me!).

Le fermier dans son pre,
Le fermier dans son pre,
Ohe, Ohe, Ohe,
Le fermier dans son pre.

Le fermier prend sa femme,
Le fermier prend sa femme,
Ohe, Ohe, Ohe,
Le fermier prend sa femme.

La femme prend son enfant,
La femme prend son enfant,
Ohe, Ohe, Ohe,
La femme prend son enfant.

L'enfant prend sa nourrice,
L'enfant prend sa nourrice,
Ohe, Ohe, Ohe,
L'enfant prend sa nourrice.

La nourrice prend son chat,
La nourrice prend son chat,
Ohe, Ohe, Ohe,
La nourrice prend son chat.

Le chat prend sa souris,
Le chat prend sa souris,
Ohe, Ohe, Ohe,
Le chat prend sa souris.

La souris prend son fromage,
La souris prend son fromage,
Ohe, Ohe, Ohe,
La souris prend son fromage.

Le fromage est battu,
Le fromage est battu,
Ohe, Ohe, Ohe,
Le fromage est battu.


If you are french, you may note that I replace all é with e. It is not important for the challenge and I prefer to stay full ASCII.

If you want to code while listening to the song, you can find it on YouTube. :)

Sandbox Questions

A not so difficult challenge. I originally thought about posting it directly, but I prefer to share it first. I don't think test case are needed. I implemented both the english and french version and the last one is far better to my taste :)

• The only thing I'd be worried about is if this is a duplicate of something. If the structure of the song is too similar to another one I think it should be closed. That said, this is pretty similar to the polar bear song, but without a second verse type and with an exception or two? I don't know whether that is enough, so I wouldn't vote to close on my own. – FryAmTheEggman Jul 20 '16 at 19:14
• This looks vulnerable to the techniques which have been used on previous songs, the canonical example of which is the rickroll. – Peter Taylor Jul 21 '16 at 7:39

Background

As you may or may not be aware, Pokemon Go's servers have not fared well under the stress of the game's extreme popularity. As an amateur programmer, I'm in the sweet spot where I know just enough to think I can solve all of their problems, but not enough to be able to understand how complex their problems actually are. Thus, I find myself constantly thinking "Why didn't they just do <insert naive suggestion here>? It would fix everything!" This challenge is focused on one of those probably-useless ideas I've thought up.

First, some very quick background, in case you haven't played the game (you can skip this paragraph if you have): In the course of gameplay, Pokemon can randomly appear at certain real-life locations. Every player in the same location sees the same Pokemon, and multiple players can catch one Pokemon.

One potential difficulty I see with this is storing all of that data. With millions of concurrent players, the game servers have to keep track of millions of Pokemon. That's a lot of IO for their database. Fortunately, I, a graduate of not one, but two introductory CS courses, have a solution! Because player interactions have nothing to do with where and when Pokemon spawn, it is essentially deterministic. This means that it should be possible to drop the database entirely (at least for this one specific task), and replace it with a function! This function could take the player's location, the current system time, and a random seed as input, and return a list of all Pokemon within a certain radius. Because no database lookup is needed, this function would be lightning fast and easily scalable to millions of players.

The Challenge

Your challenge is to write this function. Obviously, the actual game of Pokemon has way too many details to make a feasible code challenge for PPCG, so here's the simplified guidelines:

• Create a function that takes the following inputs, in any format you like:
• Player location, as 2D coordinates
• System time
• Random seed
• The function should return a list of nearby Pokemon, with the following requirements:
• "Nearby" means "within one unit of distance of the player", where distance is 2d euclidean distance. (Just ignore the edge case where the location is on a round planet)
• Each Pokemon should have a species and an exact location
• This list can be in any format you want
• The results are deterministic (i.e., for the same location, time, and random seed, the same Pokemon are always returned)
• The Pokemon should persist for some pseudorandom amount of time
• Thus, if the function is called twice with the same location and random seed, and two times that are very close, then each Pokemon returned the first time should have a large possibility of being returned the second time
• If the function is called twice with the same time and random seed, and two nearby locations, then any Pokemon that are near both locations should be returned both times
• The Pokemon should be somewhat evenly distributed across the "world" (the coordinate plane).
• The Pokemon should be distributed such that at any location and time, the probability of finding exactly n nearby Pokemon of any type is (0.5)^(n+1)
• Thus, there is a 50% chance of finding no Pokemon at all, a 25% chance of finding exactly 1, a 12.5% chance of finding exactly two, etc.
• Your algorithm should be capable of returning up to 10 nearby Pokemon, but is allowed to return more, as long as it follows the right probability distribution
• Sandbox question: I want a requirement to be that the algorithm can't simply generate all of the Pokemon in the world and then just return the nearby ones, but I don't know how to formally state this. I had some fleeting thoughts about O(1) memory usage, but that method could strictly speaking have O(1) memory usage if the world is a constant size (which I'm pretty sure it is).

Might this make a good challenge? That would fit in with the premise, and might produce some interesting algorithms.

For the sake of making this challenge somewhat reasonable, the list of possible Pokemon and their probabilities of appearing will be small:

• Weedle: 60%
• Charmander: 30%
• Blastoise: 10%

Scoring

This is part of what I need help with in the sandbox. How should I distinguish two entries that both meet all of the requirements?

Thanks for reading this far! I know this question isn't nearly ready to be a real challenge. At the very least, it need more specific requirements. But I figured I'd post what I currently have in the sandbox to see if it's worth continuing with. I've never posted or participated in a PPCG challenge before, and I'm sure that's obvious, but hopefully with your help, I can refine this to the point of being a legitimate challenge.

• Welcome to PPCG, and thanks for using the sandbox! :) Currently I'm afraid your question is rather underspecified. You need to define "nearby" as well as describe how Pokemon should be distributed, as otherwise I could just put 6 weedles, 3 charmanders and a blastoise on the north pole for some time, then swap them to the south pole, etc. You could put a time constraint on the code to try to limit the whole world generation problem, but to do that you'd probably need a reference implementation. Personally, I think code-golf is likely the best scoring method. – FryAmTheEggman Jul 22 '16 at 15:25
• I was imagining this challenge would be very difficult and require a somewhat complex answer, which is why I didn't initially tag it as code golf. But after thinking about it for a little while, I came up with a rather simple solution that isn't as interesting as I thought it would be. So maybe code golf is a better tag. As for you other remarks, I'll get to work editing the answer to make it less ambiguous. – ItsTimmy Jul 22 '16 at 15:39
• 1. Does "the usual euclidean distance" mean in the 3D embedding of the globe whose surface is parameterised by the input coordinates? Or have you decided to simplify by ignoring the fact that real Pokémon Go takes place on a round planet? 2. What does "as long as it follows the right probability distribution" mean if you curtail the probability distribution? What happens to the probability from the tail? – Peter Taylor Jul 22 '16 at 21:43
• @PeterTaylor: I have answered both of your questions by editing my post. Thanks for the feedback! – ItsTimmy Jul 22 '16 at 21:53

Punch Buggy Probabilities

A popular game among children in the USA is "punch buggy", and as with every such game, there are many variations. The one we'll consider for this challenge goes like this:

• The moment anyone sees a Volkswagon Beetle (the "buggy"), participants may punch each other (usually in the shoulder or upper arm).
• A punch must be accompanied by "punch buggy <color>!", where <color> is the color of the VW Beetle (red, green, black, gray, yellow, etc.).
• Whoever makes contact first gets priority (and for this challenge, there are no ties).
• Once person A punches person B, B cannot punch A back (usually accomplished by saying "no punch back!").
• Punches may occur between any pair of participants (for this challenge, every pair of participants).

The challenge

Assuming all possible punching configurations among n people are equally likely to happen, what is the probability of any particular punching configuration? To put it another way, for each distinct punching configuration, how many ways can it occur?

Rules

• Input is a single positive integer greater than 1.
• Output must be one of the following: A) a list of decimals, B) a list of fractions (simplified or not), or C) a list of counts. META: Should I allow these lists to be unordered, or should I require that they be associated with punching configurations somehow? I'm leaning towards the former since it seems like it'd be a headache to figure out how to specify the latter and it would likely be an extra task that doesn't really have anything to do with the core problem.
• Standard rules apply, and standard loopholes are banned.

Test cases

Input
Output A
Output B
Output C

2
1.0
2/2
2

3
0.75 0.25
3/4 1/4
3 1


Explanation of input 2: With only two people, there are exactly two possible ways: either A punches B or B punches A. These are equivalent, so the probability is 1.0, the fraction is 2/2, and the count is 2.

Explanation of input 3: There are two distinct punching configurations: A -> B -> C, A -> C; A -> B -> C -> A. The latter has only two varieties (the other is A -> C -> B -> A) and the former has six, since there are three choices for the person who punches two others and then two choices for the remaining pair. Thus, the probabilities are 0.75 and 0.25, the fractions are 3/4 and 1/4, and the counts are 3 and 1.

META

• I want to add 4 to the test cases, and I think I'm gonna need help on it since I'm having a hard time counting all 2^6 = 64 possibilities correctly.
• Any clarifications/corrections?

Teh Scrolling Codez

In many movies, computer often appear to be scrolling through some code. We should automate this process to make it easier. Your job is to write code that displays to a graphical console a scrolling view of its own source code. You have two options...

Sandbox Questions

Should this be a code golf or pop-con. Pop-con's could result in more visually pleasing solutions. or [tag:popularity contest]

• I'm wondering how you vertically scroll source code that's one line. – feersum Jul 28 '16 at 1:17
• SIngle line source code is permitted. That is why it may make more sense to scroll it horizontally @feersum – Rohan Jhunjhunwala Jul 28 '16 at 2:13
• A quine in a loop and rely on the console having finite height? – Peter Taylor Jul 28 '16 at 8:07
• Yeah that could work – Rohan Jhunjhunwala Jul 28 '16 at 12:18
• @PeterTaylor ^^ – Rohan Jhunjhunwala Jul 28 '16 at 12:18
• @PeterTaylor do you have an opinion on what tag should be used? – Rohan Jhunjhunwala Jul 28 '16 at 12:21
• I suspect that this applies and that it's not an interesting question, although I personally don't find quines interesting so I'm not the best person to comment on that. – Peter Taylor Jul 28 '16 at 13:32
• but F() in and of itself is an interesting challenge. @PeterTaylor – Rohan Jhunjhunwala Jul 28 '16 at 15:37
• F(P) is while(true) print P. That's not an interesting challenge in any language I know. – Peter Taylor Jul 28 '16 at 16:10
• @PeterTaylor than I think I should ban console output, and require graphical output – Rohan Jhunjhunwala Jul 28 '16 at 16:12
• thus F(P) becomes while(true){print(sectionOf(p))move(p)}; – Rohan Jhunjhunwala Jul 28 '16 at 16:13

Autonomous Vehicle

I need a brain for my self-driving car. Something that will take still frames from the front-facing camera and give the navigation system commands. Obviously, if my car is driving me somewhere, I don't want to stop. However, I also don't want to:

1. Kill someone
2. Die

Knowing myself, we can assume that:

• At the speed I drive, hitting the curb or otherwise leaving the road will kill me and thus violate Don't #2
• With my luck, running a stop light, will violate Don't #1 or #2 or both

• Also hitting a pedestrian (or another car) violates Don't #1 (and possibly #2)

Input

The program/function should take an image as input. How it does this is flexible.

Output

The program/function should output one of these commands; ideally, one of the commands that doesn't result in one of the Don'ts being violated.

╔═════════╤═══════════════════════════════════════════════╗
║ Command │ Navigational Outcome                          ║
╠═════════╪═══════════════════════════════════════════════╣
║ Forward │ No course correction, continue straight ahead ║
╟─────────┼───────────────────────────────────────────────╢
║ Left    │ Veer left                                     ║
╟─────────┼───────────────────────────────────────────────╢
║ Right   │ Veer right                                    ║
╟─────────┼───────────────────────────────────────────────╢
║ Stop    │ Screech to a grinding halt                    ║
╚═════════╧═══════════════════════════════════════════════╝


Specifications

• Take an image as input in someway
• Output a command [ Forward, Left, Right, Stop ]
• Commands can be aliased as [ 0, 1, 2, 3 ] respectively
• Returning one valid command and no invalid commands is sufficient to pass a test
• Stop is only valid iff every other command would violate one of the Don'ts
• Rules for valid commands:
• No running stop lights
• No running over people
• No running into vehicles
• No running off the road
• If a command does not violate any of the above, then it is valid
• Program/Function must be deterministic

Scoring

Lowest score wins! The scoring function is:

• ( # of Bytes ) / ( Number of Passed Tests )

For example, a 450 byte Python solution that passes 2 test cases earns a score of 450 / 2 or 225.

Test Cases

1. Valid Commands: Forward

2. Valid Commands: Left, Right

• Straight ahead there are pedestrians crossing

1. Valid Commands: Forward, Right

2. Valid Commands: Forward

3. Valid Commands: Left, Right

4. Valid Commands: Stop

• I like this challenge. However, I don't see any test cases for lights. I also think that the test case for pedestrians is pretty bad. Also, realize that people might be using the text on the images (the road labels) to determine orientation, so make sure you're ok with that. I'd also recommend more test cases. Your current set is a good example set, but not comprehensive enough for testing IMO. – Nathan Merrill Jul 30 '16 at 1:19
• will all testcases be available? if so i would determine the output by the value of the pixel in the top-left corner. – KarlKastor Jul 30 '16 at 19:47

Embed a graph into the Rado graph

The Rado graph is an infinite undirected graph whose vertices are labelled with natural numbers {0, 1, 2, ...}.

The edge (i,j) with i<j is in the graph whenever the binary expansion of j has a 1 in its ith place. Here, place values are counted from the end, with the 0'th place being the least significant bit. In terms of bitshifts, this means (j>>i)&1==1.

The Rado graph is universal in that any finite graph is a subgraph of it. This means that any finite graph can be embedded in the Rado graph: to each vertex of the finite graph, assign a distinct vertex of the Rado graph so that any two vertices of the original graph have an edge if and only if the corresponding vertices of the Rado graph have an edge.

Your task is to output such an embedding for a finite graph given as input.

TODO: Lots of stuff

• Lovely challenge :). Is there a known algorithm to find the embedding? If so, might it be worth linking to it with a spoiler warning? – Martin Ender Jul 31 '16 at 10:05
• 1. It would be more accurate to say that this is one of several constructions of the Rado graph, and to state that answers are required to work with this construction in particular. 2. The statement of universality is incorrect. It should say induced subgraph rather than subgraph. 3. I assume that by "an embedding" you mean a mapping from vertices of the input graph to vertices of this construction of the Rado graph, but it would be good to make that explicit. 4. @MartinEnder, there's a greedy algorithm described in Wikipedia. – Peter Taylor Jul 31 '16 at 20:02

Draw Concentric Squarephabets

Challenge

Write a program or function that, given an input integer n, outputs a concentric squarephabet of size n×n.

A concentric squarephabet is an ASCII-art square of concentric rings, where the outside ring of characters are As, the second Bs, the third Cs, etc. For example, a 25×25 squarephabet looks like this:

AAAAAAAAAAAAAAAAAAAAAAAAA
ABBBBBBBBBBBBBBBBBBBBBBBA
ABCCCCCCCCCCCCCCCCCCCCCBA
ABCDDDDDDDDDDDDDDDDDDDCBA
ABCDEEEEEEEEEEEEEEEEEDCBA
ABCDEFFFFFFFFFFFFFFFEDCBA
ABCDEFGGGGGGGGGGGGGFEDCBA
ABCDEFGHHHHHHHHHHHGFEDCBA
ABCDEFGHIIIIIIIIIHGFEDCBA
ABCDEFGHIJJJJJJJIHGFEDCBA
ABCDEFGHIJKKKKKJIHGFEDCBA
ABCDEFGHIJKLLLKJIHGFEDCBA
ABCDEFGHIJKLMLKJIHGFEDCBA
ABCDEFGHIJKLLLKJIHGFEDCBA
ABCDEFGHIJKKKKKJIHGFEDCBA
ABCDEFGHIJJJJJJJIHGFEDCBA
ABCDEFGHIIIIIIIIIHGFEDCBA
ABCDEFGHHHHHHHHHHHGFEDCBA
ABCDEFGGGGGGGGGGGGGFEDCBA
ABCDEFFFFFFFFFFFFFFFEDCBA
ABCDEEEEEEEEEEEEEEEEEDCBA
ABCDDDDDDDDDDDDDDDDDDDCBA
ABCCCCCCCCCCCCCCCCCCCCCBA
ABBBBBBBBBBBBBBBBBBBBBBBA
AAAAAAAAAAAAAAAAAAAAAAAAA


(and yes I typed that by hand ☺)

If the input is an even number, the centre of the squarephabet will be a 2×2 square instead of a single letter. For example, for input 8:

AAAAAAAA
ABBBBBBA
ABCCCCBA
ABCDDCBA
ABCDDCBA
ABCCCCBA
ABBBBBBA
AAAAAAAA


Specification

• Standard loopholes are forbidden.
• The input to your program or function will never be less than 1 or greater than 52 (26×2). This means you do not have to deal with letters after Z.
• You may output uppercase or lowercase letters, but you must be consistent in your choice.

Test Cases

Format:

Input
Output


Test cases:

1
A

2
AA
AA

3
AAA
ABA
AAA

10
AAAAAAAAAA
ABBBBBBBBA
ABCCCCCCBA
ABCDDDDCBA
ABCDEEDCBA
ABCDEEDCBA
ABCDDDDCBA
ABCCCCCCBA
ABBBBBBBBA
AAAAAAAAAA

25
AAAAAAAAAAAAAAAAAAAAAAAAA
ABBBBBBBBBBBBBBBBBBBBBBBA
ABCCCCCCCCCCCCCCCCCCCCCBA
ABCDDDDDDDDDDDDDDDDDDDCBA
ABCDEEEEEEEEEEEEEEEEEDCBA
ABCDEFFFFFFFFFFFFFFFEDCBA
ABCDEFGGGGGGGGGGGGGFEDCBA
ABCDEFGHHHHHHHHHHHGFEDCBA
ABCDEFGHIIIIIIIIIHGFEDCBA
ABCDEFGHIJJJJJJJIHGFEDCBA
ABCDEFGHIJKKKKKJIHGFEDCBA
ABCDEFGHIJKLLLKJIHGFEDCBA
ABCDEFGHIJKLMLKJIHGFEDCBA
ABCDEFGHIJKLLLKJIHGFEDCBA
ABCDEFGHIJKKKKKJIHGFEDCBA
ABCDEFGHIJJJJJJJIHGFEDCBA
ABCDEFGHIIIIIIIIIHGFEDCBA
ABCDEFGHHHHHHHHHHHGFEDCBA
ABCDEFGGGGGGGGGGGGGFEDCBA
ABCDEFFFFFFFFFFFFFFFEDCBA
ABCDEEEEEEEEEEEEEEEEEDCBA
ABCDDDDDDDDDDDDDDDDDDDCBA
ABCCCCCCCCCCCCCCCCCCCCCBA
ABBBBBBBBBBBBBBBBBBBBBBBA
AAAAAAAAAAAAAAAAAAAAAAAAA

52
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
ABBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBA
ABCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCBA
ABCDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDCBA
ABCDEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEDCBA
ABCDEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEDCBA
ABCDEFGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGFEDCBA
ABCDEFGHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHGFEDCBA
ABCDEFGHIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIHGFEDCBA
ABCDEFGHIJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJIHGFEDCBA
ABCDEFGHIJKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKJIHGFEDCBA
ABCDEFGHIJKLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLKJIHGFEDCBA
ABCDEFGHIJKLMMMMMMMMMMMMMMMMMMMMMMMMMMMMLKJIHGFEDCBA
ABCDEFGHIJKLMNNNNNNNNNNNNNNNNNNNNNNNNNNMLKJIHGFEDCBA
ABCDEFGHIJKLMNOOOOOOOOOOOOOOOOOOOOOOOONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPPPPPPPPPPPPPPPPPPPPPPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQQQQQQQQQQQQQQQQQQQQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRRRRRRRRRRRRRRRRRRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTTTTTTTTTTTTTTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUUUUUUUUUUUUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVVVVVVVVVVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWWWWWWWWVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWXXXXXXWVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWXYYYYXWVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWXYZZYXWVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWXYYYYXWVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWXXXXXXWVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWWWWWWWWVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVVVVVVVVVVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUUUUUUUUUUUUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTTTTTTTTTTTTTTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRRRRRRRRRRRRRRRRRRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQQQQQQQQQQQQQQQQQQQQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPPPPPPPPPPPPPPPPPPPPPPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOOOOOOOOOOOOOOOOOOOOOOOONMLKJIHGFEDCBA
ABCDEFGHIJKLMNNNNNNNNNNNNNNNNNNNNNNNNNNMLKJIHGFEDCBA
ABCDEFGHIJKLMMMMMMMMMMMMMMMMMMMMMMMMMMMMLKJIHGFEDCBA
ABCDEFGHIJKLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLKJIHGFEDCBA
ABCDEFGHIJKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKJIHGFEDCBA
ABCDEFGHIJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJIHGFEDCBA
ABCDEFGHIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIHGFEDCBA
ABCDEFGHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHGFEDCBA
ABCDEFGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGFEDCBA
ABCDEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEDCBA
ABCDEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEDCBA
ABCDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDCBA
ABCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCBA
ABBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA


Scoring

This is , so shortest answer wins. Good luck!

• We're getting slightly into idea-milking territory here. While this isn't a bad idea, a lot of similar challenges in short succession tend to lose interest and popularity fast so you might want to think twice whether you want to post this any time soon. That said, the construction seems simple enough that I'm pretty sure it's been done before. For instance this challenge requires the exact same computation at the core: codegolf.stackexchange.com/q/57845/8478 (although yours probably allows for other approaches, too). – Martin Ender Aug 1 '16 at 16:31

A meander is a self-avoiding closed curve which intersects a line a number of times.

Your task is, given a self-avoiding walk on a lattice/grid, produce a meander a la the following:

Input

{{{3, 4}}, {1, 2}, {2, 6}, {6, 7}, {7, 3}, {3, 4}, {4, 8}, {8, 12}, {12, 11}, {11, 10}, {10, 9}, {9, 5}, {5, 1}}


Output

or similar.

Test cases:

Inputs

a={{{3, 5}}, {{1, 2}, {2, 3}, {3, 8}, {8, 9}, {9, 4}, {4, 5}, {5, 10}, {10, 15}, {15, 14}, {14, 13}, {13, 8}, {8, 7}, {7, 12}, {12, 11}, {11, 6}, {6, 1}}}
b={{{3, 6}}, {{1, 2}, {2, 8}, {8, 9}, {9, 3}, {3, 4}, {4, 10}, {10, 11}, {11, 5}, {5, 6}, {6, 12}, {12, 18}, {18, 17}, {17, 16}, {16, 10}, {10, 9}, {9, 15}, {15, 14}, {14, 13}, {13, 7}, {7, 1}}


Output

In the above examples, the numbers correspond to a grid, bottom to top, left to right, so 1 is bottom-left, and 18 on a 3*6 grid is top-right. The orientation of your grid doesn't have to follow this order: it can have any desired orientation.

You can assume dimensions of the grid are given at the begining of the input, as per the obove examples.

Feel free to use either pre-existing images - eg

or generate your own. This is Code Golf, so the shortest answer in bytes wins.

• I'm still not clear how the points relate the the final image. For the pre-existing images, can we use them at no bytes cost? Is the code for loading them free? – xnor Aug 4 '16 at 10:44
• @xnor I think you are right - it is not clear as it stands - think I will leave it on the back-burner for the moment. – martin Aug 4 '16 at 12:31

ASCII Art converter

see ASCII Art on Esolangs

Your task is to take input of a brainf*** program and output its equivalent ASCII art program. Your challenge: You may not use the following symbols in your program: \ / - | _ # Standard loopholes not allowed...

This is a so shortest answer in bytes wins

ACII Art Interpreter

Your task is to create an interpreter for the ASCII art language. ASCII Art is a variant of brainf*** where characters are instead ASCII art figures 5 lines tall.

< looks like

 /
/
\
\


> looks like

\
\
/
/


+ looks like

  |
|
-----
|
|


- looks like

-----


[ looks like

____
|
|
|
|___


] looks like

____
|
|
|
___|


. looks like

##
##


, looks like

##
##
_|


Characters that are less than 5 characters tall may be placed anywhere within the top line and bottom line of input.

____________________ top line
\
\
/
/
<--- gap because this char is only 5 characters tall
_____________________bottom line


There may be any amount of white space between characters. Also characters can be "nested" in each other, as long as they do not touch. EG

____ |  ##
|    |  ##
|  -----_|
|    |
|___ |


is perfectly valid

Your code should not allow improperly formatted ASCII art, and should print to Standard error. For example, the following code should not work

\
\
|
|
|____


This is a , so the shortest answer in bytes wins!

• What is the winning criterion (is it codegolf, popularty contest, anything else...), and what is the font to use? – TuxCrafting Aug 3 '16 at 17:06
• @TùxCräftîñg By font, what do you mean - the ASCII art page on esolangs depicts what each and every symbol should look like – vikarjramun Aug 3 '16 at 17:31
• Nevermind, I haven't seen this part – TuxCrafting Aug 3 '16 at 17:39
• Welcome to PPCG and thanks for using the sandbox! Unfortunately, this is basically a dupe of this challenge with a do X without Y bit tacked on, so I don't think this will be received well. I'm not really sure if there is a way to salvage your intent, here, but I recommend trying something different. Best of luck! – FryAmTheEggman Aug 3 '16 at 17:45
• 1. If at all possible, posts should be self-contained. The Esolangs page you link to might change or disappear. 2. You should specify how the commands should be chained (horizontally, vertically or something else), how they should be aligned, and how much whitespace has to separate them. 3. In my opinion, forbidding those characters doesn't make the challenge more interesting. – Dennis Aug 3 '16 at 17:49
• @FryAmTheEggman Except my challenge is meant to convert only brainf*** code – vikarjramun Aug 3 '16 at 17:49
• I'm afraid that isn't nearly enough to make it not a duplicate, in my opinion. However, Dennis brings up a potentially interesting point, you may be able to salvage this by also requiring that the code be "formatted" a certain way. I also agree with the rest of the advice Dennis gave you, and I think you should address them before deciding on what else to do. – FryAmTheEggman Aug 3 '16 at 17:52
• What if I change it to a ASCII art interpreter – vikarjramun Aug 3 '16 at 17:57

Find the Watermark

At the moment, I don't have time to outline this properly. The idea is simple: Find the watermark in an image. The implementation, however, is obviously not simple. Since watermarks can have a variety of characteristics, I'd like to admit a variety of answer styles and make it a . Some ideas for the output format:

• Return coordinates of the (centre|corner(s)?) of the watermark
• Return a line in some form (e.g., endpoints or equation) that runs through the watermark
• Return an image that contains only a mask matching the watermark

Input, obviously, would be an image containing a watermark. Images without watermarks are not valid input; as such, submissions do not need to handle them in any special way.

• I fear that this is far too vague, and probably too difficult. – Joe Aug 21 '16 at 2:10
• Maybe a test-battery tag? – Rohan Jhunjhunwala Aug 21 '16 at 2:19
• Yes, seeing the proposed test cases would give a much better idea of whether this is realistic. – trichoplax Aug 21 '16 at 7:40
• I hereby encourage any member of the community to take over this challenge. I have no experience with graphical I/O, and I don't foresee myself gaining any in the near future. I doubt that I can write a reasonable spec; also, I'm just not that interested in it anymore. – Joe Sep 5 '16 at 20:37