485
\$\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\$

2929 Answers 2929

1
41 42
43
44 45
98
1
\$\begingroup\$

Distinct Dice Sum Algorithm

From a puzzle on Brainden. Paraphrasing,

What is the best set of 8 sided dice, each identical, such that 3 dice can generate 120 distinct sums? "Best" means the minimum highest sided die configuration.

With 7 sided dice, the best possible sides for each (identical) die is: 1, 2, 8, 51, 60, 79, 83.

For the sake of discussion, use sides=s, and dice=d.

Note1: 120 is the maximum number of distinct sums with s=8, d=3. The formula is:

$$ \frac{(s+d-1!)}{(s-1)!(d)!} $$

Similarly, for s=7, d=3, the formula gives 84. And brute force shows that a side of at least 83 is required for this easier problem.

Note2: The lowest numbered side is always 1 for an optimal solution to the original question. (See comments.)

My question is, "What's the fastest algorithm to discover the minimum highest sided die for maximum distinct sums?".

Specifically, is there some existing algorithm, or better yet, formula, for the minimum highest sided die? For determining all sides?

While there are obvious choices for languages, I'm not interested in that. I'm interested in the best algorithm possible in general. A sketch of the algorithm with the best (smallest) Big-O score wins.

Complexity of answers should be expressed by Big-O notation, e.g., M(s) = O(???), with d=3. Ties will be broken according to number of dice, i.e., M(s,d) = O(???).

As a puzzle toy to idle time some years ago, I wrote a brute force solver. Unfortunately, for (s=8, d=3), and even knowing an upper limit, my program never completed the search (uptime was an issue).

| |
\$\endgroup\$
  • 3
    \$\begingroup\$ To turn this into a challenge, you'll have to pick an objective winning criterion. fastest-algorithm would work if you want to minimize asymptotic time complexity, but since the complexity will depend on s and d, you'll have to combine them somehow. \$\endgroup\$ – Dennis Aug 28 '18 at 14:08
  • 1
    \$\begingroup\$ Exactly 120 distinct sums or at least 120 distinct sums? \$\endgroup\$ – Peter Taylor Aug 30 '18 at 10:12
  • 2
    \$\begingroup\$ "it would be preferable to word your challenge more like a challenge and less like a help request." – quote Dennis. \$\endgroup\$ – user202729 Aug 30 '18 at 13:39
  • \$\begingroup\$ The challenge can be trivially solved in linear time in the output (which is optimal time), because note that the largest face need to be at least 41 (otherwise 3 ≤ sum ≤ 120 and there can't be 120 values, assuming all values are positive integers), therefore for all s ≥ 41 just output 1 ... 41 and a bunch of other 1s to fill up the faces. Not interesting. \$\endgroup\$ – user202729 Aug 30 '18 at 13:46
  • \$\begingroup\$ @user202729 I don't think that works. You have 8 faces to work with, which is less than 41. \$\endgroup\$ – Nathan Merrill Aug 30 '18 at 20:46
  • \$\begingroup\$ @NathanMerrill No, you have s faces to work with. If s<41 just brute force it (O(1)). Otherwise use the algorithm above. \$\endgroup\$ – user202729 Aug 30 '18 at 23:54
  • \$\begingroup\$ @user202729 Right, for s>41, it's trivial. What is not trivial is less than 41, which I don't see the algorithm for. Which algorithm are you talking about? \$\endgroup\$ – Nathan Merrill Aug 31 '18 at 0:41
  • \$\begingroup\$ @NathanMerrill Note that the challenge requires smallest asymptotic complexity, not runtime. All (correct) algorithm which only operates on bounded input works in O(1), by the definition of "asymptotic". \$\endgroup\$ – user202729 Aug 31 '18 at 0:52
  • \$\begingroup\$ @user202729 True, but it is trivial to increase 120 as well, to provide a way for measuring the asymptotic nature of the algorithm. \$\endgroup\$ – Nathan Merrill Aug 31 '18 at 0:54
  • \$\begingroup\$ @NathanMerrill Then the challenge needs to be edited to explicitly specify that. \$\endgroup\$ – user202729 Aug 31 '18 at 1:01
  • \$\begingroup\$ @user202729 perhaps, but I could see an argument that the 120 is useful to provide a solid ground for the algorithm, as long as they indicate that it is arbitrary. \$\endgroup\$ – Nathan Merrill Aug 31 '18 at 1:03
  • \$\begingroup\$ 120: For s=8, d=3, 120 is the maximum number of distinct sums. I believe the formula is M=((s-1)+d)!/((s-1)!d!). Not sure how to write that well in a comment, but sCd with repetitions. \$\endgroup\$ – Quantum Mechanic Aug 31 '18 at 15:25
  • \$\begingroup\$ Big-Oh notation does not assume a fixed input. If the input is fixed, any algorithm can be said to be O(1), which is unhelpful. For example, f(a) = O(a^2). It's often harder to describe this with more than one variable, but it might be f(a,b) = O(max(a,b)^2). \$\endgroup\$ – Quantum Mechanic Aug 31 '18 at 16:01
  • \$\begingroup\$ @QuantumMechanic for scoring the algorithms, I think you could assume a constant d, but as a tie-breaker, include d. \$\endgroup\$ – Nathan Merrill Aug 31 '18 at 16:13
  • \$\begingroup\$ I think there's an implicit assumption that the smallest permitted value on the side of a die is 1, but that should be made explicit. \$\endgroup\$ – Peter Taylor Sep 5 '18 at 11:09
1
\$\begingroup\$

What is the simplest reversible circuit that computes conjugacy of transpositions?

,,

Motivation

Reversible computation refers to computation in which little or no information is deleted. Reversible computation a major component of quantum computation, and reversible computation is potentially many times more energy efficient than conventional computation. I want to know how easy it is to compute the conjugacy of transpositions reversibly?

Challenge

Let T5 be the set of all transpositions on the set {1,2,3,4,5}. Let * be the conjugacy operation on T5 defined by x * y=xyx^(-1) (here concatenation denotes the group operation). In other words, the underlying set of T5 consists of all 10 pairs (a,b) of distinct numbers from {1,2,3,4,5} and where we declare (a,b)=(b,a). The operation * is the unique operation on the underlying set that satisfies

  • (a,b) * (c,d)=(c,d),
  • (a,b) * (b,c)=(a,c),
  • (a,b) * (a,b)=(a,b)

whenever a,b,c,d are distinct.

What is the simplest n bit input reversible circuit C along with an injective function R:T5->{0,1}^n such that C(R(x),R(y))=(R(x),R(x*y)) for all x,y in T5?

The gate cost of a reversible circuit shall be the sum of the costs of every individual logic gate in the reversible circuit.

Here is the price chart per logic gate (see this link for a description of the logic gates) along with a description of the reversible gates.

Each SWAP gate (x,y)->(y,x) will have a cost of 0.

Each NOT gate x-> NOT x shall have a cost of 1.

Each CNOT gate (x,y)->(x,x XOR y) shall have a cost of 2.

Each Fredkin gate (x,y,z)->(x,(NOT x AND y) OR (x AND z),(x AND y) OR (NOT x AND z)) shall have a cost of 4 (the Fredkin gate can also be described as the reversible logic gate where (0,x,y)->(0,x,y) and (1,x,y)->(1,y,x)).

Each Toffoli gate (x,y,z)->(x,y,(x AND y) XOR z) shall have a cost of 5.

No other gates are allowed.

Observe that each reversible gate has the same number of inputs as it has outputs (this feature is required for all reversible gates).

The complexity of your circuit will be the product of the gate cost or your circuit with the number n which you choose. The goal of this challenge will be to minimize this measure of complexity.

Format

Complexity: This is your final score. The complexity is the product of the number n with your total gate cost.

Space: State the number n of bits that your circuit C acts on.

Total gate cost: State the sum of the costs of each of the individual gates in your circuit C.

NOT gate count: State the number of NOT gates.

CNOT gate count: State the number of CNOT gates.

Toffoli gate count: How many Toffoli gates are there?

Fredkin gate count: How many Fredkin gates are there?

Legend: Give a description of the function R. For example, you may write

(1,2)->0000,(1,3)->0001,(1,4)->0010,(1,5)->0011,(2,3)->0100, (2,4)->0101,(2,5)->0110,(3,4)->0111,(3,5)->1000,(4,5)->1001.

Gate list: Here list the gates in the circuit C from first to last. Each gate shall be written in the form [Gate type abbreviation,lines where the gates come from]. For this problem, we shall start with the 0th bit. The following list specifies the abbreviations for the type of gates.

T-Toffoli gate S-Swap gate C-CNOT gate F-Fredkin gate N-Not gate.

For example, [T,1,5,3] would denote a Toffoli gate acting on the 1st bit, the 5th bit, and the 3rd bit. For example, [T,2,4,6] produces the transformation 01101010->01101000 and [C,2,1] produces 011->001,010->010 and [N,3] produces 0101->0100. For example, one could write [S,7,3],[N,2],[T,1,2,3],[F,1,2,5],[C,7,5] for the gate list.

The gates act on the bit string from left to right. For example, the gate list [C,0,1],[C,1,0] will produce the transformation 01->11.

Sample answer

Complexity: 80

Space: 5

Total gate cost: 16

NOT gate count: 3

CNOT gate count: 2

Toffoli gate count: 1

Fredkin gate count: 1

Legend: (1,2)->00001,(1,3)->00011,(1,4)->00101,(1,5)->00110,(2,3)->01000,(2,4)->01011,(2,5)->01100,(3,4)->01110,(3,5)->10001,(4,5)->10011

Gate list: [N,1],[N,0],[N,4],[S,1,2],[S,2,3],[C,0,1],[C,2,3],[T,3,2,1],[F,4,3,2,1]

Sandbox

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ It would be helpful to define conjugacy, transposition and the group operation. If the challenge is to write a program that does these things then you should specify that along with desired input/output format and winning criterium (e.g. shortest code, fastest code, custom scoring, etc.) \$\endgroup\$ – dylnan Dec 18 '17 at 21:26
  • \$\begingroup\$ is x^(-1) the inverse of x on the group? \$\endgroup\$ – Ad Hoc Garf Hunter Dec 18 '17 at 21:38
  • \$\begingroup\$ Yes. x^(-1) denotes the inverse of x in the group. For transpositions x, we have x^(-1)=x. \$\endgroup\$ – Joseph Van Name Dec 18 '17 at 21:46
  • \$\begingroup\$ It would be helpful if you format the code properly. \$\endgroup\$ – user202729 Dec 19 '17 at 1:22
  • 1
    \$\begingroup\$ "The operation * is the unique operation on the underlying set that satisfies (a,b) * (c,d)=(c,d),(a,b) * (b,c)=(a,c),(a,b) * (a,b) whenever a,b,c,d are distinct." I find that list hard to read with the whitespace as is, but is it incomplete? I think it's missing = (a,b) at the end. For readability, I suggest either using code markup separately for each identity or putting them in an unordered list. \$\endgroup\$ – Peter Taylor Dec 19 '17 at 8:48
  • \$\begingroup\$ I think the C on the right hand side of the condition is wrong. \$\endgroup\$ – Christian Sievers Dec 19 '17 at 21:39
  • 1
    \$\begingroup\$ After reading this a few more times, I find that I'm uncertain as to what branching is allowed. Can I use the same value as input to more than one gate, or is a line "used up" when it goes into a gate? Also, are constant 0 and 1 available, or do they have to be included as extra bits in the output of R? \$\endgroup\$ – Peter Taylor Dec 20 '17 at 11:10
  • \$\begingroup\$ Sorry for being away for a while. I am going to get back to editing this proposed challenge so that it will be up and ready as soon as possible. \$\endgroup\$ – Joseph Van Name Sep 8 '18 at 14:33
  • 1
    \$\begingroup\$ @PeterTaylor. Reversible circuits do not have any branching. Every reversible gate has the same number of input bits as it has output bits. I will clarify this in the post. \$\endgroup\$ – Joseph Van Name Sep 8 '18 at 14:39
1
\$\begingroup\$

Compile Brainbash to BF

Background

BF is an esolang known for it's terseness and small character set. The language operates on a tape of unsigned 8-bit integers, and with a pointer to modify certain values. This pointer starts at the first cell. BF has the following commands available to program with:

+       increment the current cell
-       decrement the current cell
>       move the pointer to the next cell on the right
<       move the pointer to the next cell on the left
.       output the current cell as a character
,       take a character of input
[       begin a loop while the current cell is not zero
]       end that loop

Brainbash is a language similar to BF, but it has two tapes. To deal with this, Brainbash has a "tape focus"; one tape at a time is being worked on. Each tape also has its own pointer. Thus, Brainbash has a few more commands in addition to BF's:

~       swap the tape focus
*       swap tapes and copy the pointer from the previous tape to the next one
{       if the current cell is not zero, execute the code until the next `}` that matches 
}       marks the end an if statement

(There are more commands, but they are not being considered for the purposes of this challenge.)

Challenge

Given a non-empty Brainbash program P, translate that program to BF. That is, output a program Q whose I/O behavior is identical to that of P.

This is a code-golf, so the shortest in program (in bytes) that successfully does this wins.

Specific rules

  • You may assume that each tape is infinite to the right starting at the origin.
  • You may assume that the input is a valid program which has matching { and } and [ and ].

Example Test Cases

(to be introduced)

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ Do the Brainbash tapes wrap, or are they infinite in each direction? Are the Brainfuck commands also Brainbash commands? \$\endgroup\$ – AdmBorkBork Sep 7 '18 at 20:21
  • \$\begingroup\$ What does it mean to translate? Only keep I/O behaviour the same or also some tape structure? \$\endgroup\$ – Jonathan Frech Sep 8 '18 at 9:14
  • \$\begingroup\$ @AdmBorkBork (1) You must support at least 30000 cells to the right of the origin for both tapes (2) Yes \$\endgroup\$ – Conor O'Brien Sep 8 '18 at 16:52
  • \$\begingroup\$ @JonathanFrech Keep I/O behaviour \$\endgroup\$ – Conor O'Brien Sep 8 '18 at 16:53
1
\$\begingroup\$

Make it rotationally-symmetric

(sandbox note: am I using the wrong terminology?)

Background

While looking at this challenge, I notice many some of the answers has 4-fold rotational symmetry. I think it would be convenient to have a program to automatically do it.

Challenge

  • Take input as a string, for which when separated by newlines, all line has equal length. (i.e., the input is rectangular)
  • The output is the smallest square with 4-fold rotational symmetry, where the top-left corner is equal to the rectangle.

Sample input/output

Input:
aba
bab
aba

Output:
aba
bab
aba

Input:
 begin write('left')end.// 
/e .dne)'thgir'(etirw nigeb

Output:
 begin write('left')end.// 
/e .dne)'thgir'(etirw nigeb
/g                        e
.i                       .g
dn                       di
n                        nn
ew                       e 
)r                       )w
'i                       'r
tt                       ti
fe                       ht
e(                       ge
l'                       i(
'r                       r'
(i                       'l
eg                       (e
th                       ef
it                       tt
r'                       i'
w)                       r)
 e                       we
nn                        n
id                       nd
g.                       i.
e                        g/
begin write('right')end. e/
 //.dne)'tfel'(etirw nigeb 

Input:
abc
cde

Output:
abcca
cdedb
ce ec
bdedc
accba

Winning criteria

.

| |
\$\endgroup\$
  • \$\begingroup\$ Could input be a list of strings? \$\endgroup\$ – Kroppeb Sep 13 '18 at 19:39
  • \$\begingroup\$ Do the filler characters have to be spaces? \$\endgroup\$ – dylnan Sep 15 '18 at 0:16
  • \$\begingroup\$ Suggested test case: 'ab\naa' \$\endgroup\$ – dylnan Sep 15 '18 at 0:19
1
\$\begingroup\$

Mini Castle Wars

Note: This is very early draft, and I'll try to develop when I get some time to spare.


Inspired by a previous KOTH based on a card game (but not actually a card game).

Background

This challenge involves a simplified version of the card game Castle Wars.

Game rules

Gameplay

Just like many other card games, Castle Wars is a two-player turn-based game.

Each player starts with 30 units of castle, 5 units of fence, no shield, 2 workers, 8 bricks, 2 magicians, and 8 crystals. Each player is dealt (TBD, 5?) cards from his own deck at start.

Each resource has the following function:

  • Castle: Directly related to the winning condition (see below).
  • Fence: Fences can block the opponent's attack. If the attack would damage the castle by N units, the fence is damaged N units instead. If the fence is less than N units, it becomes zero and the remaining damage is dealt to the castle.
  • Shield: If a castle is shielded, it can nullify any amount of damage to the castle AND the fence, exactly once. Shield can't be stacked.
  • Workers: Each worker produces one brick every turn.
  • Magicians: Each magician produces one crystal every turn.
  • Bricks and Crystals: Every card spends some of these resources to take effect.

Each turn works as follows:

  1. He gets the resources produced by his own workers and magicians.
  2. The player draws a card from his own deck.
  3. He plays a card. If he has enough resources, the card takes effect immediately (including the resources spent). Otherwise, it has no effect whatsoever.
  4. The played card returns to the deck, and the deck is shuffled.

In order to compensate the first-player advantage, resource generation is skipped at the first turn of the game. (TBD)

Cards & deck

A deck consists of at least (TBD) cards, and may include at most (TBD) copies of the same card.

Here is the full list of cards.

  • (TBD, will reflect the actual cards in the game)

Winning condition

A player wins if the opponent's castle is destroyed (0 units or below), or his own castle grows to 100 units or higher. If 100 turns are passed without a player winning, the one with higher castle is declared the winner. Same castle height after 100 turns is a draw.

Tournament

Every bot will have (TBD, even number) matches with every other bot, alternating the first turn.

Controller

TBD. This will ideally be implemented in KOTH-Webplayer.

Submission guide

A submission will look like this:

Deck

'AAAAABBBBBCCDDEXYZ'

Bot

return hand[Math.random()*hand.length|0];

The Deck is a string literal that describes the list of cards your bot will use. The Bot is a snippet that will fit into the following function's body:

function play(hand, myResources, opResources, opPlayed, storage) {
    // function body here
}

The description of parameters:

  • hand is an Array of (TBD) cards in your bot's hand. Your bot's job is to choose a card to play.
  • myResources and opResources are two Objects that have the information of all the resources (the bot's and the opponent's, respectively). Available keys are castle, fence, worker, brick, magician, crystal, shield. (shield is a Boolean indicating whether the player's castle is shielded or not; others are simple numbers.)
  • opPlayed is the card played at the opponent's last turn.
  • storage is an Object you can freely use to store information between turns. It is initially empty ({}).

Meta

  • I originally planned to have a simplified version of the original Castle Wars, but on second thought, the rules are not that complicated and removing some resource types may break the balance of the game (as some interesting cards have to be revised). Would it be good to implement the full game instead?
| |
\$\endgroup\$
  • \$\begingroup\$ Fantastic to see this brewing in the sandbox! Here are a couple pieces of criticism and some potential solutions: a) No tournament type is specified - I'm assuming it's round-robin. This should be added to the spec. a) Is there a need to compensate for the first-player advantage? Surely, a two-way round-robin would be fair enough, no? I'm not sure how large the first-player advantage is, though, so I could be wrong here. c) I've found that there's a handy way to handle persistent storage of things in JavaScript - closures. \$\endgroup\$ – Alion Sep 20 '18 at 9:30
  • \$\begingroup\$ cont. c) I would recommend that all future JS KOTHs required a function factory pattern from players. Here's an example of how that can be useful for entries. Here's how that looks without the closure pattern, and how it negatively affects entries. \$\endgroup\$ – Alion Sep 20 '18 at 9:49
  • \$\begingroup\$ cont. c) For this challenge, this could be additionally useful, since you require players to choose a deck for themselves. The bots could return a {deck, func} object during setup that way. \$\endgroup\$ – Alion Sep 20 '18 at 9:56
