459
\$\begingroup\$

What is the Sandbox?

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

To post to the Sandbox, scroll to the bottom of this page or click on the "Add Proposal" link below, and click "Answer This Question". Click "OK" when it asks if you really want to add another answer. Write your challenge just as you would when actually posting it. You may also add some notes about specific things you would like to clarify before posting it. Other users will help you improve your challenge by rating and discussing it. When you think your challenge is ready for the public, go ahead and post it, replace the post here with a link to the challenge and delete it.

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

The Sandbox works best if you sort posts by "active".

Add Proposal

Search the Sandbox

Browse your pending proposals

Get the Sandbox Viewer to view the sandbox more easily

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

\$\endgroup\$
  • \$\begingroup\$ How are tags added to questions? \$\endgroup\$ – guest271314 Jan 9 at 7:51
  • \$\begingroup\$ @guest271314 You can use this markup to create a tag in a draft: [tag:code-golf] \$\endgroup\$ – DJMcMayhem Aug 29 at 15:19
  • \$\begingroup\$ Why no featured anymore? Can't we have it auto-added or something? \$\endgroup\$ – JL2210 Sep 26 at 15:57
  • 1
    \$\begingroup\$ @JL2210 We now have a permanent info box that links to the Sandbox, so the featured tag isn't necessary \$\endgroup\$ – caird coinheringaahing Sep 29 at 13:43
  • \$\begingroup\$ I think the sentence 'replace the post here with a link to the challenge and delete it' may specify that the deletion should be done immediately . \$\endgroup\$ – AZTECCO Oct 5 at 19:39

2566 Answers 2566

0
\$\begingroup\$

There is a nice task One Ring to rule them all. One String to contain them all. But rule define a string as a linear buffer. A linear buffer is not a Ring :)

My suggestion is:

  • create a new task with title "One Ring to rule them all. One Ring to bring them all"
  • add link to old task in the body of the new task
  • modify an Objective: Output a String which contains every positive integer strictly below 1000 and the String is a Ring.
\$\endgroup\$
  • 1
    \$\begingroup\$ It would be a dupe \$\endgroup\$ – Peter Taylor Sep 28 '18 at 11:32
  • \$\begingroup\$ ok. thanks, Peter \$\endgroup\$ – mazzy Sep 28 '18 at 11:52
  • \$\begingroup\$ I've been thinking about it - no, It is not a duplicate. Main different: 0, 00, 000, ... are different elements in a de Bruijn sequence and same element in a Ring of numbers. This moment make golfed algoritms different. \$\endgroup\$ – mazzy Oct 1 '18 at 8:08
  • 1
    \$\begingroup\$ In a de Bruijn sequence containing all 3-digit sequences over 0-9, 000 is an element but 0 and 00 are not. Moreover, if the ring contains 100, 200, etc. then it must contain 00 at least nine times. See my comment of Nov 5 '13 at 11:28 on /q/13088. \$\endgroup\$ – Peter Taylor Oct 1 '18 at 9:51
0
\$\begingroup\$

Make words (need a better title)

Write a program or function that takes a string and an integer \$ n \$ as input and outputs all the \$n\$-letter words formed using only the letters in the string.

Notes:

The input string will have only small alphabets \$a-z\$.

All the letters in the input string will be unique.

Input integer will be positive.

Winner: This is code-golf so shortest code wins. (Fastest algorithm will also be good in this right?)

Examples:

input:"abcd",5
output: "aaaaa","aaaab","aaaac",.....,"ddddc","ddddd"

P.S. The output does not have to be sorted.

Any input and output format will do as long as its distinguishable.

Example:

input: abcd,5 (ok)
       abcd 5 (ok)
       abcd5 (not allowed)
output: ["aaaaa","aaaab",.... (ok)
        "aaaaa","aaaab",.... (ok)
        "aaaaa""aaaab""aaaac"..... (ok)
        aaaaa aaaab aaaac ..... (ok)
        aaaaaaaaabaaaac...... (not allowed)
\$\endgroup\$
  • \$\begingroup\$ Related, related, related. \$\endgroup\$ – Arnauld Oct 1 '18 at 10:18
  • 3
    \$\begingroup\$ For this kind of challenge, neither fastest-algorithm nor fastest-code should be used. For the first one: all answers are likely to have the same time complexity. For the 2nd one: ~99% of CPU time is going to be spent printing the results. \$\endgroup\$ – Arnauld Oct 1 '18 at 10:24
  • \$\begingroup\$ BTW: this is basically count from \$0\$ to \$b^n\$ in custom base \$b\$, which may have already been covered in some other challenge. I failed to find one, though. \$\endgroup\$ – Arnauld Oct 1 '18 at 11:24
  • \$\begingroup\$ It's product in python: docs.python.org/2/library/itertools.html (May help giving a title to the challenge, or searching for duplicates) \$\endgroup\$ – Nathan Merrill Oct 2 '18 at 2:54
  • 1
    \$\begingroup\$ @Arnauld It's mostly a duplicate of Cartesian product of a list with itself n times. The only difference is that builtins aren't allowed in that linked challenge, which is probably better since this is 3 bytes in 05AB1E due to an optional parameters requiring an explicit input and even just 1 byte in Jelly (not sure how to pretty-print it as a list in the footer..). \$\endgroup\$ – Kevin Cruijssen Oct 3 '18 at 8:13
0
\$\begingroup\$

Golf A Programming Language


Code golf languages are languages built to complete programming challenges in few lines of code. Instead of creating a code golf language, you will be creating an interpreter for a programming language in as few bytes as possible.

Scoring

As you are not creating a code golf language, instead your score will be based on the number of bytes in the interpreter.

I/O

You may provide a program as input to your interpreter as input using any standard input method

Output provided by a program in your language may be passed on through your interpereter using any standard output method

Tasks

You must write a program to solve each task in the language you created:

  • Hello World - Output the string "Hello World"

  • Fizz Buzz - List numbers from 1 to 100 replacing multiples of 3 with Fizz, 5 with Buzz, and 15 with FizzBuzz

  • Prime Check - Check if a given number is prime

Loopholes

Your programming language must be implemented yourself. Using builtin functions such as Javascript's eval or CHIQRSX9+'s I on input makes this not very interesting.

\$\endgroup\$
  • \$\begingroup\$ This is too broad, as defining "interpreter" is pretty impossible. The only way this is viable is if you specify the language to be interpreted. \$\endgroup\$ – Nathan Merrill Oct 2 '18 at 2:48
  • \$\begingroup\$ @NathanMerrill Anything can be built for the interpreter. It could have 3 instructions, one for each challenge, but that could mean the interpreter increases length because it has the tasks built in. It might need more tasks, 3 tasks might mean building an actual language takes more code than just hardcoding 3 functions \$\endgroup\$ – pfg Oct 2 '18 at 3:39
  • 1
    \$\begingroup\$ Writing a general purpose language will take more characters than providing built-ins for those. In essence, you're looking for a program that returns a program that takes 1 of 3 characters and evals it. You are correct that eval makes this not interesting, but it's also the best way. Unless you make the language significantly harder (and specify the input required to do each of the tasks), I don't see this being interesting. \$\endgroup\$ – Nathan Merrill Oct 2 '18 at 3:44
  • 3
    \$\begingroup\$ codegolf.stackexchange.com/questions/111278/… \$\endgroup\$ – user202729 Oct 2 '18 at 5:27
0
\$\begingroup\$

Eeny Meeny Miny Moe

Inspired (somewhat) by this question:

Where should I stand to be captain of my team?

Introduction

The childhood song Eeny, meeny, miny, moe was often used to select who was a captain when playing some game. Everyone on one team would stand in a line and someone would point at the first person in the line. Although there are several variations, where I grew up, they would sing:

Eeny, meeny, miny, moe,
Catch a tiger by the toe.
If he hollers, let him go,
Eeny, meeny, miny, moe.

adding to the traditional:

My mother told me to pick the very best one and you are not it.

As we sung each word, we pointed at the next person in line, then (if the rhyme wasn't over yet) we would continue the rhyme and start over at the beginning of the line. The person being pointed to when the final "it" was sung would be removed from the line, eliminating them from being captain. Then the rhyme would start over at the beginning of the line to remove the next person. This continued until only one person was left, and that person would be captain.

It didn't take long for me to recognize that if there were two people left (or if we started with just two people), it seemed like the second person would always win. Studying this for a bit I realized that since there are 35 beats this would always happen. I further figured out if there are 3 people, the third would win. So I wondered: could I chart it out for any number? Can I create a formula for it?

Challenge:

Write a program, function or (etc. as standard) where given input of an integer number of starting children greater than one, output what starting child number will be the winner, and where I need to stand so that I can be captain!

Examples:

Input        Output
  2             2
  3             3
4,5,6or7        4
 8 or 9         5
  10            6
11,12or13       7
  14            8
  15            9
  16           10
17,18,19or20   11 

Winner for each language is that with the least number of bytes. And of course, standard loopholes and all that legal jazz are not allowed as is typically expected in these challenges.

\$\endgroup\$
  • 1
    \$\begingroup\$ aka, the Josephus problem, possibly duplicate \$\endgroup\$ – ngn Oct 2 '18 at 19:49
  • \$\begingroup\$ @ngn Wow! I learn something new every day! Is this a duplicate, then? \$\endgroup\$ – Keeta Oct 2 '18 at 19:50
  • \$\begingroup\$ I'm not sure, yours is a special case for k=35 \$\endgroup\$ – ngn Oct 2 '18 at 19:52
  • \$\begingroup\$ by the way, you may find this video enlightening :) \$\endgroup\$ – ngn Oct 2 '18 at 19:53
  • \$\begingroup\$ Different from listed duplicate in several ways. Mine restarts at the beginning after each elimination (which really makes it questionable whether it is Josephus or not). Mine requires only one input. Mine is a firm case for k and mine has a cool backstory :) \$\endgroup\$ – Keeta Oct 3 '18 at 12:16
0
\$\begingroup\$

Permutations to the nines

This question is based on an unresolved inquiry which began at Permutations without recursive function call and was followed up at How to improve efficiency of algorithm which generates next lexicographic permutation? (TL;DR), after finding help removing duplicate numbers at Most efficient method to check for range of numbers within number without duplicates, where after performing arithmetic by hand found that for an array having length less than or equal to 9, if we ignore the value held at each index of the initial array and instead convert the indexes to a whole number, the next lexicographic permutation can be determined by adding 9 to the current index as number until a whole number, e.g., [1,2,3] // 123 1-based index or 23 0-based index is reached that satisfies two the conditions

  • Contains only the numbers of the indexes of the original array

  • Does not contain any duplicate numbers

e.g., 123+9=132 // "abc" -> "acb" 132-9=123 // "acb" -> "abc"; the graph for "abcd" is

[9,81,18,81,9,702,9,171,27,72,18,693,18,72,27,171,9,702,9,81,18,81,9]

which does not appear to be linear.

As the linked answers disclose, adding 9 to a whole number is not the most efficient method of determining the next lexicographic permutation, and what found independently by hand has been found by others, consider OEIS A217626

A217626 First differences of A215940, or first differences of permutations of (0,1,2,...,m-1) reading them as decimal numbers, divided by 9 (with 10>=m, and m! > n).

1, 9, 2, 9, 1, 78, 1, 19, 3, 8, 2, 77, 2, 8, 3, 19, 1, 78, 1, 9, 2, 9, 1, 657, 1, 9, 2, 9, 1, 178, 1, 29, 4, 7, 3, 66, 2, 18, 4, 18, 2, 67, 1, 19, 3, 8, 2, 646, 1, 19, 3, 8, 2, 67, 1, 29, 4, 7, 3, 176, 3, 7, 4, 29, 1, 67, 2, 8, 3, 19, 1, 646, 2, 8, 3, 19, 1

Also of interest is that the graph of the specific multiples of 9 to derive all lexicographic permutations of a set can be found by computing only half 1/2 of the total permutations +1, as the declination slope is identical to the inclination slope of multiples of 9, for example, given an input of the string "abc" or array ["a","b","c"], we only need to reach the inverted peak of the graph, that is bca 120 3 18, where the previously calculated values can be reversed and added to the current whole number, 120, to generate the remainder of the lexicographic permutations

abc 012 0
acb 021 1 9
bac 102 2 81
bca 120 3 18
cab 201 4 81
cba 210 5 9

 /\/\
/    \

Errata

This challenge is not to determine the most efficient algorithm to calculate permutation 9!, as, again, adding 9 to a whole number to reach that goal can be outperformed by swapping values or other method, as demonstrated at the accepted at the first SO link above.

This challenge is to derive the most efficient method of determining the next lexicographic permutation by calculating the next multiple of 9 that meets the above listed criteria, preferably directly using math, if possible.

The reason am posting this question here and now is because was reminded by the graph of the peaks (particularly the third item) in this question Different combinations possible

Just to give a visual example, they are the following:

   /\     /\      /\/\
/\/  \   /  \/\  /    \

that in spite of performing various calculations using the index of the !n within the resulting array of permutations, e.g.,

var n = N = 1234;
var res = [9,81,18,81,9,702,9,171,27,72,18,693,18,72,27,171,9,702,9,81,18,81,9].map((x)=>n=n+x);
// try to determine the rate of growth
var j = res.map((x)=>x/N);

console.log(res, j);

var tryStuff = 1234*(4321/1234);
console.log(tryStuff, (4321/1234));

am still vexed by and have not been able to independently determine the mathematical formula to derive the next lexicographic permutation directly without adding 9 multiple times to reach the required number; or if that is even mathematically possible for any input set from 2! through 9!. That is, this code

function getNextLexicographicPermutation(arr) {

  for (var l = 1, i = k = arr.length; l < i; k *= l++);

  function checkDigits(min, max, n) {
    var digits = 0;
    while (n) {
      d = (n % 10);
      n = n / 10 >> 0;

      if (d < min || d > max || (digits & (1 << d)))
        return false;
      else
        digits |= 1 << d;
    }
    return true;
  }

  var len = arr.length,
    idx = arr.map(function(_, index) {
      return index
    }),
    p = 9,
    min = 0,
    max = len - 1,
    last = Number(idx.slice().reverse().join("")),
    curr = Number(idx.join("")),
    res = [curr],
    diff = [],
    result = [],
    next, times = 0;

  while (res.length < (k / 2) + 1) {
    ++times;
    next = (curr += p);
    if (checkDigits(min, max, next)) res[res.length] = next;
    curr = next;
  };

  for (var i = 0; i < res.length; i++) {
    var item = res[i];
    item = String(item).split("").map(Number);
    item = (item.length < arr.length ? [0].concat(item) : item)
      .map(function(index) {
        return arr[index]
      }).filter(Boolean);
    result.push(item)
  }

  res.reduce(function(a, b) {
    diff.push(b - a);
    return b
  });

  for (var i = 0, curr = res[res.length - 1], n = diff.length - 2; result.length < k; i++, n--) {
    curr = curr + diff[n];
    result.push(
      String(curr).split("")
      .map(function(index) {
        return arr[index]
      })
    );
  }
  return [result, diff, res, times];
}

var arr = ["a", "b", "c", "d"];

console.log(getNextLexicographicPermutation(arr));

which generates the second half-1 of the permutations from the first half+1 of the permutations checks if the next whole number meets the necessary conditions 210 times for an input array of ["a","b","c","d"] which has a resulting .length of 24. Ideally, we want to generate 24 lexicographic permutations using only 12 or 13 checks; or no checks at all, by determining the irrational number or other mathematical algorithm which will directly calculate (or approximate close enough to determine the next multiple of 9) the next whole number which meets the necessary criteria.

