571
\$\begingroup\$

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

Sandbox FAQ

Posting

To post to the sandbox, scroll to the bottom of this page 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, though you can optionally add a title at the top. 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, and replace the post here with a link to the challenge and delete the sandbox post.

Discussion

The purpose of the sandbox is to give and receive feedback on posts. If you want to, feel free to give feedback to any posts you see here. Important things to comment about can include:

  • Parts of the challenge you found unclear
  • Comments addressing specific points mentioned in the proposal
  • Problems that could make the challenge uninteresting or unfit for the site

You don't need any qualifications to review sandbox posts. The target audience of most of these challenges is code golfers like you, so anything you find unclear will probably be unclear to others.

If you think one of your posts requires more feedback, but it's been ignored, you can ask for feedback in The Nineteenth Byte. It's not only allowed, but highly recommended! Be patient and try not to nag people though, you might have to ask multiple times.

It is recommended to leave your posts in the sandbox for at least several days, and until it receives upvotes and any feedback has been addressed.

Other

Search the sandbox / Browse your pending proposals

The sandbox works best if you sort posts by active.

To add an inline tag to a proposal, use shortcut link syntax with a prefix: [tag:king-of-the-hill]. To search for posts with a certain tag, include the name in quotes: "king-of-the-hill".

\$\endgroup\$
1
  • \$\begingroup\$ What if I posted on the sandbox a long time ago and get no response? \$\endgroup\$
    – None1
    May 15 at 14:05

4687 Answers 4687

1
134 135
136
137 138
157
0
\$\begingroup\$

Deterministic oozes

Task

Output the next generation of the input.

These conversions happen if there is food . or : next to them:

"o" → "O"
"O" → "8"
"8" → "oo"

^ These are called oozes.

Rules for eating

  • The food should disappear if it gets eaten.
  • If there is a single food ., with oozes on both sides, the left one eats it.
  • If there is a double food :, with oozes on both sides, both eat one.
  • If there is a double food : with only one ooz beside it, the ooz eats the entire food and advances 2 generations.
  • A food with no oozes on the either side, stays the same.
  • Spaces between oozes should be preserved.

Scoring

Number of bytes, shortest code wins!

Test Cases

"o. o" → "O o"
"oooo.8" → "oooO8"
"8:8" → "oooo"
":8" → "Oo"
"8:" → "oO"
"o:o.o" → "O8o"
"ooo" → "ooo"
"o.o.o" → "OOo"
"o:8:o" → "OoOO"
" .  o o 8." → " .  o o oo"

Meta:

  • Tags?
  • Clear?
\$\endgroup\$
8
  • \$\begingroup\$ There's a lot still missing here. It seems like most the challenge has to be guessed from a handful of test cases. \$\endgroup\$
    – Wheat Wizard Mod
    Jan 24, 2022 at 14:54
  • \$\begingroup\$ @WheatWizard ok ill add more test cases tomorrow. \$\endgroup\$
    – zoomlogo
    Jan 24, 2022 at 14:55
  • \$\begingroup\$ No that is the opposite of what I am saying. You need to specify the challenge not just add more test cases. \$\endgroup\$
    – Wheat Wizard Mod
    Jan 24, 2022 at 14:56
  • \$\begingroup\$ The challenge should be completely understandable with the test cases removed. \$\endgroup\$
    – Wheat Wizard Mod
    Jan 24, 2022 at 14:56
  • \$\begingroup\$ @WheatWizard ok i see, will do that tomorrow \$\endgroup\$
    – zoomlogo
    Jan 24, 2022 at 14:59
  • \$\begingroup\$ Having multiple generations happen at a time seems contrary to "output the next generation" \$\endgroup\$ Jan 25, 2022 at 20:41
  • 1
    \$\begingroup\$ Suggested testcase: "o:o.o" \$\endgroup\$
    – tsh
    Jan 26, 2022 at 5:43
  • \$\begingroup\$ Will the input have leading/trailing spaces? How to handle them? Also, the o:8:o test-case is not covered by your specs (or anything like .o.). \$\endgroup\$
    – pajonk
    Mar 23, 2022 at 12:27
0
\$\begingroup\$

Given a current page number (p), pages to show (s), and max pages (m), create the classic pagination, marking the current page as active (*) and using ...'s for any outside the range.

For example:

p = 1, s = 5, m = 15

Should output:

1* 2 3 4 5 ... 15

Or

p = 7, s = 5, m = 15 

should output

1 ... 5 6 7* 8 9 ... 15

and

p = 2, s = 5, m = 4 

Should output

1 2* 3 4

It can be assumed that pages to show (s) is always odd, so the active page is often in the middle of the set of numbers.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Welcome and thanks for using the Sandbox! I feel this challenge may be a duplicate of codegolf.stackexchange.com/q/243701/55372 \$\endgroup\$
    – pajonk
    Mar 24, 2022 at 14:09
  • \$\begingroup\$ Oh yes... it has some confusion over what the correct output should be for the edge cases as well. Ah well! \$\endgroup\$
    – Djave
    Mar 24, 2022 at 15:58
0
\$\begingroup\$

Integer divisors of a decimal number