1
\$\begingroup\$

Prettify Pixiedust


So Pixiedust is a new esolang I've created. One of the primary points is that it should look like pixie dust—exactly the things that your programs should fix.

Input

The input will be a program written in Pixiedust. Since this is not a challenge to parse the language, it won't be in raw code, but a list of numbers and the strings separating them. The numbers can be taken as the number itself, or their representation in the program.

Randomizing the Literals

For each numeric literal, there are many ways to represent them:

  • Randomly pad the beginning with . characters. It should be an even distribution between padding it to 32 bits and padding it to the base length.
  • If the number is at the end of the line, then take an even split between including and excluding the terminating *.

Scattering

At this point, you should have the lines calculated—let's call this the half-pretty program. For each line of output:

  • Start with a line of pure spaces 4 times the length of the longest half-pretty line.
  • Randomly select spaces from it to replace with program characters. Every combination of spaces should have an equal chance.
  • Replace those spaces with the corresponding characters, without changing the order that they appear in.
  • (Optional) trim off trailing spaces.

Scoring

The winner will be the shortest answer in bytes. Additionally, there will be a 50-rep bounty for the first answer written in Pixiedust.


Examples will be coming once I finish the interpreter and make some submissions to other challenges in Pixiedust.

| |
\$\endgroup\$
  • \$\begingroup\$ Since this is not a challenge to parse the language, I mean, it's not that hard. \$\endgroup\$ – RamenChef Sep 29 '18 at 0:20
1
\$\begingroup\$

Iteration Hierarchy

This is based on the m(n) map. mk takes in k functions and one natural input n, and iterates the first function n times onto the next argument, and then fills in the rest of the arguments.

\$m_1=f_0\mapsto n\mapsto f_0^n(n)\$

\$m_2=f_1\mapsto f_0\mapsto n\mapsto f_1^n(f_0)(n)\$

\$m_3=f_2\mapsto f_1\mapsto f_0\mapsto n\mapsto f_2^n(f_1)(f_0)(n)\$

etc. where \$f^n(x)=f(f(f(\dots f(x)\dots)))\$ with \$n\$ calls to \$f\$ (a.k.a. function iteration).

Note particularly that \$m_2(f_1)(f_0)(2)=f_1(f_1(f_0))(2)\ne f_1(f_1(f_0(2)))\$ i.e. it iterates the first argument over the second argument and then applies the remaining arguments afterwards.


Examples:

Let \$s(n)=n+1\$.

m1(s)(5)

m₁(s)(5)
= s(s(s(s(s(5)))))                                x5 iterations of s
= 10

m1(m1(s))(4)

m₁(m₁(s))(4)
= m₁(s)(m₁(s)(m₁(s)(m₁(s)(4))))                   x4 iterations of m₁(s)
= m₁(s)(m₁(s)(m₁(s)(s(s(s(s(4)))))))              x4 iterations of s
= m₁(s)(m₁(s)(m₁(s)(8)))
= m₁(s)(m₁(s)(s(s(s(s(s(s(s(s(8))))))))))         x8 iterations of s
= m₁(s)(m₁(s)(16))
= ...
= m₁(s)(32)
= ...
= 64

m2(m1)(s)(3)