Kindly disregard the length of this post, as am trying to include as much information as consider relevant to the inquiry.

Rules

This challenge must use the number 9 (addition, multiplication, division, other mathematical operation) to determine the next lexicographic permutation using the indexes of the current lexicographic permutation converted to a whole number, ideally, in a single operation, else in the least amount of operations necessary to achieve the expected result.

Again, this challenge is not asking how to code the most efficient code which determines the next lexicographic permutation, but what is the most efficient approach is using only the number 9 and math to generate the permutations.

Since we can get the first and last lexicographic permutations by reversing the indexes of the input array, that is not counted as an operation within the program.

Input

An array or sting having .length less than or equal to 9!.

Output

Lexicographically sorted array of permutations of input.

Task

Remaining within the Rules above, determine a mathematical algorithm which directly generates the next lexicographic permutation using only the current indexes of the original input or current permutation. Ideally, directly, without having to add 9 in multiple operations until the listed criteria is met, that is, we want a single algorithm to calculate that we need to add 81 to 132 to get the sum 213 and add 702 to 321 to get the sum 1023 and so forth. Explain the math in the algorithm. Note: The requirement might not be possible. If that is the case, explain why.

\$\endgroup\$
  • 1
    \$\begingroup\$ 1. As I commented elsewhere, it's hard to separate the core challenge from the fluff. 2. I assume there's a typo in the "Input" section, because an array of the permutations of 9! elements would take more memory than is physically possible in this universe. \$\endgroup\$ – Peter Taylor Oct 4 '18 at 21:37
  • \$\begingroup\$ @PeterTaylor Kindly indicate specifically what content in the question that you are referring to. From perspective here, there is no "fluff" in the question. No, there is no typo in the "Input" section. The algorithm MUST be true for 9!->362880 if true for 4!->24. We can check the result of the algorithm by incremental sections and by hand. Simplified core challenge: Find the multiple of 9 required to precisely equal the next p lexicographic permutation (as a whole number) from current p number in least math computations. \$\endgroup\$ – guest271314 Oct 4 '18 at 22:06
  • \$\begingroup\$ @PeterTaylor E.g., if we have input ['a','b','c'] we ignore values and "see" 12, 012 (or, as described at this question for simplification 1-based indexing 123). The next lexicographic permutation is one computation 123+(9*1)=132 from we can "see" ['a','c','b']. In JavaScript we could even use Math.pow(9,1), but that would be a false-positive for a method or pattern to use, because the next multiple is 132+(9*9)=213 (we can "see" ['b','a','c']). How to get from 132 to 213 without adding 9 nines times (Task: least mathematical computations in this step) to 132? \$\endgroup\$ – guest271314 Oct 4 '18 at 22:33
  • \$\begingroup\$ Should we take an array of items (['a','b','c']), an array of indices ([1,2,3]) or its value converted to decimal (123) as input? And what should be the output -- 132, ['1','3','2'] or 9? \$\endgroup\$ – user202729 Oct 5 '18 at 13:08
  • \$\begingroup\$ @user202729 The input is a decimal derived from the first lexicographic permutation or an array of items from which the decimal will be derived; e.g., 123 from ['a','b','c'], or 123456789 (1-based indexing) or 012345678 (0-based indexing) derived from ["a","b","c","d","e","f","g","h","i" ]. The maximum number is the reverse order of the decimal number, 987654321 or 876543210, which is the last lexicographic permutation (as a decimal number) of the input number or array [8,7,6,5,4,3,2,1,0] (0-based) or [9,8,7,6,5,4,3,2,1] (1-based). \$\endgroup\$ – guest271314 Oct 5 '18 at 20:48
  • \$\begingroup\$ @user202729 We can derive all lexicographic permutations of input up to 9! by adding 9 to the first lexicographic permutation as decimal and following the two conditions at the question; that is, by adding 9 to the initial decimal number where no duplicate numbers are found within the resulting number and each number is found within the original decimal number. Example "abc"->curr=123->123+9=132->"acb"; curr becomes 132. We are trying to reduce the number of additions to meet the two conditions by creating a formula to determine the precise number of 9's to add to curr. \$\endgroup\$ – guest271314 Oct 5 '18 at 21:09
  • \$\begingroup\$ @user202729 Is the question clear to you now? \$\endgroup\$ – guest271314 Oct 5 '18 at 21:43
  • \$\begingroup\$ @user202729 The output is n<=9! permutations. We can already achieve that by the code at the question. However the challenge is to reduce the mathematical steps required to reach the result consider "How to get from 132 to 213 without adding 9 nines times (Task: least mathematical computations in this step) to 132". When curr is 132, we do not necessarily know that we will have to add 9 to 132 nine times (81) to reach the sum 213. We find that out now by nine computations, adding. The challenge is to reach the sum 213 using what we have in less than nine computations. \$\endgroup\$ – guest271314 Oct 5 '18 at 23:27
  • \$\begingroup\$ @user202729 There are other mathematical relationships between the indexes of the lexicographically sorted permutations. For example, if we have the input ['a','b','c'] or "abc", when we ignore the values, using 1-based indexing, we can "see" 123 at index 1. 123+90=213 our lexicographically sorted permutation at index 3, 132 at index 2 is 132+90=231; max number is always input reversed. We only need to find 132 (3 operations) to derive all 6 permutations, as the declination slope of [123,132,213] is the reverse order of each number; this relationship differs for 1234. \$\endgroup\$ – guest271314 Oct 5 '18 at 23:46
  • \$\begingroup\$ What is n in that case? /// Consider a specific example. If the input is 132 (1-indexing) what should the output be? \$\endgroup\$ – user202729 Oct 6 '18 at 11:13
  • \$\begingroup\$ @user202729 The output is always n! lexicographic permutations. We already are able to achieve that. Whether the input is 123 or 132 makes no substantial difference here; we "see" that 132 is greater than its constituent parts, 123 and thus know that we are at index 2 (1-indexing), 321 is always the max, and n! is 6. What this challenge is asking is how to use this specific method of determining permutations, that is, adding 9 to the indexes as a whole number until the listed conditions are met, in less mathematical operations that is currently being used - simple addition. \$\endgroup\$ – guest271314 Oct 7 '18 at 16:55
  • \$\begingroup\$ Let me see. So, if 132 is given, the output should be [123,132,213,231,312,321], but with a restriction -- only addition, subtraction, multiplication, and division is allowed. Correct? \$\endgroup\$ – user202729 Oct 7 '18 at 16:59
  • \$\begingroup\$ @user202729 There is no restriction on the mathematical methods which can be used. You can use calculus if that will generate 132 from 123 in the least amount of calculations - using 9 within the calculations. If you can use mathematical relationships between the expected resulting set which uses other numbers, then those methods should be described in detail. The code at the question uses only the number 9 to add to the indexes represented as a whole number, though for some 90 or 711 could be used. The challenge is to use the least number of total math computations. \$\endgroup\$ – guest271314 Oct 7 '18 at 17:05
  • \$\begingroup\$ @user202729 We are trying to generate the next lexicographic permutation using only 1) the current permutation; 2) the maximum possible number (our last permutation); 3) mathematics; as our resources. We begin with a number less than 321 and know that our first permutation must be 123, our last 321, and that between 321 and 123 there are relationships between the numbers which allow us to derive each number that meets our criteria. In the code at the question 9 is suitable to achieve that goal by adding 9 to the number where the sum contains no duplicate and only input numbers. \$\endgroup\$ – guest271314 Oct 7 '18 at 17:12
0
\$\begingroup\$

Qwixx KoTH

In this King of the Hill, our bots will be playing Qwixx. In Qwixx each player will try to get as many points by picking the sum of two dices and marking that number on your own scoresheet. The scoresheet has four rows with different colors (red, yellow, green, blue) with numbers ranging from 2 to 12, where green and blue have the numbers ranked in descending order. You can only mark out a number if you haven't marked a number to the right of it, i.e. after marking red 3 you cannot mark red 2 anymore.

Rules

All of the rules of Qwixx are:

  • Red and yellow have numbers 2, 3, ..., 12, and a padlock.
  • Green and blue have numbers 12, 11, ..., 2, and a padlock.
  • There are 6 dices: red, yellow, green, blue and two white dices.
  • On your turn you will throw all the dices, except for deleted ones.
  • Everyone can mark one number on one color equal to the sum of the white dices. Also if it is not your turn.
  • If it is your turn, you can also mark one number in a specific color, with the sum of one colored dice and one white dice. The colored dice that you pick denotes in which color you need to mark the number.
  • You can only mark numbers to the right of already marked numbers.
  • The last number can only be marked if you have already marked at least 5 numbers before. If you do this, you will automatically also mark the padlock, which will give you extra points. If you do this, that colored dice is not thrown anymore and nobody can mark a number in that color. This dice is deleted from the game (thrown as 0).
  • Only on your turn you need to mark at least one number. If you don't do this, you will automatically mark a penalty box, which costs you 5 points.
  • The amount of points is equal to the sum of 1 up to the amount of marks in each color, minus 5 times the amount of penalties. I.e.: 4 in red, 3 in green and 2 penalties is 4+3+2+1 + 3+2+1 = 16 - 2 * 5 = 6 points.
  • Each turn is simultanouesly.
  • The game ends when the second dice is deleted or when a scoresheet contains 4 penalties.

Tournament

The tournament rules are as follows:

  • The tournament consists of 10000 * amount of bots games.
  • Each game will be played with 5 random bots, in a randomized order.
  • If multiple bots end up with the same amount of points in one game, each bot gets a win.
  • The winner of the tournament is the bot who has the highest win percentage.

Bots

The bot needs to be defined in Python and needs to have two functions:

  • __init__(self, index) with the index in scoresheets, so that you know which scoresheet is yours
  • turn(self, scoresheets, dices, my_turn), with the current scoresheets, the dices of this turn and a boolean being True when it is your turn. This function needs to return a tuple of two tuples containing (color, number) with what your bot wants to mark, where the first tuple is for the white dices, and the second tuple only if its your turn.

The simplest bot can be defined as:

class DoNothing:
    def __init__(self, index):
        return
    def turn(self, scoresheets, dices, my_turn):
        return ([],[])

Which does absolutely nothing.

A randomized bot that tries to always mark something when possible is:

class RandomAllowedCombinations:
    def __init__(self, index):
        self.index = index
        return
    def turn(self, scoresheets, dices, my_turn):
        (any_combs, turn_combs) = scoresheets[self.index].allowed_combinations(my_turn, dices)

        any_comb = []
        if any_combs:
            any_comb = any_combs[random.randint(0, len(any_combs)-1)]

        turn_comb = []
        if my_turn and turn_combs:
            turn_comb = turn_combs[random.randint(0, len(turn_combs)-1)]

        return (any_comb, turn_comb)

This also shows some of the utility functions: you can use scoresheets[self.index].allowed_combinations(my_turn, dices) to check what you can mark with the white dices, and if its your turn with one of the colored dices as well.

Both classes (Dices and Scoresheet) have several utility functions. You can check themselves to improve your bot. Note that Dices also contains the indices for each color. And the value of a dice is 0 if it is deleted (i.e. when someone in the game marked the last number and thus the padlock in one of the previous turns).

Controller

The controller contains 5 example bots. These will not be used in the tournament, unless there are too few participants.

import random
import numpy

### Bots ###
class DoNothing:
    def __init__(self, index):
        return
    def turn(self, scoresheets, d, my_turn):
        return ([],[])

class AlwaysWhitesInRed:
    def __init__(self, index):
        return
    def turn(self, scoresheets, d, my_turn):
        return ((d.red, d.dices[d.white1] + d.dices[d.white2]),[])

class AlwaysBlueOnlyTurn:
    def __init__(self, index):
        return
    def turn(self, scoresheets, d, my_turn):
        return ([],(d.blue, d.dices[d.blue] + d.dices[d.white2]))

class RandomAllowedCombinations:
    def __init__(self, index):
        self.index = index
        return
    def turn(self, scoresheets, dices, my_turn):
        (any_combs, turn_combs) = scoresheets[self.index].allowed_combinations(my_turn, dices)

        any_comb = []
        if any_combs:
            any_comb = any_combs[random.randint(0, len(any_combs)-1)]

        turn_comb = []
        if my_turn and turn_combs:
            turn_comb = turn_combs[random.randint(0, len(turn_combs)-1)]

        return (any_comb, turn_comb)

class RandomButOnlyOwnTurn:
    def __init__(self, index):
        self.index = index
        return
    def turn(self, scoresheets, dices, my_turn):
        (any_combs, turn_combs) = scoresheets[self.index].allowed_combinations(my_turn, dices)

        turn_comb = []
        if my_turn and turn_combs:
            turn_comb = turn_combs[random.randint(0, len(turn_combs)-1)]

        return ([], turn_comb)

### Classes ###
class Dices:
    def __init__(self):
        self.dices = []
        self.deleted = []
        self.red = 0
        self.yellow = 1
        self.green = 2
        self.blue = 3
        self.white1 = 4
        self.white2 = 5
        self.colors = [self.red, self.yellow, self.green, self.blue]
        self.whites = [self.white1, self.white2]
        self.diff_dices = self.colors + self.whites

    def roll_dice(self):
        self.dices = [0,0,0,0,0,0]
        for i in range(6):
            if i not in self.deleted:
                self.dices[i] = random.randint(1, 6)

    def delete_dice(self, color):
        if not color in self.deleted:
            self.deleted.append(color)
        return len(self.deleted) > 1

    def combinations(self):
        combs = [(color, white) for color in self.colors for white in self.whites]

        any_combs = [(color, self.dices[self.white1] + self.dices[self.white2]) for color in self.colors if self.dices[color] >= 1]
        turn_combs = [(color, self.dices[color] + self.dices[white]) for (color, white) in combs if self.dices[color] >= 1]

        return (any_combs, turn_combs)

class Game:
    def __init__(self, bots):
        self.bots = [bots[i](i) for i in range(len(bots))]
        self.scoresheets = [Scoresheet() for i in self.bots]
        self.dices = Dices()
        self.turn_number = 2

    def round(self):
        self.dices.roll_dice()
        (any_combs, turn_combs) = self.dices.combinations()

        finished = False

        for i, bot in enumerate(self.bots):
            my_turn = self.whos_turn() == i
            moves = bot.turn(self.scoresheets, self.dices, my_turn)
            deleted_colors = self.scoresheets[i].mark(moves, my_turn, any_combs, turn_combs, self.dices)
            if deleted_colors:
                finished = finished or any([self.dices.delete_dice(deleted_color) for deleted_color in deleted_colors]) 
            finished = finished or self.scoresheets[i].too_many_penalties()

        self.turn_number += 1

        return finished

    def whos_turn(self):
        return (self.turn_number - 1) % len(self.bots)

    def runGame(self):
        finished = False
        while not finished:
            finished = self.round()
        #for i, scoresheet in enumerate(self.scoresheets):
            #print self.bots[i], scoresheet.values, scoresheet.penalties, scoresheet.points()

