476
\$\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 '19 at 7:51
  • \$\begingroup\$ @guest271314 You can use this markup to create a tag in a draft: [tag:code-golf] \$\endgroup\$ – James Aug 29 '19 at 15:19
  • 3
    \$\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 '19 at 13:43

2839 Answers 2839

1
81 82
83
84 85
95
0
\$\begingroup\$

Morse with Binary

For every input string (in ASCII, containing only lowercase alphabetic characters), output the alphabetic string converted from Morse code to Binary code.

In this case we are assuming that . is 0 and - is 1.

How to do the conversion

For reference, here are a few Morse code libraries:

a .-
b -...
c -.-.
d -..
e .
f ..-.
g --.
h ....
i ..
j .---
k -.-
l .-..
m --
n -.
o ---
p .--.
q --.-
r .-.
s ...
t -
u ..-
v ...-
w .--
x -..-
y -.--
z --..

What's amazing about those codes is that the code length never exceeds 4 codes.

And now we are trying to cofuse binary with Morse code. First let's convert sample to morse code:

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

And consider the whole thing as a binary:

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

Here is an alternative table for mapping the characters:

a ....
b ...-
c ..-.
d ..--
e .-..
f .-.-
g .--.
h .---
i -...
j -..-
k -.-.
l -.--
m --..
n --.-
o ---.
p ----

The result of this operation, after conversion, is aomi. You are never going to end up with a letter past p.

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ What if there is a group of characters remaining? Input: e, Output: ? \$\endgroup\$ – Element118 Jan 1 at 5:23
0
\$\begingroup\$

Quine Generator Generator... of any* length!

A Quine Generator Generator... is a quine when the input is empty or 0. Otherwise, for any other sufficiently large positive integer input, it should print a Quine Generator Generator... of that specified length (in the same language, same options).

Let S be the (most likely theoretically infinite) set of Quine Generator Generator... you can generate from your initial Quine Generator Generator....

Your score is the smallest N such that any Quine Generator Generator... in S can generate a Quine Generator Generator... of length N or longer (for reasonably sized N).

Input can be from standard input or as an argument of a function.

Lowest score wins.

Sandbox Meta:

Typically, code is scored by bytes, but now the length would depend on how that is interpreted, since it is included in the description of the question. Hence would it be a problem to put: "You may choose to define characters in terms of bytes or characters (should they differ) for purposes of the program length and scoring purposes."

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

Integer Keys and Duplicates

Given a list/vector of positive integers, write a function to check the following conditions in as few bytes as possible.

  1. Take the first integer (the key, or k1) and check that the next k1 values have no duplicate values, excluding k1.
  2. Take the last integer (the second key, or k2) and check that the k2 values before k2 have no duplicate values, excluding k2.

Note that both keys, k1 and k2, are elements of the list/vector as either key could contain the other.

Also, k1 and/or k2 can be greater than the number of integers within the list, which means you should check every element of the list besides the given key for duplicates, excluding the key.

If both steps return True, return True, else, return False.

Test Cases

[5,1,2,5,3,4,3] is TRUE because [k1=5][1,2,5,3,4] has no duplicates, nor does [5,3,4] have any duplicates, excluding 3

[6,9,12,15,18,19,8,8,3] is FALSE because [k1=6][9,12,15,18,19,8] has no duplicates while [19,8,8][k2=3] has a duplicate.

[100,100,100,100,101,102,3] is TRUE because [k1=100][100,100,100,101,102,3] has no duplicates, and [100,101,102][k2=3] has no duplicates.

[100,100,100,100,101,102,4] is FALSE. [k1=100][100,100,100,101,102,4] has no duplicates, but [100,100,101,102][k2=4] has duplicates.

[6,6,6,6,6,6,6,3,3,3,3] is TRUE. [k1=6][6,6,6,6,6,6] has no duplicates and [3,3,3][k2=3] has no duplicates.

[1,2] is TRUE (clearly)

[1] is TRUE (clearly)

[] the empty list is also TRUE (if you can make a valid argument why it should be FALSE then I might give it to you)
| |
\$\endgroup\$
0
\$\begingroup\$

Drum fill generator

Create a program that generates a drum fill. Your program will output a pattern of L (left hand hits), 'R' (right hand hits), and K for kick drum hits.

Rules

  • The pattern must never have more than 2 of the same hits consecutively.
  • The pattern must be loopable, so it mustn't have more than 2 of the same hits when it loops.
  • Your program accepts 1 argument which is the length of the pattern. You can assume this will always be an integer > 0.
  • Program output must be random each time it's ran.
  • IO can be used with any convenient method.
  • Standard loopholes are forbidden.
  • This is code-golf, so smallest program wins!

Example valid output:

RLRRKKLL
LRLLKKLR
LKKRLRKLRRKL
LRLR

Example invalid output:

LRLL // 3 characters when looped
LRLRRRLLR // 3 characters in a row
RRLRLLRR // 4 characters when looped
| |
\$\endgroup\$
  • \$\begingroup\$ What's a paradiddle? You should include a description in your question \$\endgroup\$ – Jo King Jan 4 at 5:18
  • \$\begingroup\$ How's that? I added more detail on what the rules/patterns are. \$\endgroup\$ – TMH Jan 4 at 21:18
  • 1
    \$\begingroup\$ No it must be random each time the program is ran, I'll add that to the rules now, thanks :). \$\endgroup\$ – TMH Jan 5 at 21:16
0
\$\begingroup\$

Theorem proving code golf: a+(b+c)=b+(c+a)

Notes

This challenge is restricted to the languages with dependent type support. Some examples include Idris, Agda, Coq, Lean (which are designed for theorem proving), and Haskell with certain extensions enabled.

In these languages, a theorem is considered equivalent to a type, and writing a proof of a theorem is equivalent to providing a value of the given type (due to Curry-Howard correspondence). For example, the "modus ponens" rule

$$ P,(P \rightarrow Q) \rightarrow Q $$

could be expressed as a function type

(p : P) -> (pq : P -> Q) -> Q

and have a proof by function application like the following:

thm : (p : P) -> (pq : P -> Q) -> Q
thm p pq = pq p

But a recursive definition requires an additional constraint that it is terminating, i.e. the recursive calls are done with smaller arguments so that it eventually reaches the base case. This is to prevent erratic proofs like a : False := a, which evokes an infinite loop to fake a value of empty type False.

A recursive proof is usually analogous to a proof by (weak or strong) induction.

Task

Given the Peano natural numbers and addition

$$ n : \mathbb{N} := \text{Zero } | \text{ Succ }n \\ a+ \text{Zero} := a, a+ \text{Succ } b := \text{Succ }(a+b) $$

express the following statement in code and prove it:

$$ \forall a,b,c\in \mathbb{N}, a+(b+c)=b+(c+a)$$