m₂(m₁)(s)(3)
= m₁(m₁(m₁(s)))(3)                                x3 iterations of m₁
= m₁(m₁(s))(m₁(m₁(s))(m₁(m₁(s))(3)))              x3 iterations of m₁(m₁(s))
= m₁(m₁(s))(m₁(m₁(s))(m₁(s)(m₁(s)(m₁(s)(3)))))    x3 iterations of m₁(s)
= m₁(m₁(s))(m₁(m₁(s))(m₁(s)(m₁(s)(s(s(s(3)))))))  x3 iterations of s
= m₁(m₁(s))(m₁(m₁(s))(m₁(s)(m₁(s)(6))))
= ...
= m₁(m₁(s))(m₁(m₁(s))(24))
= m₁(m₁(s))(m₁(s)(m₁(s)(m₁(s)(m₁(s)(m₁(s)(m₁(s)(m₁(s)(m₁(s)(m₁(s)(m₁(s)(m₁(s)(m₁(s)(m₁(s)(m₁(s)(m₁(s)(m₁(s)(m₁(s)(m₁(s)(m₁(s)(m₁(s)(m₁(s)(m₁(s)(24)))))))))))))))))))))))))
= ...
= m₁(m₁(s))(402653184)
= ...
= ???

m3(m2)(m1)(s)(2)

m₃(m₂)(m₁)(s)(2)
= m₂(m₂(m₁))(s)(2)                                x2 iterations of m₂
= m₂(m₁)(m₂(m₁)(s))(2)                            x2 iterations of m₂(m₁)
= m₁(m₁(m₂(m₁)(s)))(2)                            x2 iterations of m₁
= m₁(m₂(m₁)(s))(m₁(m₂(m₁)(s))(2))                 x2 iterations of m₁(m₂(m₁)(s))
= m₁(m₂(m₁)(s))(m₂(m₁)(s)(m₂(m₁)(s)(2)))          x2 iterations of m₂(m₁)(s)
= m₁(m₂(m₁)(s))(m₂(m₁)(s)(m₁(m₁(s))(2)))          x2 iterations of m₁
= m₁(m₂(m₁)(s))(m₂(m₁)(s)(m₁(s)(m₁(s)(2))))       x2 iterations of m₁(s)
= m₁(m₂(m₁)(s))(m₂(m₁)(s)(m₁(s)(s(s(2)))))        x2 iterations of s
= m₁(m₂(m₁)(s))(m₂(m₁)(s)(m₁(s)(4)))
= m₁(m₂(m₁)(s))(m₂(m₁)(s)(8))
= m₁(m₂(m₁)(s))(m₁(m₁(m₁(m₁(m₁(m₁(m₁(m₁(s))))))))(8))
= ...
= ???

Aside:

This hierarchy is closely related to the fast-growing hiearchy when using a base function of s.

In fact, the last example is already much larger than Graham's number, and \$m_n(m_{n-1})\dots(m_1)(s)(n)\approx f_{\varepsilon_0}(n)\$ in the fast-growing hierarchy.

Code Golf Challenge:

Write the shortest possible function subprogram for \$m_k\$. Code size is measured in bytes.

Here's an example program (Ruby, I can golf this down to about 140 bytes):

iterate=->f,n{->g{
    i=g
    n.times{i=f[i]}
    i}}

m=->k{
    x="->n{y=iterate[f#{k-1},n]; (0...#{k-1}).map{|l| y=eval(\"y[f\#{l}]\")}; y[n]}"
    (0...k).map{|l| x="->f#{l}{"+x+"}"}
    eval(x)}

NB: As noted above, the growth rate of \$m_n(m_{n-1})\dots(m_1)(s)(n)\$ is comparable to \$f_{\varepsilon_0}(n)\$. If this can be golfed far enough below 100 bytes, it could well place in the top 5 of the Largest Number Printable question.

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

Challenge

Max Sum String

Given an input string, return the max word based on the sum of each word's unicode characters.

Rules

  • The input should be seperated by whitespace
  • The value of each word is based on the sum of each character in the word's UTF-16 code
  • The output should be the word

Examples

Input: "a b c d e"
Output: "e"

Input: "this is a test"
Output: "test"

Input: "test Test"
Output: "test"

Input: "hello world"
Output: "world"

Input: "💀 👻 🤡 🦇 🕷️ 🍬 🎃"
Output: "🕷️"

I doubt it's optimal at all, but here's the code I came up with to accomplish this challenge:

let str = "hello world";
Object.keys(str.split(' ').map(w => {return {[w]: [...w].map(c => c.charCodeAt(0)).reduce((a, b) => a + b, 0)}}).reduce((a, b) => { return Object.values(a)[0] > Object.values(b)[0] ? a : b}))[0];
| |
\$\endgroup\$
  • \$\begingroup\$ Will all words be unique, or can there be duplicated words? For example, is "testing testing this is a test" a valid input? I would advice to keep all words unique, but it's your choice. If duplicated words are possible, would this test case result in "testing", ["testing", "testing"], or either is allowed? \$\endgroup\$ – Kevin Cruijssen Oct 4 '18 at 12:50
  • 1
    \$\begingroup\$ Also, even if duplicated words aren't allowed, what if the sum of two words have equal values, and are the max? Do we output either of the possible words, both of them, or either of these options is allowed? (I would suggest allowing both, and add a test case like that. For example "àà as a test" resulting in ["àà", "test"].) Other than that it's a nice challenge, so +1 from me. Already prepared an 8-bytes solution for it. :) \$\endgroup\$ – Kevin Cruijssen Oct 4 '18 at 12:54
  • \$\begingroup\$ I thought it should print out the first word, that's an easy fix to my js code. Thank you for the feedback, I'll post it soon! \$\endgroup\$ – GammaGames Oct 5 '18 at 15:31
1
\$\begingroup\$

Converting a number from Zeckendorf Representation to Decimal

moved to main

| |
\$\endgroup\$
  • \$\begingroup\$ Questions should try to be self-contained so that people don't have to go off-site, and so links don't end up being dead. \$\endgroup\$ – Jo King Oct 7 '18 at 7:37
1
\$\begingroup\$

Be there, for the square

| |
\$\endgroup\$
  • \$\begingroup\$ Same idea, but extended to a cube: codegolf.stackexchange.com/q/92410/56433 \$\endgroup\$ – Laikoni Oct 6 '18 at 1:16
  • \$\begingroup\$ Good catch! I think that the cube challenge is different enough that the answers won't just be taken from there. My challenge skips a lot of the special cases, which could make for some optimization. \$\endgroup\$ – maxb Oct 6 '18 at 7:07
1
\$\begingroup\$

Ascii Table to UTF-8

When I write documentation, comments, etc. I love making ASCII tables. They usually end up looking pretty good, but I always feel that they could look even better - especially since UTF-8/Unicode includes the box drawing characters. However, these characters are very burdensome to use, requiring several key presses to insert. Your task? Write a program or a function that can automatically convert ASCII tables to the UTF-8/Unicode equivalent.

Challenge

Write a program, that given an ASCII table as an input string, outputs the table redrawn with the Unicode/UTF-8 box drawing characters. Specifically, the characters that are a part of the table should be translated as follows:

(Unicode)
- to ─ (\u2500)
| to │ (\u2502)
= to ═ (\u2550)

and + to one of:
   ┌ (\u250C), ┐ (\u2510), └ (\u2514), ┘ (\u2518),
   ├ (\u251C), ┤ (\u2524), ┬ (\u252C), ┴ (\u2534),
   ┼ (\u253C)
or, if '=' on either side:
   ╒ (\u2552), ╕ (\u2555), ╘ (\u2558), ╛ (\u255D),
   ╞ (\u255E), ╡ (\u2561), ╤ (\u2564), ╧ (\u2567),
   ╪ (\u256A)

Details

I/O:

  • Default I/O is allowed
  • You may take a path to a file instead of the table as a string.
  • You may output to a file and take the file name as an additional argument.
    • However, you may not modify the input file. (It should be retained for ease of future editing)

Input:

  • You may assume that every row of input has been padded to be the same length with .
  • You may not assume that the first character after a newline is a part of the table borders (as it may be whitespace).
  • Input is considered a valid table if all characters (that are a part of the table) -=| are connected to exactly two characters and + are connected to at least one character both horizontally and vertically.
  • Your program may not produce any errors with valid inputs.
  • If the input is not valid the behavior is undefined and you may produce any output.

Output:

  • Any of the characters -=|+ that are not a part of the table must be left as-is.
  • Similarly, any other characters must be left as-is.
  • A single leading and/or trailing newline is allowed.

Other:

  • Standard loopholes are forbidden, as per usual.
  • If your preferred language has a built-in that solves this problem, you may not use it.
    • This means programs, functions, subroutines or instructions that would be valid submissions for this challenge with no additions.

Connected characters:

A character is connected to another, if:

  • It is | and is directly above or below + or |;
  • It is - and is directly before or after + or -;
  • It is = and is directly before or after + or =;
  • It is + and is directly above or below | or +, or is directly before or after -, = or +.

A character is considered a part of the table, if it is connected to any character that is a part of the table. By definition, the first + in the input is a part of the table.

Examples

Examples available here as a copy-pastable version.

 Input:                    Output:
+------------------+      ┌──────────────────┐
|   Hello+World!   |      │   Hello+World!   │
+==================+      ╞══════════════════╡
| This is+my first |  ->  │ This is+my first │
|+-+ code|golf  +-+|      │+-+ code|golf  +-+│
|+-+chall|enge! +-+|      │+-+chall|enge! +-+│
+------------------+      └──────────────────┘

     +===+===+===+             ╒═══╤═══╤═══╕
     | 1 | 2 | 3 |             │ 1 │ 2 │ 3 │
 +---+===+===+===+         ┌───╪═══╪═══╪═══╡
 | 1 | 1 | 2 | 3 |         │ 1 │ 1 │ 2 │ 3 │
 +---+---+---+---+    ->   ├───┼───┼───┼───┤
 | 2 | 2 | 4 | 6 |         │ 2 │ 2 │ 4 │ 6 │
 +---+---+---+---+         ├───┼───┼───┼───┤
 |-3 |-3 |-6 |-9 |         │-3 │-3 │-6 │-9 │
 +===+---+---+---+         ╘═══╧───┴───┴───┘

      +-----+         ->      <Undefined>

      +-----+         ->      ┌─────┐
      +-----+                 └─────┘

+-----------------+
|  Hello, World!  |
| This is invalid |   ->      <Undefined>
|      input      |
 -----------------+

       ++++                      ┌┬┬┐
       ++++           ->         ├┼┼┤
       ++++                      └┴┴┘

       +--+
       ++++           ->      <Undefined>
       +--+

Finally...

This is , so the least amount of bytes wins. Happy golfing!

| |
\$\endgroup\$
  • \$\begingroup\$ This is a solid first challenge, nice job. The test cases are good as well. 1. What should happen on the input + (all by itself?), or the input +---+? \$\endgroup\$ – Nathan Merrill Oct 8 '18 at 17:04
  • \$\begingroup\$ @NathanMerrill Good question. I'll clarify. \$\endgroup\$ – user77406 Oct 8 '18 at 18:02
1
\$\begingroup\$