class Scoresheet:
    def __init__(self):
        self.red = []
        self.yellow = []
        self.green = []
        self.blue = []
        self.penalties = 0
        self.values = [self.red, self.yellow, self.green, self.blue]

    def points(self):
        points = self.penalties * -5
        for color in self.values:
            points += sum(range(len(color)+1))
        return points

    def allowed_combinations(self, my_turn, dices):
        (any_combs, turn_combs) = dices.combinations()
        any_combs = [(color, number) for (color, number) in any_combs if self.allowed(color, number, any_combs, dices)]
        turn_combs = [(color, number) for (color, number) in turn_combs if self.allowed(color, number, turn_combs, dices)]

        if not my_turn:
            turn_combs = []

        return (list(set(any_combs)), list(set(turn_combs)))

    def allowed(self, color, number, combs, d):
        if color not in d.deleted:
            if (color, number) in combs:
                if color == d.red or color == d.yellow:
                    if not self.values[color] or max(self.values[color]) < number:
                        if number < 12 or self.end_number(color, number, d):
                            return True
                if color == d.green or color == d.blue:
                    if not self.values[color] or min(self.values[color]) > number:
                        if number > 2 or self.end_number(color, number, d):
                            return True
        return False

    def end_number(self, color, number, d):
        if len(self.values[color]) > 5:
            return (number == 2 and (color == d.green or color == d.blue)) or (number == 12 and (color == d.red or color == d.yellow))
        return False

    def mark_one(self, color, number, combs, deleted, d):
        if self.allowed(color, number, combs, d):
            self.values[color].append(number)
            if self.end_number(color, number, d):
                self.values[color].append(0)
                deleted.append(color)
        return deleted

    def mark(self, moves, my_turn, any_combs, turn_combs, d):
        beforePoints = self.points()

        deleted = []
        if moves[0]:
            deleted = self.mark_one(moves[0][0], moves[0][1], any_combs, deleted, d)
        if my_turn and moves[1]:
            deleted = self.mark_one(moves[1][0], moves[1][1], turn_combs, deleted, d)

        if my_turn and beforePoints == self.points():
            self.penalties += 1

        return deleted

    def too_many_penalties(self):
        return self.penalties >= 4

class Qwixx:
    def __init__(self, bots, bots_per_game):
        self.bots = bots
        self.games = [0 for i in range(len(self.bots))]
        self.points = [0 for i in range(len(self.bots))]
        self.wins = [0 for i in range(len(self.bots))]
        self.amountOfGames = len(bots) * 1000
        self.bots_per_game = bots_per_game

    def run_tournament(self):
        for g in range(1, self.amountOfGames + 1):
            bot_indices = numpy.random.choice(range(len(self.bots)), self.bots_per_game, replace=False)
            bots_this_game = [self.bots[i] for i in bot_indices]

            game = Game(bots_this_game)
            game.runGame()

            maxPoints = max([game.scoresheets[i].points() for i in range(len(bot_indices))])
            for bot_index_game, bot_index_total in enumerate(bot_indices):
                points = game.scoresheets[bot_index_game].points()
                self.points[bot_index_total] += points
                self.games[bot_index_total] += 1
                if points == maxPoints:
                    self.wins[bot_index_total] += 1
                    print "GAME", g, "is",  self.wins[bot_index_total], "th win by", self.bots[bot_index_total].__name__

    def tournament(self):
        self.run_tournament()

        win_rates = {i: self.wins[i] / float(self.games[i]) for i in range(len(self.bots))}
        format_result = '{:>30}: {:.4f}  {:>6} {:>8} {:>8}' 
        format_header = '{:>30}: {:>6}  {:>6} {:>8} {:>8}' 
        print(format_header.format('Name', 'Win %', 'Wins', 'Games', 'Points'))
        for j, i in enumerate(sorted(win_rates, key=lambda i: win_rates[i], reverse=True)):
            print(format_result.format(self.bots[i].__name__, win_rates[i], self.wins[i], self.games[i], self.points[i]))

### List of all bots ###
all_bots = [DoNothing, BadRandom, RandomAllowedCombinations, Random50, RandomButOnlyOwnTurn]

### Run tournament ###
Qwixx(all_bots, 5).tournament()

Sandbox

  • If someone can check my Python programming capabilities that would be great. I'm no native Python programmer.
  • There are quite some rules. Maybe I should simplify it? These are the official rules, but for example I could change that even on your turn you can only move once instead of twice.
  • This is my first challenge, so any feedback is welcome.
  • Note that I have not yet tested my controller thoroughly, I will do this before posting it as an actual challenge.
\$\endgroup\$
  • 1
    \$\begingroup\$ 1. Simplification of the rules is definitely needed. This post is hard to understand and even harder to come up with strategies about. Under "Rules", I'd immediately start explaining the actions bots can perform and their consequenses. 2. Why are there two types of turns (only-white turn, vs color turn)? How does this affect strategies? 3. What's the purpose of marking the last box to prevent other players? How does this affect strategies? 4. I don't understand the scoring, please expound. \$\endgroup\$ – Nathan Merrill Oct 8 '18 at 16:56
  • \$\begingroup\$ 1. It's not entirely clear to me whether on my turn I can choose to make my "colour mark" before my "white mark" if they're on the same colour. 2. Dice is an irregular noun in English: the singular is die and the plural is dice. 3. 10000 * number of bots games is a lot, so it's going to be slow to run the tournament, but at the same time with 13 bots it's too few to run every possible combination once. This might need a more complicated tournament structure with elimination rounds. \$\endgroup\$ – Peter Taylor Oct 11 '18 at 14:20
0
\$\begingroup\$

The goal of this challenge is to make an interpreted language that can print anything! The format of the language needs to be

[command eg: print] [args];

You have to use regex, even though it is not the typical way to write a language, to avoid people finding loopholes. Your interpreter also needs to ask for a file to open to interpret; example input file prompt:"File to interpret: "

Some tests to try:

print Hello World;


print This is a very very very very very long test;

ktrgjkfgjk;

print hi

If your interpreter runs these tests correctly, you can submit your interpreter.

Notes:

Do not just cut off the print!

If the command given does not exist, or if semicolon not present, print "Error"

This is so the lowest byte count + working code wins!

\$\endgroup\$
  • 1
    \$\begingroup\$ I recommend some more explanation of the "File: " part \$\endgroup\$ – trichoplax Oct 7 '18 at 19:06
  • \$\begingroup\$ @trichoplax Thats the input file prompt \$\endgroup\$ – Menotdan Oct 7 '18 at 19:09
  • \$\begingroup\$ @trichoplax, well then i wont accept those answers, hold on let me edit \$\endgroup\$ – Menotdan Oct 7 '18 at 19:11
  • \$\begingroup\$ Read it again: it says: The format of the language needs to be [command eg: print] [args]; <--- note semicolon It was just a typo (I didnt type the ;) \$\endgroup\$ – Menotdan Oct 7 '18 at 19:14
  • \$\begingroup\$ The problem with saying "do not just cut off the print" is that there may be other ways of achieving the same thing, then the challenge just becomes a long list of things which are banned. You can avoid this by trying to set the requirements and inputs in a way that doesn't have these loopholes. \$\endgroup\$ – trichoplax Oct 7 '18 at 19:16
  • \$\begingroup\$ @trichoplax Ok i only want the print though \$\endgroup\$ – Menotdan Oct 7 '18 at 19:20
  • 2
    \$\begingroup\$ Writing challenges can be tricky, and people have posted advice on meta that can help: things to avoid when writing challenges and things to consider when creating a challenge \$\endgroup\$ – trichoplax Oct 7 '18 at 19:21
  • 1
    \$\begingroup\$ If you only want print, then is there a difference between this challenge and "remove the first 6 characters and the last character from this string"? If you don't want people to solve it that way, you could consider what they need to do when the input is not a valid print command, and specify that in that case it should do something different (like not output anything). \$\endgroup\$ – trichoplax Oct 7 '18 at 19:24
  • \$\begingroup\$ @trichoplax Yes, i didnt think of that \$\endgroup\$ – Menotdan Oct 7 '18 at 19:25
  • \$\begingroup\$ "do not just cut off the print" is an example of a non-observable requirement. Here's a good explanation of why that can be a problem \$\endgroup\$ – trichoplax Oct 7 '18 at 19:26
  • \$\begingroup\$ Here, new update \$\endgroup\$ – Menotdan Oct 7 '18 at 19:31
  • \$\begingroup\$ I hope all the comments don't put you off - writing challenges is difficult, but we get much more answers than challenges so more challenges are needed. I had lots of useful feedback from this community when I started out. \$\endgroup\$ – trichoplax Oct 7 '18 at 19:32
  • \$\begingroup\$ Is this better @trichoplax and where else can i improve \$\endgroup\$ – Menotdan Oct 7 '18 at 19:36
  • \$\begingroup\$ Let us continue this discussion in chat. \$\endgroup\$ – Menotdan Oct 7 '18 at 19:37
  • 1
    \$\begingroup\$ you have to use regex ... , to avoid people finding loopholes This seems very arbitrairly restricting. What about languages without regexes? You haven't actually said what the outputs of the test are. And what exactly is the program meant to have as input? I recommend a string input instead of messing around with files \$\endgroup\$ – Jo King Oct 8 '18 at 12:35
0
\$\begingroup\$

Roulette Bots II

Last week I posted Roulette Bots, which was a lot of fun. I think the basic format has potential to be even more interesting, so I've been shopping some tweaks in my head and I'd like to hear feedback before I give it another shot. In a nutshell, the first iteration of the game was as follows:

Everyone starts with 100 hp. Each round, 2 players are chosen at random from the pool of contestants who have not yet competed in that round. Both players pick a number between 0 and their current hp, and reveal those numbers at the same time. The player who chose the lower number immediately dies. The other player subtracts their chosen number from their remaining hp and goes on to the next round.

From the bracket of contestants, 2 are chosen at random. They face off, and one or both of them dies. A player dies if:

  1. They choose a number smaller than that of their opponent
  2. Their hp drops to or below zero
  3. They tie three times in a row with their opponent

In the case of ties, both players simply generate new numbers, up to 3 times. After the faceoff, the survivor (if any) is moved to the pool for the next round, and the process repeats until we have exhausted the current round pool. If there is an odd number in the pool, then the odd one out moves on to the next round for free.

Players were given as input their own hp, and their opponent's complete betting history for that round. The idea being that players must balance resource consumption and long-term performance against the danger of dying right now if they don't bid high enough.

There are two things I'd like feedback on:

  1. The minimal set of restrictions on user submissions required to make an interesting game without limiting creativity
  2. Format tweaks that will allow for more creativity within the scope of the rules

The rule set I ended up on for the last game was that you were not allowed to take any action that unambiguously identified your opponent. This was for the purpose of avoiding things like players simply reading the stack to figure out exactly who their opponent was, since then you can simply simulate your opponent and more or less guarantee a win. While clever, it's doesn't really fit the spirit of the game. So the first question is whether or not there is a less restrictive rule that could be applied, or if someone can see a glaring loophole in that rule which would allow for game-breaking behavior in future versions of a similar game.

On the subject of format tweaks, the biggest issue I found with the game was that with a relatively small pool of contestants, very little history was actually generated and so bots that tried to use history to predict opponent guesses fared poorly overall. The first tweak I had in mind was to bootstrap a very large (256 or 512, maybe) initial tournament by random resampling of existing bots so that there would be many rounds and a good history pool to work with by the end of it.

Coupled with the larger pool, I intend to change the scoring system to reward longevity, to encourage more careful resource management, as compared to the previous game which rewarded just living through the first round. Something like making participating in the nth rounds worth n points, so that a player which survives to the nth round gets n(n-1)/2 points total. This puts more stringent constraints on resource management, since you need to survive a lot of rounds to do well. I'd probably bump the starting hp up to 1000, so that there is a bit more room to refine bets. and to make ties even less likely.

Second, there were a couple of attempts to make teams of bots that communicated via betting history in order to feed easy wins to one of them. I like the idea, but but because of the limited options presented by betting history they didn't fare very well. I am considering having bots exchange a "greeting" before each fight - a string or integer which they send to their opponent before battling, which could be used to identify teammates or clones of yourself. Does it add enough possibilities to gameplay to be worth the extra effort? Since with a resampled population you would likely be competing with yourself fairly regularly, having a way to recognize yourself (while at the same time avoiding others being able to recognize you from your greeting) seems like it could be interesting, but I worry that it will just degenerate into people updating their greeting at the last second to avoid other people using them, which would make it pointless to use the greeting to recognize opponents and make a lot of work for me. Can anyone suggest a good way to handle this? I want a way for people to recognize an opponent as probably (but not certainly) friendly without making it a game of "who updates last".

Feedback on the proposed gameplay tweaks, or ideas for others that I have not considered, would be appreciated!

\$\endgroup\$
  • \$\begingroup\$ Please do not allow the "feed" strategy. We want all of the bots to be competitive, and the feeder bots aren't competitive, and creates an unfair advantage to individual bots (hmm...I wonder who will win 3v1). I also am not a fan of "send a message" actions: They either don't work or they make abuse possible. (The only exception is if you are making a team-based KotH) Scoring based on longevity is a good idea. If you want a longer history, you can also do a lives-based mechanic where a player has 3 lives. If they choose the lower number 3 times, then they are out of the tournament. \$\endgroup\$ – Nathan Merrill Oct 10 '18 at 14:55
  • \$\begingroup\$ @NathanMerrill the idea for the feeding was that if I have to have multiple copies of each bot in the tournament to get a large pool, then it would be useful to recognize yourself. By default, you will always have "teammates" as long as resampling happens. But I understand the objection. How would lives work, practically? If a bot bids lower, how would I handle that? Ignore the result up to 3 times, and just let them through to the next round without cost to either player? \$\endgroup\$ – KBriggs Oct 10 '18 at 15:32
  • \$\begingroup\$ Oh, I like the idea of feeding copies of your bot. Perhaps giving them a single boolean variable that indicates if it's a clone or not (or something along those lines?). If both both Bot A and B have multiple lives, they would both have their HP removed, but the one that bid lower would have a life removed. Perhaps "life" is the wrong term here: Maybe they get a "strike", and 3 strikes and you are out. \$\endgroup\$ – Nathan Merrill Oct 10 '18 at 15:36
  • 1
    \$\begingroup\$ Actually! If you have multiple clones of a bot, there's an easier solution than a 3-strike system: Simply give the opponent the entire history of all of the clones. \$\endgroup\$ – Nathan Merrill Oct 10 '18 at 15:39
  • \$\begingroup\$ I think if I used the 3 strike system what would happen is that everyone would just bid 0 twice in a row to get into the later rounds with full hp and go from there. Realistically I can't stop the feeding strategy, since you can use betting history to set up a recognizable pattern, so I think it's better to build it into the game somehow. Simply telling people if it's a clone is an option, but then it would just advance one to the next round for free without generating a meaningful bid history data point, so why have the clones in the first place? The entire history of clones is a neat idea... \$\endgroup\$ – KBriggs Oct 10 '18 at 15:49
  • \$\begingroup\$ You tell people if they are playing against their own clone. There's not like an "original bot" or a "clone bot". You simply have a variable that is true if it is Bot 1 vs Bot 1 and false if it is Bot 1 vs Bot 2. You are right that there are no systematic ways to stop feeding, but we have rules against that on SE, and so you can use human judgement to disallow those bots. \$\endgroup\$ – Nathan Merrill Oct 10 '18 at 15:58
  • \$\begingroup\$ I know what you mean. But if I tell them that, then they get to advance deterministically with a bet of 1, which is not a useful data point for anyone else predicting their behavior. I would like to find a solution that forces at least a meaningful bet (or that they have to take the risk of mistaken identity to make the 1-bet). If they know for certain they are facing a clone, then there is no value to having clones at all, since their purpose was to make a longer tournament with more history to use in predictions. But I realize as I say this that the "message passing" idea doesn't work either \$\endgroup\$ – KBriggs Oct 10 '18 at 16:01
  • \$\begingroup\$ Yeah. Perhaps you setup the tournament so that clones never actually fight each other. These battles aren't interesting, and only hurt the bot that randomly got assigned itself. The existence of clones would solely be to have a longer history. \$\endgroup\$ – Nathan Merrill Oct 10 '18 at 16:26
  • 1
    \$\begingroup\$ The only really sound way to avoid the who updates last problem is to host it in such a way that people can't see their competitors' code - i.e. somewhere other than PPCG. On this site you'll always have people special-casing specific opponents. \$\endgroup\$ – Peter Taylor Oct 11 '18 at 11:54
  • \$\begingroup\$ @PeterTaylor probably true. Perhaps I could collect submissions by some other means and just ask players to put a placeholder answer which they can edit with code after the deadline. Would that be allowed? I'd have to keep the controller private, and maybe provide a suite of unit tests that entries should pass before submission. \$\endgroup\$ – KBriggs Oct 11 '18 at 15:16
  • \$\begingroup\$ Something vaguely similar has been done once (a Kolmogorov-complexity question where OP asked people to post a hash of their code, and then after the deadline to post their actual code, so that people couldn't just port someone else's answer to a golfier language), but it's a lot of hassle. Really when you're having to fight the site's design that much, you may as well not bother and just accept that some challenges don't work here. \$\endgroup\$ – Peter Taylor Oct 11 '18 at 15:23
  • \$\begingroup\$ Looking at what happened with your previous challenge, though, I would suggest requiring that answers be self-contained so that the deletion of a function defined in someone else's answer won't break them. \$\endgroup\$ – Peter Taylor Oct 11 '18 at 15:24
  • \$\begingroup\$ @PeterTaylor fair enough, that does seem like a lot of unnecessary work. I'll shop the format a bit more and see if I can come up with something a little simpler. Disallowing interaction between entries is certainly doable, but having people post lat-second updates will always be a problem, I think. \$\endgroup\$ – KBriggs Oct 11 '18 at 15:24