The input is a decimal number larger than zero, given in decimal form. You can use any unambiguous printable character(s) to enclose or separate a possible repeating part in the input, such as 0._3_, 0.(3) or 0.(3 for \${0.\overline{3}}\$ to represent an exact third.

The output is the pair of the smallest integer dividend and divisor that give the exact value represented by the input. The output format doesn't matter, 1/3, 1 3 and (1,0b011) are all valid for an input value representing an exact third.
Examples:

Input:  1
Output: 1 / 1

Input:  0.(3)
Output: 1 / 3

Input:  1.234
Output: 617 / 500

Input:  1.1(3)
Output: 17 / 15

Input:  3.454(54)
Output: 38 / 11

Input:  3.14159
Output: 314159 / 100000

Input:  3.(142857)
Output: 22 / 7

Input:  12.345(6789)
Output: 10287037 / 833250

Input:  9.(9)
Output: 10 / 1

Reference implementation in Python 3

It does \$12.345\overline{6789} = \frac{12345}{1000} + \frac{6789}{9999*1000} = \frac{123444444}{9999000} = \frac{10287037}{833250}\$

def greatest_common_denominator(a, b):
	while b:
		a, b = b, a%b
	return a

def r(inp):
	x, _, repeating = inp.rstrip(')').partition('(')
	x = x.split('.')
	dividend = int(''.join(x))
	divisor = 10**(len(x[1]) if len(x) == 2 else 0)
	if repeating:
		repeating_nines = 10**len(repeating) - 1;
		dividend = int(repeating) + dividend*repeating_nines
		divisor *= repeating_nines
	d = greatest_common_denominator(dividend, divisor)
	return dividend//d, divisor//d

Try it online!

  • This is , so the lowest byte count wins!
\$\endgroup\$
2
  • \$\begingroup\$ I recommend the title "Integers divided to obtain a decimal number" \$\endgroup\$
    – ophact
    Apr 2, 2022 at 6:23
  • \$\begingroup\$ Unfortunately this is a duplicate of Convert a repeated decimal to a fraction. \$\endgroup\$
    – pxeger
    Apr 2, 2022 at 11:02
0
\$\begingroup\$

Generate a clue for an arbitrary MultiSoft URL

Here is the program that will verify your output (transcripted into javascript, and modified for my own ease)

Sheet of paper containing a small program in python. Javascript version below

let s = '';
const a = 'your output here'
for(const i = 1; i < a.length; i+=1){
  if (a[i] % 2 === a[i-1] % 2) {
    s = `${s}${Math.max(a[i], a[i-1])}`;
  }
}
if ('your program input' === `www.multisoft.se/${s}`){
   return true;
}

Where you're given 'your program input', which will look like www.multisoft.se/9109382911 and you need to generate an a ('your output here') that generates that URL.

Test cases:

// TODO make test cases

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

Wordle but Harder

If you've been online in the last year, you probably know the rules of Wordle. I was implementing a (very bad) Wordle algorithm, when I thought of another game:

Task

One 5-letter word from wordle's answer list is randomly selected. Your task is to guess the word.

Each failed guess gives you one piece of information - the amount of letters in your guess that are also in the word.

For example, if the answer was hello and you guessed loser, you would get 2, because 2 of your letters are in the answer. Conversely, if the answer was loser and you guessed hello, you would get 3, as 3 of the letters in your guess are in the answer.

Scoring

Each guess must be made within 10 seconds. Separate categories for lowest average and lowest worst-case scenario.

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

Draw my shower curtain

I got a shower curtain and it looks cool, so today you get to draw it.

But how do we do this?

I'm glad you asked.

Part 1: the shape

circles

The image shows a blue, red, and green circle. This is a subsection of the pattern. The actual pattern of circles can be imagined by placing a circle of radius 4 at (8i, 8j) and (8k + 4, 8l + 4) for all (i, j, k, l) in the integers.

sectors

This image shows the three circles from the first image, but with two sectors coloured in. These sectors are defined as the area in at least two circles, or the area in a circle centred at (8i, 8j) and in on at (8k + 4, 8l + 4), for (i, j, k, l) in the integers. I would provide a closed form for this, but I don't know one.

more circles and sectors

The above image shows more circles and sectors. In this image, you can begin to see how the pattern fills an infinite grid. For this challenge, you will take two integers as input and output a grid with that many of the pattern on each side. For example, this (specifically the intersections between two circles because I was too lazy):

(3, 1) pattern

is the output for (3, 1), and this (again I didn't mark the sectors because there were too many of them):

(2, 2) pattern

is the output for (2, 2).

As well as this, your image must be at least 800 pixels on each side.

Part 2: the color

shades of grey: #0B, #22, #37, #4E, #66, #7F, #98, #B3, #CF and #EB

The above shows some examples of shades of grey. All of them have the values of their red, blue and green component set to be the same. For your program, you must use all 256 possible shades of grey, with a non-zero chance of each occurring. You may not use any other colours than these.

Since this is , shortest answer wins.

NBs

You may assume both numbers are greater than 0.

You can take width or height first (examples take width first), but say which in your answer.

You are allowed to be +/- 0.1% off.

Meta

Is this well specified?

Anything to change?

\$\endgroup\$
2
  • \$\begingroup\$ 1. What is to be "coloured" with the 256 shades of gray? The circles, the areas, both? What if there are less circles/areas than 256? Nevertheless, I suggest just letting the golfers to choose two distinct colours for background and objects; or three for background, circles and areas. 2. Could you please add at least one test-case that will fully comply with the specs? \$\endgroup\$
    – pajonk
    Apr 7, 2022 at 13:25
  • \$\begingroup\$ Ok - on hiatus now, but will fix this later. \$\endgroup\$ Apr 9, 2022 at 15:13
0
\$\begingroup\$

Construct integers from 1, -, and (

In this answer, I used only 1, -, and ( to construct any integer (although ( is technically unnecessary) in TI-Basic. Your task is to make a program or function that takes an integer (or a different convenient format to represent it) as input and output the shortest possible string made from 1, -, and ( that will evaluate to the integer in TI-Basic. If there are multiple possible outputs, then choose the one with the least amount of (. If there are still multiple left, then any one of them is valid as an output.

Some things to note:

  • - is the subtraction symbol, not the negative sign.
  • TI-Basic automatically closes all ( at the end.
  • ( can also be used for implied multiplication (e.g. 11(11 is 121)

Rules

  • It should work for numbers from -128 to 127.
  • Standard loopholes apply.
  • This is , so the shortest code in bytes in each language wins.

Test cases

Input    | Possible Output

-128     | 1-(11-1-1-(1-11(11
-124     | 1-111-11-1-1-1
-44      | 11(1-1-1-1-1-1
-5       | 1-1-1-1-1-1-1
-3       | 1-1-1-1-1
-1       | 1-1-1
0        | 1-1
1        | 1
2        | 1-(1-1-1
3        | 1-(1-1-1-1
5        | 11-1-1-1-1-1-1
8        | 11-1-1-1
10       | 11-1
11       | 11
14       | 11-(1-1-1-1-1
18       | 11-1-1-1-(1-11
19       | 11-1-1-(1-11
21       | 11-(1-11
22       | 11-(1-11-1
33       | 11-11(1-1-1-1
43       | 11-(1-11-11-11
78       | 111-11-11-11
123      | 111-(1-11-1-1
127      | 11-1-1-1-1-(1-11(11

If your output is different from the one listed, then it should have the same length and the same amount of (.

Meta

  • Is anything unclear?
  • Are any of the outputs for the test cases incorrect?
\$\endgroup\$
6
  • \$\begingroup\$ Are there any inputs for which there is more than one ( in the output? If that's false, maybe specifying that at most one ( is permissible would make the rules simpler? Or that's just me? \$\endgroup\$
    – pajonk
    Apr 3, 2022 at 18:30
  • \$\begingroup\$ @pajonk 127 becomes 11-1-1-1-1-(1-11(11 and -128 becomes 1-(11-1-1-(1-11(11. I suppose I will add those as test cases. \$\endgroup\$
    – Yousername
    Apr 3, 2022 at 19:08
  • \$\begingroup\$ Ok, thanks for clarification. \$\endgroup\$
    – pajonk
    Apr 3, 2022 at 19:47
  • \$\begingroup\$ But 127 can be done with 1-(-111-11-1-1-1-1? Any nonnegative integer can be made with 1-(1-1-1-1-1-1-1-1-1-1-1-1-... with at most one (, and any negative integer can be made with -1-1-1-1-1-1-... with no (s. \$\endgroup\$
    – pxeger
    Apr 5, 2022 at 19:31
  • \$\begingroup\$ @pxeger As stated in the beginning, - is the subtraction symbol, not the negative sign (TI-Basic makes a distinction between the two). The main priority is to make the shortest possible string with 1, -, and ( to represent the number, then to have it have the least amount of ( possible. \$\endgroup\$
    – Yousername
    Apr 5, 2022 at 21:45
  • \$\begingroup\$ Maybe you should either move "shortest" to the "Rules" section, or move "If there are multiple possible outputs, then choose the one with the least amount of (. " tie-breaker into the header. Currently, it placed in different places and may be confuse. \$\endgroup\$
    – tsh
    Apr 18, 2022 at 8:46
0
\$\begingroup\$

Make a PDF look scanned

META: This challenge still needs more work, including some examples - if you already have suggestions and hints feel free to post them, but due to the nature of popularity contests I definitely want to discuss it again when I added the missing part.

Do you know the situation where you have to print some document, scan it and send the scan back? Let's automate that! Your task is making a program that, given some input, makes it believably look like it was scanned.

A few people have done that before (links see 1 2 3) which inspired this challenge, but they all still look too uniform and pristine in my opinion.

Here some examples of the test file, a real scan and the output of (TODO: use one of these tools):

TODO: add examples of scan artifacts, compare real scan with examples.

Details

  • Validity Criterion: The input and output are raster images of any resolution (they should have the same resolution).
  • For simplicity you can assume that both the input and output are grayscale images.
  • You can assume that the input - no matter the resolution - has roughly the size of an A4 or Letter page.
  • You should run your program on the test image below, and include it in your submission using <img src="[image ]" width="400" alt="processed" /> (TODO: determine exact format), but you can also include other examples to illustrate the inner workings.
  • You are encouraged to explain how your program processes the image.

TODO: Add test image.

\$\endgroup\$
2
  • \$\begingroup\$ IMHO, It's going to be difficult to specify well, but sincerely: good luck. I think it might be worth adding some suggested requirements (see comment below your link 2). \$\endgroup\$
    – pajonk
    Apr 20, 2022 at 9:27
  • \$\begingroup\$ Thanks:) I intend to add some images that actually show examples of artifacts like the ones you mentioned (I'm planning to actually make some prints/scans). But only as suggestions, as in my experience for this kind of challenge compulsive requirements really must be measurable objectively to work well. And thanks for your input, I'll let you know if/when I update the draft! \$\endgroup\$
    – flawr
    Apr 20, 2022 at 10:05
0
\$\begingroup\$

Heapify a List into a Binary Max Heap

Given a list of integers, write the shortest program or function that will heapify the list into a binary max-heap, and return the heap as a list of integers.

Additional Resources

Additional Rules

Tags:

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

Multiples Game

Given an array of divisors A, loop n from 1 to infinity and do one of the following:

  • If n is divisible by an even number of divisors of A, print out n
  • If n is divisible by an odd number of divisor(s) of A, print out * (clap)

Examples

Input:

A = [3, 5]

Output:

1
2
*
4
*
*
7
8
*
*
11
*
13
14
15
16
17
*
19
...

Input:

A = [2, 3, 5]

Output:

1
*
*
*
*
6
7
*
*
10
11
12
13
*
15
*
17
18
19
...

Input:

A = [3, 6]

Output:

1
2
*
4
5
6
7
8
*
10
11
12
13
14
*
16
17
18
19
...

Rules

  • Fetching outer sources are forbidden
  • UTF-8 encoding
  • A newline count as 1 byte (UNIX newline)
  • The answer with the least bytes wins
\$\endgroup\$
0
\$\begingroup\$

Shift a string gradually

\$\endgroup\$
12
  • \$\begingroup\$ Surely the output for the first test case should be bdf. \$\endgroup\$
    – chunes
    Apr 21, 2022 at 22:02
  • \$\begingroup\$ @chunes fixed.. \$\endgroup\$ Apr 22, 2022 at 0:08
  • \$\begingroup\$ I suggest adding a test case that requires wrapping. \$\endgroup\$
    – chunes
    Apr 22, 2022 at 20:28
  • \$\begingroup\$ @chunes implemented \$\endgroup\$ Apr 22, 2022 at 20:30
  • \$\begingroup\$ Suggested test cases of length other than 3. How to treat empty string? \$\endgroup\$
    – pajonk
    Apr 23, 2022 at 15:17
  • \$\begingroup\$ @pajonk done, i hope i didn't write the wrong result \$\endgroup\$ Apr 23, 2022 at 15:24
  • \$\begingroup\$ Last test case output should be "bdfhjlm" right? \$\endgroup\$
    – ophact
    Apr 25, 2022 at 14:39
  • \$\begingroup\$ @ophact fixed it \$\endgroup\$ Apr 25, 2022 at 15:08
  • \$\begingroup\$ Wait actually it's bdfhjln \$\endgroup\$
    – ophact
    Apr 25, 2022 at 15:10
  • \$\begingroup\$ @ophact fixed it \$\endgroup\$ Apr 25, 2022 at 15:13
  • \$\begingroup\$ You should remove all but the title, which should be linked to the posted challenge. Then delete this post. \$\endgroup\$
    – Adám
    Apr 26, 2022 at 6:47
  • \$\begingroup\$ @Adám fixed it. \$\endgroup\$ Apr 26, 2022 at 13:03
0
\$\begingroup\$

Split given integer into a given number of integers, each within given bounds

Input variables:

(Names are just examples, they don't need to be named like this)

  • GrandTotal - integer to divide
  • SplitCount - number of output integers required
  • UpperLimit - highest valid value for any one output integer
  • LowerLimit - lowest valid value for any one output integer

There must be SplitCount values returned, each of which is a uniformly random integer between UpperLimit and LowerLimit (your language's RNG is fine), the sum of which is GrandTotal.

Also, the order of the output matters: 5,8,7 is not an equal set to 5,7,8. Both outputs must be equally likely if either is possible.
(This does mean that output where all three integers are the same is less likely output to one where all three are different: Given GrandTotal=6, SplitCount=3, UpperLimit=4, LowerLimit=1, a set including 1, 2 and 3 can appear in 6 different configurations, while a set of all 2s can only appear in one, making it 6 times as likely that one of the varied sets will appear, rather than the set of 3 2s.)

Assumptions:

Any input variables should work, assuming that the following is true

  1. UpperLimit * SplitCount >= GrandTotal
  2. LowerLimit * SplitCount <= GrandTotal
  3. all input variables are positive integers.

Sample in-out range

GrandTotal SplitCount UpperLimit LowerLimit Possible Output Range
11 2 10 2 10,1;9,2
8 3 11 2 2,3,3;3,2,3;3,3,2;2,2,4;2,4,2;4,2,2
13 2 8 4 8,5;7,6;6,7;5,8
16 2 8 4 8,8
16 2 10 4 10,6;9,7;8,8;7,9;6,10
16 4 10 4 4,4,4,4

\$\endgroup\$
13
  • \$\begingroup\$ I don't think I've ever seen a question that specifies language, but couldn't see anything in the help that said it shouldn't... \$\endgroup\$ Apr 28, 2022 at 4:14
  • \$\begingroup\$ Language-specific challenges are technically allowed, but make sure that this challenge utilizes some language-specific feature, and that it's not just arbitrarily restricting to this one language. I don't know enough about SQL to fully judge this challenge, so you will have to make your own judgement call on this. \$\endgroup\$
    – Aiden Chow
    Apr 28, 2022 at 4:28
  • \$\begingroup\$ @AidenChow Practically, it's SQL because I have a yucky version of this I'm using at the moment in a SQL environment, and I want to see just how un-yucky it can get, but it did seem like a reasonably valid code-golf idea based on my limited experience of this stack, so thought I'd give it a bash. Given that there are some limitations on the specific built-in functions you have in SQL that other languages don't share, opening up the languages to other ones would be less useful for me... \$\endgroup\$ Apr 28, 2022 at 4:48
  • \$\begingroup\$ @AidenChow also I'd be very interested to see if anyone has really simple/fast ways of adding other language-code in, like a shortcut CLR function (a concept I definitely need to become more familiar with...) \$\endgroup\$ Apr 28, 2022 at 4:51
  • \$\begingroup\$ Code golf isn't really the place to go to if you are looking for "un-yucky" code; code golfers will do any atrocity you can think of in order to shorten the length of their code, most times sacrificing readability and actually making "yuckier" code in most cases. Though if you are fine with that, then I don't see anything inherently wrong with this challenge. You could definitely add some test cases though. \$\endgroup\$
    – Aiden Chow
    Apr 28, 2022 at 4:54
  • 1
    \$\begingroup\$ Actually now that I'm looking at it, there are some things wrong with this post. First, you need to indicate what the winning criterion is, whether that be code-golf, code-challenge, or something else entirely; this is required for ALL code golf challenges. Second, as I stated in my comment above, you definitely should add some test cases, so that people attempting this challenge can easily test their code. Third, it is recommended that you add a short worked example for an example test case. Just a short explanation would suffice. \$\endgroup\$
    – Aiden Chow
    Apr 28, 2022 at 5:02
  • \$\begingroup\$ Oh wait sorry, I didn't read the challenge fully; it's random, so there are no set test cases. In that case, just include an example input and a possible output, and a short explanation. \$\endgroup\$
    – Aiden Chow
    Apr 28, 2022 at 5:12
  • \$\begingroup\$ @AidenChow better or worse? \$\endgroup\$ Apr 28, 2022 at 9:07
  • \$\begingroup\$ It's better, though I fear that with a scoring system with that many rules, there is bound to be some ambiguity that's going to arise when people actually start attempting the challenge and scoring their programs. I don't know enough about this particular language though, so I will leave it up to others to give a better judgement on this. My gut feeling is that there are just way too many rules for scoring; I haven't seen a scoring system in a challenge with quite as many rules as this before. \$\endgroup\$
    – Aiden Chow
    Apr 28, 2022 at 9:13
  • 1
    \$\begingroup\$ Also, it is pretty standard to include the tags you are going to apply to this challenge when you are going to post it to the main website. You can add a tag like so: [tag:(tag name)]. With a complex scoring system like your challenge, I think you may want to add the code-challenge or maybe the atomic-code-golf tag (I'm not too sure how applicable this tag is to your challenge, though; as I said, I'm not entirely familiar with SQL). \$\endgroup\$
    – Aiden Chow
    Apr 28, 2022 at 9:19
  • \$\begingroup\$ @AidenChow thanks, was wondering how to add that. \$\endgroup\$ Apr 28, 2022 at 9:21
  • \$\begingroup\$ Good as a language-agnostic solution? \$\endgroup\$ Apr 28, 2022 at 10:59
  • \$\begingroup\$ You may also like to add [tag:random]. Also, consider specifying what kind of randomness are you looking for (be it uniform, any other or leave it to the golfers). \$\endgroup\$
    – pajonk
    Apr 28, 2022 at 19:40
0
\$\begingroup\$

Convert JSON object of directories to list of paths

\$\endgroup\$
12
  • 1
    \$\begingroup\$ What's the scoring criterion? Does the shortest code win? If so, then please specify the code-golf tag. \$\endgroup\$
    – ophact
    Mar 15, 2022 at 14:02
  • \$\begingroup\$ May we expect the input to be non-empty? \$\endgroup\$
    – pajonk
    Mar 15, 2022 at 19:24
  • \$\begingroup\$ Can we take the input in other formats (I'm thinking in favour of languages without native JSON support)? E.g. as a ragged named list, list of nested tuples etc? \$\endgroup\$
    – pajonk
    Mar 15, 2022 at 19:28
  • 1
    \$\begingroup\$ JSON typically doesn't have order defined. And some standard doesn't allow duplicate keys while some others support duplicate keys. For example {"a":{"b":{}},"a":{"c":{}}} could be a valid JSON in some standard. \$\endgroup\$
    – tsh
    Mar 16, 2022 at 3:08
  • \$\begingroup\$ @pajonk Shouldn't JSON be string? And I believe most language should support string at least any languages that support ragged list. \$\endgroup\$
    – tsh
    Mar 16, 2022 at 3:09
  • \$\begingroup\$ @tsh, yeah, I was thinking about built-in JSON parsing to other structure. Some languages may have advantage from it, while other will be stuck to string-parsing. But that was just a suggestion for OP to decide. \$\endgroup\$
    – pajonk
    Mar 16, 2022 at 5:26
  • \$\begingroup\$ @pajonk The input is non-empty, in the sense that there will always be a JSON object, but it could be {}. In this case, the output must be empty or a newline. \$\endgroup\$
    – matteo_c
    Mar 16, 2022 at 8:56
  • \$\begingroup\$ @pajonk I was thinking to allow as input either a string, a dictionary, or a list of tuples, each tuple contains the name and the value (which is a list of tuples). What you think? I'm open to suggestions. \$\endgroup\$
    – matteo_c
    Mar 16, 2022 at 9:04
  • \$\begingroup\$ @tsh Since I would allow dictionary as a valid input format, and since the JSON object represents a directory structure, the input won't have duplicate keys. \$\endgroup\$
    – matteo_c
    Mar 16, 2022 at 9:06
  • \$\begingroup\$ I would allow the use of basic JSON parsing libraries in languages that don't have built in JSON support \$\endgroup\$
    – matteo_c
    Mar 16, 2022 at 9:08
  • 2
    \$\begingroup\$ @MatteoC. Yes, I think allowing reasonable equivalents to JSON seems fine. Also, with this relaxed rule I would not allow "basic JSON parsing libraries" as it may be ambiguous what to qualify as "basic". \$\endgroup\$
    – pajonk
    Mar 16, 2022 at 12:22
  • \$\begingroup\$ I strongly discourage too narrow output format (at least a list of directories should be acceptable IMO). \$\endgroup\$
    – pajonk
    Mar 19, 2022 at 20:58
0
\$\begingroup\$

Infinite Candle Sequence

\$\endgroup\$
6
  • \$\begingroup\$ I'm not sure if this is really two challenges (generate sequence, draw colours). Please let me know! \$\endgroup\$ Apr 28, 2022 at 3:52
  • \$\begingroup\$ This really does seem like two challenges. I recommend just requiring answers to output the number sequence, as it does make the challenge more accessible to languages that do not have any form of graphical output. That being said, if it is going to be a purely sequence challenge: Is floating point precision error allowed? Or does the whole decimal number have to be outputted? Or are we outputting as a list of pairs (numerator, denominator)? I also recommend including the first 100 terms or so of this sequence in the challenge body somewhere, as to remove any ambiguity. \$\endgroup\$
    – Aiden Chow
    Apr 28, 2022 at 3:59
  • \$\begingroup\$ If it's going to be graphical output: How should the colors be displayed (square, circle, any shape that you choose, etc.)? \$\endgroup\$
    – Aiden Chow
    Apr 28, 2022 at 4:02
  • \$\begingroup\$ If it's graphical output, you should provide hex codes or screenshots of the first few colors in the sequence. \$\endgroup\$
    – Aiden Chow
    Apr 28, 2022 at 8:22
  • \$\begingroup\$ Thanks for the feedback. I think I'll reduce this to just outputting the sequence. I'll add more info as well. \$\endgroup\$ Apr 28, 2022 at 22:06
  • 2
    \$\begingroup\$ I've edited this down to a stub now that it's been posted to save space \$\endgroup\$ May 4, 2022 at 23:12
0
\$\begingroup\$

Draw the Location's Flag

Take as input the latitude-longitude coordinates of a location on Earth, and return a flag that corresponds to that location. You may return any official flag that is at the level of a country or smaller. For example, if the location was 40.712775, -74.005973, you may return the flag of the USA, the New York state flag, or the flag of New York City, but you can't return the UN flag.

Rules

The outputted flag must be at least 50 pixels in its shortest direction (or be vector graphics/some other scalable image).

Internet data IS allowed in this challenge.

Areas not officially controlled by any country are undefined behavior. This includes Antarctica, Bir Tawil, and international waters.

Any flag returned must be an official flag that currently corresponds to that location. For example, you cannot return the flag of the British Empire for countries that used to be its territories.

In cases where control is disputed (including South Sudan, eastern Ukraine...) you may output any country that has a claim.

This is a code golf challenge, so shortest code wins.

Standard I/O rules apply. Examples would include a list/tuple of two numbers, a Location class, a vector, or Mathematica's GeoPosition.

All flags must be recognizable as the flag they are.

For flags with differing sides (like Paraguay), you may return only one face.

For non-rectangular flags, you may pad the other area with any color distinct from the primary color of the flag.

\$\endgroup\$
8
  • \$\begingroup\$ This is a bit hard tho... \$\endgroup\$ May 10, 2022 at 6:24
  • \$\begingroup\$ It's supposed to be quite difficult. I imagine some programming languages have builtins to fetch the flags of a country (mathematica in particular), which would make things easier, but other languages will still struggle. I have considered changing it to be a code challenge where your score is increased (a bad thing here) if you miss some, but you don't have to get every country right. \$\endgroup\$
    – Romanp
    May 10, 2022 at 13:22
  • \$\begingroup\$ I mean, it would be sort of unfair, right? To non-mathematica languages? \$\endgroup\$ May 10, 2022 at 13:25
  • \$\begingroup\$ Yes and no. It would likely have a far shorter solution (but some other languages might also have these builtins, so they might be shorter), but its solution isn't going to be short either. There isn't a quick way I know of to check if a point is in a country, it will just help with drawing the flags. \$\endgroup\$
    – Romanp
    May 10, 2022 at 13:31
  • \$\begingroup\$ I think I can do it in 37 bytes in Mathematica, but I'm not 100% sure it works all the time and it could potentially be shorter. My guess is other languages will need quite a bit more, but it still feels doable. \$\endgroup\$
    – Romanp
    May 10, 2022 at 13:54
  • \$\begingroup\$ Yeah, but I think Mathematica has way too big an advantage at that. \$\endgroup\$ May 10, 2022 at 13:55
  • \$\begingroup\$ It has a very large advantage for sure, but it's mostly a language-by-language competition. I've been wondering about methods to make it a little closer, but the goal isn't for Mathematica to compete against everything else, just like the goal isn't for Vyxal to compete against Python. I feel like on most challenges, if they are simple, a golflang wins, and if they are complicated, some Mathematica-esque language with a lot of builtins wins. This question is just more towards the complicated side compared to most code golf problems. \$\endgroup\$
    – Romanp
    May 10, 2022 at 14:03
  • \$\begingroup\$ this does actually seem to me to be a somewhat interesting challenge, although I do feel that it is kinda two challenges in one: 1) given an arbitrary latitude/longitude coordinate, find some governmental entity that claims control of that location and 2) given that governmental entity, output its flag. it might be better breaking this into two, or selecting only one of them \$\endgroup\$
    – des54321
    Jun 5, 2022 at 1:41
0
\$\begingroup\$

Alternating sums of multidimensional arrays

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

Irradiated Polyglots

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

Quickly approximate the square root of a float


As in like, constant-time and almost instant, but off by a lot. No time for looping here. This is going to take a lot of work, since I'm going to make an emulated CPU which will allow more precise timing.

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

Desmosian Music

Create a script that takes in notes as numbers and note lengths as decimals.

You do not have to accept rest notes.

For instance, when given [[1,1],[2,2],[3,0.5]] you should return a desmos code that plots:

      -  <== 3
  ----   <== 2
--       <== 1

In this case it can be:

\left\{x>0:\left\{x<2:1,\left\{x<6:2,\left\{x<7:3\right\}\right\}\right\}\right\}

Scale the note lengths to fit entirely inside the graph.

This is and I appreciate desmos answers.

\$\endgroup\$
2
  • \$\begingroup\$ What’s the winning criteria? code-golf? Metagolf? \$\endgroup\$
    – ATaco
    May 30, 2022 at 0:56
  • \$\begingroup\$ Probably best to explain the output. Does it need to be ascii art? A drawn graph? Desmos code? Could you provide an example of passing code? \$\endgroup\$
    – ATaco
    May 30, 2022 at 1:14
0
\$\begingroup\$

Can we do it with an 89?

This was originally meant to be a Puzzling Challenge:

Can we do it with an 89?

89 is my favorite number. Your task is to make 1~100 using only one 89. Operations allowed are:

  • Factorial (3! = 6)

  • Parenthesis ((3!)! = 6! = 720)

  • Double Factorial (4!! = 4*2 = 8)

  • Square Root (sqrt(9) = 3)

  • Floor and Ceiling (floor(3.5) = 3 and ceil(3.5)=4)

  • Negation (-3 = well, -3, duh)

Note that 4!! = 4*2 and not (4!)!

Your task is to output the equation given a number greater than 1 (no longer restricted to be less than 100), inclusive.

Meta:

  • Should this be ?

  • Or should we aim to end with the shortest equation?

  • Or should we aim for a shorter run time?

  • Could this be 3 challenges?

  • Or should I ask for code that outputs the shortest equation?

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

Good Rectangles and Evil Numbers

This is meant to be a Puzzling Challenge:

Good Rectangles and Evil Numbers - Integrated

Original: https://puzzling.stackexchange.com/questions/116168/good-rectangles-and-evil-numbers

Good Rectangle

We define a good rectangle with base \$ x \$ as a rectangle in which \$ rac lw = x \$ where \$ l \$ is the length of the rectangle and \$ w \$ is the width of the rectangle.

Tiling

This is simply to clarify. There should be no problem if you ignore this section, but I would like the question to be robust.

We define a tiling of a group of shapes onto another shape as a way to place the group of shapes such that:

  • The shapes do not overlap

  • The group of shapes covers the entire target shape

  • The target shape covers the entire group of shape

(The latter two combined is equivalent such that the union of all shapes in the group is congruent to the target shape)

Good Numbers

We define a positive integer as a good number in base \$ x \$ if it is possible to tile that many good rectangles of base \$ x \$ (not necessarily of the same size) onto a square of any side length.

Evil Numbers

We define an evil number as a positive integer that is not a good number in that base.

...

Your Task: Given a number as the base \$ x \$ and a number as the number of rectangles \$ n \$, assuming that \$ n \$ is not an evil number in base \$ x \$, graphically output a tiling with \$ n \$ good rectangles in base \$ x \$.

This is .

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

Tapes, Pointers, And sub-tapes: BrainFuck+


In this challenge we make an interpreter for a subset of BrainFuck+.

As with BrainFuck we start with the tape [0] and pointer at index 0.


BrainFuck+ Simplified: Commands


+ and -


Update the current cell, as in BrainFuck.


++

=>

[2]
 ^

--+--++

=>

[-1]
  ^

(There exists no wrap around)


< and >


Update the pointer, as in BrainFuck.


>

=>

[0,0]
   ^

An attempt to go right at the rightmost point of a tape creates a cell with value 0 at the right.


++>+>++>-

=>

[2,1,2,-1]
        ^

++<+

=>

[1,2]
 ^

An attempt to go left at the leftmost point of a tape creates a cell with value 0 at the left.


v and ^


v

=>

[[0]]
  ^

An attempt to go down a numerical value overrides the cell with the empty subtape [0].


>+<v+>-^>

=>

[[1,-1],1]
        ^

^ exits the subtape.


v>^v

=>

[[0,0]]
  ^

An attempt to go down a subtape will enter the subtape at index 0.


^

=>

Program Termination

An attempt to exit the main tape terminates the program. Otherwise the program must run completely.


Revisiting + and -


v^+

=>

Program Termination

An attempt to increment or decrement a list will fail and terminate the program. However no error will be raised.


Other characters...


...will not appear.


Your Task:


Make a Simplified BrainFuck+ Interpreter. This is .


Test Cases


See above.


\$\endgroup\$
3
  • \$\begingroup\$ I like this concept a lot, but it could stand to be reorganized a bit for ease of reading, but thats' just my opinion. \$\endgroup\$ May 30, 2022 at 4:20
  • 1
    \$\begingroup\$ @thejonymyster how specfically \$\endgroup\$ May 30, 2022 at 4:23
  • \$\begingroup\$ IMO: Could summarize the whole feature-set up front, rather than introducing each feature one at a time. +-<> on their own are simple enough to have a sentence or two for, maybe some small examples alongside the explanations for ^v and how they interact with <>, and then some more complex test cases all lined up in a single code block at the end. Also, the line breaks are bulky and not necessary here. \$\endgroup\$ May 30, 2022 at 4:28
0
\$\begingroup\$
--\/--
--/\--

Morse Tangles: ASCII Art

Given a word (with only letters, case insensitive), say SOS:

  • Change the word into Morse code, in this case, ... --- ...

  • Change dots to parallel bars and dashes to tangles.

Output the result as ASCII art:

------  \/\/\/  ------
------  /\/\/\  ------

Note that the spaces are two characters wide. This is .

Morse Code Chart:

https://cdn.shopify.com/s/files/1/2223/4507/files/morse-chart_grande.png?v=1501447409

\$\endgroup\$
3
  • \$\begingroup\$ Please, add a morse code table to the post for reference and provide some more test-cases. Please consider changing overline ¯ to a dash - as it's outside of ASCII range and that may exclude some languages from participating. I also suggest changing underscores to - for more golfing opportunities and removing the spaces between characters in the final tangle. \$\endgroup\$
    – pajonk
    May 30, 2022 at 10:21
  • \$\begingroup\$ Done @pajonk .. \$\endgroup\$ May 31, 2022 at 0:27
  • \$\begingroup\$ IMHO the Morse code table is short enough to be posted verbatim in the question (e.g. as a code block for easy copying) to make the question self-contained. Also, again, please add some more test-cases. \$\endgroup\$
    – pajonk
    May 31, 2022 at 4:20
0
\$\begingroup\$

Extracting nth character of FizzBuzz

I was inspired by the challenge to output FizzBuzz as fast as possible. I have written and optimized some code to the degree that it computed the 10^1000000th character of FizzBuzz within 5 minutes (it's "7"). (Not the 10^1000000th line, this is the 10^1000000th character, and I don't mean 1000000, I really mean 10^1000000). See here. I'm not sure how the challenge would work, perhaps it could be "how fast can you extract the nth digit of FizzBuzz, where n is a random number with a million digits"? Or perhaps a simple king of the hill for "what's the furthest power of ten index you can compute"? I wonder if someone can up that to 10^10000000?

\$\endgroup\$
2
  • \$\begingroup\$ codegolf.stackexchange.com/questions/219009/… \$\endgroup\$
    – emanresu A
    Jun 3, 2022 at 5:27
  • \$\begingroup\$ Thanks! But, that is just for the shortest code, rather than the most performant, or the highest character index computed. I commented my approach anyway though! \$\endgroup\$
    – lurf jurv
    Jun 3, 2022 at 6:12
0
\$\begingroup\$

Rational numbers


Challenge

Every rational numbers (can be written in a fraction form \$a / b\$ ( \$a\$,\$b\$ are integers)) can be represent as a periodic, repeating decimal number.

For example, \$1 / 3\$ is \$0.3333333333333333...\$, so we represent it as \$0.(3)\$. Another example, \$3227 / 555\$ is \$5.8144144144...\$ so we represent it as \$5.8(144)\$.

Your task is, given a fraction \$a / b\$, print out its periodic, repeating decimal number,

Input/Output

  • Input/Output can be taken in any resonable format, containing the fraction.

Testcase:

5/2 -> 2.5(0)
1/3 -> 0.(3)
3227/555 -> 5.8(144)
557/495 -> 1.1(25)
35/17 -> 2.(0588235294117647)

This is , so so shortest answer (in bytes) wins!

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

Infinite Prisoner's Infilemma

Introduction

In this challenge, you are going to write a program that will play the game of the Infinite Prisoner's Infilemma.

This game is based on the classic game of the name Infinite Prisoner's Dilemma .

The original inspiration for this game came from this game by Nicky Case.

By default we will include the sample bots from Nicky Case's game. You can also add your own bots.

How to Play

Given a list of bot models [1,2,3,4,5]:

  • First, multiply the list by 10 to get 10 bots of each model.
  • Then, battle every two bots together.

During a battle there will be 10 rounds. Each round:

  • Both players will enter x dollars into a machine, where x is non-negative (not neccessarily an integer) and less than or equal to the amount of money they have. They start with $100.
  • The other player will recieve 1.1 times the amount of money.

Default Bots

Default bots are:

  • Copycat, which starts by cooperating with 1/3 of his money, and then cooperates with the same ammount of money as the ammount of money you cooperated last turn. (Unless he doesn't have enough money, which he will use all of them).

  • AlwaysCheat, which, always cheats by giving no money. DUH!

  • AlwaysCooperate, which, always cooperates by giving 1/2 of his money.

  • Grudger, which starts by cooperating with 1/3 of his money but gives no more money if you have ever cheated and give less than $10.

  • Detective, which cooperates $20, $5, $10, but if the opponent always gave at least $50, will act like an AlwaysCheat, else will act like a Copycat.

  • Copykitten, which is similar to Copycat, but cooperates with the same ammount of money as the max of the opponent's last two turns.

  • Simpleton, which starts by cooperating 1/2 of his money, then at every turn, if the opponent gave less than $20, switch a state between 1/2 of his money and none.

  • Random, which give, randomly, 2/3 to none of his money.

Instructions

Your bot should be a class. It will inherit from this Bot class:

class Bot:
    def __init__(self):
        self.money = 100
        self.information = {}

    def log(self, bot, money):
        if bot not in self.information:
            self.information[bot] = [money]
        else:
            self.information[bot] += [money]

    def change_money(self, money):
        self.money += money

    def choice(self, bot):
        pass # override in subclass

    def name(self):
        pass # should return the name of the bot

    def get_choice(self, bot):
        choice = self.choice(bot)
        assert 0 <= choice <= self.money, \
            f"Invalid choice {choice}, bot money {self.money}" # check if choice is valid
        return choice

You may not use any other libraries other than math and random. (If you have any requests, let me know. I mainly want to ban the use of inspect, sys, and os.)

You may also not override any methods other than choice and name.

You may not set self.money. (Else, you can come up with self.money = 10000, etc.)

The following is a sample bot:

from main import Bot # <-- import the Bot class
from random import random as r # <-- import the random function

class TestBot(Bot): # <-- create a class called TestBot
                    # <-- that inherits from Bot
    def choice(self, bot): # <-- override the choice method
        return self.money*r()/10 # random number between 0 and
                                 # 10% of the bot's money
    def name(self): # <-- override the name method
        return "randombot" # <-- return the name of the bot

bot = TestBot # <-- IMPORTANT: create a variable called bot

The Information Log

Well, sometimes you want to know what the opponent did. Thus, sometimes you need the "information log", called via self.information. Remember the bot argument that is passed in the choice method? That is your opponent. To get the information log of your opponent, use the following:

self.information[bot] # <-- get the information log of the opponent

What does that information look like? Well, it's like [[Y1,O1],[Y2,O2],...]. Y1 is what you gave the opponent in round 1. The rest is fairly easy to infer.

Controller Script

# This is the controller script for the Infinite Prisoner's Infilemma King of the Hill game.

bots = ['testbot','randombot'] # Will change.

# to make it fold-able.
if True:

    from rich.console import Console
    from rich.table import Table
    console = Console()
    with open('log.txt','w') as f: pass

    def print(*args, **kwargs): console.print(*args, **kwargs)

    def log(*text):
        with open('log.txt','a') as f:
            f.write(' '.join(list(map(str,text)))+'\n')

    def play(Bot1, Bot2):
        log(Bot1.name(), 'vs', Bot2.name())
        b1_choice, b2_choice = Bot1.get_choice(Bot2), Bot2.get_choice(Bot1)
        Bot1.change_money(-b1_choice)
        Bot2.change_money(-b2_choice)
        log(b1_choice, b2_choice)
        Bot1.change_money(1.001*b2_choice)
        Bot2.change_money(1.001*b1_choice)
        log(Bot1.name(), 'has', Bot1.money, 'dollars')
        log(Bot2.name(), 'has', Bot2.money, 'dollars')
        Bot1.log(Bot2, b1_choice, b2_choice)
        Bot2.log(Bot1, b2_choice, b1_choice)
        log('\n\n')

    class Bot:
        def __init__(self):
            self.money = 100
            self.information = {}

        def log(self, bot, money):
            if bot not in self.information:
                self.information[bot] = [money]
            else:
                self.information[bot] += [money]

        def change_money(self, money):
            self.money += money

        def choice(self, bot):
            pass # override in subclass

        def name(self):
            pass # should return the name of the bot

        def get_choice(self, bot):
            choice = self.choice(bot)
            assert 0 <= choice <= self.money, \
                f"Invalid choice {choice}, bot money {self.money}" # check if choice is valid
            return choice

    def leaderboard(Bots):
        table = Table(show_header=True, header_style="bold #00ffff")
        table.add_column("Bot", style="bold #ffff00") # yellow
        table.add_column("Money", justify="right", style="#00ff00") # green
        for bot in sorted(Bots, key=lambda x:-x.money):
            table.add_row(bot.name()+'     ',
                          f"     ${str(round(bot.money,2)) if str(round(bot.money,2))[::-1][1] != '.' else str(round(bot.money,2))+'0'}")
        print(table)

    def main():
        print('\n\n\n')

        Bots = []
        for bot in bots:
            for i in range(10): Bots.append(__import__(bot).bot())

        for Bot1 in Bots:
            for Bot2 in Bots:
                if Bot1 is not Bot2:
                    for i in range(10): play(Bot1,Bot2)

        leaderboard(Bots)
        print('\n\n\n')

    if __name__ == '__main__':
        main()

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

Compute the cophenetic correlation coefficient

Meta question at the end.

Background

The cophenetic correlation coefficient is used in bioinformatic to measure how close the distances of a tree are to the distances of the original distance matrix.

It is defined as follows: \${\displaystyle c={\frac {\sum _{i < j}(D_{ij}-{\bar {D}})(T_{ij}-{\bar {T}})}{\sqrt {\sum _{i < j}(D_{ij}-{\bar {D}})^{2}\sum _{i<j}(T_{ij}-{\bar {T}})^{2}}}}}\$

More information:

Input:

  • D: CSV style-string to first matrix
  • T: CSV style-string to second matrix

The input have the following format:

Eg 1: D.dist

N31
B14A.0, 2.0
N20, 3.0, 4.1
N20S, 12.0, 23.9, 4.3
EES.0, 10.3, 19.0, 16.0, 17.0
S2.0, 201.1, 99.6, 233.0, 297.0, 281.00

Eg. 2: T.dist

N31
B14A.0, 1.7
N20, 3.9, 4.1
N20S, 32.0, 25.1, 4.3
EES.0, 12.3, 19.5, 16.1, 17.1
S2.0, 202.2, 105.6, 227.1, 281.1, 283.5

The first column is a for us uninteresting identifier, the values (floats) are separated by a ,.

Output:

The cophenetic correlation coefficient.

Example:

Using the two matrices from above: 0.9982682565

Meta

Is it okay to use a file path as input? Or should I reformulate this question to input two matrices directly?

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

Don't like the middles

There will be no winner on these question. Just for the fun of the challenge.

Your job will be to output every sequence of each 10 numbers, alternating between the evens and odds, but removing the middle number, which means all numbers terminating in 4 or 5 must not be generated.

Here it goes exemplified for the first elements:

0 2 6 8
1 3 7 9
10 12 16 18
11 13 17 19
...

It is not mandatory you need to pretty format or have a list of sub-lists as shown here. One list or a string where each element is clearly separated from the previous and the next ones is enough.

\$\endgroup\$
1
  • 4
    \$\begingroup\$ Objective scoring criteria don't make challenges less fun; they're what make a challenge a challenge. They're also mandatory :P \$\endgroup\$ Jun 13, 2022 at 20:34
0
\$\begingroup\$

Perform division for fuzzy numbers

Objective

Given two positive "fuzzy" numbers (as defined below), perform division between them.

Definition

Here, a fuzzy number consists of two integers: \$n\$ and \$r\$. It indicates that the number is from a measurement, and thus may carry an error. The measured number is \$n×2^r\$, and the maximum error is \$2^{r-1}\$.

In other words, the pair \$(n,r)\$ indicates that the exact number can be any of those from \$n×2^r - 2^{r-1}\$ and \$n×2^r + 2^{r-1}\$. As per the rounding convention, the boundaries are inclusive if \$n\$ is even, and exclusive if \$n\$ is odd.

In this challenge, only positive fuzzy numbers shall be considered. In other words, \$n\$ shall be positive.

Operation

Here, the operation in concern is division. Performing \$(n_1,r_1) ÷ (n_2,r_2)\$, the exact result of division is within the range from \$(n_1×2^{r_1} - 2^{r_1-1})/(n_2×2^{r_2} + 2^{r_2-1})\$ to \$(n_1×2^{r_1} + 2^{r_1-1})/(n_2×2^{r_2} - 2^{r_2-1})\$, where boundaries are inclusive if and only if both \$n_1\$ and \$n_2\$ are even.

The range indicated by result \$(n,r)\$ shall cover the range above as precisely as possible. That is, \$r\$ must be as small as possible. As a tiebreaker, the range must be as accurate as possible. That is, \$n\$ must be chosen so that \$n×2^r\$ would be as near as possible to: $$ ½((n_1×2^{r_1} - 2^{r_1-1})/(n_2×2^{r_2} + 2^{r_2-1}) + (n_1×2^{r_1} + 2^{r_1-1})/(n_2×2^{r_2} - 2^{r_2-1})) \\ =(4n_1n_2+1)/(4n_2^2-1)×2^{r_1-r_2} $$

For ranges with equal radii, those excluding boundaries shall be considered preciser than those including boundaries. This ensures uniqueness of the result.

Ungolfed solution

(WIP)

\$\endgroup\$
1
  • 1
    \$\begingroup\$ I think apart from unglofed solution (WIP, but I'm not a fan of posting reference implementations in a question) and some test-cases, there should be at least one or two thoroughly worked out examples. Also, please remember about specifying an objective scoring criterion and I/O requirements (if any). \$\endgroup\$
    – pajonk
    Jun 23, 2022 at 12:28
0
\$\begingroup\$

I X the source code, you Y the output!


There's a zillion challenges of the form "I [do a thing to] the source code, you [do a thing to] the output!", like I double the source, you double the output! and I reverse the source code, you negate the output!. In this challenge you'll generalize that, writing a program that, given two functions x and y, will print a program p which prints some output o, with the property that x(p) prints y(o).

Task:

Your program (or function) should take two inputs, x and y, which can either be functions/lambdas, strings containing code, or some similar representation of a function in your language. You can assume these functions are pure: they have no side effects and do not depend on anything aside from their input. Other reasonable assumptions may be made based on your language's requirements, such as the input to x being a string of a certain length.

Your program should then print or return a program p, once again either as a pure lambda function (so it can't rely on x and y in the scope above it), a string representation of a program, function, or snippet, or some similar representation, such as writing an executable to a file. When p is run, it should take no input, and produce a deterministic value o. When x(p) is run, a second program will be produced, which, when run without input, should produce y(o) deterministically.

You may assume the data type of y(o) is the same as o, and make any other reasonable assumptions for your language. You may use any consistent data type for o, as long as it can hold more than 128 or so values (ints, floats, or strings would be preferred).

Sandbox:

This would be a very difficult challenge, and I'm not entirely sure what it would involve to answer or if it would even be possible to do so. I'm going to have to make some additional rules I think. maybe the inverse of x would be another input, that sort of thing. Feel free to suggest any ideas for rules to make this more possible and/or interesting, including across languages.

\$\endgroup\$
4
  • 1
    \$\begingroup\$ what if x is, say, return ""? or something else disruptive like z=>return "exitprogram()"+z \$\endgroup\$ Jun 27, 2022 at 15:49
  • 1
    \$\begingroup\$ If x is an arbitrary function, this is impossible. Consider x being the identity function: p and x(p) are the same, so their outputs must be the same (since they must be pure and deterministic). For almost all y (in fact, all y except the identity function), this becomes impossible. You'd have to put some kind of very strong restriction on x for this to be doable, which I don't think can make it an interesting challenge. Either that, or allow solutions to be uncomputable (...cont'd) \$\endgroup\$
    – pxeger
    Jun 27, 2022 at 16:03
  • \$\begingroup\$ (...cont'd) (A "valid" but uncomputable solution could be of the form: generate every program p and compute x(p), and check that y(eval(p)) == eval(x(p))). Some more (less trivial) logic can be used to show that this is also impossible if y is an arbitrary function. \$\endgroup\$
    – pxeger
    Jun 27, 2022 at 16:03
  • 1
    \$\begingroup\$ @pxeger Yes, it's not possible with a number of xs and ys. I don't think restricting it so that it's possible makes it less interesting though. \$\endgroup\$ Jun 27, 2022 at 16:29
1
134 135
136
137 138
157

You must log in to answer this question.

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