One line keyboard

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ Some questions: What happened to the tab key? Why are there no upper-cased letters in the alternate section? I think it would be a bit more clear if you'd wrap the actual characters in `. OT: This challenge remind me a bit of this :) \$\endgroup\$ – ბიმო Oct 8 '18 at 16:20
  • \$\begingroup\$ Another thing: I can't think of a language/algorithm rn, but someone might struggle with the empty string and it doesn't really add much to the core of the challenge. You might want to loosen that requirement to only allow non-empty inputs, but it's your call and either way is fine. \$\endgroup\$ – ბიმო Oct 8 '18 at 16:24
  • \$\begingroup\$ @BMO I've excluded the tab key as it will never appear in the input (not in ascii range 32-126) and as far as I'm aware it can't be used to input other special characters. I didn't include the upper cased letters in the alternate section as they're always the same key as their lowercase counterpart (although am happy to edit if it makes it clearer). Finally, I wanted to wrap the characters in a backtick but was unsure how to escape it in the first line :) \$\endgroup\$ – Luke Stevens Oct 8 '18 at 16:25
  • 1
    \$\begingroup\$ Ah forgot about the printable range, makes sense. It wouldn't hurt to add them and would make it more complete, but it is not really essential to the challenge. I think using <code>...</code> is the easiest way or you can use double backticks. \$\endgroup\$ – ბიმო Oct 8 '18 at 16:32
  • \$\begingroup\$ Why does {} matters, as you can't access Shift key on that line anyway? \$\endgroup\$ – user202729 Oct 8 '18 at 16:39
  • \$\begingroup\$ @user202729 Originally I just typed out all the keys to leave it up to each person to work out what they could use, but thinking about it that seems unecessary so I'll change it to just characters \$\endgroup\$ – Luke Stevens Oct 8 '18 at 17:12
  • \$\begingroup\$ please delete this now that this has been posted. Thanks! :) \$\endgroup\$ – Giuseppe Oct 15 '18 at 17:33
1
\$\begingroup\$

Idolize Me! - JS idol simulation KotH

Introduction

There are quite a lot of ACG titles featuring idols in Japan. Inspired by different kinds of such games, I decided to make up my idol simulation game.

What is "Idolize Me!™"?

Idolize Me!™ (tentative) is based on an idol training facility featuring a monthly tournament, in which all idols compete for fame. Every idol has the following 4 kinds of attributes (or abilities):

  • Eloquence (How well you speak)
  • Singing (How well you sing)
  • Dance (How well you dance)
  • Performance (How well you act)

Also, every idol has the corresponding improvisation level (affects on-stage performance) and specialized skills. There are training courses to upgrade these abilities and skills, and idols can also "learn" from rivals during monthly tournaments to gain abilities and improvisation.

The tournament is a Swiss-system tournament, idols gain and lose fame during 1-on-1 performance battles, and gain fame according to their overall tournament results. Each battle consists of 3 rounds, selected from the 4 types of performances with different focusing attributes:

  • Stand-up comedy battle (Eloquence)
  • Duet battle (Singing)
  • Dance battle (Dance)
  • Drama battle (Performance)

Each idol can choose to ban one type he/she does not want to participate, and can choose to specify one type he/she want to participate. Other rounds will be selected randomly, and after 3 rounds, the idol who wins more rounds wins the battle. It is possible to end up with a draw, but this is very rare.

Every one starts with the same amount of fame. After 3 years of training and competitions, the most famous idol will become the Super Idol!

Algorithmic Explanation

  • Each idol starts with 2500 units of fame, 10000 units of ability to be allotted to the 4 attributes by yourself, and 20 units of improvisation and 10 units of skill per attribute.
  • The main loop consists of the following components, and will be run for 36 rounds (=3 years):
    • Training (4 rounds per round): Each idol will be given 100 units of ability and 5 units of improvisation. You can allot however you wish, but beware that improvisation caps at 50 units per attribute. After allotment you can learn some skills or to strengthen your abilities at the cost of losing some improvisation. Every unit of improvisation can be converted to 5 units of ability or 0.2 units of skill. Beware that skill also caps at 50 units per attribute.
    • Tournament: After 4 rounds of training there will be the tournament. The tournament will be a Swiss-system tournament, and consist of \$\lceil log_2(n+1) \rceil\$ rounds, where \$n\$ is the number of idols. Each round will be run in the following manner:
      1. Group the idols into a group of 2 according to their running rankings.
      2. For each group, each idol chooses one attribute from the 4 attributes, and discloses its corresponding ability.
      3. Then, being told the attributes and abilities, each idol decides one attribute to ban. Giving up the chance to ban is allowed.
      4. Next, being told the choice of ban, each idols decides one round to battle. They can still choose the banned choice, but the choice will be replaced by random rounds.
      5. Fill the remaining rounds with random rounds not being banned until there are 3 rounds.
      6. In each round, each idol can choose whether to use skill of the attribute of the round. There is only one chance of using skills per idol per a 3-round battle. Then the final score of each idol will be calculated with the following formula:

$$ score=\sum_{attr}{\Biggl\lfloor ability_{attr}\times multiplier_{type,attr}\times\left[0.7+r\times \left(0.3+\frac{improvisation_{attr}}{100}\right)\right]\times\left(1+\frac{skill_{attr}}{100}\right)\Biggr\rfloor} $$

Where \$ability_{attr}\$ is your ability, \$improvisation_{attr}\$ is your improvisation, \$skill_{attr}\$ is your skill, all of the attribute \$attr\$, and \$r\$ is a random number in the range\$[0, 1)\$, with a slightly larger probability near \$1\$. The value of \$multiplier_{type,attr}\$ is in the table below:

      type   | Stand-up comedy     Duet Battle  Dance Battle  Drama Battle
attr         | Battle (Eloquence)  (Singing)    (Dance)       (Performance)
-------------+-------------------------------------------------------------
Eloquence    | 1.5                 0.8          0.5           1.2
Singing      | 0.8                 1.5          1.2           0.5
Dance        | 0.5                 1.2          1.5           0.8
Performance  | 1.2                 0.5          0.8           1.5   
  • (contd)
    • (contd)
      1. The idol with higher score wins the round, and idol who wins more rounds wins the battle.
      2. Winner of the battle will be award 2 points, loser 0 points, and in the case of a draw, 1 point each.
      3. Winner gets extra 10 units of ability and 1 unit of improvisation. For each losing round, the defeated idol gets 20 units of ability and 2 unit of improvisation, and for each draw round, each idol gets 30 units of ability and 3 unit of improvisation, to be allotted at the same time (Beware again that improvisation caps at 50 units per attribute.) -- This is the core of so-called "learning from rivals".
      4. The delta fame is calculated as \$\lfloor10\times diff\times\frac{fame_{loser}}{fame_{winner}}\rfloor\$, where \$diff\$ is the difference of winning rounds in the battle. Winner gets this amount and loser loses this amount of fame.
      5. If the number of idols is odd, the idol who ranked the last will be consider a 0-battle win automatically, so fame, ability and improvisation are not affected.
      6. Sort the idols according to the following order, with the one at the top having the highest priority, all in descending order:
        1. Tournament points (TP)
        2. Number of battles won
        3. Battle difference (BD) (Number of rounds won - Number of rounds lost)
        4. Number of rounds won (BF)
        5. Score difference (PD) (Total score got - Total score lost)
        6. Total score got (PF)
        7. Drawing lots
    • After all rounds, fame will be awarded by the following formula:

$$ increase_{fame_{idol}}=\Biggl\lfloor\left[\left(\frac{n - rank + 1}{n}\right)^{1.5}\times 80+20\right]\times\frac{fame_{average}}{fame_{idol}}\Biggr\rfloor $$

Where \$n\$ is the number of idols.

Submission requirements:

Your bot must be a JS function with a name, prefably a human name (because the idol theme), distinct from other bots, that accepts an integer argument id (you must not change this argument name) and returns an object with 2 fields and 8 functions. The 2 fields are id and name (please don't change the id, line in the template). The 8 function are as follows:

  1. allot(type, amount): Allotment of amount units of type.

    • Arguments:
      • type: one of "ability" or "improvisation", the type to be allotted
      • amount: an integer, the amount to be allotted
    • Return values:
      • An object with 4 numbers named E, S, D and P, denoting your decision of the allotment of the 4 attributes. The 4 numbers must sum up to amount, otherwise your decision will be voided.
  2. review(ranking, battles): Your bot can review the battle results and adjust your plans.

    • Arguments:
      • ranking: an array of objects of the following entries, in ascending order of the bots' ranking, the running ranking during the tournament:
        • id: an integer, the ID of the bot
        • W: an integer, battle wins
        • D: an integer, battle draws
        • L: an integer, battle losses
        • BF: an integer, rounds won
        • BA: an integer, rounds lost
        • BD: an integer, BF - BA
        • PF: an integer, total score won by the bot
        • PA: an integer, total score won by opponent
        • PD: an integer, PF - PA
        • pts: an integer, tournament points
      • battles: an array of objects of the following entries, the details of all battles:
        • aID: an integer, the ID of idol A
        • aWin: an integer, rounds idol A won
        • aPtTotal: an integer, total score idol A got
        • bID: an integer, the ID of idol B. -1 stands for no opponent
        • bWin: an integer, rounds idol B won
        • bPtTotal: an integer, total score idol B got
        • result: an array of the following entries, the details of the sub-rounds of the battle:
          • attribute: one of "E", "S", "D" or "P", the attribute of the round
          • aTotal: an integer, the score of idol A
          • bTotal: an integer, the score of idol B
    • Return values:
      • None.
  3. learn(): Your bot can learn one type of skill at the cost of the improvisation of that attribute.

    • Arguments:
      • None.
    • Return values:
      • null, or an object of the following entries, the decision:
        • attribute: one of "E", "S", "D" or "P", the skill you want to learn
        • unit: a positive number, the amount you want to learn. You cannot learn more than your improvisation of that attribute allows.
  4. convert(): Your bot can strengthen one type of ability at the cost of the improvisation of that attribute.

    • Arguments:
      • None.
    • Return values:
      • null, or an object of the following entries, the decision:
        • attribute: one of "E", "S", "D" or "P", the ability you want to strengthen
        • unit: a positive number, the amount you want to strengthen. You cannot strengthen more than your improvisation of that attribute allows.
  5. disclose(rival): Disclose your attribute during battle.

    • Arguments:
      • rival: an integer, rival's ID
    • Return values:
      • one of "E", "S", "D" or "P", the attribute you want to disclose
  6. forbid(rival, attribute, value): Bans an attribute during battle.

    • Arguments:
      • rival: an integer, rival's ID
      • attribute: one of "E", "S", "D" or "P", the attribute rival discloses
      • value: an integer, the ability of that attribute rival discloses
    • Return values:
      • one of "E", "S", "D" or "P", the attribute you want to ban
  7. choose(attribute, value, forbidden): Chooses an attribute during battle.

    • Arguments:
      • attribute: one of "E", "S", "D" or "P", the attribute rival discloses
      • value: an integer, the ability of that attribute rival discloses
      • forbidden: one of "E", "S", "D" or "P", the attribute rival bans
    • Return values:
      • one of "E", "S", "D" or "P", the round you want to choose
  8. skill(attribute): Decides whether to use skill.

    • Arguments:
      • attribute: one of "E", "S", "D" or "P", the attribute of the round
    • Return values:
      • true or false, the decision whether to use skill of the attribute of the round.

enter image description here

Here is a template to use:

function YourIdolBot(id) {
    // Your local storage
    
    return {
        id, // Don't change this line
        name: "", // Your bot's name
        allot(type, amount) {
            // Your logic
            
            // Your return value
            return {
                E: 0,
                S: 0,
                D: 0,
                P: 0
            };
        },
        review(ranking, battles) {
            // Your logic
            
        },
        learn() {
            // Your logic
            
            // Your return value
            return {
                attribute: "",
                unit: 0
            };
        },
        convert() {
            // Your logic
            
            // Your return value
            return {
                attribute: "",
                unit: 0
            };
        },
        disclose(rival) {
            // Your logic
            
            // Your return value
            return "";
        },
        forbid(rival, attribute, value) {
            // Your logic
            
            // Your return value
            return "";
        },
        choose(attribute, value, forbidden) {
            // Your logic
            
            // Your return value
            return "";
        },
        skill(attribute) {
            // Your logic
            
            // Your return value
            return false;
        }
    }
}

Your submissions must not:

  • Corrupt the simulation;
  • Return values beyond requirements;
  • Call IdolizeMeAPI.query() with other bot's ID (see below);
  • Affect other bots' code;
  • Fetch external sources;
  • Define and use new global variables;
  • Has expletive inside the code (Beware of idols' image)

Violations will render the bot invalid and thus be disqualified and excluded from the simulation.

API

Idolize Me! provides an API that lets your idol bot query the current stats of its own. By calling IdolizeMeAPI.query(id) with your bot's ID. YOU MUST NOT CALL IdolizeMeAPI.query() WITH OTHER BOT'S ID. THIS WILL LEAD TO DISQUALIFICATION. This method returns an object with the following entries, which is the details of your bot:

  • id: an integer, your bot's id
  • name: a string, your bot's name
  • ability: an object with 4 numbers named E, S, D and P, your bot's ability of each attribute
  • improvisation: an object with 4 numbers named E, S, D and P, your bot's improvisation of each attribute
  • skill: an object with 4 numbers named E, S, D and P, your bot's skill of each attribute
  • fame: a number, your bot's fame

Test Area

Here is a snippet that allows test on the bots:

function log(msg) {
  $("#log").html($("#log").html() + msg + "\n\n");
}

function cls() {
  $("#log").html("");
}

function startIdolizeMeAPI(bots, seed, loopRounds, logBattles) {
	const ALLOT_LIMIT = {
		ability: Infinity,
		improvisation: 50,
		skill: 50
	};
	const MULTIPLIER = {
		E: {E: 1.5, S: 0.8, D: 0.5, P: 1.2},
		S: {E: 0.8, S: 1.5, D: 1.2, P: 0.5},
		D: {E: 0.5, S: 1.2, D: 1.5, P: 0.8},
		P: {E: 1.2, S: 0.5, D: 0.8, P: 1.5}
	};

	function checkAllot(idol, type, amount, add) {
		var values = idol.idol.allot(type, amount);
		var total = 0;
		for (var i of "ESDP")
			total += values[i];
		if (Math.abs(total - amount) < 1e-10) {
			if (add) {
				for (var i of "ESDP") {
					idol[type][i] += values[i];
					if (idol[type][i] > ALLOT_LIMIT[type])
						idol[type][i] = ALLOT_LIMIT[type];
				}
			}
			else {
				for (var i of "ESDP") {
					if (values[i] > ALLOT_LIMIT[type])
						values[i] = ALLOT_LIMIT[type];
				}
				return values;
			}
		}
		else if (!add)
			return {E: 0, S: 0, D: 0, P: 0};
	}
	var Random = (function(randomSeed) {
		function next() {
			return Math.random();
		}
		function nextInt(n) {
			return next() * n |0;
		}
		return {
			next,
			nextInt,
			pick: a => a[nextInt(a.length)],
			shuffle: function(a) {
				for (var l = a.length; l > 1;) {
					var o = nextInt(l--);
					[a[l], a[o]] = [a[o], a[l]];
				}
				return a;
			}
		};
	})(seed);

	var idols = bots.map(x => ({
		id: x.id,
		name: x.name,
		idol: x,
		ability: checkAllot({idol: x}, "ability", 10000, false),
		improvisation: {E: 20, S: 20, D: 20, P: 20},
		skill: {E: 10, S: 10, D: 10, P: 10},
		fame: 2500
	}));
	var numIdols = bots.length;

	function calcTotal(attr, idol, skill) {
		var total = 0;
		for (var i of "ESDP")
			total += idol.ability[i] * MULTIPLIER[attr][i] * (70 + Math.pow(Random.next(), 0.8) * (30 + idol.improvisation[i]) + skill * idol.skill[i]) / 100 |0;
		return total;
	}

	function battle(a, b) {
		var aDis = a.idol.disclose(b.id), bDis = b.idol.disclose(a.id), aSkill = false, bSkill = false, aWin = 0, bWin = 0, aAllot = 0, bAllot = 0;
		var aForbid = a.idol.forbid(b.id, bDis, b.ability[bDis]), bForbid = b.idol.forbid(a.id, aDis, a.ability[aDis]);
		
		var rounds = [Random.pick("ESDP"), a.idol.choose(bDis, b.ability[bDis], bForbid), b.idol.choose(aDis, a.ability[aDis], aForbid)].filter(x => x != aForbid && x != bForbid);
		while (rounds.length < 3) {
			var round = Random.pick("ESDP");
			if (round != aForbid && round != bForbid)
				rounds.push(round);
		}
		Random.shuffle(rounds);
		var result = rounds.map(function (x) {
			var aUseSkill = a.idol.skill(x), bUseSkill = b.idol.skill(x);
			var aTotal = calcTotal(x, a, !aSkill && aUseSkill), bTotal = calcTotal(x, b, !bSkill && bUseSkill);
			aSkill |= aUseSkill;
			bSkill |= bUseSkill;
			if (aTotal > bTotal) {
				aWin++;
				bAllot += 20 * aTotal / bTotal |0;
			}
			else if (bTotal > aTotal) {
				bWin++;
				aAllot += 20 * bTotal / aTotal |0;
			}
			else {
				aAllot += 30;
				bAllot += 30;
			}
			return {
				attribute: x, 
				aTotal, 
				bTotal
			};
		});
		if (aWin > bWin) {
			aAllot += 10;
			var deltaFame = 10 * Math.abs(aWin - bWin) * b.fame / a.fame |0;
			a.fame += deltaFame;
			b.fame -= deltaFame;
		}
		else if (bWin > aWin) {
			bAllot += 10;
			var deltaFame = 10 * Math.abs(aWin - bWin) * a.fame / b.fame |0;
			a.fame -= deltaFame;
			b.fame += deltaFame;
		}

		if (aAllot > 0) {
			checkAllot(b, "ability", aAllot, true);
			if (aAllot >= 10)
				checkAllot(b, "improvisation", aAllot / 10 |0, true);
		}
		if (bAllot > 0) {
			checkAllot(b, "ability", bAllot, true);
			if (bAllot >= 10)
				checkAllot(b, "improvisation", bAllot / 10 |0, true);
		}
		var aPtTotal = 0, bPtTotal = 0;
		for (var i of result) {
			aPtTotal += i.aTotal;
			bPtTotal += i.bTotal;
		}

		return {
			aID: a.id,
			bID: b.id,
			result, 
			aWin, 
			bWin,
			aPtTotal, 
			bPtTotal
		};
	}

	var totalBattleResult = {};
	idols.map(x => totalBattleResult[x.id] = {
		W: 0,
		D: 0,
		L: 0,
		BF: 0,
		BA: 0,
		BD: 0,
		PF: 0,
		PA: 0,
		PD: 0,
		pts: 0,
		rankings: []
	});

	function swissBattle() {
		var idolRanking = idols.map(x => ({
			idol: x,
			W: 0,
			D: 0,
			L: 0,
			BF: 0,
			BA: 0,
			BD: 0,
			PF: 0,
			PA: 0,
			PD: 0,
			pts: 0
		}));
		function sortRanking() {
			for (var idol of idolRanking)
				idol.lots = Random.next();
			idolRanking.sort((a, b) => b.pts - a.pts || b.W - a.W || b.BD - a.BD || b.BF - a.BF || b.PD - a.PD || b.PF - a.PF || b.lots - a.lots);
		}
		sortRanking();

		for (var i = numIdols; i > 0; i >>= 1) {
			var battles = [];
			for (var j = 0; j < numIdols - 1; j += 2) {
				var a = idolRanking[j], b = idolRanking[j + 1]
				var result = battle(a.idol, b.idol);
				battles.push(result);
				if (result.aWin > result.bWin) {
					a.W++;
					b.L++;
				}
				else if (result.bWin > result.aWin) {
					a.L++;
					b.W++;
				}
				else {
					a.D++;
					b.D++;
				}
				a.pts = a.W * 2 + a.D;
				b.pts = b.W * 2 + b.D;
				a.BF += result.aWin;
				a.BA += result.bWin;
				b.BF += result.bWin;
				b.BA += result.aWin;
				a.PF += result.aPtTotal;
				a.PA += result.bPtTotal;
				b.PF += result.bPtTotal;
				b.PA += result.aPtTotal;
				a.BD = a.BF - a.BA;
				b.BD = b.BF - b.BA;
				a.PD = a.PF - a.PA;
				b.PD = b.PF - b.PA;
			}
			if (numIdols % 2 == 1) {
				idolRanking[numIdols - 1].W++;
				idolRanking[numIdols - 1].pts += 2;
				battles.push({
					aID: idolRanking[numIdols - 1].idol.id, 
					bID: -1, 
					result: [], 
					aWin: 0, 
					bWin: 0
				});
			}
			sortRanking();
			var publicRanking = idolRanking.map(function(x) {
				var l = {};
				for (var i in x) {
					if (i == "idol")
						l.id = x.idol.id;
					else if (i != "lots")
						l[i] = x[i];
				}
				return l;
			});
			for (var idol of idols)
				idol.idol.review(publicRanking, battles);
			if (logBattles) {
        log("Battle Results:\n" + JSON.stringify(battles, null, 2));
        log("Ranking:\n" + JSON.stringify(publicRanking, null, 2));
      }
		}
		var averageFame = idols.reduce((a, b) => a + b.fame, 0) / numIdols;
		for (var i = 0; i < numIdols; i++)
			idolRanking[i].idol.fame += (Math.pow((numIdols - i) / numIdols, 1.5) * 80 + 20) * averageFame / idolRanking[i].idol.fame |0; 

		var r = 0;
		for (var p of idolRanking) {
			for (var q in p) {
				if (q != "idol" && q != "lots")
					totalBattleResult[p.idol.id][q] += p[q];
			}
			totalBattleResult[p.idol.id].rankings.push(++r);
		}
	}

	function showResult(round) {
		var temp = [...idols].sort((a, b) => b.fame - a.fame);
		var a =        " ID                 | Name                        | Fame  | Win  | Lose | Draw | BF   | BA   | BD   | Pts For   | Pts Aga.  | Pts Diff. | TP   | Tournament Rankings                                                                                         \n"
		      +        "--------------------+-----------------------------+-------+------+------+------+------+------+------+-----------+-----------+-----------+------+-" + "-".repeat(Math.max(20, loopRounds * 3));
		for (var i of temp) {
			a += `\n ${("" + i.id).padStart(18)} | ${i.name.padEnd(27) } | ` + ("" + i.fame).padStart(5);
			for (var j of ["W", "L", "D", "BF", "BA", "BD", "PF", "PA", "PD", "pts"])
				a += " | " + ("" + totalBattleResult[i.id][j]).padStart(j[0] == "P" ? 9 : 4);
			a += " | " + totalBattleResult[i.id].rankings.map(x => ("" + x).padStart(2)).join` `;
		}
		log("Round " + round + " results:\n" + a);
    return a;
	}

	function loop() {
		for (var i = 0; i < loopRounds; i++) {
			for (var j = 0; j < 4; j++) {
				for (var k of idols) {
					checkAllot(k, "ability", 100, true);
					checkAllot(k, "improvisation", 5, true);
					var convertPlan = k.idol.convert();
					if (convertPlan) {
						var {attribute, unit} = convertPlan;
						var converted = Math.min(unit, k.improvisation[attribute] * 5);
						k.improvisation[attribute] -= converted / 5;
						k.ability[attribute] += converted;
					}
					var learnPlan = k.idol.learn();
					if (learnPlan) {
						var {attribute, unit} = learnPlan;
						var learnt = Math.min(unit, k.improvisation[attribute] / 5);
						k.improvisation[attribute] -= learnt * 5;
						k.skill[attribute] += learnt;
						if (k.skill[attribute] > ALLOT_LIMIT.skill)
							k.skill[attribute] = ALLOT_LIMIT.skill;
					}
				}
			}
			swissBattle();
			showResult(i + 1);
		}
	}

	return {
		loop,
		query(id) {
			var idol = idols.filter(x => x.id == id)[0];
			if (idol) {
				var publicIdol = {};
				for (var i in idol) {
					if (i != "idol")
						publicIdol[i] = idol[i];
				}
				return publicIdol;
			}
			else 
				return null;
		},
		showResult
	};
}

var players = 0;
function addPlayer() {
  var id = Math.random() * Math.pow(2, 53);
  $("#players").append(`
    <div class="bot" id="bot-${id}">
      <textarea cols="100" rows="10"></textarea> ${++players > 2 ? `<input type="button" value="Delete this bot" onclick="deletePlayer(${id})">` : ""}
    </div>
  `);
}

function deletePlayer(id) {
  $("#bot-" + id).remove();
  players--;
}
/*
$("#run").on("click", function(e) {
  e.preventDefault();
  e.stopPropagation();
  e.target.checkValidity();
  console.log("test");
});*/
var IdolizeMeAPI;
$(document).on("submit", "form", function(e) {
  e.preventDefault();
  cls();
  var bots = [], submissions = {};
  $(".bot").each(function(s) {
    var code = $(this).find("textarea").val();
    var botFunctionName = /function (\w+) *\(id\) *{/.exec(code);
    if (botFunctionName) {
      botFunctionName = botFunctionName[1];
      code = code.replace(/function (\w+) *\(id\) *{/, `submissions["$1"] = function(id) {`);
      eval(code);
      bots.push(new submissions[botFunctionName](+$(this).attr("id").slice(4)));
    }
  });
  IdolizeMeAPI = startIdolizeMeAPI(bots, "whatever it is we don't use seeds at all", +$("#rounds").val(), $("#logbattle").prop("checked"));
  IdolizeMeAPI.loop();
  return false;
});

addPlayer();
addPlayer();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  Rounds: <input id="rounds" pattern="\d+" value="6" required/><br>
  Log battle results: <input type="checkbox" id="logbattle"><br>
  Player Bots:
  <div id="players">
  </div>
  <input type="button" value="Add a bot" onclick="addPlayer()"><br>
  <input id="run" type="submit" value="Run simulation">
</form>
<pre id="log">
</pre>

You may want to open the snippet in a new page.

Demo Bots

2 simple demo bots will be in the same contest with submitted bots, of exactly the same implementation, but with different names: One called Yamada Ransu (山田 乱數) and one called Sato Midare (佐藤 乱).

function TheTwoSimpleDemoBotsYouAreCompetingWith(id) {
    return {
        id: id,
        name: "???",
        allot(type, amount) {        
            return {
                E: amount/4,
                S: amount/4,
                D: amount/4,
                P: amount/4
            };
        },
        review(ranking, battles) {},
        learn() {
            return {
                attribute: "ESDP"[Math.random() * 4 |0],
                unit: Math.random() * 5 |0
            };
        },
        convert() {
            return null;
        },
        disclose(rival) {
            return "ESDP"[Math.random() * 4 |0];
        },
        forbid(rival, attribute, value) {
            return "ESDP"[Math.random() * 4 |0];
        },
        choose(attribute, value, forbidden) {
            return "ESDP"[Math.random() * 4 |0];
        },
        skill(attribute) {
            return Math.random() < 0.5;
        }
    }
}

Winning Criteria

Submission is open for 2 weeks from the posting day, until 15:00 GMT on the end day, or until there are more than 20 submissions, whichever is later. You are welcomed to submit multiple entries during the period. After the the submission period ends, the 36 rounds will be simulated within 3 days. After the 36 rounds, the bot with the highest fame wins, and the corresponding submission will be accepted as "best answer". The simulation result will be posted.

| |
\$\endgroup\$
  • \$\begingroup\$ Will we have access to the controller? \$\endgroup\$ – Alion Oct 9 '18 at 9:06
  • \$\begingroup\$ @Alion If by "controller" you mean the function which runs the rounds, sorry but no, except the IdolizeMeAPI.query(id). However the data you'll need will be passed into your functions (e.g. the rankings and battle history). Please make good use of the review() function. You can't define global storage, but you can define local storage inside the function. I hope this may help you. \$\endgroup\$ – Shieru Asakoto Oct 9 '18 at 9:25
  • \$\begingroup\$ As a footnote: all 8 functions are called actively by the controller during the loop. Maybe I should add a diagram to explain this. \$\endgroup\$ – Shieru Asakoto Oct 9 '18 at 9:34
  • \$\begingroup\$ Sorry, that wasn't what I meant. I was wondering if a runner for the game will be available for testing our bots - to debug, improve, compare against others, etc. Sort of how one was provided in this or that challenge. \$\endgroup\$ – Alion Oct 9 '18 at 9:34
  • \$\begingroup\$ @Alion Oh I see. I didn't consider that when I was writing the KotH, but I think I'd like to make a test snippet simulating several rounds for a smaller group of players, if the post isn't too long yet. \$\endgroup\$ – Shieru Asakoto Oct 9 '18 at 10:13
  • \$\begingroup\$ BTW may I ask how long can my post be? I checked the markdown and it's now @14.4kB \$\endgroup\$ – Shieru Asakoto Oct 9 '18 at 10:15
  • \$\begingroup\$ IIRC, the post length is capped at 65536 characters. If you plan on providing a controller for players to use to test their bots, I would highly recommend Dave's JS KotH Framework. It takes a while to get used to, but it does quite a lot of work for you, without restricting your challenge too much. \$\endgroup\$ – Alion Oct 9 '18 at 11:12
  • \$\begingroup\$ @Alion Oh thanks, I'll go and have a look. And it seems there is still quite a bunch of vacancy, so I'll add the test drive into the sandbox first. \$\endgroup\$ – Shieru Asakoto Oct 9 '18 at 11:20
  • \$\begingroup\$ @Alion I've added the snippet to the post. \$\endgroup\$ – Shieru Asakoto Oct 10 '18 at 2:50
1
\$\begingroup\$

Posted: Is this number secretly Fibonacci?

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

Toy floating point coprocessor: ceil

Summary: implement the ceiling function for 16-bit IEEE 754 floating point numbers in logic gates, using as few gates as you can.

16-bit IEEE 754 floating point

For a more detailed description, see Wikipedia:Half-precision floating-point format.

The 16 bits are divided into three chunks: sign (1 bit), exponent (5 bits), mantissa (10 bits).

  • The sign is 0 for positive numbers and 1 for negative numbers.
  • The exponent is biased: interpret as an unsigned 5-bit number and subtract 15 to get the true exponent. Special cases are described below.
  • The mantissa is an unsigned 10-bit number with an implicit leading 11th bit which depends on the exponent.

If the exponent is 00000 (corresponding to -15), the number is subnormal. The implicit leading bit of the mantissa is 0, but there's a bonus factor of two, so the interpreted value is \$(-1)^{\textrm{sign}}\; 2^{-14}\; 0.\textrm{mantissa}\$, or (expanding the \$0.\textrm{mantissa}\$ binary notation) \$(-1)^{\textrm{sign}}\; 2^{-24}\; \textrm{mantissa}\$.

If the exponent is 11111 (corresponding to 16), the number is either infinite (if the mantissa is 0000000000) or a NaN.

For all other exponents, the implicit leading bit of the mantissa is 1, so the interpreted value is \$(-1)^{\textrm{sign}}\; 2^{\textrm{exponent}-15}\; 1.\textrm{mantissa}\$, expanded to \$(-1)^{\textrm{sign}}\; 2^{\textrm{exponent}-25}\; (2^{10} + \textrm{mantissa})\$

Ceiling function

The ceiling function maps real numbers to integers, rounding up. So if the input value is an integer, the output value is unchanged; if the input value is not an integer, the output value is the smallest integer greater than the input value.

Examples:

$$\begin{array}{c|c} x & \textrm{ceil}(x) \\ \hline -1 & -1 \\ -0.5 & 0 \\ 0 & 0 \\ 0.00001 & 1 \\ 1 & 1 \\ 1.8 & 2 \\ \end{array}$$

Corner cases

Given an infinity, the output must be the same infinity.

Given a NaN, the output must be a NaN, but it can be any NaN.

IEEE 754 floating point systems have signed zeroes. Given a zero, the output must be the same zero.

Gates and scoring

You must implement a logic gate with 16 inputs and 16 outputs. You may use any two-input logic gates and you may mix different types of logic gates. We idealise the gates: don't worry about things like fan-out limitations or propagation delays. The score is the number of gates, and the fewer the better. If you choose to explain your design by giving code which uses bitwise operation on integers, be sure to document clearly how many bits are being processed by each operation.

Test cases

TODO, but will cover both infinities, both signed zeroes, positive and negative subnormals, positive and negative integer values, positive and negative non-integer values, and a NaN.

| |
\$\endgroup\$
  • \$\begingroup\$ I assume 2-to-1 gate, or 2-to-any? \$\endgroup\$ – l4m2 Nov 16 '18 at 15:21
1
\$\begingroup\$

Minimize your standard deviation


The standard deviation of a collection of numbers is calculated in the following manner:

  1. Find the arithmetic mean of the collection.
  2. Find the difference of each item from the mean.
  3. Square each difference and sum them.
  4. Divide by the number of items in the collection minus 1.
  5. Take the square root.

Or, expressed mathematically:

$$ s = \sqrt{ \frac{ \sum^N_{i=1} (x_i - \bar x)^2 }{N - 1} }, $$

where \$N\$ is the number of items, \$x_i\$ is the \$i\$th item, and \$\bar x\$ is the arithmetic mean.

Challenge

Your challenge is to write a program or function in your language of choice that, given an array of bytes, calculates the standard deviation of the array. The catch: the standard deviation of the bytes in your code will be added to your score.

Rules

  • Input may be in any reasonable format (e.g. numbers separated by newlines or commas, an actual array or buffer, etc.)
  • You may assume that the items in the input are all integers \$0 \le n < 256\$.
  • You may assume that there are at least two integers in the input.
  • The output or return value must be the standard deviation of the array as calculated above, accurate to at least 2 decimal places (i.e. \$ \pm 0.005 \$)

Test cases

(test cases to come)

Scoring

The score of your code is its length in bytes, plus the standard deviation of its bytes (i.e. \$N + s\$). The code with the lowest score in each language wins.

(If you somehow find a language with a 1-byte built-in that fulfills the challenge, your score will just be 1. In the impossible case of a 0-byte built-in, your score will be \$0 + \frac{0}{-1} = 0\$.)

Sandbox questions

  • Is this too similar to the vanilla standard deviation challenge?
  • For non-golfing languages that primarily use ASCII, the standard deviation will likely be much lower than the byte count, leading to golfing the code being significantly more important than reducing \$s\$. How could this best be combated? \$\sqrt N + s\$? \$N + s^2\$? (where \$N\$ is the length of the code) Obviously I wouldn't want to just use \$s\$, as you could just append one byte (e.g. ; in many languages) over and over to lower it arbitrarily.
| |
\$\endgroup\$
  • \$\begingroup\$ Standard deviation was my enemy in algebra. \$\endgroup\$ – MilkyWay90 Nov 11 '18 at 1:19
  • \$\begingroup\$ It seems difficult to create a scoring that penalizes appending redundant bytes and that the shortest solution wouldn't always win. \$\endgroup\$ – lirtosiast Nov 20 '18 at 1:48
1
\$\begingroup\$

Calculate your Icy Score

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

Classify arity of verbs inside trains in J

Related: Clearly parenthesize APL trains

Background

J is an APL-family language. While it inherits the basic train syntax from APL (take a look at the linked challenge above), J is more versatile with the introduction of [:, & and @ among many others. But the problem is, the more features a tacit expression has, the harder it is to read and understand what it does. Even worse, most of the built-in verbs have both monadic and dyadic usage, and some of them have two completely different meanings! So let's build a helper to classify the arity of verbs.

Notations

  • # is a monadic verb.
  • + is a dyadic verb.
  • [ is a special symbol called "cap" which can appear at specific positions inside a train.
  • @ and & are conjunctions, which take two verbs on both sides and form a single verb.
  • x and y are left and right arguments to a given train, respectively. If x is missing, the train is called monadically (with one argument y); otherwise, dyadically (with both arguments).

Basics

  • In a train of verbs, the last 3 verbs are recursively grouped.
  • Conjunctions bind from left to right.

Rules

Monadic
(# + #) y   =>  (# y) + (# y)
(+ #) y     =>  y + (# y)
([ # #) y   =>  # (# y)
(+ # + #) y =>  (+ (# + #)) y
(# + # + # + #) y => (# + (# + (# + #))) y
(# + [ # # + #) y => (# + ([ # (# + #))) y

Dyadic
x (+ + +) y   =>  (x + y) + (x + y)
x (+ #) y     =>  x + (# y)
x ([ # +) y   =>  # (x + y)
x (+ # + #) y =>  x (+ (# + #)) y    <= the 3-group is run monadically
x (+ + + + + + +) y => x (+ + (+ + (+ + +))) y
x (+ + [ # + + +) y => x (+ + ([ # (+ + +))) y

Conjunction &
(#&#) y   => # (# y)
x (+&#) y => (# x) + (# y)

Conjunction @
(#@#) y   => # (# y)
x (#@+) y => # (x + y)

How to determine arity of each verb

   (?  (? ?&?@?    ?) ?) y
=> (# d(? ?&?@?    ?) #) y    monadic 3-train: # + #
=> (#  (+ d?&?@?   +) #) y    dyadic 3-train:  + + +
=> (#  (+ d(?&?)@? +) #) y    conjunction binds from left; arity is determined from right
=> (#  (+ m(?&?)@+ +) #) y    dyadic `@`:  #@+
=> (#  (+  (#&#)@+ +) #) y    monadic `&`: #&#

Challenge

Given an expression that represents the structure of a J train, determine the arity of every verb in the expression.

Input & output

TBD

Test cases

TBD

Scoring & winning criterion

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

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

How fast can I Flood-It?

There's a one-player game called Flood-It, in which the player must flood the whole board with one color within a certain number of moves.

  • The board is a two-dimensional square grid of size n.
  • At the start, each square in the grid is one of k colors.
  • A move consists of selecting a color, and doing a 4-connected flood fill with that color starting in the top left corner.

For example, selecting Red on this size-3 board with 4 colors:

GGE
RGB
RDE

causes the board to change to this—now the two already-red squares are connected to the top left:

RRE
RRB
RDE

After the further moves DBE, all squares are colored Emerald, and the game has been won in an optimal 4 moves.

Challenge

Given two integers n and k, output the number of moves required to win the game of Flood-It with those parameters, in the worst case over all possible arrangements of colors.

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

mAkE a StRiNg EpIc

Now that the meme is mostly dead, we can have this challenge. It's pretty simple: take a string (either as stdin or a parameter to a function), and change the case to alternate capital and lowercase letters, starting with lowercase. Examples:

"Hello, World!" -> "hElLo, WoRlD!"
"PPCG" -> "pPcG"
"Ok now this is epic" -> "oK nOw ThIs Is EpIc"
"" -> ""

Rules:

  • Can take input as a parameter to a function or as stdin

  • Punctuation marks are left alone

  • Must not take any input other than the input string

  • It's , so the shortest code in bytes wins!

Sandbox questions:

  • The obvious one: is it a duplicate? I don't think so, but I don't know for sure.

  • Is it too trivial for some languages?

Thanks everyone!

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

Find the best K year period to have invested

A stock index is a way of measuring the overall performance of the stock prices of a group of companies (which may change from time to time). An example from the US is called the S&P 500. An index fund is an investment that grows at the same rate as the underlying index.

Here are the annual returns for a hypothetical S&P 500 stock index fund for each calendar year from 1928 to 2017, expressed as a multiplier. So in 1927 you might say "the index went up by 37.88%" which I've represented here by 1.3788.

1.3788, 0.8809, 0.7152, 0.5293, 0.8485, 1.4659, 0.9406, 1.4137, 1.2792, 0.6141,  1.2521, 0.9455, 0.8471, 0.8214, 1.1243,  1.1945, 1.138, 1.3072, 0.8813, 1,  0.9935, 1.1026, 1.2178, 1.1646, 1.1178,  0.9338, 1.4502, 1.264, 1.0262, 0.8569,  1.3806, 1.0848, 0.9703, 1.2313, 0.8819,  1.1889, 1.1297, 1.0906, 0.8691, 1.2009,  1.0766, 0.8864, 1.001, 1.1079, 1.1563,  0.8263, 0.7028, 1.3155, 1.1915, 0.885,  1.0106, 1.1231, 1.2577, 0.9027, 1.1476,  1.1727, 1.014, 1.2633, 1.1462, 1.0203,  1.124, 1.2725, 0.9344, 1.2631, 1.0446,  1.0706, 0.9846, 1.3411, 1.2026, 1.3101,  1.2667, 1.1953, 0.8986, 0.8696, 0.7663,  1.2638, 1.0899, 1.03, 1.1362, 1.0353,  0.6151, 1.2345, 1.1278, 1, 1.1341,  1.296, 1.1139, 0.9927, 1.0954, 1.1942

Challenge

Given as inputs this array of annual returns and an array of size \$1\le K \le 89\$ non-negative real numbers (the amounts to invest in each year), write a program or function that outputs what would have been the best \$K\$ year period to have invested each amount in the array in this hypothetical index fund, assuming the returns from each year are reinvested at the beginning of the next year.

Rules

  1. This is , so the fewest bytes in each language wins.

  2. If you don't like the way I've represented the array of annual returns, you can change them to any other array of 89 numbers that you prefer. (SANDBOX NOTE: This is intended to allow for some input flexibility (people might prefer to use the given array minus 1, or the cumulative returns) but not too much (so that people don't cheat and change the array to some multi-dimensional monster that nearly solves the whole problem).)

  3. You can output the best \$K\$ year period in any consistent manner (e.g. 0-indexed or 1-indexed, the first or the last period to have invested, the entire range of years, the actual years themselvs, etc.) but you need to say what your output represents if it isn't obvious.

  4. In case of a tie, output any or all correct answers.

Example

Suppose the array consisted of \$[ 10000, 20000, 30000]\$.

If you had invested these amounts in 1928, 1929, and 1930 (the 1-indices 1, 2, and 3) you would have ended up with \$42743.10\$.

But if you had invested those amounts in 2015, 2016, and 2017 (the 1-indices 87, 88, and 89) you would have ended up with \$66722.66\$.

It turns out the best three year period to have invested these amounts would have been 1995, 1996, and 1997 (1-indices 68, 69, and 70).

Test cases

1-indexed, first year of optimal period

[ 1, 2, 3 ]                          ->  68
[ 1 ]                                ->   6
*any array of length 89*             ->   1
[ 1, 1 ]                             ->  27
[ 1, 2 ]                             ->   8
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]  ->  63
[ 1, 2, 3, 4, 5, 4, 3, 2, 1 ]        ->  64
* 1 repeated 20 times *              ->  53
| |
\$\endgroup\$
  • \$\begingroup\$ I remember there being a challenge about when to invest before. Have you checked for duplicates? \$\endgroup\$ – lirtosiast Nov 20 '18 at 22:52
  • \$\begingroup\$ @lirtosiast I did check. I did not see any non-King of the Hill investment questions. That being said it's not always easy to find dupes. \$\endgroup\$ – ngm Nov 21 '18 at 1:44
1
\$\begingroup\$

Exploring generalzations of Cheryl's birthday problem

In this challenge we will generalize the Cheryl's birthday problem to arbitrary finite subsets of pairs of integers

Challenge

Cheryl gives Albert and Bernard a finite collection of pairs of integers S. Cheryl chooses an element (x, y) from S and tells x to Albert and y to Bernard. Assume everyone speaks truthfully.

Albert says: "I don't know what x and y are, but I know that Bernard doesn't know". More precisely: Albert does not know what y is, but using only the information given in the first paragraph, the elements of S and the value x, Albert is certain that Bernard doesn't know what x is.

Bernard says: "At first I didn't know what x and y were ,but now I do". - That is, before Albert said anything, Bernard doesn't know what x and y are, but after Albert spoke, Bernard knew.

Albert says: "Now I also know what x and y are".

Your task is to write a computer program that takes as input the set S, and outputs a list of all possible values for the (x, y) that Cheryl chose, in any order. (therefore you must use a programming language that can handle lists of pairs of numbers). If there is no solution or that conversation is impossible, output an empty list.

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

Example Input and Output

Input:

[(1,1),(2,2),(3,3),(4,4)]

Output:

[]

There is no solution to this problem because the conversation is impossible. Knowing either x or y will result in knowing the other one. Therefore, it's impossible for Bernard to know y but not x.

Input:

[(5,15),(5,16),(5,19),(6,17),(6,18),(7,14),(7,16),(8,14),(8,15),(8,17)]

Output:

[(7,16)]

This is the original problem.

Input:

[(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)]

Output:

[]

The conversation is impossible as Bernard cannot deduce x from y and the fact that Albert knows that Bernard does not know x.

Input:

[(1,0),(1,1),(1,2),(2,1),(2,2),(2,3),(3,2),(3,3),(3,4),(4,1),(4,3)]

Output:

[(2,2)]

If x was 1, then Albert cannot be sure that Bernard doesn't know x, because if y was 0, then Bernard would know that x was 1. Similarly for if x was 3. Therefore x was 2 or 4.

After Albert spoke, Bernard can eliminate x=1 and x=3, and then he can deduce what x was. If Bernard had y = 1 or 3, then Bernard could not distinguish between (2,1) and (4,1), or between (2,3) and (4,3). As Bernard knew, we must have y = 2. After Bernard spoke, Albert knew that y=2, and x=2.

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

Sequences that sum to n

Barely too late for Fibonacci Day :(

Given a positive integer n, your challenge is to output a sequence of 1 and 2 that adds to n. For example, for input 8, acceptable outputs include 11111111, 2222, and 121211.

It's not quite that simple, though. Given n, the number of possible outputs is the nth term of the Fibonacci sequence (starting with F(0) = F(1) = 1); you must return each with equal probability. This means that the following Python 3 is invalid:

def foo(n):
  out = ""    # String output is by no means required.
  while n:
    a = min(random.randint(1, 2), n)
    out += str(a)
    n -= a
  return out

While this will return each allowed result with nonzero probability and everything else with zero probability, the distribution is not uniform. In particular, foo(3) is twice as likely to be 21 is it is to be 111 or 12.

Standard IO and loophole rules apply. Output is flexible, but you must use 1 and 2, not 0 and 1 or some other weird thing.

This is , so the shortest code (in bytes) wins! Happy golfing!

| |
\$\endgroup\$
  • \$\begingroup\$ Do you think there will be a choice of strategy for many languages? I have a hard time coming up with a language where creating each string and choosing one uniformly isn't the best approach. This isn't a huge problem, and otherwise I think this is a fine challenge. \$\endgroup\$ – FryAmTheEggman Nov 25 '18 at 18:46
  • \$\begingroup\$ @FryAmTheEggman I could see someone perhaps using a function of the remaining value to tweak probabilities, something that would choose 2 only a third of the time for n = 3. Not sure, though—I haven't yet given this a try :/ \$\endgroup\$ – Khuldraeseth na'Barya Nov 25 '18 at 23:56
1
\$\begingroup\$

Given element count, minimum GCD and maximum LCM, compute the number of distinct integer arrays

Inspired by a question in Turkish National Computing Olympiad.

You are given 3 numbers: n, x and y.

Compute the number of distinct integer arrays with n elements whose GCD is greater than x and lcm is less than y.

Test cases: (n,x,y -> result)

1,1,10 -> 10 // there are 10 1 element arrays with gcd>=1 and lcm<=10, which are [1],[2],[3],...[10].

I can not add much test cases because I could not solve the question (well, I got 10 points by writing a python script which outputs a c++ file which hardcodes the first subtask, but I think the does not count.), please help with test cases.

Rules: i/o is flexible. Standard loopholes are not allowed.

This is code-golf, so the shortest answer in every language wins.

| |
\$\endgroup\$
  • \$\begingroup\$ Should the specification be "greater than or equal"/"less than or equal"? \$\endgroup\$ – user202729 Nov 24 '18 at 17:26
  • \$\begingroup\$ But you still can make small test cases, right... \$\endgroup\$ – user202729 Nov 24 '18 at 17:29
  • \$\begingroup\$ greater than/equal and less than or equal. also, I can only generate cases with n=1 in reasonable time. i may try to write a n=2 or n=3 test-case too if that helps \$\endgroup\$ – Windmill Cookies Nov 24 '18 at 17:31
  • \$\begingroup\$ "Standard loopholes are allowed" - please rethink that. \$\endgroup\$ – Shaggy Nov 25 '18 at 14:22
  • \$\begingroup\$ ok, now they are not allowed \$\endgroup\$ – Windmill Cookies Nov 25 '18 at 15:07
  • \$\begingroup\$ Be advised that the shortest solution in many languages will be "filter all N element subsets of numbers less than Y by whether they meet the criteria" which will take Y^N time to run. \$\endgroup\$ – lirtosiast Nov 25 '18 at 19:46
1
\$\begingroup\$

Fully modular C program

Modularity means that instead of writing one big long procedure, we break up our logic into small, composable functions. We all know that modularity is a good thing. But why settle for a good thing when you can have the best thing? Let's make our programs fully modular. This means that each function must contain zero assignment statements and no more than one function call and one binary operator (if it contains more than that, that's a sign your function is getting too long and you need to break it up).

Example 1:

int multiply_add(int a, int b, int c) { return a * b + c; }

might become

int multiply(int a, int b) { return a * b; }
int multiply_add(int a, int b, int c) { return multiply(a, b) + c; }

Example 2:

int foo(int x)
    int y = x + 3;
    bar(y, y);
}

might become

int bar2(int y) { return bar(y, y); }
int foo(int x) { return bar2(x + 3); }

Sandbox note: I am working on the fully modular C verifier question before this one.

| |
\$\endgroup\$
  • \$\begingroup\$ Is there a name pool or we need to check if a name is used? \$\endgroup\$ – l4m2 Nov 23 '18 at 15:04
  • \$\begingroup\$ Sounds interesting. Is the input a less than fully modular program, and the required output any valid fully modular program that has identical behaviour? Also wondering if the score will be length of the solution code, or length of the output, or something else \$\endgroup\$ – trichoplax Nov 23 '18 at 20:59
  • \$\begingroup\$ @l4m2 You'll be responsible for generating new identifiers that don't clash. Though I'm thinking about making it actually a program where only the behavior of main() needs to be preserved. \$\endgroup\$ – feersum Nov 23 '18 at 23:44
  • \$\begingroup\$ @trichoplax Yes to the first question, and standard code golf with length of the modularizer. \$\endgroup\$ – feersum Nov 23 '18 at 23:45
  • \$\begingroup\$ Sounds interesting, theres going to be a lot of breaking sum_stuff(return a + b + c + d) down into sum_stuff(sum_pair(sum_pair(a, b), sum_pair(c, d))) like rearrangement. \$\endgroup\$ – alan2here Nov 24 '18 at 22:05
  • \$\begingroup\$ Needs more examples. I suggest Fibonacci and integer power. \$\endgroup\$ – Peter Taylor Nov 26 '18 at 17:10
  • \$\begingroup\$ I suggest you name the challenge "Monadic C" \$\endgroup\$ – Vaelus Nov 27 '18 at 0:08
1
\$\begingroup\$

Solve Newcomb's paradox

Newcomb's paradox is a problem that has been stumping philosopher's for decades. And, as anyone who uses reddit knows, a problem posed by a philosopher is best solved by a software engineer.

In Newcomb's paradox, you are presented with two boxes, A and B. You can either take B or take A and B. A contains $1000. B contains $0 if a predictor predicts you will take box A and $1000000 if it predicts you will not take box A.

For this challenge, the predictor will be an execution function or command, such as python's exec function, or the bash eval command. Therefore, you must use a programming language that has one.

Therefore, to solve Newcomb's paradox your program must:

  • Output the string "B" when run with an eval function.
  • Output the string "A+B" when run normally.

This will allow you to win $10001000.

This is , so the shortest answer wins!

| |
\$\endgroup\$
  • \$\begingroup\$ Adequately defining "an eval function" is notoriously difficult, and that lack of clarity is compounded here by the implicit quantifier in "run with an eval function". Does this mean that there must exist a function which takes a string and executes it as code, and the answer should state what this function is; or does it mean that the function must detect when run by any function which takes a string and evaluates it as code? \$\endgroup\$ – Peter Taylor Nov 29 '18 at 12:46
  • \$\begingroup\$ @PeterTaylor I was thinking of a specific eval function that the answer specifies. It should be built into the language though (since its trivial if you make your own). You are right though about the definition of an eval function being vague. Do you think the challenge is salvageable with some modifications? \$\endgroup\$ – PyRulez Dec 1 '18 at 22:41
  • \$\begingroup\$ I'm not sure. It would be good to get some input from a LISPer (where AIUI eval is trivial). I think that .Net is probably an example of a situation where "built in" is imprecise (I'm not sure that there is exactly an eval method for strings in the standard library, but I think it's fairly straightforward to write one with System.CodeDom.Compiler, and third party libraries exist which do that). Then there's a question as to whether an eval method must accept a string, or whether detecting the difference between f() and f.invoke([]) (JavaScript, I think) or similar counts. \$\endgroup\$ – Peter Taylor Dec 1 '18 at 23:08
  • \$\begingroup\$ @PeterTaylor I am thinking of eliminating the eval function aspect entirely. Any ideas as to two different conditions under which to run a program that would be in the spirit of Newcomb's paradox (in a cheeky way)? \$\endgroup\$ – PyRulez Dec 1 '18 at 23:14
1
\$\begingroup\$

Output The End Poem. Outputting as array, or with only one \n or three \n to separate sentences, etc. are fine. Shortest code win.

Upvote to prefer: You can take an input containing all letters in lowercase or uppercase

Downvote to prefer: You can take an input containing all letters in their original cases(upper/lower)

P.S. The two old choices are too similar

Comment if duplicate, fell the length is bad, etc

| |
\$\endgroup\$
  • \$\begingroup\$ I don't see why this isn't a duplicate of codegolf.stackexchange.com/q/6043 \$\endgroup\$ – Peter Taylor Nov 22 '18 at 16:13
  • \$\begingroup\$ @PeterTaylor You're given the text as input and only need to insert the spaces. \$\endgroup\$ – user202729 Nov 22 '18 at 16:13
  • \$\begingroup\$ Optionally, (in the second option) you're allowed to encode (part of) the data into the case of the input. \$\endgroup\$ – user202729 Nov 22 '18 at 16:14
  • 4
    \$\begingroup\$ "Upvote/Downvote" to prefer isn't actually the right approach for the sandbox, votes indicate likelihood of the challenge being well-received on main. \$\endgroup\$ – Erik the Outgolfer Nov 22 '18 at 16:29
  • \$\begingroup\$ @EriktheOutgolfer Any other suggestion? \$\endgroup\$ – user202729 Nov 22 '18 at 16:32
  • \$\begingroup\$ @EriktheOutgolfer The "right" way it was doesn't work fine, usually too inconsistant to main; also occupying the vote for other usage make like/dislike go to comment for clearer reason \$\endgroup\$ – l4m2 Nov 23 '18 at 0:18
  • \$\begingroup\$ I vote all letters in their original cases. Inserting spaces and punctuation is enough of a challenge in itself. \$\endgroup\$ – lirtosiast Nov 29 '18 at 8:27
  • \$\begingroup\$ @lirtosiast Uppercase only be first letter, I and PLAYERNAME I see. Taking input in original cases mean possible ability to learn from cases how to insert spaces \$\endgroup\$ – l4m2 Nov 29 '18 at 12:44
1
\$\begingroup\$

Sums of Bessel Polynomial Coefficients [WIP]

This is https://oeis.org/A001515.

Interesting alternate characterizations include:

Equivalently, number of sequences of n unlabeled items such that each item occurs just once or twice (cf. A105749). - David Applegate, Dec 08 2008

Numerator of (n+1)-th convergent to 1+tanh(1). - Benoit Cloitre, Dec 20 2002

a(n) is also the numerator of the continued fraction sequence beginning with 2 followed by 3 and the remaining odd numbers: [2,3,5,7,9,11,13,...]. - Gil Broussard, Oct 07 2009

Also, number of scenarios in the Gift Exchange Game when a gift can be stolen at most once.

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

Compressed RSA keys

Silly cops-and-robbers idea.

As computers get more powerful, RSA keys have grown longer and longer to maintain security. This makes it difficult to:

  • hand out your encryption key on business cards
  • recite it over the telephone
  • quickly scribble it down when you meet someone at a bar
  • etc.

But we are all programmers (maybe even that someone that you met in a bar), so let's come up with RSA keys that can be generated by very short programs. We should be careful, though, that these keys remain resistant to cracking.

Cops

Write a short program (or function) that outputs an RSA key. For this challenge, an RSA key is just any positive integer less than \$2^{1024}\$ that has a non-trivial divisor.

Your program must:

  • take no input
  • output the same number every time it's run
  • finish quickly (a few seconds at most)

Post your program, its language, and what it outputs.

Also, prove that you can use it as an RSA key. Provide a SHA-256 hash of a string that lists all the prime factors of your key.

Robbers

Crack the RSA keys! If an RSA key is the integer \$n\$; find any integer \$1<d<n\$ that divides \$n\$.

Scoring

A key is vulnerable to cracking for 7 days after it's posted. After that, it is considered safe and eligible for scoring.

Cops: The shortest uncracked program wins.

Robbers: Most cracks wins.

(Related: compress RSA public keys on crypto.SE)

| |
\$\endgroup\$
  • \$\begingroup\$ What's to prevent me from feeding random numbers into a 700-bit hash function until I get a semiprime, which I factor on huge amounts of cloud computing time and then post? No one can crack it unless they have a bigger computer. \$\endgroup\$ – lirtosiast Dec 7 '18 at 9:18
  • \$\begingroup\$ Nothing, I guess. It might cost you a lot of money to do that, though. \$\endgroup\$ – japh Dec 7 '18 at 9:37
  • \$\begingroup\$ Also for what it's worth, not all semiprimes have large factors, so you'd have to factor many of them until you get a strong one. The robber only has to factor the one you posted. \$\endgroup\$ – japh Dec 7 '18 at 9:39
1
\$\begingroup\$

Not a challenge, but not certain of the wording so trying it out here:


Tips for golfing in JSLint


What general tips do you have for golfing in JavaScript restricted to satisfying JSLint with default options? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to JSLint (e.g. "remove comments" is not an answer).

| |
\$\endgroup\$
1
41 42
43
44 45
98

You must log in to answer this question.

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