0
\$\begingroup\$

Is it a valid snooker break?

In snooker, the objective is to score as many points as possible by potting two types of balls: red balls, 15 of them, each valued 1 point, and colour balls, 6 of them, valued 2, 3, 4, 5, 6 and 7 points. A break is a sequence of potted balls. The balls must be potted in a predetermined order: the break must start with potting a red ball, then a colour ball and continued with alternating in potting red and colour balls until all of the red balls are potted, then potting colour balls in ascending order of their values (if all of the red balls have already been potted, start with the colour ball with the lowest value). However, if a free ball is declared after an opponent's foul, the break may start with any ball, replacing the ball that should be usually potted first (red if some red balls are still on the table, colour with the lowest value if all reds are potted).

Your task is to determine if the given sequence of balls adheres to the rules mentioned above.

Input

A list of integers representing values of snooker balls. The list will not be empty.

Output

A truthy value if the list is a valid snooker break and falsey if it isn't.

Test cases

Truthy:

6
1,7
2,5
2,3,4
1,5,1,5,1
1,3,1,5,1,4
6,4,5
5,2,1,4,1,6,1,6
1,6,2,3,4,5,6,7
3,2,3,4,5,6,7
4,4,1
5,6,1,7
1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,2,3,4,5,6,7 //"maximum break"
7,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,2,3,4,5,6,7

Falsey:

1,1
4,4,4
4,2,3,1
1,2,3
5,1,7,1
2,5,6,7 //2 is already off the table
5,4,2,3
1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,2,3,4,5,6,7     //one red too many
7,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,2,3,4,5,6,7 //as well as here

To sandbox:

I am thinking about including lists with values out of range of snooker balls' values (less than 1 or greater than 7) in which cases the result should be falsey. As this is a decision problem, I think that these cases should be covered as well.

\$\endgroup\$
  • \$\begingroup\$ Maybe you can let the submissions assume that only a list of [1-7]s are inputted. This would be more flexible for the submissions to do. \$\endgroup\$ – Shieru Asakoto Oct 12 '18 at 7:48
0
\$\begingroup\$

Implement JavaScript's Abstract Equality Comparison Algorithm.

Background

As many know, JavaScript has quite confusing equality rules and it's generally recommended to use === instead to avoid the weird corner cases that come with using ==.

The logic behind the == operator is documented as "The Abstract Equality Comparison Algorithm" in the ECMAScript specification. For this particular question we will be implementing from the ECMAScript 5.1 edition specification. The algorithm is documented in section 11.9.3 of this specification.

Task

Implement the abstract equality comparison algorithm in JavaScript without using == or !=.

Input & output

The input is two variables. These variables can be anything that is not a Reference type. The output is a truthy or falsy value that represents the result of performing the abstract equality comparison algorithm.

Test Cases

Since there are a lot of edge cases, I took these test cases from the test262 repository.

Examples that return truthy values:

true == true
false == false
true == 1
false == "0"
0 == false
"1" == true
+0 == -0
-0 == +0
Number.POSITIVE_INFINITY == Number.POSITIVE_INFINITY
Number.NEGATIVE_INFINITY == Number.NEGATIVE_INFINITY
Number.POSITIVE_INFINITY == -Number.NEGATIVE_INFINITY
1.0 == 1
"" == ""
" " == " "
"string" == "string"
1 == "1"
1.100 == "+1.10"
255 == "0xff"
0 == ""
"-1" == -1
"-1.100" == -1.10
"5e-324" == 5e-324
undefined == undefined
void 0 == undefined
undefined == eval("var x")
undefined == null
null == void 0
null == null
{ var x, y; x = {}; y = x; x == y; } // two variables pointing to same object
new Boolean(true) == true
new Number(1) == true
new String("1") == true
true == new Boolean(true)
true == new Number(1)
true == new String("+1")
new Boolean(true) == 1
new Number(-1) == -1
new String("-1") == -1
1 == new Boolean(true)
-1 == new Number(-1)
-1 == new String("-1")
new Boolean(true) == "1"
new Number(-1) == "-1"
new String("x") == "x"
"1" == new Boolean(true)
"-1" == new Number(-1)
"x" == new String("x")
{valueOf: function() {return 1}} == true
{valueOf: function() {return 1}, toString: function() {return 0}} == 1
{valueOf: function() {return 1}, toString: function() {return {}}} == "+1"
{valueOf: function() {return "+1"}, toString: function() {throw "error"}} == true
{toString: function() {return "+1"}} == 1
{valueOf: function() {return {}}, toString: function() {return "+1"}} == "+1"
true == {valueOf: function() {return 1}}
1 == {valueOf: function() {return 1}, toString: function() {return 0}}
"+1" == {valueOf: function() {return 1}, toString: function() {return {}}}
true == {valueOf: function() {return "+1"}, toString: function() {throw "error"}}
1 == {toString: function() {return "+1"}}
"+1" == {valueOf: function() {return {}}, toString: function() {return "+1"}}

Examples that return falsy values:

true == false
false == true
Number.NaN == true
Number.NaN ==  1
Number.NaN == Number.NaN
Number.NaN == Number.POSITIVE_INFINITY
Number.NaN == Number.NEGATIVE_INFINITY
Number.NaN == Number.MAX_VALUE
Number.NaN == Number.MIN_VALUE
Number.NaN == "string"
Number.NaN == new Object()
true == Number.NaN
-1 == Number.NaN
Number.POSITIVE_INFINITY == Number.NaN
Number.NEGATIVE_INFINITY == Number.NaN
Number.MAX_VALUE == Number.NaN
Number.MIN_VALUE == Number.NaN
"string" == Number.NaN
new Object() == Number.NaN
1 == 0.999999999999
" " == ""
" string" == "string "
"1.0" == "1"
"0xff" == "255"
1 == "true"
"false" == 0
undefined == true
undefined == 0
undefined == "undefined"
undefined == {}
null == false
null == 0
null == "null"
null == {}
false == undefined
Number.NaN == undefined
"undefined" == undefined
{} == undefined
false == null
0 == null
"null" == null
{} == null
new Boolean(true) == new Boolean(true)
new Number(1) == new Number(1)
new String("x") == new String("x")
new Object() == new Object()
new Boolean(true) == new Number(1)
new Number(1) == new String("1")
new String("1") == new Boolean(true)
{valueOf: function() {return {}}, toString: function() {return "+1"}} == "1"
"1" == {valueOf: function() {return {}}, toString: function() {return "+1"}}

Examples that throw an error:

{valueOf: function() {throw "error"}, toString: function() {return 1}} == 1 // throws "error"
{valueOf: function() {return {}}, toString: function() {return {}}} == 1 // throws TypeError
1 == {valueOf: function() {throw "error"}, toString: function() {return 1}} // throws "error"
1 == {valueOf: function() {return {}}, toString: function() {return {}}} // throws TypeError

Rules

Standard rules apply. The shortest code in bytes wins.

Sandbox Questions

  • Is it ok that I am restricting the language to JavaScript? Should I allow languages that compile to JavaScript or have the types listed here?
  • Have I got too many test cases here? Should I cut it down? Perhaps instead I could create a tio.run template which runs all the tests instead of listing them all out here.
  • Is the requirement of not using == and != strict enough? I feel that I want to avoid answers where some inbuilt function indirectly calls == and getting around it that way but I don't know how to enforce that.
\$\endgroup\$
  • \$\begingroup\$ I'd say the number of test cases is still acceptable, though creating a TIO template sounds like a good idea anyway. \$\endgroup\$ – Laikoni Oct 14 '18 at 12:43
  • \$\begingroup\$ We still can use === and !==, can't we? \$\endgroup\$ – Shieru Asakoto Oct 15 '18 at 9:07
  • \$\begingroup\$ @ShieruAsakoto yes \$\endgroup\$ – Cameron Aavik Oct 15 '18 at 9:48
  • \$\begingroup\$ @CameronAavik Build a custom Javascript interpreter where calls to == errors out, then use that. \$\endgroup\$ – user202729 Oct 15 '18 at 10:18
  • \$\begingroup\$ Here's a link to a test framework in TIO. I don't think it's possible to overload operators in javascript though \$\endgroup\$ – Jo King Oct 17 '18 at 9:06
  • \$\begingroup\$ (for example when someone edits the interpreter to ban some features, see i.snag.gy/7ELPOt.jpg - the link "this branch" links to github.com/Mego/Seriously/tree/… --- of course that's a lot of work, but that would make sure that people definitely don't cheat) \$\endgroup\$ – user202729 Oct 19 '18 at 1:40
0
\$\begingroup\$

Cologne Phonetics

From Wikipedia: Cologne phonetics is a phonetic algorithm which assigns to words a sequence of digits, the phonetic code. The aim of this procedure is that identical sounding words have the same code assigned to them. The algorithm can be used to perform a similarity search between words. For example, it is possible in a name [collection?] to find entries like "Meier" under different spellings such as "Maier", "Mayer" or "Mayr".

The Cologne phonetics matches each letter of a word to a digit between 0 and 8. To select the appropriate digit, at most one adjacent letter is used as context.

Procedure:

Processing of a word is done in three steps:

  1. Encode letter by letter from left to right according to the conversion rules below.
  2. Remove all digits occurring more than once next to each other.
  3. Remove all code "0" except at the beginning

Conversion rules

  • A, E, I, J, O, U, Y become 0
  • H becomes nothing
  • B becomes 1
  • P becomes 1, unless it's before H
  • D, T become 2, unless they're before C, S, Z
  • F, V, W become 3
  • P becomes 3, if it's before H
  • G, K, Q become 4
  • C becomes 4 in initial position before A, H, K, L, O, Q, R, U, X
  • C becomes 4, if it's before A, H, K, O, Q, U, X, except after S, Z
  • X becomes 48, unless it's after C, K, Q
  • L becomes 5
  • M, N become 6
  • R becomes 7
  • S, Z become 8
  • C becomes 8, if it's after S, Z
  • C becomes 8 in initial position except before A, H, K, L, O, Q, R, U, X
  • C becomes 8, if it's not before A, H, K, O, Q, U, X
  • D, T become 8, if they're before C, S, Z
  • X becomes 8, if it's after C, K, Q

Challenge

Implement a program or a function that takes a single string as input and returns the phonetic code according to the rules stated above. You may choose your own output format, but keep in mind that the expected output may have leading zeros. The input string is guaranteed to match /^[a-zA-Z ]*$/, this means it may contain characters from the lowercase and uppercase alphabet, as well as spaces.

Test cases

Input                 Output

[empty string]        [empty]
Kolner Phonetik       45673624
Meier                 67
Mayer                 67
Augsburg              048174
Xanten                48626
Telephon              2356
Chemie                46
Muller Ludenscheid    65752682

This is , the shortest code for each language wins.

\$\endgroup\$
  • \$\begingroup\$ Related: Soundex function \$\endgroup\$ – Laikoni Oct 14 '18 at 12:49
  • \$\begingroup\$ What's the difference between "initial sound" and "initial position"? \$\endgroup\$ – Laikoni Oct 14 '18 at 12:58
  • \$\begingroup\$ Apparently there is none, from what I was able to find \$\endgroup\$ – oktupol Oct 15 '18 at 7:11
  • \$\begingroup\$ Ideally there would be a test case for each conversion rule as the challenge is probably mainly about handling those edge cases in the rules. \$\endgroup\$ – Laikoni Oct 15 '18 at 13:27
0
\$\begingroup\$

Keyboard Row Shift

Given an input string of characters, output the number of times we have to shift to another row while typing that string using a qwerty keyboard.

The input string will contain lower case alphabets,numbers and spaces. The newline key(enter) must also be considered at the end (only at the end). All shifts, from any row to any other will be considered as 1 shift only.

Layout:

1234567890
qwertyuiop
asdfghjkl enter
zxcvbnm
space

Examples:

"sdkflsd" -> 0
"asdwexc" -> 3 # to end the string one enter has to pressed which is in the middle
"poierlkdjfpoeirldskjf" ->3
"123 jkjk" -> 2
"llsdkfj ldkfj" -> 2
"lkasdjmnbcv " -> 3
"jnjn 5" -> 6

This is code-golf, so shortest code wins.

\$\endgroup\$
  • \$\begingroup\$ You need some test cases that contain a space and numbers. I'd also make it clear in your description that a shift can go any distance (going from the top row to the bottom is only 1 shift) \$\endgroup\$ – Nathan Merrill Oct 16 '18 at 12:48
  • \$\begingroup\$ Done, @NathanMerrill \$\endgroup\$ – Vedant Kandoi Oct 17 '18 at 5:36
  • \$\begingroup\$ How flexible is input? Is uppercase OK? How about an array of character strings or even an array that mixes digits and character strings? \$\endgroup\$ – Shaggy Oct 18 '18 at 21:47
  • 1
    \$\begingroup\$ I have mentioned only lower case, input has to be string only not an array. \$\endgroup\$ – Vedant Kandoi Oct 19 '18 at 5:15
0
\$\begingroup\$

Not All Sums Are Equal

Introduction

When computing the sum of a list of floating point values, the order in which we add up the summands matters. A good way to reduce errors is beginning with the summand with the least modulus and working your way up to the numbers with a greater modulus. As an illustrative example, let us assume our computer uses floating point numbers that comprise 2 (decimal) digits \$m_1,m_2\$ for the mantissa (and a sufficiently large number of digits for the exponent \$e\$.) These represent a number \$0.m_1m_2 \cdot 10^e\$. Let us consider the list