The theorem should have the type of (or your language's equivalent of)

forall a b c : nat, a + (b + c) = b + (c + a)

or, in function notation,

(a : nat) -> (b : nat) -> (c : nat) -> a + (b + c) = b + (c + a)

Condition

You're free to use a library provided with your language of choice. If the library uses the flipped definition of Peano addition, it's fine to use it instead. As usual for , you need to count the bytes used for imports.

For theorem-proving languages (where infinite loops are rejected by the compiler), a successful compilation usually means a correct proof. If it is not the case, you should provide an explanation that the definition is indeed terminating.

If you find a bug in some theorem-proving language that allows to prove anything, using it is not allowed, as it is not considered as a solution to the given task.

Scoring and winning criterion

Standard rules apply. The shortest code in bytes wins.


Meta

  • Is it a good idea for a CGCC challenge? I once learned Coq and a bit of Lean, and I thought minimizing code by clever usage of tactics and/or explicit definitions could be interesting.
  • Is the task appropriate for an introductory challenge in this topic? I just made up a statement that looks less likely to be in a standard library, but is easy enough to prove by commutativity and associativity.
| |
\$\endgroup\$
  • 1
    \$\begingroup\$ There is already proof-golf, which has all well received questions (though they've all been asked by one user). This is a bit different, and I think you need to try to work out some of the kinks if you want to ask it this way. Mostly, your definition of "prove" feels a tad loose. I've not used such languages, but I recommend trying to find a common element amongst them so you can be more precise. Perhaps you will want to prove something over a finite field instead, so an exhaustive proof can terminate? \$\endgroup\$ – FryAmTheEggman Jan 7 at 21:41
  • \$\begingroup\$ @FryAmTheEggman Thanks for the suggestion. I tried to clarify what a proof means in this context. I initially thought about proof-golf too, but listing out the rules of entire CIC theory is probably out of the question. (Probably I could extract the needed rules if I limit to the natural number type; I'll think about it later.) \$\endgroup\$ – Bubbler Jan 8 at 0:44
0
\$\begingroup\$

Interpret LCGFuck™

Introduction

LCGFuck™ is a Brainfuck-like esoteric programming language invented by me. Inspired by Brainfuck and linear congruential generators (LCGs), LCGFuck™ combined both things into one.

An LCG in LCGFuck™ is defined with 5 integers, namely multiplier a, adder b, modulus c, offset d and seed e. Let x be its current state, then the corresponding output will be x + d, and the next internal state x' of the LCG can be calculated by x' = (a * x + b) mod c. All numbers should be non-negative except for d. Moreover, b and e should be in the range [0, c).

Technical details

An LCG is defined with 5 numbers, like 12345 678 90 -123 45. The last two numbers are optional and default to 0.

LCGFuck™ has 3 storage variables, the LCG list, the number list and the number memory. The functions are as follows:

  • LCG list: Cyclic list that stores all LCGs created. Every entry is in turn a list of 5 numbers in the order [a, b, c, d, e] as notated in the introduction. It has a pointer that controls which LCG is chosen at the moment, and moves in a cycle through the list.
  • Number list: Ordinary list that stores the numbers for LCG definition. It can store at most 5 numbers.
  • Number memory: A single variable that can be read and written with an input or an LCG output.

LCGFuck™ has 14 operators, namely:

  • \n (newline): Creates an LCG with the numbers in the order of [a, b, c(, d(, e))] and clears the list if the number list contains 3 or more numbers. No-op if the number list contains no more than 2 numbers.
  • <: Shifts to the previous LCG circularly (back to the last when moving from the first).
  • >: Shifts to the next LCG circularly (back to the first when moving from the last).
  • +: Moves the current LCG to the next state (calculates x' = (a * x + b) mod c)
  • c: Prints the output of the current LCG as a character (with the output as the codepoint).
  • n: Prints the output of the current LCG as a number (with a trailing space)
  • o: Writes the output of the current LCG to number memory
  • i: Reads a value from the input and writes it to number memory. There is two input mode, one reading a character one time, and one reading a number one time. You do not need to implement this operator in this challenge.
  • s: Reads the value from number memory and seeds the current LCG with it
  • m: Reads the value from number memory and pushes it to the number list
  • []: Output loop. Executes the loop if the current LCG is non-zero
  • {}: State loop. Executes the loop if the state of the current LCG is non-zero

An integer, optionally with a negative sign at the front, pushes the number to the number list. Any characters other than the newline \n and any of -0123456789[]{}<>+cimnos are no-ops.

The code runs linearly from the first characters, except when loop ends are encountered. Loops can be nested but must be paired accordingly from the innermost loop to the outermost loop.

Challenge

Write an interpreter, making it as short as possible, that interprets the LCGFuck source code given as the input. You need not implement the i operator in this challenge. The output should be printed to STDOUT or returned in case of writing a function.

You may assume that your interpreter always receives valid programs, i.e.:

  1. An LCG is always defined before any of the commands that manipulate the LCG or the LCG list pointer
  2. At any moment the number list contains at most 5 numbers
  3. All brackets are paired accordingly

Standard loopholes are forbidden by default.

Sample implementation with operator i (Primality check)

Sample

The LCG list need not be printed out. It is just for illustration purpose.

  1. The "Hello world!" program in LCGFuck™ is as follows:

    1 29 30 72
    1 3 9 108
    1 1 2 32
    c+c>cc+co>c
    1 8 9 m
    >+c<<c+c+c<+c>>+c
    
    • Output: Hello world!

    • LCG list after execution:

      [1, 29, 30, 72, 28]
      [1, 3, 9, 108, 0]
      [1, 1, 2, 32, 1] < Current LCG
      [1, 8, 9, 111, 8]
      
  2. An example that outputs the values of x - 16, where x is the states of the LCG x' = (19x + 17) mod 32, starting with seed x = 4, until the output is 0:

    19 17 32 -16 4
    [n+]n
    
    • Output: -12 13 8 9 -4 5 -16 1 4 -3 -8 -7 12 -11 0

    • LCG list after execution:

      [19, 17, 32, 16, -16] < Current LCG
      
  3. An example that outputs all possible values of 5(x + 12), where x is the states of the LCG x' = (5x + 3) mod 8:

    5 3 8 12
    5 0 99
    o>s+n<+{o>s+n<+}
    
    • Output: 60 75 70 85 80 95 90 65

    • LCG list after execution:

      [5, 3, 8, 12, 0] < Current LCG
      [5, 0, 99, 0, 65] 
      
  4. An example illustrating the 3-number restriction of \n (the 9 in the 3rd line is pushed to the number list but the LCG is defined before the 9 is pushed):

    12 34
    56 78
    9
    n
    
    • Output: 78

    • LCG list after execution:

      [12, 34, 56, 78, 0] < Current LCG
      
  5. An example that determines whether 97 is a prime:

    1 -1 97 0 -1
    {o+1 1 m 0 97
    }>{>}o+{o+}<{<}s
    1 1 1 32
    1 4 12 69 4
    1 1 7 78 2
    {<+++++c+c+++++c+++
    <<c>>>{+}}<c++c<c+c+c
    
    • Output: PRIME

    • LCG list after execution:

      [1, -1, 97, 0, 0]
      [1, 1, 96, 0, 1]
      [1, 1, 95, 0, 2]
      [1, 1, 94, 0, 3]
      [1, 1, 93, 0, 4]
      [1, 1, 92, 0, 5]
      [1, 1, 91, 0, 6]
      [1, 1, 90, 0, 7]
      [1, 1, 89, 0, 8]
      [1, 1, 88, 0, 9]
      [1, 1, 87, 0, 10]
      [1, 1, 86, 0, 11]
      [1, 1, 85, 0, 12]
      [1, 1, 84, 0, 13]
      [1, 1, 83, 0, 14]
      [1, 1, 82, 0, 15]
      [1, 1, 81, 0, 16]
      [1, 1, 80, 0, 17]
      [1, 1, 79, 0, 18]
      [1, 1, 78, 0, 19]
      [1, 1, 77, 0, 20]
      [1, 1, 76, 0, 21]
      [1, 1, 75, 0, 22]
      [1, 1, 74, 0, 23]
      [1, 1, 73, 0, 24]
      [1, 1, 72, 0, 25]
      [1, 1, 71, 0, 26]
      [1, 1, 70, 0, 27]
      [1, 1, 69, 0, 28]
      [1, 1, 68, 0, 29]
      [1, 1, 67, 0, 30]
      [1, 1, 66, 0, 31]
      [1, 1, 65, 0, 32]
      [1, 1, 64, 0, 33]
      [1, 1, 63, 0, 34]
      [1, 1, 62, 0, 35]
      [1, 1, 61, 0, 36]
      [1, 1, 60, 0, 37]
      [1, 1, 59, 0, 38]
      [1, 1, 58, 0, 39]
      [1, 1, 57, 0, 40]
      [1, 1, 56, 0, 41]
      [1, 1, 55, 0, 42]
      [1, 1, 54, 0, 43]
      [1, 1, 53, 0, 44]
      [1, 1, 52, 0, 45]
      [1, 1, 51, 0, 46]
      [1, 1, 50, 0, 47]
      [1, 1, 49, 0, 48]
      [1, 1, 48, 0, 1]
      [1, 1, 47, 0, 3]
      [1, 1, 46, 0, 5]
      [1, 1, 45, 0, 7]
      [1, 1, 44, 0, 9]
      [1, 1, 43, 0, 11]
      [1, 1, 42, 0, 13]
      [1, 1, 41, 0, 15]
      [1, 1, 40, 0, 17]
      [1, 1, 39, 0, 19]
      [1, 1, 38, 0, 21]
      [1, 1, 37, 0, 23]
      [1, 1, 36, 0, 25]
      [1, 1, 35, 0, 27]
      [1, 1, 34, 0, 29]
      [1, 1, 33, 0, 31]
      [1, 1, 32, 0, 1]
      [1, 1, 31, 0, 4]
      [1, 1, 30, 0, 7]
      [1, 1, 29, 0, 10]
      [1, 1, 28, 0, 13]
      [1, 1, 27, 0, 16]
      [1, 1, 26, 0, 19]
      [1, 1, 25, 0, 22]
      [1, 1, 24, 0, 1]
      [1, 1, 23, 0, 5]
      [1, 1, 22, 0, 9]
      [1, 1, 21, 0, 13]
      [1, 1, 20, 0, 17]
      [1, 1, 19, 0, 2]
      [1, 1, 18, 0, 7]
      [1, 1, 17, 0, 12]
      [1, 1, 16, 0, 1]
      [1, 1, 15, 0, 7]
      [1, 1, 14, 0, 13]
      [1, 1, 13, 0, 6]
      [1, 1, 12, 0, 1]
      [1, 1, 11, 0, 9]
      [1, 1, 10, 0, 7]
      [1, 1, 9, 0, 7]
      [1, 1, 8, 0, 1]
      [1, 1, 7, 0, 6]
      [1, 1, 6, 0, 1]
      [1, 1, 5, 0, 2]
      [1, 1, 4, 0, 1]
      [1, 1, 3, 0, 1]
      [1, 1, 2, 0, 1]
      [1, 1, 1, 0, 0]
      [1, 1, 1, 32, 0]
      [1, 4, 12, 69, 0] < Current LCG
      [1, 1, 7, 78, 4]
      

Winning criteria

Since this is a code-golf challenge, the shortest solution for every language wins.

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

I'm stepping down

You are given 4 positive integers: volume of the first container (v1), volume of the second container (v2), volume of the liquid in the first container (l1), and volume of the liquid in the second container (l2). Your task is to move (or "step down", if appropriate) some of the liquid from container 1 to container 2, making the amount of empty space in the containers equal to each other, outputting how much liquid should be moved.

An example

Here is an example of some possible input (formatted for the ease of test cases. The input isn't formatted.):

8 11
6  5

Here, you need to make sure that the differences between the volumes and the containers are equal. Currently the difference is not equal:

  8 11
- 6  5
======
   6 2

So we need to try to make them equal, by taking some of the values in one container to another container:

  8 11
- 4  7
======
  4  4

After you have succeeded, output how much liquid you need to take from container 1 to container 2. Therefore the above example should output 2.

Test cases

15 16
 9  2

We move into this state:

 15 16
- 5  6
======
 10 10

Therefore 4 is the expected result.

Test case #2

16 12
13  1

We move into this state:

 16 12
- 9  5
======
  7  7

Therefore 4 is the expected output.

Test case #3

20 12
10 2

Moved:

 20 12
-10 2
======
 10 10

Therefore 0 is the expected output.

Rules

  • The test cases will be made so that the result is always possible as a positive integer. The result will never be a decimal.
  • Input can be taken in any convenient and reasonable format.
  • Output can be given in any convenient and reasonable format.
  • The input string will be made so that a moving is always possible without involving decimals or negative numbers. Also there will not be more liquid than how much a container can hold.
  • Of course, this is , so the answer in each language consisting of the fewest number of bytes wins. Happy golfing!
  • An extra restriction for the test cases: you can assume that there is always going to be space available in the second container. So a test case like this:
10 2
 2 2

is not going to be a valid testcase.

| |
\$\endgroup\$
  • \$\begingroup\$ So, it just calculate abs(v1-l1-v2+l2)/2? It seems trivial to me. And what should I do if the calculate result is not an integer? \$\endgroup\$ – tsh Jan 13 at 6:03
  • \$\begingroup\$ May I assume the solution always exits? What should I do if input is v1=10,l1=2,v2=2,l2=2? \$\endgroup\$ – tsh Jan 13 at 9:17
  • \$\begingroup\$ The test cases will not contain calculations that yield decimal results; also you can assume that there is always enough empty space in the second container to move the liquid. \$\endgroup\$ – user85052 Jan 13 at 13:26
  • \$\begingroup\$ I find the challenge title confusing. Please change it. \$\endgroup\$ – Beefster Jan 20 at 17:40
  • \$\begingroup\$ @Beefster The challenge is already posted, and after at least 35 people agreed with you, someone else changed the title. @ a'_': please edit this Sandbox post so it only contains the title and link to the posted challenge and delete it from the Sandbox please (as mentioned in bold in the "What is the Sandbox?" post at the top). \$\endgroup\$ – Kevin Cruijssen Jan 22 at 10:49
0
\$\begingroup\$

He. Might. Go. All. The. Way. Touchdown!

[in-progress]

Premise:

In American Football, a team has to drive up the field to their opponent's end-zone to score points. But here's the catch, they have 4 tries (called downs) to go at least 10 yards to gain a new set of downs. They repeat this until they score a Touchdown, or until they fail to get 10 yards and (at least in this challenge) punt it away or go for a Field Goal.

Your task is to simulate such a drive.

Challenge:

You are to output the state of each down, i.e. which down it is, how far to the next down (or the end-zone), and where the ball is. Football location counts up from a team's end-zone (0yd line) up to the 50yd line (the middle), then back down to 0 for the opponent's end-zone.

We differentiate the sides of the field by prefixing the location with the team's name. In this challenge, you can use a 1 character label or use positive and negative values. It must go 0-49,50,49-0 and have a way to differentiate between the sides. Your choice on who owns the 50yd line.

Sample Output: (Our team is A, the opponent's team is B)

1st & 7 on A 13
2nd & 10 on A 48
3rd & 12 on 50 OR 3rd & 12 on A 50 OR 3rd & 12 on B 50
4th & 8 on B 10
2nd & Goal on B 7 (read ahead)

Your team will start on your own 1 yard line on 1st & 10 (1st down, 10 yards to go for another first down). You will then gain a uniformly random number of yards between [-3,10] called N. If you didn't get enough for a 1st down, it will now be 2nd & (10 - N). Repeat drawing another number between [-3,10] and adding the yardage for 2nd and 3rd downs if it's still not enough for a 1st down. If you do gain enough for a 1st down, you simply go back to 1st & 10 on the next go and continue going down the field.

On 4th Down, your team is playing safe and will either punt or go for a Field Goal. If you are further away than their 40, output P. If you're within 40 yards, you will attempt a Field Goal with 100 - Yards Away% chance of success. If you succeed, output FG. If you miss, output NG ("No Good"). Afterwards, terminate.

However, there are two special situations that must be handled.

If you get within 10yd (inclusive) and gain a 1st Down, It will then be 1st & Goal and there are no more opportunities to gain 1st downs. Do or die! If you score, output TD and terminate, otherwise you'll follow the normal Field goal rules.

If you lose enough yards to go into your own end-zone, that's called a Safety. Simply output a S and terminate.

Rules:

  • No usable input will be provided
  • Output is flexible. Tuples and lists of lists are all fine.

Sample Runs:
To-Do

Tags: Code-golf, random, game


Feedback? Does the Field goal add enough meat to be worth including?

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

What order(s) can I fire my tonics in?


Helsing's Fire is a classic mobile game about light. You fire blasts of holy retribution (from chemicals called tonics), using cover to selectively hit enemies in the right sequence.

For this challenge, we're going to ignore the line-of-sight stuff and focus on just the tonic order. Each monster is represented by a string like RBBGB—this indicates that, in order to kill it, you need to hit it with a red tonic, followed by 2 blue tonics, then one green tonic and finally one more blue tonic.

Since you're allowed to ignore cover and pick any subset of the monsters to hit, any of the following sequences will kill it:

RBBGB
GRBBGBRR
RBBBBBBBBBBBBBBBGGGGBR
RRRBGGGBBRGRBB

Your goal is to take in a list of monsters as well as how many of each tonic you have, and output every possible ordering of tonics that kills every monster, including ones where not every tonic is fired. For instance:

R; 2 red -> R, RR
R; 1 red/1 blue -> R, RB, BR
No monsters, but tonics -> every possible permutation of the tonics listed
No tonics, but monsters -> no output, empty set output, or single trailing separator
Neither tonics nor monsters -> empty string
RB,BR; 2 red/2 blue -> RBR, BRB, BRBR, RBBR, RBRB, BRRB
RR,RR,GRG,R,GBR,GR,GRRR,GGR,GB,G,R,BBR; 3 red/2 blue/2 green -> BGRRBGR, BGRRGBR, BGRBRGR, BGRBGRR, BGRGRBR, BGRGBRR, BGBRRGR, BGBRGRR, GRRBBGR, GRRBGBR, GRRGBBR, GRBRBGR, GRBRGBR, GRBBRGR, GRBBGRR, GRBGRBR, GRBGBRR, GRGRBBR, GRGBRBR, GRGBBRR, GBRRBGR, GBRRGBR, GBRBRGR, GBRBGRR, GBRGRBR, GBRGBRR, GBBRRGR, GBBRGRR
BR,R,BR,RBBR,RBR,RGB,RGBR,GB,RGR,GG,GRB,G; 3 red/2 blue/2 green -> RBGRBRG, RBGRBGR, RBGRGBR, RBGGRBR, RGRBBRG, RGRBBGR, RGRBGBR, RGRGBBR, RGBRBRG, RGBRBGR, RGBRGBR, RGBGRBR, RGGRBBR, RGGBRBR, GRRBGBR, GRRGBBR, GRBRGBR, GRBGRBR, GRBGBR, GRBGBRR, GRGRBBR, GRGBRBR, GRGBBR, GRGBBRR

Would there be a duplicate for this?

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

Elect the Doge of Venice!

The Venetian election system was... complicated.

The Great Council came together and put in an urn the ballots of all the councilors who were older than 30. The youngest councilor went to St Mark's Square and chose the first boy he met who drew from the urn a ballot for each councillor and only those 30 who got the word ‘elector' remained in the room. The 30 ballots were then placed back in the box and only 9 contained a ticket, so the 30 were reduced to 9, who gathered in a sort of conclave, during which, with the favourable vote of at least seven of them, they had to indicate the name of 40 councillors.

With the system of ballots containing a ticket, the 40 were reduced to 12; these, with the favourable vote of at least 9 of them, elected 25 others, which were reduced again to 9 who would elect another 45 with at least 7 votes in favour. The 45, again at random, were reduced to 11, who with at least nine votes in favour elected another 41 that finally would be the real electors of Doge.

These 41 gathered in a special room where each one cast a piece of paper into an urn with a name. One of them was extracted at random. Voters could then make their objections, if any, and charges against the chosen one, who was then called to respond and provide any justification. After listening to him, they preceded to a new election, if the candidate obtained the favourable vote of at least 25 votes out of 41, he was proclaimed Doge, if they were unable to obtain these votes a new extraction took place until the outcome was positive.

Venice is no longer an independent republic, but if they were, they would be dying to automate this system! (because we all know electronic voting is the future!) Time for you to step in. Your program is to do the following.

  • Here is the list of members of the Great Council (who are all older than 30). Take this as input, by perhaps reading it from a file, or whatever you prefer. The number of councillors varied over time, so your program should work for any list of sufficient length.
  • Take the youngest member of the council. Because there are no ages given, you'll have to guess. Pick a person at random, and print: "[Name] goes to St Mark's Square".
  • The boy at the square will pick thirty members from an urn. So, randomly choose 30 people from the list (not including the youngest councillor). Print "1 selected 30: " followed by the names of each of the thirty members in this round, separated by ", ".
  • Of those thirty, nine are randomly selected to go to the next round. So randomly choose 9 from that group, and print "30 reduced to 9: " followed by those nine electors.
  • Those nine electors have to choose forty different councillors. So, from the list of councillors, excluding the electors (but including the twenty-one people from the previous round of thirty who did not become electors), pick forty members. Print "9 selected 40: " followed by those forty people.
  • The forty were reduced to twelve by lot. Pick twelve from these members at random, print "40 reduced to 12: " followed by the dozen.
  • The dozen elected twenty-five councillors. You know the rules by now: pick 25 councillors excluding the 12 (but including anyone not in the 12 who partook in previous rounds), and print "12 selected 25: " followed by the twenty-five.
  • The twenty-five got reduced to nine again. Pick 9 random people from the 25 and print: "25 reduced to 9: " followed by those nine.
  • Those nine selected forty-five councillors. Pick 45 people not in the 9, and print: "9 elected 45: " followed by those people.
  • The forty-five were reduced to eleven. Pick 11 random councillors from those 45, and print "45 reduced to 11: " followed by those 11.
  • The eleven picked forty-one councillors who would elect the doge. Pick 41 people not in the 11, print "11 selected 41: " followed by those people.
  • Finally, these people will elect the Doge of Venice. Pick 1 person, randomly, from the 41. Then print "The new doge is [Name]" And then you can rest and watch the sun set on a democratic universe.

This horrendously complicated system was made to reduce corruption; so however you implement it, every member of the Great Council must have an equal chance of getting elected in the end. I will run your implementation ten thousand times to ensure that's roughly what happens. Abberating programs are corrupt and therefore disqualified.

Other rules:

  • Capitalisation of names must be kept. Expect only names with readable ascii characters (I had to remove a few Nicolò's from the list to make the challenge mildly easier).
  • Always print a list of names separated by the string ", ". A period at the end is not necessary.
  • Print every new instruction on a new line.
  • The list will always have at least 54 people, so enough for this process.
  • For every non-overlapping Italian word of at least 4 characters that can be found in your source code, remove 3/4ths of the length of that word (round up) from your score. A word counts as a sequence of alphanumeric characters that does not have to be consecutive, so "new random: (am-m)[a]" would count because it contains "mamma". Recent English loanwords (words that originate in English, even if they happen to occur in modern Italian, and are still spelled the same way) are not allowed. For golfing languages, modifications/variants of letters like ʀ and ʁ are allowed to count as the letters they are recognisable as. I'll be the judge if it's ambiguous.
  • This is , so your score is the number of bytes in your code. Lowest score wins!

Will add example output later.

Tags:

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ This is rather full of unnecessary requirements that don't seem to add much of anything to the challenge. Why not just require each of these random selections to be unambiguously separated in any format? Why demand odd prefaces to each subtask? Finally the Italian bonus is very weird, and seems to require that you provide an entire lexicon of valid words to be fully specified. \$\endgroup\$ – FryAmTheEggman Jan 17 at 20:02
  • \$\begingroup\$ I have to be honest (not a native Anglophone): I am not sure I can understand what your first two concerns say. The reason I ask for every step to be printed out, if that's what you mean, is because I cannot read Malbolge or Befunge and if I didn't get an indication that this repeated selection is being followed to a tee, I would not be able to tell if the solutions were doing it at all. As for the Italian, that was just a creative addition similar to the even-or-odd puzzle that requires alternating cardinality for source code characters. I'm not married to it though; it just felt right to me. \$\endgroup\$ – KeizerHarm Jan 17 at 20:36
  • 1
    \$\begingroup\$ I'm sorry that I wasn't clear. I intend to ask why you require outputs like "30 reduced to 9:". Since the order of the operations is fixed, there's no reason to require this. I guarantee your challenge will be better received if you remove those requirements. The Italian addition would be fine, only it is deeply unclear. "I'll be the judge if it is ambiguous" isn't the standard we hold challenges to - you need to specify precisely what counts and what doesn't if you want to keep it. \$\endgroup\$ – FryAmTheEggman Jan 17 at 20:41
  • \$\begingroup\$ @FryAmTheEggman Alright. Funny, I did not expect the printing to be the less desirable requirement, but I'll follow your judgement. And I can specify the lexicon, sure - I'll take an Italian word list, and subtract an English one (because loanwords). Just, taking into account golfing languages is going to be ambiguous - they frequently use modifications of Latin letters, and I want to allow those to be treated as their equivalent letters, but you might run into ambiguous situations like whether a Cyrillic к (don't know if any language uses it) can be a regular k. \$\endgroup\$ – KeizerHarm Jan 17 at 21:00
0
\$\begingroup\$

Fun with Lasers and Prisms (WIP)

Given a rectangular grid of objects, one or more laser pointers, and a target, determine if any laser beam will hit the target.

Objects

ASCII will be used for illustration purposes

  • Laser Pointer: ^, V, <, > - a beam will shoot up, down, left, right, respectively, starting from this cell.
  • Target: O - return true if a beam reaches this cell
  • Mirror: /, \ - reflects a beam 90 degrees
  • Prism: # - the laser will split into three beams, one for each direction
  • One-way block: A, U, (, ) - a beam will pass up, down, left, right, respectively, but not other directions
  • Corridor block: =, " - a beam will only pass horizontally or vertically, respectively
  • Gate block: I, H - a beam will pass through horizontally if another beam touches it vertically, or vice-versa, respectively

Rules

  • Use any convenient representation
| |
\$\endgroup\$
  • \$\begingroup\$ I think it is likely that your gate blocks prevent this from being a dupe of other similar challenges, though I haven't thoroughly checked yet. \$\endgroup\$ – FryAmTheEggman Jan 18 at 3:19
0
\$\begingroup\$

How low can you go?

Time to play so ascii-art limbo!

Here's the bar:

|--|
|  |
|  |

Can you fit under it?

Goal

Write a program or function that takes an ascii string representing a some shape, and a positive integer representing a bar height.

Output the shape from the input after it has attempted to do the limbo.

Details

In limbo you lean back to make yourself as small as possible to fit under the bar, and that is just what the input shapes will try and do.

If the input shape contains any repeating patterns in its lines, then you can remove all but the last of the repetitions that are in the pattern. In additions the pattern must start at the top line, and once the repeating pattern is broken no more sections can be removed.

If there is a repeating pattern that contains another repeating pattern, only the innermost pattern is stripped.

For example this is how the following inputs would look after "Leaning back":

1. XXX              2. xxx            3. xxx           4. xxx      
   YYY                 xxx       xxx     xxx              xxx      xxx
   XXX   -->   XXX     yyy  -->  yyy     xxx  -->         yyy      yyy
   YYY         YYY     zzz       zzz     xxx              yyy      yyy
   zzz         zzz     aaa       aaa     xxx      xxx     xxx  --> xxx
                                                          xxx      xxx
                                                          yyy      yyy
                                                          yyy      yyy

Note how in example number 4 there was a repetition ox xxx insinde of another repetition of xxx, xxx, yyy, yyy. In this case only the inner repeating lines got reduced.

The bars will be drawn as shown below for the given heights:

1 -> |--|    2 -> |--|   3 -> |--|  etc...
                  |  |        |  |
                              |  |

If the given input shape in its reduced form does not fit underneath the bar then the bar will be drawn on the ground like this |__|

Exmaples

Inputs:

a. height: 3      b.  height: 2     c.  height: 1
   shape: xxx         shape: xxx        shape: (emptystring)
          xxx                xxx
          xxx                xxx
          yyy                yyy

Outputs:

a. |--|           b. |  | xxx       c. |--| 
   |  | xxx          |__| yyy  
   |  | yyy

Notes

  1. You can assume only valid inputs will be given, handle invalid input however you want
  2. The input shape will be drawn 1 space after the bar, and the bottom of the input shape will always line up with the bottom of the bar.
  3. Extra whitespace after is fine as long as all the lines are properly aligned.
  4. If there is whitespace in the given input then that should be included in the output
  5. The shape will not necessarily always line up in a perfect rectangle as I drew it.

This is for code-golf so the answer using the fewest bytes wins.


Please let me know what you think / if anything is unclear and needs to be improved. Hope you guys like it!


EDIT: Would whoever down voted please explain whats wrong with it?

| |
\$\endgroup\$
  • \$\begingroup\$ I'm not the voter, but I'd bet they voted because what you have right now is very difficult to understand. I had to read this three times to figure out what you wanted. It may be worth revisiting the concept of "leaning over" as it is deeply unintuitive to me at the moment. On top of that, this requires a lot of "boring" golfing for the required output format when true/false seems to be basically the same. I hope this is helpful! \$\endgroup\$ – FryAmTheEggman Jan 20 at 20:24
  • \$\begingroup\$ @FryAmTheEggman Hmm, I thought I'd explained it fairly clearly - its just removing any lines that form a repetitive pattern, but I will try to update it. The output is slightly more than just T/F because of wanting to see the "limbo'ed" input shape with the shaved lines, and having to draw the bar different if it fails... though maybe that is what you meant by boring golf? \$\endgroup\$ – Quinn Jan 20 at 20:30
  • \$\begingroup\$ @FryAmTheEggman I tried updating the explanation, though I'm not sure if it is any clearer, please let me know if it makes more sense now \$\endgroup\$ – Quinn Jan 20 at 20:33
  • \$\begingroup\$ Explaining things is often harder than one would guess. Here I think a big problem is that your definition of bending is not what I would expect, so it makes the whole idea harder to grasp - particularly the rules about which repetitions happen first. Since I don't get the why I struggle to get the what. Maybe try explaining this to someone verbally to see if you can get rapid and direct feedback. What you have now is better, but I still think I'd have a hard time following on a first read. \$\endgroup\$ – FryAmTheEggman Jan 20 at 20:35
0
\$\begingroup\$

Factorise a floating point number

Given a target floating point number, \$T\$ and a set of \$N\$ floating point numbers \$\{x_{1},..,x_{N}\}\$ and a permissible error \$tol\$ , find a set of integer coefficients \$A\$, \$\{m_{1},..,m_{N}\}\$ such that: $$ A\prod\limits_{i=1}^{N}x_{i}^{m_{i}} = T\pm{}tol $$

Input

Input will be a target number, a set of real numbers and a tolerance as a decimal or percentage (note which) in any order or format required by your language.

Output

Output should be \$A\$, \$\{m\}\$ and the corresponding error as a percentage. If multiple combinations are valid any or all sets of \$A\$ and \$\{m\}\$ are within tolerance.

General rules

  • This is , so shortest answer in bytes wins.
    Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
  • Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
  • Default Loopholes are forbidden.
  • If possible, please add a link with a test for your code (i.e. TIO).
  • Also, adding an explanation for your answer is highly recommended.

Examples

\$3*(3.2^4*7.1^2)=15857.614848\$

15857.6 [3.2, 7.1] 0.05 => 3, [4, 2]

\$2*(e^2*\pi{}^2)=145.854121188\$

145.85 [2.7182, 3.1415] 0.1 => 2, [2, 2]

\$3*(\pi^0*0.1^1)\$

0.3 [3.14159, 0.1] 0.05 => 3, [0, 1]
| |
\$\endgroup\$
0
\$\begingroup\$

The periodic table and the chemical symbols

Periodic table

The periodic table is a large tablecitation needed where we can find the chemical elements written out with their chemical symbols. For example, Helium shows up as He and Carbon shows up as C. You can read Wikipedia's article on the periodic table, if you want.

Your task

You have to write a function/program/procedure/... that, given a chemical element's name, returns its chemical symbol. For the purposes of this challenge, we will use the 118 elements listed below:

['Hydrogen', 'Helium', 'Lithium', 'Beryllium', 'Boron', 'Carbon', 'Nitrogen', 'Oxygen', 'Fluorine', 'Neon', 'Sodium', 'Magnesium', 'Aluminium', 'Silicon', 'Phosphorus', 'Sulfur', 'Chlorine', 'Argon', 'Potassium', 'Calcium', 'Scandium', 'Titanium', 'Vanadium', 'Chromium', 'Manganese', 'Iron', 'Cobalt', 'Nickel', 'Copper', 'Zinc', 'Gallium', 'Germanium', 'Arsenic', 'Selenium', 'Bromine', 'Krypton', 'Rubidium', 'Strontium', 'Yttrium', 'Zirconium', 'Niobium', 'Molybdenum', 'Technetium', 'Ruthenium', 'Rhodium', 'Palladium', 'Silver', 'Cadmium', 'Indium', 'Tin', 'Antimony', 'Tellurium', 'Iodine', 'Xenon', 'Cesium', 'Barium', 'Lanthanum', 'Cerium', 'Praseodymium', 'Neodymium', 'Promethium', 'Samarium', 'Europium', 'Gadolinium', 'Terbium', 'Dysprosium', 'Holmium', 'Erbium', 'Thulium', 'Ytterbium', 'Lutetium', 'Hafnium', 'Tantalum', 'Tungsten', 'Rhenium', 'Osmium', 'Iridium', 'Platinum', 'Gold', 'Mercury', 'Thallium', 'Lead', 'Bismuth', 'Polonium', 'Astatine', 'Radon', 'Francium', 'Radium', 'Actinium', 'Thorium', 'Protactinium', 'Uranium', 'Neptunium', 'Plutonium', 'Americium', 'Curium', 'Berkelium', 'Californium', 'Einsteinium', 'Fermium', 'Mendelevium', 'Nobelium', 'Lawrencium', 'Rutherfordium', 'Dubnium', 'Seaborgium', 'Bohrium', 'Hassium', 'Meitnerium', 'Darmstadtium', 'Roentgenium', 'Copernicium', 'Nihonium', 'Flerovium', 'Moscovium', 'Livermorium', 'Tennessine', 'Oganesson']

with the respective element symbols:

['H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne', 'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'Cl', 'Ar', 'K', 'Ca', 'Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Cu', 'Zn', 'Ga', 'Ge', 'As', 'Se', 'Br', 'Kr', 'Rb', 'Sr', 'Y', 'Zr', 'Nb', 'Mo', 'Tc', 'Ru', 'Rh', 'Pd', 'Ag', 'Cd', 'In', 'Sn', 'Sb', 'Te', 'I', 'Xe', 'Cs', 'Ba', 'La', 'Ce', 'Pr', 'Nd', 'Pm', 'Sm', 'Eu', 'Gd', 'Tb', 'Dy', 'Ho', 'Er', 'Tm', 'Yb', 'Lu', 'Hf', 'Ta', 'W', 'Re', 'Os', 'Ir', 'Pt', 'Au', 'Hg', 'Tl', 'Pb', 'Bi', 'Po', 'At', 'Rn', 'Fr', 'Ra', 'Ac', 'Th', 'Pa', 'U', 'Np', 'Pu', 'Am', 'Cm', 'Bk', 'Cf', 'Es', 'Fm', 'Md', 'No', 'Lr', 'Rf', 'Db', 'Sg', 'Bh', 'Hs', 'Mt', 'Ds', 'Rg', 'Cn', 'Nh', 'Fl', 'Mc', 'Lv', 'Ts', 'Og']

Input

The code you write should receive an element name in any sensible format, such as a string "helium". You may assume whatever capitalization that suits your needs.

Output

The code you write should return the element's symbol as a string, with any capitalization that suits your needs. Bonus imaginary internet points if you return the symbol with the standard capitalization.

Scoring

This is so your answer doesn't win by being the shortest! You will be provided 118 test cases. Your score will be your code's byte count divided by the percentage of test cases your code passes correctly. Lowest score wins!

E.g. my code has 1 byte and I get 1 test case correct. My score is \$1 / \frac{1}{118} = 118 \$. Someone else writes some code with 110 bytes but gets all the test cases correct. The other person scores \$ 110 / \frac{118}{118} = 110 \$, meaning the other person has a better score than me.

Test cases:

'Hydrogen' -> 'H'
'Helium' -> 'He'
'Lithium' -> 'Li'
'Beryllium' -> 'Be'
'Boron' -> 'B'
'Carbon' -> 'C'
'Nitrogen' -> 'N'
'Oxygen' -> 'O'
'Fluorine' -> 'F'
'Neon' -> 'Ne'
'Sodium' -> 'Na'
'Magnesium' -> 'Mg'
'Aluminium' -> 'Al'
'Silicon' -> 'Si'
'Phosphorus' -> 'P'
'Sulfur' -> 'S'
'Chlorine' -> 'Cl'
'Argon' -> 'Ar'
'Potassium' -> 'K'
'Calcium' -> 'Ca'
'Scandium' -> 'Sc'
'Titanium' -> 'Ti'
'Vanadium' -> 'V'
'Chromium' -> 'Cr'
'Manganese' -> 'Mn'
'Iron' -> 'Fe'
'Cobalt' -> 'Co'
'Nickel' -> 'Ni'
'Copper' -> 'Cu'
'Zinc' -> 'Zn'
'Gallium' -> 'Ga'
'Germanium' -> 'Ge'
'Arsenic' -> 'As'
'Selenium' -> 'Se'
'Bromine' -> 'Br'
'Krypton' -> 'Kr'
'Rubidium' -> 'Rb'
'Strontium' -> 'Sr'
'Yttrium' -> 'Y'
'Zirconium' -> 'Zr'
'Niobium' -> 'Nb'
'Molybdenum' -> 'Mo'
'Technetium' -> 'Tc'
'Ruthenium' -> 'Ru'
'Rhodium' -> 'Rh'
'Palladium' -> 'Pd'
'Silver' -> 'Ag'
'Cadmium' -> 'Cd'
'Indium' -> 'In'
'Tin' -> 'Sn'
'Antimony' -> 'Sb'
'Tellurium' -> 'Te'
'Iodine' -> 'I'
'Xenon' -> 'Xe'
'Cesium' -> 'Cs'
'Barium' -> 'Ba'
'Lanthanum' -> 'La'
'Cerium' -> 'Ce'
'Praseodymium' -> 'Pr'
'Neodymium' -> 'Nd'
'Promethium' -> 'Pm'
'Samarium' -> 'Sm'
'Europium' -> 'Eu'
'Gadolinium' -> 'Gd'
'Terbium' -> 'Tb'
'Dysprosium' -> 'Dy'
'Holmium' -> 'Ho'
'Erbium' -> 'Er'
'Thulium' -> 'Tm'
'Ytterbium' -> 'Yb'
'Lutetium' -> 'Lu'
'Hafnium' -> 'Hf'
'Tantalum' -> 'Ta'
'Tungsten' -> 'W'
'Rhenium' -> 'Re'
'Osmium' -> 'Os'
'Iridium' -> 'Ir'
'Platinum' -> 'Pt'
'Gold' -> 'Au'
'Mercury' -> 'Hg'
'Thallium' -> 'Tl'
'Lead' -> 'Pb'
'Bismuth' -> 'Bi'
'Polonium' -> 'Po'
'Astatine' -> 'At'
'Radon' -> 'Rn'
'Francium' -> 'Fr'
'Radium' -> 'Ra'
'Actinium' -> 'Ac'
'Thorium' -> 'Th'
'Protactinium' -> 'Pa'
'Uranium' -> 'U'
'Neptunium' -> 'Np'
'Plutonium' -> 'Pu'
'Americium' -> 'Am'
'Curium' -> 'Cm'
'Berkelium' -> 'Bk'
'Californium' -> 'Cf'
'Einsteinium' -> 'Es'
'Fermium' -> 'Fm'
'Mendelevium' -> 'Md'
'Nobelium' -> 'No'
'Lawrencium' -> 'Lr'
'Rutherfordium' -> 'Rf'
'Dubnium' -> 'Db'
'Seaborgium' -> 'Sg'
'Bohrium' -> 'Bh'
'Hassium' -> 'Hs'
'Meitnerium' -> 'Mt'
'Darmstadtium' -> 'Ds'
'Roentgenium' -> 'Rg'
'Copernicium' -> 'Cn'
'Nihonium' -> 'Nh'
'Flerovium' -> 'Fl'
'Moscovium' -> 'Mc'
'Livermorium' -> 'Lv'
'Tennessine' -> 'Ts'
'Oganesson' -> 'Og'

I used this code to shape the list into the test cases, might be useful to you.

Elements and symbols extracted from https://www.thoughtco.com/element-list-names-atomic-numbers-606529, visited at the 9th of February of 2020. At the time of writing, 118 elements were available. Source included "Aluminum" and "Aluminium" as alternatives, dropped "Aluminum" for the purposes of this challenge.

| |
\$\endgroup\$
  • \$\begingroup\$ This is just a massive lookup table. I don't like it. \$\endgroup\$ – S.S. Anne Feb 10 at 0:50
  • \$\begingroup\$ "Aluminum" might be in the dictionaries of some languages. I suggest allowing either but and/or both in the solution and specifying which one was chosen. \$\endgroup\$ – S.S. Anne Feb 10 at 1:07
  • \$\begingroup\$ Dupe \$\endgroup\$ – Jo King Feb 10 at 2:55
  • \$\begingroup\$ @JoKing this being a code challenge doesn't make it different from the dupe you linked? \$\endgroup\$ – RGS Feb 10 at 7:02
  • \$\begingroup\$ I think the problem you have is that your scoring strongly incentivises submitting H as the best answer. The other question had a shortest solution of 200 bytes - which can't get a better score than the 1 byte 1 answer program. \$\endgroup\$ – FryAmTheEggman Feb 10 at 19:52
  • \$\begingroup\$ @FryAmTheEggman thanks for the feedback. Would you suggest tweaking the score or dropping this challenge? \$\endgroup\$ – RGS Feb 10 at 20:19
  • 2
    \$\begingroup\$ You might consider a similar idea but with something that hasn't been done as much. I think it depends on how you feel, it certainly isn't unsalvageable. \$\endgroup\$ – FryAmTheEggman Feb 10 at 20:27
  • 1
    \$\begingroup\$ @FryAmTheEggman very nice idea. I am thinking airport codes, country codes or military rank abbreviations... \$\endgroup\$ – RGS Feb 10 at 21:21
  • \$\begingroup\$ I really like this idea, and I think allowing approximate answers makes it distinct enough from this that it's not a dupe. However, the current scoring encourages very inaccurate, trivial answers. The best I could find in 05AB1E is (05AB1E to output the first 2 characters of the input), which gets 45 test cases correct, scoring better than a 6 character answer that gets everything right. \$\endgroup\$ – Grimmy Feb 14 at 16:03
  • \$\begingroup\$ @Grimmy thanks for your very detailed feedback! Like I mentioned above, I'm exploring the possibility of using something other than chemical symbols. In your opinion, would you tweak the scoring or would you suggest something other than chemical symbols? \$\endgroup\$ – RGS Feb 14 at 16:20
0
\$\begingroup\$

Count switches in a smallest square root sequence mod \$2^n\$

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

Compress even permutations

Factorial number system

Every nonnegative integer can be encoded by factorial number system. Factorial number system doesn't have a fixed radix, but uses the factorial of nonnegative integers as radices. The place of \$0!\$ can have \$0\$ as the digit, the place of \$1!\$ can have \$0\$ or \$1\$ as the digit, the place of \$2!\$ can have \$0\$, \$1\$, or \$2\$ as the digit, and so on. Subscript exclamation mark denotes that the integer is encoded in factorial number system. For example:

$$ 41010_! = 4 \times 4! + 1 \times 3! + 0 \times 2! + 1 \times 1! + 0 \times 0!= 103_{10} $$

Permutations

Numbers encoded by factorial number system has one-to-one correspondence to permutations:

$$ 41010_! \cong \begin{pmatrix} 0 \\ 0 \end{pmatrix} \begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix} \begin{pmatrix} 2 & 1 & 0 \\ 2 & 1 & 0 \end{pmatrix} \begin{pmatrix} 3 & 2 & 1 & 0 \\ 0 & 3 & 2 & 1 \end{pmatrix} \begin{pmatrix} 4 & 3 & 2 & 1 & 0 \\ 3 & 2 & 1 & 0 & 4 \end{pmatrix} = \begin{pmatrix} 4 & 3 & 2 & 1 & 0 \\ 1 & 3 & 2 & 0 & 4 \end{pmatrix} $$

That is, each the place of \$n!\$ represents a right-direction rotation of \$n\$ through \$0\$, and its digit represents what \$0\$ becomes after the rotation.

It follows that the parity of the permutation is same as the parity of the sum of digits at the places of factorials of odd numbers. For \$41010_!\$, the permutation is even because \$1 + 1 = 2\$ is even.

Objective

An even permutation of 5 elements, or any equivalent object will be the input. That leaves \$5! \div 2 = 60\$ distinct permutations. Compress it to \$\lceil \log_2{60}\rceil=6\$ bits.

Rules

  • Input type and format doesn't matter. Possible choices of input format include (in C++):

    • std::map<int,int> scrambling the numbers from \$4\$ to \$0\$

    • int[5] containing the digits of the factorial number system

    • int[4] containing the digits of the factorial number system, except the place of \$0!\$ (it doesn't contribute to the permutation)

    • int encoded by the factorial number system

  • Output type and format doesn't matter either. It may be:

    • bool[6]

    • int8_t

    • a bit field

    • std::string containing ASCII digit 0s and 1s

  • Invalid inputs fall in don't care situation.

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

Simplify a directed graph

Input

A connected directed graph, in any convenient format. A valid format (and probably the most convenient) would be a list of edges.

Simplification

These two reductions are performed as often as possible. It does not suffice to apply one reduction first, then the other, as each of them can cause more of the other one.

Let \$E\$ be the set of all edges of the graph in the following explanations. For example \$E = \{(0, 1), (1, 2), (2, 0)\}\$ represents the following graph:

0 ----> 1
^       |
'-- 2 <-'

Let \$E_a\$, where \$a\$ is a vertex, indicate the set of edges involving \$a\$:

$$E_a := \{(u, v) \in E : u = a \vee v = a\}$$

Two graphs are isomorphic iff all vertices from one graph can be relabeled to make it equal to the other graph.

Deduplication

If there are disjoint sets of vertices \$M\$ and \$N\$ (\$M \cap N = \emptyset\$) not directly connected (\$((M, N) \cup (N, M)) \cap E = \emptyset\$) and the graphs with edges \$E \setminus E_M\$ and \$E \setminus E_N\$ are isomorphic, then the vertices \$M\$ (or \$N\$, but not both, are removed).

This means that of any two non-overlapping, non-directly-connected subgraphs that leave isomorphic graphs behind when removed, one is removed.

Simple example:

b --> 1
      ^  ==>  b --> 1
      |
      a

Relay removal

If there are vertices \$a\$ and \$b\$ and a non-empty set of vertices \$N\$, such that \$b \notin N\$ and \$E_b = \{(a, b)\} \cup (b, N)\$, then \$b\$ is removed from the graph and edges \$(a, N)\$ are added if they do not alreay exist.

This means that a vertex with exactly one edge ending there, at least one edge starting there and no self-loop can be removed, moving the starting edges to the start of the ending edge.

Simple example:

            1             1
            ^             ^
            |             |
O --> a --> b  ==>  O --> a ----.
      ^     |             ^     |
      |     v             |     v
      '---- 2             '---- 2

Output

The output is the result of the reductions, in any convenient format. If identifiers are used for edges or vertices, as in a list of edges, these identifiers are not required to correspond to identifiers in the input.

A different format may be used for input and output.

Scoring

This is : Lowest bytecount in each language wins. No answer will be accepted, as there is no overall winner.

Other rules

  • Standard loopholes apply
  • Functions or programs
  • Any input and output methods (STDIN, arguments, prompt(), ...)

Test cases

not yet

Meta:

  • Everything clear?
  • Better explanations?
  • Better title?
  • I'm not sure whether output might depend on the order in which reductions are performed.
| |
\$\endgroup\$
0
\$\begingroup\$

Let's Play Countdown!

(The Numbers round this time)

Countdown is a British TV game show composed of three different styles of rounds; the letters round, the conundrum, and the numbers round.

The conundrum could be solved with the same program you'd make for the Letters round, so let's tackle the third option that hasn't been done yet!

Challenge

Take in a set of numbers. One of which is the "Target" number, and the rest are the building numbers.

The Countdown Number Round asks you to take the building numbers and to construct the Target number only using the four elementary operators. Every step must result in another strictly-positive integer (so non-perfect division is disallowed). Output the method to which you can construct the target number. If that's impossible, get as close as possible (above or below are scored the same). Numbers do not need to be used, but may NOT be reused.

Note - You will perform at most N-1 operations, where N is the number of building numbers. Every elementary operator takes in two inputs and provides one, so you "lose" one from your ranking every operation. That should give you an idea of the size of your output.

I/O is in any reasonable format, but target vs building numbers must be obviously distinct (either by the target being the first or the last number, or outside an array, or a different type, etc).

Output needs to explain exactly what operations are being performed on what numbers, and what the output for each operation would be, but can be done in whichever way seems reasonable.

Example I/O

In these examples, the first element is the target.

[888 100 2 75 3 1 10]
75-1=74
10+2=12
74x12=888

[766 22 10 8 3 1]
22+10=32
32x8=256
256-1=255
255x3=765 #You cannot get this one exactly, but one-off is close.

Sandbox Questions

I'm... like 85% sure this isn't anywhere here yet. I did a chunk of searching and couldn't find anything that fit the bill, so I think this is clear?

Any other neat examples you guys got?

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ As you say, I don't think we have exactly this challenge, but there are many similar ones. I doubt you will get anything besides brute forcing all possible arrangements then sorting them by nearness to the target. Separately, if there are multiple tying solutions you don't require that e.g. the shortest be output, correct? It is probably worth mentioning that. \$\endgroup\$ – FryAmTheEggman Feb 21 at 21:24
0
\$\begingroup\$

Iterative Quadratics

Recently, in my algebra class, we proved that the following process always stops at some point, so I thought it would be a cool challenge!

Input: Two reals a,b.

Output Non-negative integer

Challenge:

Given two reals a,b, initialize a count variable c to 0, consider the quadratic equation

x^2+ax+b

If this quadratic has real roots r,s (r<=s), increment the counter by 1, and replace a,b with r,s and repeat the process.

If the quadratic has complex roots, return c.

Test Cases

To be added.

| |
\$\endgroup\$
  • \$\begingroup\$ you need to specify the precision required for stopping \$\endgroup\$ – qwr Mar 11 at 19:16
  • \$\begingroup\$ @qwr good catch. Any suggestions? \$\endgroup\$ – Don Thousand Mar 11 at 19:51
0
\$\begingroup\$

Doubly stochastic matrix

A doubly-stochastic matrix is a square matrix of non-negative real entries each of whose rows and columns sums to 1. Given a doubly-stochastic matrix, express it as a non-negative linear combination of permutation matrices, as is guaranteed to exist by the Birkhoff–von Neumann theorem.

TODO: Example, better explanation, test cases. If you want to develop and post this challenge, it's yours.

| |
\$\endgroup\$
  • \$\begingroup\$ I liked this idea! May I work on this and give you credit? If I manage to do so before you, of course. \$\endgroup\$ – RGS Feb 24 at 19:33
  • \$\begingroup\$ @RGS You're very welcome to fully take it. \$\endgroup\$ – xnor Feb 26 at 2:01
0
\$\begingroup\$

Implement GF(2²)

Introduction to groups and fields

An additive group is a set with addition and negation defined. They must satisfy the following conditions:

  • \$0\$ is the additive identity.

  • Addition is associative.

  • For every \$x\$, the negation of \$x\$, \$-x\$ exists, and \$x + (-x) = (-x) + x = 0\$.

If addition is also commutative, the additive group is called abelian.

A field is an additive abelian group with multiplication and reciprocal defined. They must satisfy the following conditions:

  • \$1\$ is the multiplicative identity.

  • Multiplication is associative and commutative.

  • For every nonzero \$x\$, the reciprocal of \$x\$, \$x^{-1}\$ uniquely exists, and \$x\times x^{-1} = x^{-1}\times x = 1\$.

  • Multiplication distributes over addition.

Modular Arithmetic

For every positive integer \$n\$, you can define an additive abelian group as follows:

  • Define the set as integers from \$0\$ to \$n-1\$.

  • Define addition as usual addition with the result moduloed by \$n\$.

  • Define negation as usual negation with the result moduloed by \$n\$.

This group is denoted by \$ℤ_n\$. If \$n\$ is prime, multiplication can be analogously defined, making it a field. In particular, the operation tables of \$ℤ_2\$ are:

$$ \begin{array}{l|ll} + & 0 & 1 \\ \hline 0 & 0 & 1 \\ 1 & 1 & 0 \end{array} \begin{array}{l|ll} x & -x \\ \hline 0 & 0 \\ 1 & 1 \end{array} \begin{array}{l|ll} × & 0 & 1 \\ \hline 0 & 0 & 0 \\ 1 & 0 & 1 \end{array} \begin{array}{l|ll} x & x^{-1} \\ \hline 0 & \text{NaN} \\ 1 & 1 \end{array} $$

Galois Field GF(2²)

A Galois field \$\text{GF}(p^k)\$ emerges when one takes the set as polynomials over \$ℤ_p\$, and defines addition and multiplication as the usual operation with polynomial modulo, where the modding polynomial is irreducible and has degree of \$k\$. Since \$x^2+x+1\$ is an (in fact, the only) irreducible polynomial over \$ℤ_2\$ that has degree \$2\$, this results in \$\text{GF}(2^2)\$. Its operation tables are:

$$ \begin{array}{l|ll} + & 0 & 1 & x & x+1 \\ \hline 0 & 0 & 1 & x & x+1 \\ 1 & 1 & 0 & x+1 & x \\ x & x & x+1 & 0 & 1 \\ x+1 & x+1 & x & 1 & 0 \end{array} \begin{array}{l|ll} f(x) & -f(x) \\ \hline 0 & 0 \\ 1 & 1 \\ x & x \\ x+1 & x+1 \end{array} \\ \begin{array}{l|ll} × & 0 & 1 & x & x+1 \\ \hline 0 & 0 & 0 & 0 & 0 \\ 1 & 0 & 1 & x & x+1 \\ x & 0 & x & x+1 & 1 \\ x+1 & 0 & x+1 & 1 & x \end{array} \begin{array}{l|ll} f(x) & f(x)^{-1} \\ \hline 0 & \text{NaN} \\ 1 & 1 \\ x & x+1 \\ x+1 & x \end{array} $$

Your task is to implement the set and the operations. As a conseuqence, you must have:

  • The members of the set defined as constants (2-bit bitstring, an ASCII digit, or whatever). This won't contribute to the score.

  • Four codes that defines each operations, whose input(s) is/are as defined above.

Rules

  • Though defined as polynomials, the type and format of the inputs doesn't matter. You must have the same type for every input.

  • The type and format of the outputs doesn't matter either, but it must be the same as the input(s).

  • The reciprocal of \$0\$ must result in an "error" condition. This includes returning an errornous value, throwing an error, or terminating the program. It must halt.

  • Other invalid inputs fall in don't care situation.

  • Since there are multiple codes, the score for code golf is alloted by the sum of their lengths in bytes.

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ Related: GF(2^8) and GF(3^2), though neither asks for negation or multiplicative inverse. Also, A code that defines the set as a type can be problematic in many languages where the concept of "type" is not well-defined. I'd suggest to exclude it from the code size and just ask the answerer to provide the four values corresponding to \$0, 1, x, x+1\$ respectively. \$\endgroup\$ – Bubbler Feb 24 at 0:02
  • \$\begingroup\$ @DonThousand Requiring the uniqueness of a negation resolves the issue. Also, it would take too long to explain the "actual" definition of \$\mathbb{Z}_p\$. So I defined it with usual modulo. \$\endgroup\$ – Dannyu NDos Feb 24 at 1:25
  • \$\begingroup\$ @DonThousand \$(-a) + a = 0\$ implies \$(-(-a)) + (-a) = 0\$. So both \$a\$ and \$-(-a)\$ are additive inverses of \$-a\$. By uniqueness of additive inverse, it follows \$-(-a) = a\$. \$\endgroup\$ – Dannyu NDos Feb 24 at 1:57
  • \$\begingroup\$ @DannyuNDos Incorrect, you assume commutativity again. $a$ is a right inverse, and $-(-a)$ is a left inverse of $-a$ \$\endgroup\$ – Don Thousand Feb 24 at 2:03
  • \$\begingroup\$ @DonThousand The definition of group states that a left inverse must be the right inverse, and a right inverse must be the left inverse. Such inverse always uniquely exists. \$\endgroup\$ – Dannyu NDos Feb 24 at 3:21
  • \$\begingroup\$ @DannyuNDos That's my point. Your definition doesn't say that the right inverse = left inverse. \$\endgroup\$ – Don Thousand Feb 24 at 3:30
  • \$\begingroup\$ @DonThousand Oh my! So there was the flaw. I only remembered the definition, but not memorized it. Thanks anyways. \$\endgroup\$ – Dannyu NDos Feb 24 at 3:32
  • \$\begingroup\$ @DannyuNDos Yea, lol. Sheesh, that was a journey. \$\endgroup\$ – Don Thousand Feb 24 at 3:36
  • \$\begingroup\$ @DonThousand You only need a right zero and right inverses, then we get left zero and left inverses, and they are unique (we also don't have to demand that). Proof that right inverses are left inverses: \$(-a)+a=(-a)+a+0=(-a)+a+(((-a)+a)+(-((-a)+a)))=(-a)+(a+(-a))+a+(-((-a)+a))=((-a)+0)+a+(-((-a)+a))=((-a)+a)+(-((-a)+a))=0\$. Using this gives left zero: \$0+a=(a+(-a))+a=a+((-a)+a)=a+0=a\$. \$\endgroup\$ – Christian Sievers Feb 24 at 15:07
0
\$\begingroup\$

Shared Letters in consecutive numbers

Inspired by this puzzling question.

It turns out that, in English, every pair of consecutive integers (e.g. 0,1, 1,2, etc.) shares at least one letter when spelled out (e.g. zErO, OnE (or NOught, ONe); One, twO, etc).

Input

Any two non-negative integers (all natural numbers including 0) up to and including one googol. These can be input as any type you choose, but string representations must only use the characters 0123456789.,' (i.e. the numbers must not already be spelled out on input, but rather input as a numeral).

You can assume that the two numbers will be consecutive.

Some examples of valid inputs:

{1,2}
{"1","2"}
{1},{2}
{{"1"},{2}}
"123,245", "123,246"
"123.456", "123'457"

some examples of invalid inputs

{1,3}
{-1,0}
{1.1,1.2}
{"one","two"}

The Challenge

Given the two inputs, output all shared characters when spelled (both numbers spelled in either lower or upper-case, the same case for both numbers).

A sample implementation for spelling numbers can be found here: https://stackoverflow.com/a/3911982/318414; but I'm sure other options exist; and there are certainly efficiencies to be found given that there are large amounts of shared strings, once you get into the higher numbers. See also https://simple.wikipedia.org/wiki/Names_for_large_numbers for the names of large numbers.

, usual exclusions apply

Output The shared letters, in any reasonable format. Any of the three numbering systems on the Wikipedia page are valid.

Examples

I will be assuming British English (long form) in my examples.

{6,7} -> "s" or "S" (six, seven)

{999,1000} -> {"n","e"," ","t","h","u","a","d"} (nine hundred and ninety nine, one thousand)

{88955,88956} -> `` (eighty eight thousand nine hundred and fifty five, eighty eight thousand nine hundred and fifty six)

1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001 -> "ONE THUSADQICL" (ONE THOUSAND QUINDECILLION, ONE THOUSAND QUINDECILLION AND ONE)

9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999, 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 -> el no (nine hundred and ninety nine thousand sexdecillion **nine hundred and ninety nine thousand quindecillion nine hundred and ninety nine thousand quatturodecillion nine hundred and ninety nine thousand tredecillion nine hundred and ninety nine thousand duodecillion nine hundred and ninety nine thousand undecillion nine hundred and ninety nine thousand decillion nine hundred and ninety nine thousand nonillion nine hundred and ninety nine thousand octillion nine hundred and ninety nine thousand septillion nine hundred and ninety nine thousand sextillion nine hundred and ninety nine thousand quintillion nine hundred and ninety nine thousand quadrillion nine hundred and ninety nine thousand trillion nine hundred and ninety nine thousand billion nine hundred and ninety nine thousand million nine hundred and ninety nine thousand nine hundred and ninety nine; one googol)

| |
\$\endgroup\$
  • \$\begingroup\$ "Any two positive integers (all natural numbers including 0)" You should reword this because 0 is not a positive integer. \$\endgroup\$ – 79037662 Feb 22 at 4:34
  • \$\begingroup\$ Possibly a chameleon challenge because answerers are required to convert an integer to its English form first, which could take much more effort than finding the shared letters. \$\endgroup\$ – Shieru Asakoto Feb 29 at 3:33
  • \$\begingroup\$ @ShieruAsakoto I'm envisaging that the intermediate step won't necessarily need to be performed in code - perhaps there's a way to just look at the numbers? If not, does a challenge exist for converting numbers to words yet? \$\endgroup\$ – simonalexander2005 Mar 2 at 8:17
0
\$\begingroup\$

Find spies in a multilingual csv

Introduction

You are an NSA undercover agent in a Middle-Eastern HR company, you just received a list of people with their jobs in many different languages. Some are spies and you need to know who. Your mission, if you accept it, is to get what are people working in, and relate it to a list of job categories. Most dangerous elements are those working in Law enforcement and security. However as your code will be part of a bigger file it needs to be as short in lines as possible for stealthness. This comes from expectations I encountered in the administration to keep some mystery behind code, if ever it were to be stolen.

  • This challenges your way to handle loops, map, reduce and filter, destructuring or unpacking an array/csv/df. Last but not least it allows you to get into the fascinating world of cross-language nlp.

I provide an example in python (64 lines of code)

Challenge

The challenge is to get, in the shortest amount of bytes (libraries not included) the most similar element in an array of string with another string, and this for each line of a csv taken as input.

  • Inputs:

    1. X.csv a csv/dataframe of actual jobs that look like this one:
,new_professionactuelle
0,Entrepreneur
1,طالبة
2,ETUDIANT
3,ETUDIANT 
4,موظف
5,موجه تربوي 
6,Réalisateur film cartoon
7,إإطار مالي
8,موضف إطار
9,مهندس بمكتب دراسات
10,باحثة  _ كاتبة _ 
11,طالب
12,Chef de projet
13,ASSUREUR
14,FONCTIONNAIRE D'ÉTAT
15,Professeur Universitaire
16,cadre supérieur
17,fonctionnaire
19,professeur
20,Chef de projet
21,مدير  شركة
22,Avocat
23,cadre à Maroc Telecom
24,Employé 
25,Consultant en Immobilier
26,fonctionnaire
27,اجير أو عامل
  1. df.csv job categories that must include all the following categories:

    ['Agriculture, farming and environment',
       'Accountancy, banking and finance',
       'Teacher training and education', 'Leisure, sport and tourism',
       'Transport and logistics', 'Information technology',
       'Hospitality and events management',
       'Business, consulting and management', 'Creative arts and design',
       'Trade', 'Law enforcement and security',
       'Property and construction', 'Law',
       'Engineering and manufacturing', 'Social care',
       'Charity and voluntary work', 'Sales',
       'Public services and administration', 'Other. Please specify:',
       'Healthcare', 'Energy and utilities',
       'Marketing, advertising and PR', 'Media and internet',
       'Recruitment and HR', 'Science and pharmaceuticals']
    
    • Output would be the column in X.csv plus a new column, the most similar job. The most accurate results are:
,new_professionactuelle,category
0,Entrepreneur,Public services and administration
1,طالبة,Teacher training and education
2,ETUDIANT,Teacher training and education
3,ETUDIANT ,Teacher training and education
4,موظف,Recruitment and HR
5,موجه تربوي ,Teacher training and education
6,Réalisateur film cartoon,Creative arts and design
7,إإطار مالي,"Accountancy, banking and finance"
8,موضف إطار,Trade
9,مهندس بمكتب دراسات,Engineering and manufacturing
10,باحثة  _ كاتبة _ ,Recruitment and HR
11,طالب,Teacher training and education
12,Chef de projet,Creative arts and design
13,ASSUREUR,Business, consulting and management
14,FONCTIONNAIRE D'ÉTAT,Public services and administration
15,Professeur Universitaire,Teacher training and education
16,cadre supérieur,Business, consulting and management
17,fonctionnaire,Public services and administration
18,CDB Retraite,Recruitment and HR
19,professeur,Teacher training and education
20,Chef de projet,Public services and administration
21,مدير  شركة,Recruitment and HR
22,Avocat,Law
23,cadre à Maroc Telecom,Media and internet
24,Employé ,Sales
25,Consultant en Immobilier,Property and construction
26,fonctionnaire,Public services and administration
27,اجير أو عامل,Recruitment and HR
  • Inputs should be tested against all categories.

The winner of the challenge will be the one with the most accurate results. If on the test set. If several are as accurate, the shortest amount of bytes will be the winner. You can use any methods to get the most similar item. The state of the art method seems to be according to Google Multilingual Universal Sentence encoder. I provide an attempt with the code below but you will see it is not quite acccurate.

Example in Python

Double agent: A spy who works for two countries, and sometimes even three, in which case he is definitely a trouble. - Mots et Grumots (2003), Marc Escayrol

#@title Setup common imports and functions
import numpy as np
import os
import pandas as pd
import tensorflow.compat.v2 as tf
import tensorflow_hub as hub
from tensorflow_text import SentencepieceTokenizer
import sklearn.metrics.pairwise

from simpleneighbors import SimpleNeighbors
from tqdm import tqdm
from tqdm import trange

import json

def most_similar(embeddings_1, embeddings_2, labels_1, labels_2):

  assert (len(embeddings_1) == len(labels_1) and len(embeddings_2) == len(labels_2))

  # arccos based text similarity (Yang et al. 2019; Cer et al. 2019)
  sim = 1 - np.arccos(sklearn.metrics.pairwise.cosine_similarity(embeddings_1, embeddings_2))/np.pi

  embeddings_1_col, embeddings_2_col, sim_col = [], [], []
  for i in range(len(embeddings_1)):
    for j in range(len(embeddings_2)):
      embeddings_1_col.append(labels_1[i])
      embeddings_2_col.append(labels_2[j])
      sim_col.append(sim[i][j])
  df = pd.DataFrame(zip(embeddings_1_col, embeddings_2_col, sim_col),
                    columns=['embeddings_1', 'embeddings_2', 'sim'])

  # return the higest similarity one
  category = df['embeddings_1'].iloc[df['sim'].argmax()]
  return category

def main():

    X = pd.read_csv('X.csv')
    y = pd.read_csv('y.csv')
    df_rni = pd.read_csv('df.csv')

    # The 16-language multilingual module is the default but feel free
    # to pick others from the list and compare the results.
    module_url = 'https://tfhub.dev/google/universal-sentence-encoder-multilingual/3' #@param ['https://tfhub.dev/google/universal-sentence-encoder-multilingual/3', 'https://tfhub.dev/google/universal-sentence-encoder-multilingual-large/3']

    model = hub.load(module_url)

    def embed_text(input):
        return model(input)

    def compute_similarity(references, target):
        # I want to create as many rows as there are references and fill them with the results
        # arccos based text similarity (Yang et al. 2019; Cer et al. 2019)
        for row in target.iterrows():
            for reference in references:
                sim = 1 - np.arccos(
                result = sklearn.metrics.pairwise.cosine_similarity(row,
                                                                    reference))/np.pi

            # place the result in the column "reference"

    # get unique job categories and job of people
    job_categories = X.S02Q11_Professional_field.unique()
    # turn them to list
    job_categories = job_categories.tolist()
    # emebedding job categories 
    references_result = embed_text(job_categories[1:])

    for _, row in df_rni.iterrows():
        actual_job = row['new_professionactuelle']
        # check for nan that can't be embedded
        if str(actual_job) != 'nan':
            # embedding actual job
            target_result = embed_text(actual_job)
            # visualize similarity
            category = most_similar(references_result, target_result, job_categories[1:], [actual_job])
        else: category = None

if __name__ == "__main__":
    main()
| |
\$\endgroup\$
  • \$\begingroup\$ @Arnauld Indeed, fixed, thanks! \$\endgroup\$ – Revolucion for Monica Feb 24 at 15:19
  • \$\begingroup\$ It looks like your reference code fetches output from an external source, which is forbidden by default. Please detail within the question how one would implement the Google Universal Sentence Encoder. (If the challenge actually requires querying tfhub.dev/google/universal-sentence-encoder-multilingual/3, I don't think that's gonna be appropriate for CGCC). \$\endgroup\$ – Grimmy Feb 24 at 15:55
  • \$\begingroup\$ @Grimmy Google Universal Encoder: that's not compulsory, but I find it very handy and a good tip to start. External source: yes, that's the way I provided example data like the inputs above. Should I hard code the sources? \$\endgroup\$ – Revolucion for Monica Feb 24 at 16:05
  • \$\begingroup\$ Wait, Google Universal Encoder isn't compulsory? That seems to contradict the most similar element in an array of string with another string according to Google Multilingual Universal Sentence encoder. If GMUSE isn't required, this sentence should be replaced by a proper definition of "most similar element", and GMUSE should only be mentioned in the footnotes. \$\endgroup\$ – Grimmy Feb 24 at 16:10
  • \$\begingroup\$ External source: yes, that's the way I provided example data like the inputs above. I'm confused. Do you use tfhub.dev/google/universal-sentence-encoder-multilingual/3 only to get example data? It sure doesn't look like that in your code. \$\endgroup\$ – Grimmy Feb 24 at 16:11
  • \$\begingroup\$ @Grimmy Porbably I misunderstood "It looks like your reference code fetches output from an external source" then, my apologizes. \$\endgroup\$ – Revolucion for Monica Feb 24 at 16:19
  • \$\begingroup\$ This needs an explanation of how "accuracy" is computed. (And you still need to define "most similar"). \$\endgroup\$ – Grimmy Feb 24 at 18:45
0
\$\begingroup\$

Auto Tic Tac Toe

Okay, so after thinking about the comment I think I thought of a way to make it more interesting.


Challenge

Given no input, write a program or function which outputs an entire game of Tic-Tac-Toe where X always wins, or the game ends in a tie.

Requirements

  • X goes first
  • O must make moves at random
  • X must make smart moves such that it always wins the game, or the game ends in a tie

Example

Here's what I would expect a game to look like:

X--
---
---

XO-
---
---

XO-
-X-
---

XOO
-X-
---

XOO
-X-
--X

Notes:

  • X does not need to win in the fewest moves, it is enough to just make it always block O from winning
  • You can output the game in whatever form you like, as long as it is easily conveys every turn of the game. For example you could output a string like above, or a list of lists of ints like below, where 0 is an empty space and 1, 2 are X, O respectively:
[
  [1,0,0, 0,0,0, 0,0,0], 
  [1,2,0, 0,0,0, 0,0,0], 
  [1,2,0, 0,1,0, 0,0,0],
  [1,2,2, 0,1,0, 0,0,0], 
  [1,2,2, 0,1,0, 0,0,1]
]

This is code golf, answer in the fewest bytes wins. Standard rules apply.


Is this a better challenge? I'd love to know what people think


Working example of ungolfed code: Try it online!

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ I suspect this hasn't been asked because the huge majority of the work is spent on IO and not on an interesting problem. If you want to ask a tic-tac-toe challenge, you might be better served asking something like "can the next move win" which might still be a lot of parsing, but prevents excessive output at least. That said, you did do a good job of alleviating these problems in your notes, so you may be fine - most of what I've written here is my opinion, not precise advice. \$\endgroup\$ – FryAmTheEggman Jan 26 at 19:31
  • \$\begingroup\$ @FryAmTheEggman Made a pretty big edit, do you think this would be less boring? \$\endgroup\$ – Quinn Feb 1 at 1:15
  • \$\begingroup\$ I think the problem I have with this version is that it is probably more work to make a tic-tac-toe AI than it is to encode all the possible games and just pick one at random to output. It is possible that that isn't true, I haven't tried yet, but it still feels a bit tedious. But this might be the right direction - perhaps instead just ask for one random valid final tic-tac-toe board? Then it will likely be an encoding problem, but perhaps one with interesting strategies. Again, all opinion here, the challenge is written well, etc. \$\endgroup\$ – FryAmTheEggman Feb 1 at 5:13
  • \$\begingroup\$ Do you mean "uniformly distributed" when you write "random"? \$\endgroup\$ – Jonathan Frech Feb 4 at 9:54
  • \$\begingroup\$ Is the challenge in its current form not a kolmogorov-complexity challenge with choice? \$\endgroup\$ – Jonathan Frech Feb 25 at 1:25
  • \$\begingroup\$ @FryAmTheEggman I don't think making the AI is actually that hard for tic-tac-toe, though if im underestimating it, i could make a change that X always go first, which I think would make the ai pretty trivial \$\endgroup\$ – Quinn Feb 25 at 14:14
  • \$\begingroup\$ @JonathanFrech You tell me i have no clue, is that meaning the amount of code to output all possible tictactoe outcomes? \$\endgroup\$ – Quinn Feb 25 at 14:15
  • \$\begingroup\$ I am just saying that if you take no input and require a (semi-)static output, a part of the challenge is to find out which tic-tac-toe game requires the least bytes to represent and the rest is a kolmogorov-complexity task, which in my opinion is s slightly over-used challenge format. \$\endgroup\$ – Jonathan Frech Feb 25 at 15:59
  • \$\begingroup\$ kolmogorov-complexity challenges are code golf challenges with no input and a static output. \$\endgroup\$ – Jonathan Frech Feb 25 at 15:59
  • \$\begingroup\$ @JonathanFrech Is that a bad thing then? Do you think this challenge wouldn't be fun? \$\endgroup\$ – Quinn Feb 25 at 20:18
  • \$\begingroup\$ @FryAmTheEggman okay fixed my example, hopefully that illustrates how simple the ai could be \$\endgroup\$ – Quinn Feb 25 at 20:32
  • 1
    \$\begingroup\$ I feel as though your example does more to demonstrate that nobody would approach this by writing an AI - they would just encode each possible game as Jonathan is suggesting. That doesn't mean it isn't a good challenge, the problem I am trying to get at is that the phrasing of the challenge implies that writing a "player" is required - which I think is a bad requirement. If the challenge was just "output a random, valid, tic-tac-toe board" you could still maybe get an AI solution, if it happened to be shorter, but wouldn't come with a lot of needless baggage. Sorry if this sounds a bit rambly. \$\endgroup\$ – FryAmTheEggman Feb 25 at 20:39
  • \$\begingroup\$ @FryAmTheEggman well my example has tons of unnecessary baggage and is not doing anything in an efficient way in terms of golfing, i just wanted the general algorithm to be shown, id imagine it could easily be shortened to a couple hundred bytes in most languages. That said if they can find a way to output winning board states so long as they show each turn that was played than that would be valid, I don't intend to require anyone to write an AI, just achieve the desired output. Not sure how to rephrase the question to make sure its clear that that is a valid answer. \$\endgroup\$ – Quinn Feb 25 at 21:15
  • \$\begingroup\$ @Quinn However, finding such a game would not be done in the submission but to be able to write the submission, leaving the actual challenge itself to be a bit of a boilerplate. \$\endgroup\$ – Jonathan Frech Feb 25 at 21:19
  • \$\begingroup\$ I guess I've posted one, exactly same but ask for O's input \$\endgroup\$ – l4m2 May 14 at 7:30
0
\$\begingroup\$

Shift the letters, soldier !

Context

We're at war! You need to transfer an important message to your general to inform him from an imminent assault. The thing is, your enemy knows a lot about cryptography : you will need to be more creative in order to encode your message...

Task

Create a program that accepts an ascii message as input, and outputs the encoded message. The message should be encoded this way : each character should get its ascii value shifted by its position in the message.

For example, let's encode the message "Hello, world!"

H   e   l   l   o   ,       w   o   r   l   d   !     Original message
72  101 108 108 111 44  32  119 111 114 108 100 33    ASCII value
0   1   2   3   4   5   6   7   8   9   10  11  12    Place in the message
72  102 110 111 115 49  38  126 119 123 118 111 45    Encoded ascii (line 1 + line 2)
H   f   n   o   s   1   &   ~   w   {   v   o   -     Encoded message

The message Hello, world! should be encoded as Hfnos1&~w{vo-.

Rules

  • The message should be encoded as described before.
  • The ascii values should be set between 32 and 126.
  • If the new ascii value goes beyond the limit, it should loop back to 32.
  • Every character should be encoded. This includes punctuation, spaces etc.
  • No standard loopholes allowed.
  • This is codegolf, so the shortest code wins.
  • If you are able to decode a message, multiply your score by 0.7 Won't be part of the challenge anymore.

Meta

  • Is the challenge clear enouth ?
  • Should i only allow printable ascii values, or can i allow values between 1 and 256 ?
| |
\$\endgroup\$
  • \$\begingroup\$ Thank you for sandboxing this. I usually recommend doing so for at least a week, and periodically ask for review in TNB. \$\endgroup\$ – Adám Feb 28 at 9:09
  • \$\begingroup\$ I think people would be forced to do the bonus in this case because of the -30% margin. I got a 42 without bonus but a 57*0.7=39.9 with bonus in JS. \$\endgroup\$ – Shieru Asakoto Feb 29 at 3:16
  • \$\begingroup\$ Bonuses are discouraged for a variety of reasons. I would strongly recommend either making it mandatory or completely leaving it out. \$\endgroup\$ – FryAmTheEggman Mar 1 at 18:58
  • \$\begingroup\$ The main challenge is add by position, the bonus challenge is minus by position. So it's a good idea to completely leave the bonus out. \$\endgroup\$ – Λ̸̸ Mar 2 at 0:29
  • \$\begingroup\$ Thanks for the comments, I'll remove the bonus as it will never be balanced enouth to be interesting. I'll add some example as soon as I can. \$\endgroup\$ – The random guy Mar 3 at 20:02
  • \$\begingroup\$ I would say that allowing the usage of the ascii range 1 to 255 or a language's code page could allow for some interesting golfs :) \$\endgroup\$ – RGS Mar 3 at 20:39
  • \$\begingroup\$ Use asciii values from 0 to 255 was my original plan, but I'm afraid some interestings languages would be disadvantaged. Also, wouldn't the usage of language's code page be too permissive ? \$\endgroup\$ – The random guy Mar 4 at 15:51
  • \$\begingroup\$ @Therandomguy it depends on what you mean by "too permissive". Sometimes it is done, as it may allow some languages to do some funny things. As to the range being from 0 to 255, I don't see it hurting any language at all, but of course I may be missing something :) \$\endgroup\$ – RGS Mar 4 at 21:36
  • \$\begingroup\$ Are you interested in re-posting it? \$\endgroup\$ – Λ̸̸ Mar 6 at 7:38
  • \$\begingroup\$ This weekend I'll post it, I just need some time creating the examples \$\endgroup\$ – The random guy Mar 6 at 8:25
  • \$\begingroup\$ I'd be glad to see it posted in Main! \$\endgroup\$ – Λ̸̸ Mar 25 at 12:19
0
\$\begingroup\$

Compute the Pareto frontier

Given a set of triplets, output its Pareto frontier.

Definitions

A triplet is a list of 3 positive integers, for example [120, 15, 21] (order matters).

A triplet [A, B, C] is objectively worse than [a, b, c] when A >= a, B >= b, and C >= c (lower is better).

A triplet is on the Pareto frontier when it's not objectively worse than any other triplet in the input.

I/O rules

Input and output are both a set of triplets. Each triplet must be represented as either a list of integers ([1, 2, 3]) or a /-delimited string ("1/2/3"). The format of the outer sets is flexible (built-in set type, list, or delimited string are all okay).

Test cases

[[1, 1, 1], [2, 2, 2]] => [[1, 1, 1]]
[[3, 3, 1], [3, 1, 3], [1, 3, 3], [2, 2, 2]] => [[3, 3, 1], [3, 1, 3], [1, 3, 3], [2, 2, 2]]
... (more to come) ...
| |
\$\endgroup\$
  • \$\begingroup\$ I had sandboxed a similar challenge, but it didn't seem to be going anywhere and I wasn't going to post it. Maybe the discussion on it about filtering is somewhat relevant to this. \$\endgroup\$ – xnor Mar 8 at 18:42
  • \$\begingroup\$ The IO rule for the triplets seems odd, why not any kind of ordered list? \$\endgroup\$ – FryAmTheEggman Mar 8 at 19:35
0
\$\begingroup\$

A similar challenge was posted here but that's outdated and I have a few twists.

Challenge

Write a program, expression or subroutine which, given an arithmetical expression in infix notation, like 1 + 2, outputs the same expression in postfix notation except the numbers are now float representative in the string, i.e. 1.0 2.0 +.

The input can include parentheses (()), exponents (^), division (/) and multiplication (*), addition (+) and subtraction (-) (in that order of operation), such as

4 ^ (2 / 3) * 9 * 3 - - 4 * 6

output the same expression in prefix notation.

4.0 2.0 3.0 / ^ 9.0 * 3.0 * -4.0 6.0 * -

Spaces are optional in the input as well as the output.

Twists

  • Must support using floats too, instead of just integers. so 4 ^ (2.0/3.0) * 9.0 * 3.0 - - 4 *6 output's is the same as the ones above.
  • Must return a string with all numbers as its float representative instead of as its original form, so 9 -> 9.0 and if it was 9.0 it stays 9.0.
  • Must support negation (see example above "3.0 - - 4" ends up with "-4.0", negative sign stays in place).
  • Cannot use exec() or eval() functions.

Assumptions

  • You can assume that there will not be any special numbers such as those in scientific notation or those with hanging zeroes, e.g. 000004 or 0005.000000.
  • You should also not assume the commutative or associative properties. This means that, while the operators will move around, the numbers will always remain in the same order.
  • You can always assume a valid infix input.

Clarifications

  • You should not evaluate any expression.
  • The output should not contain any unneeded parentheses. ((2+1))-1 should reduce to 2+1-1.

Game Winning Criteria

Fewest amount of characters wins. Bytes are not of a matter here.

| |
\$\endgroup\$
  • 2
    \$\begingroup\$ To reiterate my comment on the original question: 1. Using the word "twist" is not recommended. 2. Don't ban exec/eval just because you don't like it. The task isn't about evaluating the value, so it is unnecessary and pretty much arbitrary. 3. You say "prefix notation", but 4.0 2.0 3.0 / ^ 9.0 * 3.0 * -4.0 6.0 * - is in postfix, not prefix. You should fix either the description or the example result. \$\endgroup\$ – Bubbler Mar 12 at 1:27
  • 1
    \$\begingroup\$ And you didn't explain why you want to handle unary negation in a different way (which is essentially changing the underlying expression, which seems against "You should not evaluate any expression"). By using a different symbol for unary minus (say ~), it is possible to translate the example to postfix as 4.0 2.0 3.0 / ^ 9.0 * 3.0 * 4.0 ~ 6.0 * -. \$\endgroup\$ – Bubbler Mar 12 at 1:34
  • 2
    \$\begingroup\$ For code-golf scoring, scoring by bytes is preferred over characters. (I believe there must be a more persuasive argument somewhere...) \$\endgroup\$ – Bubbler Mar 12 at 1:47
  • 1
    \$\begingroup\$ The second line in "clarifications" is unnecessary because "postfix notation" implies no parentheses. For the floating-point output, do you have a reason to demand adding .0 to integer values? A floating-point number 4 can be printed as 4, 4., or 4.0, and all of them represent the same value anyway. \$\endgroup\$ – Bubbler Mar 12 at 2:13
  • \$\begingroup\$ The linked challenge explicitly assumes left-associativity for all operators ^ * / + - (that is, 1 - 2 + 3 = (1 - 2) + 3, 4 / 5 * 6 = (4 / 5) * 6, and 7 ^ 8 ^ 9 = (7 ^ 8) ^ 9), but ^ is mathematically right-associative (7 ^ 8 ^ 9 = 7 ^ (8 ^ 9) != (7 ^ 8) ^ 9). Which one should we use? \$\endgroup\$ – Bubbler Mar 12 at 2:17
  • \$\begingroup\$ Can negation be stacked? i.e. is 1 - - - 1 a valid input? Doesn't negation in the output kinda negate (heh) the point of it being postfix, because it it prefix? \$\endgroup\$ – Jo King Mar 12 at 2:33
0
\$\begingroup\$

Lucky Numbers in a Matrix

Given a m * n matrix of distinct numbers, return all lucky numbers in the matrix in any order.

A lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column.

Test cases

Case 1:

Input: matrix = [[3,7,8],[9,11,13],[15,16,17]]
Output: [15]
Explanation: 15 is the only lucky number since it is the minimum in its row 
and the maximum in its column

Case 2:

Input: matrix = [[1,10,4,2],[9,3,8,7],[15,16,17,12]]
Output: [12]
Explanation: 12 is the only lucky number since it is the minimum in its row 
and the maximum in its column.
| |
\$\endgroup\$
  • \$\begingroup\$ What will be the smallest size of the matrix? Also, I suggest formatting the matrices 2-dimensionally in the test cases so that it is easier to see the corresponding output tio.run/##SyzI0U2pTMzJT/8PBI/… \$\endgroup\$ – user41805 Mar 15 at 8:11
0
\$\begingroup\$

Balance a Binary Search Tree

Given a binary search tree, return a balanced binary search tree with the same node values.

A binary search tree is balanced if and only if the depth of the two subtrees of every node never differ by more than 1.

If there is more than one answer, return any of them.

Test Case:

enter image description here

enter image description here

Input: root = [1,null,2,null,3,null,4,null,null]
Output: [2,1,3,null,null,null,4]
Explanation: This is not the only correct answer, [3,1,4,null,2,null,null] is also correct.
| |
\$\endgroup\$
  • 1
    \$\begingroup\$ Perhaps, you can include an explanation of this input format in the challenge body. What counts as valid input formats for the binary tree? \$\endgroup\$ – user41805 Mar 15 at 8:18
0
\$\begingroup\$

Determine the maximum value in the final array.

Description

Start with an array initialized to zeros with indices starting at 1 and a series of operations to perform on segments of the list. Each operation will consist of a starting and ending index within the array, and a number to add to each element within that range.

Determine the maximum value in the final array.

For example, start with an array of 5 elements: list = [0, 0, 0, 0, 0]. The variables a and b represent the starting and ending indices, inclusive. Another variable, k, is the addend. The first element is at index 1.


    a    b    k             list

                   [  0,  0,  0,  0,  0]

    1    2   10    [ 10, 10,  0,  0,  0]

    2    4    5    [ 10, 15,  5,  5,  0]

    3    5   12    [ 10, 15, 17, 17, 12]

The maximum value in the resultant array is 17. That is the value to be determined.

Function description

The function must return a long integer that denotes the largest value in the array after all operations have been performed.

listMax has the following parameters:

n: an integer, the size of the initial array.
operations: a 2D integer array where each element contains an operation.

Test Cases

Sample Input

5

3

3

1 2 100

2 5 100

3 4 100

Sample Output

200
Return the maximum value in the final list, 200, as the answer.

Explanation

Perform the following sequence of o = 3 operations on list = [0, 0, 0, 0, 0]:

  1. Add k = 100 to every element in the inclusive range [1, 2], resulting in list = [100, 100, 0, 0, 0].

  2. Add k = 100 to every element in the inclusive range [2, 5], resulting in list = [100, 200, 100, 100, 100].

  3. Add k = 100 to every element in the inclusive range [3, 4], resulting in list = [100, 200, 200, 200, 100].

This is code-golf so shortest submission in bytes wins! If you liked this challenge, consider upvoting it... And happy golfing!

| |
\$\endgroup\$
1
81 82
83
84 85
95

You must log in to answer this question.

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