[0.1, 0.009, 0.009]

The exact result would obviously be \$0.118\$, and the best approximation in our computer therefore \$0.12\$. But if we actually tell the computer to sum those numbers, it will truncate all intermediate results, so it will get:

 (0.1 + 0.009) + 0.009 = 0.1 + 0.009 = 0.1

If we use the recipe from above and sort the list by the modulus first, we get

(0.009 + 0.009) + 0.1 = 0.018 + 0.1 = 0.11

which is already closer to the exact result. So we see that any permutation in the order of the summation might produce a different sum. In order to estimate the possible error we're interested in the difference between the greatest and the least sum we can get by just using a permutations of the original list. This is the task of this challenge.

Examples

The following examples assume that you use IEEE-754 double numbers in your implementation. You can of course use other implementations, but the results might be different:

[0.0140534017661288 0.50942429920538 1 1.96300019759529 71.1571487560538]
1.42108547152020e-14
[-0.447570988743782 -0.30397649549556 0 0.765285061877593 3.30425088014391]
8.88178419700125e-16
\$\endgroup\$
  • \$\begingroup\$ 1. The decimal example only works because it's using a bad rounding mode. With a good rounding mode which gives an answer with half an ULP, both orders would give 0.12. 2. The example is not very clear on what the inputs and outputs are. \$\endgroup\$ – Peter Taylor Oct 22 '18 at 19:15
0
\$\begingroup\$

Remove UTF-8 BOM

As we are trying to golf every bytes from our codes, we want to avoid the text file saved in UTF-8 with BOM (Byte Order Mark). So, let's remove it.

BOM for is a character with code point U+FEFF. When written in UTF-8, its byte sequence is EF BB BF (or 239 187 191 in decimal).

Input

Input the file or content of the file. Input may be one of the following format:

  • Input content of the file from stdin;
  • Input a string for filename;
  • Input an UTF-8 string;
  • Input an array of 0~255 integers represent every bytes in the file;

An optional string for output path.

The input file may / may not contain a BOM in the very beginning of the content.

Output

If input file contains the BOM mark, you should remove it. Otherwise, just keep it as is. You should output the content of the file. You may chose to output:

  • Output to stdout;
  • Rewrite the input file;
  • Output to another file;
  • Return a UTF-8 string;
  • Return an array of 0~255 integers;

Rules

  • BOM will only appear at the beginning. You may assume there will not be any BOMs in the middle of the file.
  • You should only removing BOM, and avoid changing any thing else including
    • No additional trailing new line;
    • Keep line ending as is;
  • If your program contains non-visible characters (e.g. U+FEFF), remember to include a xxd dump (or something similar) or description of it in your post;
  • This is code-golf, shortest codes win.

Testcases

File A

JSON encoded: "\ufeffSample test\r\nWith different line ending\nAnd\tothers\u2028\u2029What about emoji \uD83D\uDE02. "

xxd:

00000000: efbb bf53 616d 706c 6520 7465 7374 0d0a  ...Sample test..
00000010: 5769 7468 2064 6966 6665 7265 6e74 206c  With different l
00000020: 696e 6520 656e 6469 6e67 0a41 6e64 096f  ine ending.And.o
00000030: 7468 6572 73e2 80a8 e280 a957 6861 7420  thers......What
00000040: 6162 6f75 7420 656d 6f6a 6920 f09f 9882  about emoji ....
00000050: 2e20                                     .

File B

JSON encoded: "Sample test\r\nWith different line ending\nAnd\tothers\u2028\u2029What about emoji \uD83D\uDE02. "

xxd:

00000000: 5361 6d70 6c65 2074 6573 740d 0a57 6974  Sample test..Wit
00000010: 6820 6469 6666 6572 656e 7420 6c69 6e65  h different line
00000020: 2065 6e64 696e 670a 416e 6409 6f74 6865   ending.And.othe
00000030: 7273 e280 a8e2 80a9 5768 6174 2061 626f  rs......What abo
00000040: 7574 2065 6d6f 6a69 20f0 9f98 822e 20    ut emoji .....

File download:

function download(text, filename) {
  bytes = new TextEncoder().encode(text);
  blob = new Blob([bytes], { type: 'octet/stream' });
  url = URL.createObjectURL(blob);
  link = document.createElement('a');
  link.href = url;
  link.setAttribute('download', filename);
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
};
<button onclick="download('\ufeffSample test\r\nWith different line ending\nAnd\tothers\u2028\u2029What about emoji \uD83D\uDE02. ', 'a.txt')">Download File A</button>
<button onclick="download('Sample test\r\nWith different line ending\nAnd\tothers\u2028\u2029What about emoji \uD83D\uDE02. ', 'b.txt')">Download File B</button>

  • Input file A, output should match file B.
  • Input file B, output should match file B.
\$\endgroup\$
  • \$\begingroup\$ I would include that EF BB BF as 0~255 integers is [239,187,191]. I guess we aren't allowed to input a hexadecimal string where every 2 chars represents a byte (i.e. "EFBBBF0AB4" would result in "0AB4")? \$\endgroup\$ – Kevin Cruijssen Oct 23 '18 at 9:51
  • \$\begingroup\$ @KevinCruijssen I don't think "EFBBBF4732" is a valid input form. But [239, 187, 191, 71, 50] is. Would there be any one get benefit from getting input like this? \$\endgroup\$ – tsh Oct 23 '18 at 10:53
  • \$\begingroup\$ Well, in Retina for example, a simple ^239,187,191\n (13 bytes) (or ^EFBBBF\n (8 bytes) if that input format would have been allowed) would already suffice, and I suspect other language could do something similar with regex-replacements. \$\endgroup\$ – Kevin Cruijssen Oct 23 '18 at 10:57
  • \$\begingroup\$ @KevinCruijssen Retina can handle raw bytes in its source code anyway. \$\endgroup\$ – user202729 Oct 23 '18 at 11:49
  • \$\begingroup\$ So is there anything else I need to do beyond removing a single character? \$\endgroup\$ – Nissa Oct 24 '18 at 17:41
  • \$\begingroup\$ @StephenLeppik Nothing. \$\endgroup\$ – tsh Oct 25 '18 at 2:33
  • \$\begingroup\$ Then I don't see where the difficulty comes from. \$\endgroup\$ – Nissa Oct 25 '18 at 2:36
  • \$\begingroup\$ @StephenLeppik So, we have to ask a question which is difficult? \$\endgroup\$ – tsh Oct 25 '18 at 2:53
  • \$\begingroup\$ No, but the easier ones are usually well-known benchmarks such as Hello World or a prime test. \$\endgroup\$ – Nissa Oct 25 '18 at 2:55
0
\$\begingroup\$

Given a program in your language, generate another program that do exactly the same thing so every bytes in it are prime.

Shortest generator in every language win. No acception.

Nop in languages that only allow prime bytes are legit, but just don't post them(or make a community answer to put them)

\$\endgroup\$
  • \$\begingroup\$ Upvote this comment if you think that the idea of the challenge is not interesting and it should not be posted. \$\endgroup\$ – user202729 Oct 26 '18 at 10:46
  • 1
    \$\begingroup\$ Upvote this comment if you think that the idea is fine, but the challenge is unclear or needs fixing; in that case also leave a comment. \$\endgroup\$ – user202729 Oct 26 '18 at 10:47
  • \$\begingroup\$ I made a small poll above ↑. I think the idea is interesting, and if it's poorly worded, the post can't be fixed without suggestions. Note that the challenge is already fully specified in the current state (task description, winning criteria), and it's impossible to give sample input/output to test programs (if you understand the challenge, you will see why). \$\endgroup\$ – user202729 Oct 26 '18 at 10:49
  • \$\begingroup\$ Lots of languages quite rely on composite(not prime) bytes, so upvote this comment if you think it's too restrict \$\endgroup\$ – l4m2 Oct 26 '18 at 12:40
  • \$\begingroup\$ I think the idea is interesting, especially in languages like Jelly which can do most anything with small subsets of its character set. My main problem is: how much of the language do we have to support in the input to our generator? Many languages which are capable of this task have far too many possible instructions, etc., every one of which would need to be remapped to an all-prime version. Unless perhaps it's possible to simply generate any given string and execute it whilst using only prime bytes... \$\endgroup\$ – ETHproductions Oct 27 '18 at 3:14
  • \$\begingroup\$ @ETHproductions I think a subset of an existing language can be considered another language? \$\endgroup\$ – user202729 Nov 11 '18 at 4:23
0
\$\begingroup\$

Are these strings character wise translatable?

Explanation with example:

Suppose you are given two strings of the same length, e.g. "code" and "golf". Try to find a set of translation rules for characters (like "All cs are replaced by gs" , or c -> g for short) such that applying those rules on "code" yields "golf" and applying them to "golf" again yields "code".

If there is such a set of translation rules, return a truthy value. Otherwise, if no such set can exist, return a falsy value.

In our example, the translation is possible with the rules g -> c, d -> l, e -> f, c -> g, l -> d and f -> e, so a truthy value should be returned.

However, if the two strings were "code" and "meta", no such rules exist: To get from "code" to "meta" we need the rule e -> a, but to get from "meta" to "code" we would need e -> o. But e cannot be translated into two different characters! Therefore, a falsy value should be returned.

Consise mathy explanation:

Given two strings \$s\$ and \$t\$ of the same length \$n\$, decide whether the following relation is bijective: $$\{(s_i,t_i)\ |\ 1 \leqslant i \leqslant n\} \cup \{(t_i,s_i)\ |\ 1 \leqslant i \leqslant n\}$$ where \$s_i\$ denotes the \$i^{th}\$ character of string \$s\$.

Test cases

truthy:

"code", "golf"
"a", "a"
"abdabdcdacabcabd", "bacbacdcbdbadbac"
TODO: Add some more

falsy:

"code", "meta"
"aa", "ab"
"abc", "bca"
TODO: Add some more
\$\endgroup\$
  • \$\begingroup\$ This seems to be very similar to Check if words are isomorphs. \$\endgroup\$ – Dennis Oct 28 '18 at 2:39
  • \$\begingroup\$ @Dennis It is definitely related. However, as far as I see most answers there work by creating some sort of fingerprint and checking whether it is the same for both inputs. This approach alone won't work here as you also need to check the symmetry of substitutions. \$\endgroup\$ – Laikoni Oct 28 '18 at 11:33
  • 1
    \$\begingroup\$ Not saying this makes it a dupe, because there might be golfier ways, but s and t are character wise translatable if and only if s++t and t++s are isomorphs. \$\endgroup\$ – Dennis Oct 28 '18 at 12:54
0
\$\begingroup\$

Guess the Q in the code

A popular puzzle known to me as Codewords takes a Crossword-like grid and consistently replaces each letter with a code value, usually a number from 1 to 26, and the solver then has to work out which code value represents each letter. There are a number of approaches to this:

  • There is a web site which can search for words given the pattern of repeating letters. Since repeated letters map to repeated code values, you can sometimes use the patten of repeated code values to determine the original word. For instance, the only word with the pattern 12.312..3... is churchwarden.
  • The puzzle normally provides a few of the letters to get you started. This may be enough to use a standard crossword solver to determine the original word. For instance, .h...h...d.. would again point you to the word churchwarden.
  • You could use frequency analysis to guess which letters are likely to be the popular letters such as e or t.
  • You could look for common prefixes or suffixes such as ally or ness. (I picked those two as they have repeating letters which are easier to spot.)
  • At least in all of the Codewords puzzles I have seen, q is always followed by a u and at least one letter. This means that if there is a code that is never the last or penultimate letter of a word, and always appears followed by the same code, then this could be a q.

However, checking all the codes to see how many distinct codes follow them is laborious. We need an automatic solution for this!

Please write a program or function that will guess which code(s) could represent the letter q. The input to the function will be an array of code values in a standard format. You will need to support 27 consistent distinct values, 26 for the codes themselves and a value for the background. These values can be integers but you could also use characters e.g. 26 letters and a space, in which case you can join them into strings, and even join the strings with a 28th character.

Your output will be all of the code values that have the property that, for each occurrence in the grid, either:

  • The previous and following cells are background or would extend past the side of the grid, or
  • There are two non-background following cells, and the first of those cells always contains the same value.

These rules apply in both the horizontal and vertical direction.

This is , so the shortest solution that breaks no standard loopholes wins!

Examples needed, I guess...

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

Hack g-code parser

\$\endgroup\$
  • \$\begingroup\$ This could be seen as asking for malicious code, which is not on-topic. \$\endgroup\$ – Laikoni Oct 25 '18 at 17:55
  • \$\begingroup\$ @Laikoni this is not malicious\harmful code, because it don't causes harm to user. It is educational programming puzzle for white-hat hackers \$\endgroup\$ – Евгений Новиков Oct 25 '18 at 18:58
  • \$\begingroup\$ @Laikoni rm -rf / is harmful, but alert("pwned") is not \$\endgroup\$ – Евгений Новиков Oct 25 '18 at 18:59
  • 3
    \$\begingroup\$ Right, I think misread the challenge. If it is only about cracking this piece of code rather than actual implementations it's probably fine as a challenge. Any way, you need an objective winning criterion. code-golf in the sense of "the shortest input to open the alert prompt" seems like a good candidate. \$\endgroup\$ – Laikoni Oct 25 '18 at 19:47
0
\$\begingroup\$

Find the pattern v2

I feel tired to do "find the pattern" exercise such as

1 2 3 4 (5)
1 2 4 8 (16)
1 2 3 5 8 (13)

Please write a program that finds the pattern for me.

Here, we define the pattern as a recurrence relation that fits the given input, with the smallest score. If there are multiple answers with the same smallest score, using any one is fine.

Let the \$k\$ first terms be initial terms for the recurrence relation, and the \$i\$'th term be \$f(i)\$ (\$i>k,i\in\mathbb N\$).

  • A non-negative integer \$x\$ adds\$1\$ to the score
  • The current index \$i\$ adds \$1\$ to the score
  • +, -, *, / (round up, down, towards zero, go further to zero, as you decide) and mod (a mod b always equal to a-b*(a/b)) each add \$1\$ to the score
  • For each initial term \$x\$, add \$1\$ to the score
  • \$f(i-n)\$ (with \$n\le k\$) adds \$1\$ to the score. E.g. Using the latest value \$f(i-1)\$ add \$1\$ to the score, and there must be at least 1 initial term.
  • Using parentheses to change the calculation order doesn't add anything to the score.

Samples:

input   -> [score]    expression(not optimized)
1 2 3 4     -> [1]    f(i) = i
1 2 4 8     -> [3]    f(1) = 1, f(i) = 2*f(i-1)
1 2 3 5 8   -> [5]    f(1) = 1, f(2) = 2, f(i) = f(i-1)+f(i-2)

Lowest score for worse case wins. If tie, shortest program in each language wins. Your program should run in polynomial time.

If someone's score is lower than 4(currently reachable), the first lowest score will be accepted. (differ from winning criticia)

p.s. See history for v1 sandbox

\$\endgroup\$
  • 1
    \$\begingroup\$ I think the challenge could benefit from a precise defining grammar for a pattern. As it stands, I feel the set of all expressions that may fit is too vast. \$\endgroup\$ – Jonathan Frech Oct 16 '18 at 9:28
  • \$\begingroup\$ @JonathanFrech Looks pretty precise to me. About "too vast" - there are only 6 bullets. \$\endgroup\$ – user202729 Oct 17 '18 at 10:43
  • \$\begingroup\$ @user202729 I am unsure if (round as you decide) includes the possibility of not rounding. \$\endgroup\$ – Jonathan Frech Oct 17 '18 at 15:28
  • \$\begingroup\$ Should "3 0 0 0 0 0 ..." be "f(1)=3, f(n)=0", do "for the recurrence relation" work? \$\endgroup\$ – l4m2 Oct 17 '18 at 16:40
  • \$\begingroup\$ @l4m2 Yes. ----- \$\endgroup\$ – user202729 Oct 17 '18 at 16:56
  • \$\begingroup\$ I don't understand the "fun fact"... \$\endgroup\$ – user202729 Oct 21 '18 at 15:42
  • \$\begingroup\$ @user202729 Do you think it no fun or can't figure it out? \$\endgroup\$ – l4m2 Oct 21 '18 at 19:24
  • \$\begingroup\$ The latter. ---- \$\endgroup\$ – user202729 Oct 22 '18 at 0:15
0
\$\begingroup\$

User ranking in language

Challenge is:

  • You need receive the input of "language". By "language" I mean the at left of the comma in the Title of an answer on the present code-golf site.
  • The source for the data are the answers posted here on code-golf site.
  • You must present results in order. Decreasing or Increasing does not matter, it only needs to be one of those two.
  • Output is a table of two columns {User, Upvotes}. Example: User enters Java and will obtain a list as the following:

user_A 9523 user_B 6000 user_C 120

Do not care very much about the output formatting as long it is clear the separation between the two columns and each line.

The will be no winner as it is a per language question.

\$\endgroup\$
  • \$\begingroup\$ "The source for the data are the answers posted here on code-golf site." The answers for this challenge, or ALL challenges on PPCG? And with your example, does this mean it searches for each user all answers given in Java, and sums their total upvote count? Also, do we differentiate java/Java/Java 7/Java 10 etc as different inputs? \$\endgroup\$ – Kevin Cruijssen Nov 1 '18 at 12:45
  • \$\begingroup\$ @KevinCruijssen 1. Yes, the scope is all answers on PPCG. 2. Yes, it is the total upvote account. 3. This is flexible on uppercase/lowercase, but not on the rest. \$\endgroup\$ – sergiol Nov 8 '18 at 19:58
0
\$\begingroup\$

Concentration (or Memory or Match) is a game where players pick pairs of cards and try to find matches. The rules are as follows:

  1. Two of each number from 1 to N are added to the deck.
  2. The deck is shuffled and placed face-down (hidden).
  3. The player selects a card. The card is revealed.
  4. The player selects another card: The card is revealed.
  5. If the two cards are different numbers, then they are hidden again.
  6. Steps 3 through 5 are repeated until all cards are revealed.

For example, lets say I have the following cards: 1 1 2 2 3 3 4 4

Shuffle them: 1 4 3 1 4 3 2 2

Place them face down: X X X X X X X X

The player will then select a card: 1 X X X X X X X

And then another card: 1 X 3 X X X X X

The numbers don't match, so we put the cards face down, and select another card: X X X 1 X X X X

The player remembers the position of the other 1: 1 X X 1 X X X X

A match was found! These cards stay face-up, and we try again.

The challenge is to do this with limited memory. You need to write a function/program that takes two parameters:

  • A list of cards (with a constant value representing the hidden cards)
  • 32 bytes of data. This can be stored as a string, a large integer, etc.

Your function must use this data (and only this data) to select the next card to reveal, and then update the 32 bytes of data. You may use a random number generator for free (as long as you do not use the seed to store data)

After the game is over, the game is scored by counting the number of times a card was revealed.

Below, I have provided a list of test cases. Your score is the length of the first test case you complete with a score of greater than 2N+30 (N is the number of distinct cards). Hard coding is not allowed, and your function should get a similar score with a different set of test cases.

2 1 4 0 0 3 3 4 2 1
3 0 4 3 2 0 4 1 1 2
1 3 2 2 4 3 0 4 0 1
2 2 0 4 4 1 1 3 3 0
3 2 1 1 0 0 4 3 4 2
3 2 0 4 2 5 1 1 0 3 5 4
4 5 0 3 2 5 3 1 0 2 1 4
4 1 2 0 2 5 1 3 3 5 0 4
2 3 2 4 3 1 0 5 4 0 1 5
3 1 4 0 2 2 5 3 1 5 4 0
1 4 0 5 2 3 6 1 0 3 5 4 6 2
6 3 5 3 1 2 1 5 2 4 4 6 0 0
5 6 0 0 5 3 1 1 2 4 6 2 4 3
1 1 6 2 2 4 0 4 5 5 6 0 3 3
3 4 6 4 6 2 5 0 0 1 3 5 2 1
3 2 6 4 1 5 7 4 3 7 0 2 6 0 1 5
7 3 1 0 6 2 3 6 4 1 5 7 5 0 4 2
2 6 5 4 2 5 0 0 7 3 1 4 6 7 3 1
4 7 5 0 6 3 0 1 3 1 7 2 6 4 2 5
4 7 5 1 4 3 2 6 0 6 7 3 2 5 1 0
7 6 5 4 5 0 1 3 8 3 4 0 1 8 6 2 2 7
2 4 1 8 7 4 6 5 3 8 1 3 7 2 0 6 5 0
6 4 7 8 5 1 4 3 0 8 3 5 2 6 1 2 7 0
3 8 0 6 4 0 1 5 2 7 7 1 5 3 2 6 8 4
7 1 8 8 3 1 3 4 5 4 6 2 2 0 0 7 6 5
9 4 1 5 7 3 4 1 6 3 9 7 2 2 0 5 6 0 8 8
2 2 6 1 8 6 5 7 3 4 5 0 9 3 0 9 7 4 8 1
7 4 3 5 2 7 1 1 0 0 9 8 6 8 3 6 2 9 4 5
1 6 3 2 7 0 7 9 1 5 0 4 8 6 3 8 9 5 2 4
8 4 5 9 9 3 0 5 6 2 2 7 0 4 1 8 7 1 3 6
1 7 0 2 1 3 8 8 6 9 2 3 4 5 6 5 10 4 7 10 0 9
3 5 10 3 5 1 9 10 1 2 0 4 0 8 6 7 8 4 9 2 6 7
9 1 7 8 2 8 9 10 2 0 6 6 5 3 5 1 10 0 4 7 3 4
7 8 2 9 8 0 0 9 3 1 5 2 4 1 3 10 4 10 5 6 6 7
3 7 9 5 1 2 8 6 3 6 4 0 10 1 2 7 10 9 8 4 5 0
7 6 9 6 2 5 5 0 11 9 3 10 8 3 4 8 4 2 11 1 1 10 7 0
10 2 8 5 11 3 4 2 6 11 4 7 10 9 8 9 1 1 6 0 5 7 3 0
4 0 7 7 4 6 11 8 3 9 3 2 5 1 11 10 8 2 9 5 0 10 1 6
10 8 8 0 0 3 7 4 11 10 9 2 4 5 6 9 5 6 7 1 1 11 3 2
1 7 0 8 9 10 4 5 10 6 5 1 4 3 7 2 0 9 3 11 8 2 6 11
3 7 10 11 1 5 10 2 9 3 8 11 5 9 6 0 0 4 12 12 4 8 1 6 2 7
0 11 9 11 2 9 10 6 5 2 7 0 12 1 10 7 6 8 3 3 4 1 12 5 8 4
3 9 5 12 1 6 8 10 2 4 11 3 6 8 9 1 10 12 7 0 11 0 5 4 7 2
1 7 11 9 0 2 6 6 5 0 8 3 10 8 7 12 3 9 12 4 2 4 11 1 5 10
8 4 9 0 7 3 1 3 9 6 11 6 8 2 12 10 2 12 5 5 0 1 10 7 4 11
13 4 13 4 1 2 9 8 10 7 3 12 2 0 5 6 0 5 8 6 9 12 11 10 1 7 3 11
13 0 0 6 1 4 11 3 12 9 2 10 9 2 7 8 12 5 7 6 11 4 10 1 5 3 13 8
13 10 3 6 12 1 0 8 5 6 3 11 4 9 2 9 8 11 12 2 5 7 7 1 4 10 0 13
7 4 11 8 10 1 6 0 3 10 6 0 8 2 11 5 3 1 7 13 9 13 12 9 4 2 5 12
13 5 7 6 1 12 8 2 8 0 5 7 10 6 4 11 12 1 2 10 3 13 11 3 0 9 9 4
9 2 4 3 7 4 2 7 10 5 13 6 5 12 8 11 0 8 14 11 0 6 1 9 3 13 14 1 10 12
8 14 8 7 11 7 2 12 4 5 13 6 1 3 5 0 1 4 9 0 10 2 11 12 13 6 3 14 10 9
4 9 5 1 5 10 2 11 2 9 13 10 3 13 12 8 7 1 6 8 14 0 4 12 14 11 3 7 6 0
5 10 4 3 2 4 2 3 9 13 14 6 0 11 5 13 12 8 0 9 7 8 6 11 14 1 12 10 1 7
11 1 10 8 0 12 9 1 7 4 4 12 6 8 14 5 10 5 14 0 11 3 7 9 2 2 3 13 6 13
0 8 15 6 4 1 9 8 14 13 2 11 4 6 9 14 0 2 3 5 1 15 5 10 13 12 3 7 12 7 10 11
13 3 4 13 2 12 9 1 5 1 6 7 11 9 10 0 15 14 12 15 14 8 7 3 4 5 8 11 0 2 10 6
6 1 7 9 3 1 15 7 5 14 9 14 0 8 10 0 4 12 12 13 3 6 11 4 15 2 11 5 2 13 8 10
2 0 14 7 13 13 15 7 3 8 15 5 10 12 4 5 3 14 9 6 12 10 9 11 8 6 1 1 4 11 2 0
3 13 12 4 10 13 8 0 7 11 11 6 8 1 12 5 5 9 6 10 14 3 2 9 14 4 1 15 15 7 0 2
16 12 7 14 13 5 5 4 11 0 0 9 12 15 15 9 14 2 6 3 11 8 16 10 6 13 3 1 2 8 1 7 10 4
5 5 10 4 9 15 0 11 11 1 13 15 9 0 3 1 16 6 8 7 2 6 8 2 14 14 16 4 3 12 12 13 10 7
0 6 7 4 12 16 0 3 6 1 7 12 8 13 15 9 2 11 2 15 11 10 5 13 14 5 9 14 3 8 4 16 1 10
8 0 1 2 16 11 3 2 15 4 15 5 14 9 13 7 14 9 10 12 11 12 16 6 13 6 1 5 10 0 7 8 4 3
9 16 15 13 11 2 5 6 16 3 9 4 10 14 14 12 8 11 0 6 0 15 10 7 13 5 1 12 3 4 2 1 7 8
11 15 14 3 8 12 17 15 1 0 12 6 9 0 9 13 11 14 16 2 4 5 13 16 10 7 8 5 10 4 17 3 6 7 1 2
11 14 5 7 14 0 12 4 8 12 11 13 16 16 15 6 3 1 8 3 1 5 7 17 10 2 17 13 15 9 9 4 2 0 6 10
15 13 6 12 5 4 9 2 11 2 13 16 3 9 1 16 10 11 1 12 14 17 8 0 17 6 8 10 5 0 7 4 14 7 3 15
0 9 13 15 8 11 6 5 9 16 11 7 14 7 5 15 3 12 4 16 2 14 3 0 1 10 13 1 6 10 17 2 17 8 4 12
10 13 14 10 5 7 16 8 8 7 6 3 0 2 17 17 2 1 15 16 3 4 5 0 12 9 1 12 14 11 13 9 15 6 4 11
7 14 0 13 15 6 12 1 14 16 10 15 8 11 0 9 2 3 4 18 12 17 8 13 9 6 4 11 5 1 5 16 17 3 18 10 7 2
12 9 17 2 7 12 4 15 13 0 17 9 11 3 6 4 8 5 11 16 8 1 7 0 13 15 16 10 3 14 18 2 14 1 10 6 18 5
4 0 5 14 7 8 1 0 12 15 11 2 11 5 3 9 15 17 6 8 7 10 12 3 6 16 2 18 16 13 4 14 9 17 13 18 1 10
13 13 18 9 0 17 12 17 8 0 14 16 14 6 10 6 9 15 1 15 2 4 11 5 1 3 4 3 11 2 5 16 8 7 10 7 18 12
18 11 13 6 14 9 13 14 9 18 17 11 0 1 17 2 0 6 10 3 8 4 1 5 15 7 5 2 12 15 4 8 7 16 10 12 3 16
0 17 5 6 19 0 11 1 7 18 9 14 16 2 16 13 1 4 3 17 15 7 10 2 15 9 18 13 8 14 6 12 5 10 3 8 11 19 12 4
4 3 10 12 2 7 9 11 0 16 16 7 19 2 13 3 12 10 5 18 4 15 15 0 11 19 18 13 14 1 5 17 6 9 14 8 6 17 8 1
0 17 16 11 7 19 8 5 17 16 14 1 10 6 11 7 15 10 14 13 15 4 2 4 1 9 6 3 13 18 18 0 19 3 9 12 8 5 2 12
10 15 10 0 2 14 3 19 1 18 4 14 8 2 5 17 4 11 17 12 13 16 9 3 0 13 7 5 18 6 8 9 12 1 19 16 11 7 6 15
15 2 16 4 14 0 1 5 12 18 10 12 4 14 16 11 8 7 13 15 11 3 19 10 3 9 17 6 13 19 9 1 0 18 8 2 7 5 17 6
1 12 17 7 8 8 12 20 5 10 20 16 13 3 18 15 5 4 10 9 6 14 11 6 7 15 16 19 0 1 9 18 19 2 2 3 13 4 17 0 11 14
7 17 2 12 19 9 0 11 17 4 12 0 10 11 16 14 3 20 7 15 2 9 8 18 16 19 5 3 8 14 6 18 1 13 5 1 4 15 13 10 6 20
0 18 12 4 20 7 14 5 10 16 1 13 9 15 12 0 6 19 2 5 16 10 1 17 15 11 20 3 14 2 18 3 17 11 7 8 4 8 6 19 13 9
9 18 15 0 16 7 19 4 13 20 5 10 2 2 0 12 8 6 3 15 16 14 17 7 10 3 13 6 1 20 1 17 19 11 5 4 12 14 11 8 9 18
13 6 16 11 20 3 10 8 5 7 17 15 14 0 7 6 14 17 4 15 2 12 8 1 13 18 11 10 1 9 20 16 5 19 18 2 12 19 3 9 4 0
4 5 16 11 2 1 14 9 16 6 20 21 0 13 12 13 7 8 15 11 10 18 14 3 15 5 21 18 12 17 19 9 0 19 7 4 3 20 1 8 2 10 6 17
10 6 7 0 18 1 19 5 8 12 15 2 5 4 11 20 16 17 13 14 17 1 16 9 21 21 0 3 6 3 2 7 8 13 19 20 14 15 9 11 10 4 18 12
2 20 12 21 10 4 8 11 13 3 20 1 6 21 12 13 4 17 19 16 17 15 14 9 16 9 5 10 8 6 11 18 1 5 2 18 0 0 3 7 19 14 15 7
16 0 17 8 11 6 3 18 9 16 14 20 12 12 10 1 14 1 10 21 4 19 0 2 13 3 15 17 21 9 6 18 2 20 4 11 7 19 5 8 7 5 13 15
3 4 4 10 0 3 16 14 19 8 17 9 5 9 6 12 7 13 13 1 15 0 5 20 2 7 1 17 21 11 11 18 20 6 15 16 2 12 14 19 8 10 18 21
12 11 7 8 8 10 9 18 5 6 15 12 10 0 14 3 6 22 17 15 17 21 14 16 9 4 18 13 1 11 4 20 3 19 22 1 13 7 21 5 0 20 2 2 16 19
2 20 10 17 6 0 21 10 19 4 12 8 0 7 18 15 17 18 9 4 2 14 1 5 14 6 16 22 13 11 11 15 21 3 7 19 8 9 22 20 3 16 13 1 12 5
12 11 6 16 18 15 12 11 10 9 8 15 22 5 21 18 20 0 2 19 17 8 10 5 3 14 9 22 20 3 1 21 19 6 0 16 1 13 4 14 2 13 17 4 7 7
20 5 16 4 17 7 8 15 0 10 9 3 16 13 8 12 1 14 17 11 18 11 2 7 6 1 4 20 3 5 22 22 2 6 13 10 19 15 12 14 18 9 0 19 21 21
11 1 0 5 7 15 0 12 3 9 6 15 7 13 11 20 9 17 8 4 22 4 10 5 21 18 16 14 13 10 18 12 21 17 16 2 6 22 3 14 19 1 8 19 20 2
10 10 18 6 4 1 9 6 15 7 7 11 21 13 15 21 22 16 12 20 2 18 3 17 19 14 14 0 16 5 3 4 1 9 13 11 22 20 19 8 5 0 23 17 23 2 8 12
3 3 19 13 5 10 17 18 4 16 6 2 21 4 12 7 13 8 7 10 6 2 1 15 5 21 23 22 0 11 9 16 20 11 20 23 1 14 18 8 14 19 9 17 0 15 22 12
14 7 15 20 19 7 13 0 20 2 18 1 11 21 17 12 16 10 8 3 15 2 22 23 18 16 9 1 3 13 10 19 8 11 6 4 5 22 0 17 21 23 14 4 12 9 6 5
1 12 15 21 11 21 18 6 4 22 5 23 14 19 13 8 15 7 5 0 8 13 16 4 1 6 12 11 14 18 20 17 9 23 19 3 2 17 9 0 16 7 3 20 10 22 2 10
23 9 15 10 13 17 17 21 12 18 2 20 3 8 0 16 2 12 6 20 7 19 16 0 8 9 4 6 5 13 18 14 1 19 21 3 22 15 1 4 22 10 5 7 11 14 11 23
3 21 22 5 19 7 2 24 18 19 9 2 24 14 6 0 12 0 21 18 23 15 8 11 6 4 8 17 16 20 14 16 4 7 10 11 1 9 17 3 23 10 20 5 13 22 13 1 12 15
13 6 5 22 1 17 2 21 5 0 14 24 19 21 7 19 6 23 12 14 4 9 3 22 15 9 2 16 20 7 13 12 8 23 18 0 15 10 8 24 20 16 3 1 4 11 10 18 17 11
12 6 19 0 9 14 22 2 13 20 19 9 6 3 21 20 24 0 4 24 1 5 11 15 1 21 8 5 16 16 23 18 7 11 10 17 15 12 3 22 7 10 2 23 17 8 14 4 13 18
6 22 2 18 16 19 12 0 17 14 23 4 6 17 3 10 4 22 13 9 20 19 0 9 8 1 24 2 23 14 11 5 7 16 13 10 12 8 7 3 20 21 15 5 18 21 11 1 15 24
18 12 6 22 19 19 9 24 5 14 13 2 22 8 4 16 3 9 18 8 0 10 23 10 2 20 21 5 23 20 1 11 0 17 7 7 17 12 15 3 16 15 13 24 14 4 6 21 11 1
7 14 19 5 4 17 1 22 23 24 12 1 20 6 24 7 21 10 8 11 20 3 25 13 0 2 16 21 0 6 9 11 4 18 22 2 15 5 18 8 13 12 3 14 23 10 17 9 16 15 25 19
10 4 1 13 11 24 7 12 15 20 11 0 23 23 5 7 25 25 17 8 20 24 2 22 19 9 12 16 4 6 21 9 17 6 5 15 10 0 18 8 22 2 14 16 3 19 21 18 1 3 13 14
16 22 3 2 25 21 11 1 10 12 4 15 0 2 13 11 3 14 19 1 18 12 8 23 18 22 9 16 4 0 20 9 17 24 7 10 6 8 23 25 15 7 21 20 19 5 14 13 6 5 17 24
21 20 8 16 1 18 4 0 14 5 22 3 0 23 22 1 9 4 24 7 21 2 23 15 11 12 14 25 8 12 7 15 13 18 3 19 10 2 5 10 16 24 19 13 6 20 6 9 17 11 17 25
6 24 17 18 24 22 10 11 20 16 16 3 4 21 23 25 14 1 0 1 7 2 5 13 6 4 10 21 17 14 23 11 9 9 15 25 0 19 19 12 20 22 12 13 15 2 3 8 5 18 8 7
11 16 25 6 19 5 26 17 24 6 12 4 15 18 21 7 10 5 23 3 13 8 13 23 20 8 11 12 9 22 1 14 21 2 25 10 15 9 0 2 0 26 3 24 17 22 14 4 18 16 20 19 1 7
26 0 19 3 0 20 1 25 13 3 12 6 20 11 21 13 2 11 23 15 17 15 24 23 10 8 26 5 18 9 16 18 4 9 19 10 14 7 22 17 22 4 16 8 24 2 25 5 14 12 6 21 1 7
9 25 13 14 19 17 20 2 11 5 19 23 25 21 0 16 8 15 7 16 24 24 3 15 20 10 8 4 0 12 13 22 9 4 26 18 22 2 23 18 3 6 6 12 17 26 21 10 1 11 14 7 5 1
17 4 20 23 13 0 3 26 25 16 3 2 13 10 8 12 9 5 14 2 26 25 21 23 22 17 7 14 24 1 4 15 19 16 12 5 9 22 1 20 19 7 11 6 21 15 11 18 6 8 18 0 10 24
14 12 3 17 7 2 19 11 0 21 10 24 4 6 8 8 25 4 6 23 9 1 25 15 12 9 23 10 2 26 1 0 11 7 19 13 18 3 17 13 16 26 20 20 16 15 22 22 18 14 5 24 21 5
4 15 22 10 27 14 7 0 2 17 3 6 20 18 0 16 21 4 3 11 11 12 23 5 15 22 9 17 2 1 10 18 25 14 27 19 16 23 20 21 6 25 26 24 13 1 24 26 9 13 8 19 8 7 5 12
3 17 8 9 3 9 23 15 10 25 0 6 26 21 11 12 27 1 11 13 14 2 6 1 20 7 19 24 22 14 22 25 16 17 26 5 24 27 12 13 18 4 23 20 19 4 7 15 21 8 5 16 10 2 0 18
9 11 14 21 3 12 10 4 14 1 5 18 27 9 6 0 3 19 7 12 17 26 26 25 15 11 16 24 17 18 20 8 7 19 15 1 4 13 22 23 8 25 20 16 22 2 6 0 10 5 2 24 23 21 13 27
7 23 2 26 5 24 19 17 2 18 11 7 16 5 8 26 24 21 8 14 10 16 18 9 27 1 4 22 15 25 17 4 0 0 21 3 15 12 11 23 19 27 10 13 6 22 3 14 6 13 12 9 20 1 20 25
17 4 24 21 11 22 12 13 0 1 17 23 15 4 6 2 27 14 3 16 8 13 3 5 2 6 0 9 23 14 25 26 10 18 19 26 8 11 10 20 21 18 22 20 25 9 7 12 1 7 19 16 5 27 15 24
8 27 28 24 9 9 16 22 13 20 23 25 13 21 0 26 21 8 16 24 27 18 26 23 3 7 3 25 22 15 14 6 5 7 11 4 1 20 17 19 17 12 4 14 2 1 5 18 2 28 12 0 10 19 15 11 6 10
21 9 3 23 27 4 15 22 12 2 16 26 4 13 28 16 20 6 6 3 10 1 18 5 11 0 21 7 8 25 23 17 9 15 22 14 24 2 5 10 12 17 20 1 24 7 18 0 14 26 19 13 28 25 11 8 27 19
26 10 19 20 17 10 9 19 7 15 4 27 0 15 18 2 6 2 22 6 12 25 11 9 24 26 5 11 5 21 17 7 8 4 18 14 16 24 28 1 3 28 27 14 12 8 13 13 23 3 16 23 25 21 22 0 1 20
1 0 19 11 20 17 8 3 2 18 7 18 21 5 26 9 10 6 20 2 28 8 26 19 21 17 16 14 3 14 22 12 13 6 24 9 10 22 0 27 11 13 27 7 15 4 28 1 16 23 25 23 25 12 24 15 4 5
5 9 12 7 19 25 6 24 12 6 25 3 1 16 28 2 3 14 16 4 5 26 7 8 20 19 18 22 10 27 13 28 21 17 11 26 4 18 0 20 27 24 15 10 23 11 0 21 9 22 13 14 8 1 17 15 23 2
\$\endgroup\$
  • \$\begingroup\$ If I use an rng, I could get very different results between runs. Perhaps score based on the average of 100 runs? \$\endgroup\$ – Spitemaster Nov 5 '18 at 19:40
  • \$\begingroup\$ @Spitemaster It is possible that a different RNG would change the score to be +1 or -1, but as scores get larger, the RNG seed matters less. If a person posts a solution that required a very specific RNG seed, it wouldn't be reproducible, and therefore, invalid. \$\endgroup\$ – Nathan Merrill Nov 5 '18 at 20:14
  • \$\begingroup\$ This seems like a nice challenge but it's a bit vague. What do you mean by "Your function must use this [32 bytes of] data". We can't use local variables? Do we have to assign that parameter that was passed to us in the function call to another value to be able to store data? \$\endgroup\$ – FireCubez Nov 8 '18 at 18:50
0
\$\begingroup\$

Name: Create a Programming Language

Tags: code-bowling, and cops-and-robbers

Cops:

The cops must design a programming language that takes in the contents of the program from a default I/O method, and do something.

Rules:

  • The program must not print anything to STDERR
  • The program must be able to output to STDOUT with certain program contents of your choice
  • The program must be able to calculate any function up to \$f_{\omega}(n)\$ where f is the fast-growing hierarchy. In other words, it needs to be able to evaluate any primitive-recursive statement.
  • There cannot be a way to execute commands in other languages (for example, if there is a command in your programming language that can execute Python code based on the argument, that would be cheating)

Since there are tons of loopholes, whether or not the answer is valid is up to me (and also, standard loopholes are also not allowed).

Robbers:

Your job is to make the same compiler (which does the same thing with the same commands given as the equivalent cop answer), with more characters. The programming language may be different.

Standard loopholes aren't allowed, and whether an answer is valid or not will be judged by me.

As always, since this is code-bowling, aim for the most bytes!

\$\endgroup\$
  • 3
    \$\begingroup\$ "whether or not the answer is valid is up to me" unfortunately, this is going to make the challenge unclear. \$\endgroup\$ – Erik the Outgolfer Nov 6 '18 at 20:35
  • 4
    \$\begingroup\$ I'm afraid I don't really understand the core of this challenge. The robbers have to make the compiler larger without affecting its functionality? That seems trivial to do; just add a comment or some whitespace. \$\endgroup\$ – Dennis Nov 6 '18 at 21:26
  • \$\begingroup\$ Your job is to make the same compiler ... with more characters Should this be less characters? also, shouldn't it be bytes? \$\endgroup\$ – Jo King Jan 29 at 5:06
  • \$\begingroup\$ @JoKing Yeah, I realized that. \$\endgroup\$ – MilkyWay90 Jan 29 at 12:24
0
\$\begingroup\$

Lunar Arithmetic

Lunar Arithmetic (also called dismal arithmetic, a play on decimal) is an alternative to elemental arithmetic in which only addition and multiplication is defined, and then only for non-negative integers. For single-digit numbers, addition is defined as the maximum of the two digits, and multiplication is defined as the smaller of the two digits. For example:

2 + 5 = 5 + 2 = 5
2 * 5 = 5 * 2 = 2

To extend lunar addition to multi-digit numbers, simply consider the digits individually, counting empty digit places as zeroes as required. For example, consider 169 + 84:

  1 6 9
+   8 4
  -----
  1 8 9

Lunar multiplication can now be dealt with in the same way as normal long multiplication, using the lunar rules for addition and multiplication. For example, consider 169 * 84:

    1 6 9
*     8 4
  -------
    1 4 4    (169 * 4)
+ 1 6 8      (169 * 8)
  -------
  1 6 8 4

The challenge

Write a function or program which, when given two integers, returns the result of their lunar addition and their lunar multiplication, in any order.

  • The input pair may be presented as a two-element list or array.
  • Input numbers may be provided in any reasonable format, including as a string, or as a list of digits.
  • Output may similarly be in any reasonable format.
  • The two output numbers must be separated in an unambiguous way, such as with newlines, spaces, as elements of a list or array.
  • Links to online demonstrations are appreciated, but not required.
  • Standard loopholes are disallowed.
  • This is , so shortest code in bytes per language wins!

In your submission, please specify the order in which the two results are presented, and your input and output formats if they are out of the ordinary.

Test cases

Test cases go here

Resources

Original paper outlining dismal arithmetic

Numberphile video discussing lunar arithmetic

Tags


Sandbox business

I see this as the potential starting point for a number of Lunar arithmetic challenges, such as computing the result of a longer calculation (such as 12+345*67*8), identification of lunar primes, lunar prime factorisation, methods of implementing subtraction and division... Of course that all depends on the response to this challenge. Any feedback on how to make this challenge better would be much appreciated!

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

Posted: FreeChat Online

\$\endgroup\$
  • 4
    \$\begingroup\$ You're posting to main way too fast. I recommend waiting for at least a couple of days; people have to read before giving you some feedback (comment, upvote, whatever) anyway. \$\endgroup\$ – Bubbler Nov 14 '18 at 4:26
  • \$\begingroup\$ okay @Bubbler I'll wait next time \$\endgroup\$ – Michael Nov 14 '18 at 5:21
  • 1
    \$\begingroup\$ After you post a challenge, please edit the post and delete it. \$\endgroup\$ – Laikoni Nov 14 '18 at 13:14
0
\$\begingroup\$

Win 2048

Win 2048. You can decide where to summon block of 2(no 4), and how you move. The output would be [place, place, move, place, move, ..., place, move](finally you reach 2048).

Shortest code win.

SN: Similar to Play a perfect game of 2048 ?

\$\endgroup\$
  • 3
    \$\begingroup\$ (in case somebody don't understand the challenge: the program should take no input, and output any sequence of moves in 2048 game such that the tile 2048 is generated. As said in the challenge, the new block must be [2] (not [4]) and the program can determine where the block appears) \$\endgroup\$ – user202729 Nov 15 '18 at 14:31
0
\$\begingroup\$

Simple ASCII Representation of a Screw Head

Inputs are a string and a number.

If the string is "Slot", the number will be 0, 60, 90, or 120. If the number is 0, output --; if 60, output /; if 90, output |, if 120, output \.

If the string is "Phillips", the number will be 0, 45, 90, or 135. If it's 0 or 90, output +; otherwise output x.

If the string is "Torx", the number will be 0, 60, or 120. Regardless of the value, output *.

If the string is "Spanner", the number will be 0 or 90. Output .. for 0 and : for 90.

Behavior for all other inputs is undefined.

[Is this challenge too simple? If so, could more test cases help?]

\$\endgroup\$
  • 1
    \$\begingroup\$ I think adding test cases that require modular division (so you could say Phillips 72270) and error handling (GenericScrewXyz 43 would throw an error). \$\endgroup\$ – wizzwizz4 Dec 2 '15 at 18:31
0
\$\begingroup\$

Display a rational tangle [WIP]

In a quest to classify mathematical knots, J. H. Conway discovered that certain simpler knotlike structures called rational tangles can be uniquely represented by rational numbers.

A tangle is an arrangement of two strands of rope such that each of the four ends lies at one corner of a rectangle. The four exceptional tangles are 0, 1, -1, and a special case usually referred to as 0/0 or ∞. A rational tangle is a tangle that can be obtained from the exceptional tangles by the following operations.

Example of rational tangles

An example of a rational tangle, and the tangles 0/0, 0, 1, and -1 respectively.

enter image description here

The rational tangle operations

Because every rational number can be obtained by addition, negation, and reciprocal, there exists some rational tangle corresponding to every rational number.

If tangle a and b have rational number values x and `y respectively, then the operations in the diagram result in the following values.

Tangle |  Value
-a          -x
1/a         1/x
a + b      x + y
a b       -x + y
a , b     -x + -y   

Challenge

Using the below representations of the four exceptional rational tangles, display an ASCII art rational tangle corresponding to a given rational number.

Exceptional rational tangles

\_/   \ /
 _    | |
/ \   / \

3x3 ASCII art representing the rational tangles 1/0 and 0

\ /   \ /
 \     /
/ \   / \

The rational tangles 1 and -1, illustrating how to display crossings

Displaying more complex rational tangles

Adding and rotating the above 3x3 blocks and rotation can yield any rational tangle.

  • To flip a rational tangle over the line x=y, switch all instances of 1 and -1, switch all instances of 0/0 and 0, and replace all extenders (below) as appropriate.

  • To rotate a rational tangle by 90 degrees in either direction, rotate the ASCII art by 90 degrees in that direction, switch all \ and /, switch all instances of 0/0 and 0, and replace all extenders (below) as appropriate.

  • To add two rational tangles, juxtapose them in the appropriate direction and orientation, adding extenders if dimensions do not match. Then surround the result with the following.

Pattern to surround the sum of two tangles in:

\ ... /

⋮      ⋮

/ ... \

Extenders:

 \        /
  |      |
 ...    ...
  |      |
   \    /

\_..._
      \

 _..._/
/

Examples

One possible representation of the tangle obtained through the equation [...]. This tangle is congruent to [...] because =.

 \       /
  \_   _/ 
    \ /  
     /   
  __/ \_ 
 /      \
 \      / 
  \ /\ / 
   \  \  
  / \/ \
 /      \
/        \

Input

A rational number. If you instead take input as an ordered pair (numerator,denominator) of integers, you will have denominator >= 0. (Denominator 0 is necessary to represent 0/0.)

Output

An ASCII-art representation of the rational tangle corresponding to said number, where a crossing is displayed as one of the above. Whitespace can occur anywhere. Output can contain unnecessary copies of 0, or have other variations as long as the rational tangle is obtained by operations whose corresponding arithmetic operations result in the input.

Further sources

A further explanation of tangles and rational tangles: (https://rationaltangle.wordpress.com/what-are-tanglesrational-tangles/)


TODO: Reciprocal operation, better example, reference implementation

Should continued fraction representations be acceptable?

Since this is probably a difficult challenge and answers to such are undervoted, I'm prepared to award a bounty to the shortest answer and any improvement thereon.

This is getting more unwieldy. I'm thinking of simplifying into a challenge to simply add two rational tangles.

\$\endgroup\$
  • \$\begingroup\$ The introduction seems to be written as a reminder to someone who already knows the topic and needs a refresher. To someone who's never heard of rational tangles before, it throws up a lot more questions than answers. What's 0/0 (other than NaN)? What's ramification? What (other than a+b, which is fairly straightforward) is the diagram supposed to show? The intro says that the ends of the rope must be in the corners of a square: should that say rectangle? In the ASCII art, how do extenders cross? \$\endgroup\$ – Peter Taylor Nov 18 '18 at 21:28
  • \$\begingroup\$ 1. Which part of the diagram corresponds to reciprocal? Does the left-hand part somehow show both negation and reciprocal at the same time? 2. Having looked at your additional reading link, the challenge turns out to be much simpler than the question made it seem. The paragraph starting "The two simplest tangles" and the subsequent one seem to be all that's needed. Perhaps you could use a simple challenge as an introduction and then have a follow-up which asks for an equality test? \$\endgroup\$ – Peter Taylor Nov 18 '18 at 22:41
  • \$\begingroup\$ @PeterTaylor 1. Reciprocal is flipping over some axis, I forget which one. 2. Will do when I have time. I probably won't end up posting this for another month. \$\endgroup\$ – lirtosiast Nov 18 '18 at 22:52
0
\$\begingroup\$

Octonion multiplication

Background

Octonion is a further extension to the quaternion number system. An octonion can be written as

$$ x = x_0 e_0 + x_1 e_1 + x_2 e_2 + x_3 e_3 + x_4 e_4 + x_5 e_5 + x_6 e_6 + x_7 e_7 $$

where \$ x_i \$ are real numbers and \$ e_i \$ are the eight unit octonions.

Octonion multiplication has the following properties:

  • It is not commutative, i.e. \$ xy \ne yx \$.
  • It is not associative, i.e. \$ x(yz) \ne (xy)z \$.
  • But, luckily, multiplication is distributive over addition, i.e. \$ x(y+z) = xy + xz \$ and \$ (x+y)z = xz + yz\$.

The multiplication rule for unit octonions is presented below:

(will add a table from Wikipedia)

The unit octonions have several properties:

  • \$ e_0 \$ behaves like a real number 1.
  • \$ e_i^2 = -1 \$ and \$ e_i e_j = -e_j e_i \$ for \$ 1 \le i,j \le 7, i \ne j \$.

Task

Multiply two octonion numbers.

Input & output

You can accept and output an octonion as any kind of consistent structure consisting of eight real numbers (four complex numbers or two quaternions or a mixture of types is also fine).

Test cases

Coming soon.

Scoring & winning criterion

Standard rules apply. The shortest program or function in bytes for each language wins.

\$\endgroup\$
  • \$\begingroup\$ \$1e_0+2e_1+3e_2+4e_3+5e_4+6e_5+7e_6+8e_7\$ is written in NARS2000 as 1i2j3k4l5ij6jk7kl8. ;-) \$\endgroup\$ – Erik the Outgolfer Nov 19 '18 at 17:11
  • 1
    \$\begingroup\$ Somehow, I think NARS APL will win this one… \$\endgroup\$ – Adám Nov 19 '18 at 18:39
0
\$\begingroup\$

Tetris battle


I guess you know what Tetris is, but if you don't I'll try to explain:

So there is a 2 dimensional board, often with size 10x20. On the top of the board, in the middle, there is a random tetrominoe (also rotated randomly), a figure made of 4 squares. There are 7 shapes:

L    J   S    Z    T   O   I

#    #   ##  ##   ###  ##  #
#    #  ##    ##   #   ##  #
##  ##                     #
                           #

Every second, the tetrominoe (later called "block") will move 1 cell to the bottom until there is no space left. Player can control it - Move it to left, right, rotate it by 90 degrees (left or right) or speed up its fall. When it can't fall down further, a new block is created and you take the control over it, losing possibility to move the previous block.

The target is to get as much points as possible. Player can get them, by filling a line (which is then removed), for example:

        !
        !
        !
****####!$ <- user scores a point, the line is now removed
 &&&&  $$$ 

different character is a different block

Player can lose if there is no place for a new block to spawn.

You can play Tetris online here


The battle

In this challenge, you will have to create a bot to play Tetris. Unlike a normal playthrough, there will be two players playing on a single board.

Let's call the bots A and B.

Block spawning

Every block will start on the left, or right side, depending which bot's it is (left - A, right - B). There will be a 2 block margin, so the block will have some space to rotate. Block will always spawn with left/right align, not centered.

If a block can't fit, it will try to rotate, so it can be placed. If all 4 directions fail, you die.

Example for 10 width board:

--A----B--

Random size board

Width: random even number between 8 and 16.

Height: random number between 15 and 25.

It's to make it a bit harder. Try to plan your strategy so it fits all the heights!

Scoring

You gain 1 point per destroyed block. Some bonus rules apply:

Enemy's block isn't my block

You can't use blocks placed by your enemy to gain score. After adding the last block to a line, you gain as much score as much sub-blocks you placed in it. Enemy sub-blocks don't count. Example:

Player A filled the line.
AAAABBBAAB
Player A gets 6 points.
Player B doesn't earn any.

Combos

If you do a move that removes more than just 1 line, you gain x times more score. Of course, x is the amount of lines.

Player A filled the line
--ABBB
AAABBBABBB <
BBBBBBABBB <
BBBBAAABBB < 
 B AA ABBB
Player A removed 3 lines.
Player A removed 12 (4+5+3) blocks he owns.
Player A scores 36 points.

Death & Game Over

When a new fails to spawn, it tries to rotate 90, 180, 270 or 360 degrees. If it still can't spawn. You lose. Note it won't try to change it's position, so be careful and try to not put any blocks in the spawn area.

When you die, you can't place any more blocks.

  • In case your enemy has more points than you, you lose.
  • Otherwise, the game doesn't end yet – the enemy will get double points for the next 10 blocks. The game will end when the bonus ends, when he beats your score or when he dies.

When the game is over, the bot with more points win.

The game will also end automatically after 300 actions. See API > Actions section for more information.

Controller

Work in progress. https://github.com/Soaku/Tetris-KOTH

API

Can't really tell you how it's gonna look like without a controller, right?

However, there is a project of how it's gonna look like:

Actions

Every game consists of actions. Your bot function will be executed at the beginning of each action. At the end of each, active tetrominoes will move 1 cell to the bottom.

The controller will wait a configurable amount of time between actions unless the preview is disabled.

Your function should return an integer in at most 0.1 seconds, otherwise your action is terminated and ignored. If it will cross the limit repeatedly, I might remove it.

Rules

  • Default loopholes are forbidden.
  • Aggressive bots are allowed but discouraged.
  • You cannot use any external libraries. The controller uses jQuery, but you aren't allowed to use it.
  • Don't try to access the document – Don't write nor read data.
  • Don't write your bot to beat specific enemies by countering their strategies.
  • Enemy spawn works like an occupied block. You cannot place anything here.

Main scoring

Every bot will play with every other bot.

Scoring works this way:

  • Victory: 2 points
  • Tie: 1 point
  • Lose: 0 points
\$\endgroup\$
  • 1
    \$\begingroup\$ I feel like the last part (bonus round) there probably isn't such a good idea. especially since bots are mostly programmed to play against one enemy, so it means a regular bot needs to implement special cases for one round, which really doesn't add much. \$\endgroup\$ – Destructible Lemon Nov 5 '17 at 22:25
  • \$\begingroup\$ If you do decide to make a massively multiplayer one, it's sort of unfair to bots that will perform better at the side that end up in the middle or vice versa, so making it a cylinder (the rows wrap around into themselves) would help \$\endgroup\$ – Destructible Lemon Nov 7 '17 at 8:04
  • \$\begingroup\$ Fine, I removed it from the answer itself, but that doesn't mean I can't do it for fun ( ͡° ͜ʖ ͡°) \$\endgroup\$ – RedClover Nov 8 '17 at 19:44
  • \$\begingroup\$ Just wanted to point out that your J, L, and T tetrominoes actually have 5 squares each; I'm fairly sure that wasn't intentional. \$\endgroup\$ – ETHproductions Nov 8 '17 at 23:48
  • \$\begingroup\$ The question describes things that happen when "enemy is dead", but does not describe what causes that or what happens when "you are dead". \$\endgroup\$ – Kamil Drakari Nov 9 '17 at 16:12
  • \$\begingroup\$ @KamilDrakari [On spawn] If a block can't fit, it will try to rotate, so it can be placed. If all 4 directions fail, you die. \$\endgroup\$ – RedClover Nov 9 '17 at 16:13
  • 1
    \$\begingroup\$ That is an awfully small section for something quite important. I would add a distinct section on Death, clarifying "when dead, you can no longer place blocks" and some edge cases for the 10 bonus pieces, such as what happens if a player dies during their bonus pieces and if they are required to continue placing the full 10 blocks or they can stop once they have a higher score. \$\endgroup\$ – Kamil Drakari Nov 9 '17 at 16:50
  • \$\begingroup\$ @KamilDrakari Oh, you're right. I'll try to add something about that, when I have some time. \$\endgroup\$ – RedClover Nov 9 '17 at 16:51
  • \$\begingroup\$ @ETHproductions I also noticed that J and L are pentominoes. T is actually a hexomino. But... \$\endgroup\$ – Heimdall Nov 11 '17 at 9:59
  • \$\begingroup\$ @ETHproductions thanks for pointing this out. Fixed \$\endgroup\$ – RedClover Nov 11 '17 at 10:00
0
\$\begingroup\$

Make numbers inflate to full width!

Related: Full Width Text

That is a challenge that changes ALL characters into full width -- BY ADDING A SPACE AFTER EACH CHARACTER. However, in this challenge only numbers are transformed, and are transform to the REAL FULL WIDTH FORM

.

This is a short and simple challenge, so I will keep the description short.

Challenge

Write a program / function that accepts an ASCII string as input and outputs a UTF string with each number 0123456789 converted to its corresponding full width form 0123456789. The range of these full width numbers is U+FF10 - U+FF19.

You may output using the following format (As an example This is 1 apple is used):

  • A UTF-8 string (showing exactly This is 1 apple in STDOUT)
  • The same string as above but displayed in a non-UTF-8 encoding (eg. showing This is 1 apple in Windows-1252 codepage). In this case you must state the codepage of the output
  • A single list of UTF-8 bytes as integers that represents the transformed string (showing ord("T"),...,ord(" "),239,188,145,ord(" "),...,ord("e") with arbitrary delimiter)

You cannot mix integer output and character output, that is, you cannot literally change This is 1 apple to This is [239,188,145] apple. You cannot output a nested list if a list is outputted either.

Sample I/O

  • Sample 1:

    Input:  0123456789
    Output: (Format 1) 0123456789
            (Format 2) 0123456789 [CP437]
            (Format 3) 239,188,144,239,188,145,239,188,146,239,188,147,239,188,148,239,188,149,239,188,150,239,188,151,239,188,152,239,188,153

  • Sample 2:

    Input:  This is 1 apple
    Output: (Format 1) This is 1 apple
            (Format 2) This is 1 apple [Windows-1252]
            (Format 3) 0x54 0x68 0x69 0x73 0x20 0x69 0x73 0x20 0xef 0xbc 0x91 0x20 0x61 0x70 0x70 0x6c 0x65

Footnote

This is a , so shortest answer for each language wins. Standard loopholes are forbidden by default.

P.S. I would like to see both practical and esoteric language submissions. Specifically the last two output formats are especially allowed for esoteric languages.

\$\endgroup\$

You must log in to answer this question.

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