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

3032 Answers 3032

1
60 61
62
63 64
102
0
\$\begingroup\$

Factorize Gaussian Integer

Given a nonzero gaussian integer your program/function should return the factorization of that integer g into prime factors pi and an unit u:

g = u * p1^e1 * ... * pk^ek

As the factorization is only unique up to units, we make following restrictions

  • All primes should p should be in the first quadrant, that means that Re(p) > 0 and Im(p) ≥ 0.

  • The unit should be represented as power of i. It should have the lowest nonnegative exponent.

  • The primefactors should be sorted by the real part increasingly. If two real parts are the same, they should be sorted by imaginary part (also increasing.)

Examples

11-27i = i^2*(1+i)*(2+i)^2*(4+i)
2     = i^3*(1+i)^2

To be added: Examples, input output spec

https://en.wikipedia.org/wiki/Table_of_Gaussian_integer_factorizations

is_gaussian_prime(z)?

https://stackoverflow.com/a/2271645/2913106

\$\endgroup\$
  • \$\begingroup\$ What about builtins? \$\endgroup\$ – lirtosiast Mar 26 '16 at 2:57
  • \$\begingroup\$ Built-ins are ok. In my experience restricting built ins is quite subjective and frequently results in trouble=) \$\endgroup\$ – flawr Mar 26 '16 at 10:54
0
\$\begingroup\$

Create a race condition

Your objective is to create program where concurrent threads race to produce a result. The program is simple. Print the sum of every element in the cartesian product of two sets.

An example of standard input would be

2 5 8 10 | 9 2 3 7 512 | 3 1 2 | 9 8 6 3

The program would then need to spin up two separate threads to calculate each result, and the first thread (and only the first thread) to complete should print "I WIN!" and the answer without using mutexes or other synchronization methods.

Rules

  • You cannot use mutexes or synchronisation
  • The operation must be run concurrently
  • Standard input will contain any multiple of two sets, and the program should use (no of sets / 2) threads, as well as the main thread that spins everything.
  • The order of execution on the slave threads is not important
  • Some failure cases where more than one thread prints "I WIN!" is acceptable, but should be a rare case Sandbox comment: Not sure about verifying this one? or should not bother at all?

Sandbox comments

I saw the TCP Server question and I liked the idea of a challenge that is specifically difficult for golfing languages, and I was thinking about a few ideas for challenges that might work based specifically on parallel programming failures. I'm not sure if this one really fits the bill, hoping for suggestions to improve the challenege itself before refining the criteria.

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

A Tiny Raytracer

Your task is to make a tiny 2D raytracer to render beautiful ascii images.

Input

Your input will be an arbitrary 2D array delimited by newlines with the following structure

########
#9     #
#      #
#  ##  #
#  ##  #
#      #
#    ###
########

The symbols are: 0-9 = Light source = Emptiness # = Wall

Your expected output should look like this:

########
#987654#
#876543#
#76##32#
#65##00#
#543000#
#43000##
########

How Light Propagates

Light will travel in a straight line from lightsources through empty space and will be completely blocked by walls. Light falls off according to this function:

light_intensity = clamp(floor(9 - source_intensity * ||dist_to_lightsource||), 0, 9)

Where || || is the euclidean norm between the cell containing the light source and the cell in question, with 1 cell = 1 unit. All light intensity values are clamped to be between 0-9.

Light falls on an empty cell c whenever a straight line can be drawn from any part of c to the cell containing the light source without passing through a wall. For example, here I have all of the cells affected by a light source marked as *:

########       ########
####   #       ####***#
#9   #     =>  #****#  
###    #       ###****#
### ####       ### ####

Whenever there are multiple light sources, their contributions to the final light intensity are summed (and clamped to be between 0-9).

For example:

################
#9            6#
################

Should yield:

################
#98765432223456#
################

Rules

Standard code golfing rules. Input can have arbitrary size.

Fun Optional Bonuses

  • Output the result as a graphical image.
  • Support light values of between 0-255 (in this case columns of the input and output will be space delimited)
  • Support colors (in this case light will be denoted by a standard 24-bit hex code 0xFFFFFF, and space delimited).

These don't give you any bonuses in the competition, but would be cool.

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

Self-decrypting code

The Caesar cipher is perhaps the earliest and most well known form of encryption. Here's a quick overview:

Pick a message, and a numerical encryption key. For this example, I'll pick "HELLO, WORLD" and 3, respectively.

First, convert each letter into its ASCII number:

H -> 72
E -> 69
L -> 76
L -> 76
O -> 79
, -> 44
[space] -> 32
W -> 87
O -> 79
R -> 82
L -> 76
D -> 68

Then, add the key (3) to each and convert back into a letter

75 -> K
72 -> H
79 -> O
79 -> O
82 -> R
47 -> /
35 -> #
90 -> Z
82 -> R
85 -> U
79 -> O
71 -> G

So the encrypted message is "KHOOR/#ZRUOG"

Your task

Write a full program that is a Caesar cipher-encrypted valid English message. The program must take no input and it will output the unencrypted version of itself.

Some rules:

  • The program must be at least length 2.
  • The key may not be 0, 32, or 256
  • All of the code must be executed (no comments to arbitrarily extend code length).
  • The Linux word list will be used to judge if a message is English. Words must be separated by ASCII character 32. Words can mix uppercase and lowercase.
  • Your program does not need to be written in printable ASCII.
  • File I/O is allowed, but only to read the source code file.
  • No other standard loopholes.

Scoring

The submission with the longest message wins. Anything over 200 characters will be scored as exactly 200 characters. Ties are broken by upvotes.

\$\endgroup\$
  • 1
    \$\begingroup\$ I think this has a bunch of problems. The scoring doesn't make much sense why does it switch between code-challenge and pop-con? Additionally, I'm almost certain that 200 won't be that hard to reach, considering it is "valid" English to say "I am very very very ... very very sad". This also doesn't explicitly give much explanation for valid English. Do you just have to have words and spaces? Or does it need to make sense? Also, "all of the code must be executed" rules basically never work: it's too easy to get around them. \$\endgroup\$ – FryAmTheEggman Apr 1 '16 at 14:13
  • \$\begingroup\$ @FryAmTheEggman How should I deal with arbitrary-length submissions (they found a way to make it as long as possible)? As for valid sentences, maybe just words separated by spaces (but no word can be repeated). How should I prevent trivial arbitrary-length programs (because comments can be used for that). \$\endgroup\$ – Daniel M. Apr 1 '16 at 14:20
  • 2
    \$\begingroup\$ The problem is that there are too many things that are basically the same as comments in too many different languages. What's to stop me from just inserting a giant numeric/string literal in my code that don't get printed? What about repeating ; in a C program? What about languages that don't even really read their source code like lenguage? I feel like if your challenge breaks because of comment like things, it's sort of doomed to be broken. \$\endgroup\$ – FryAmTheEggman Apr 1 '16 at 14:25
  • \$\begingroup\$ What constitutes a "valid English message"? What modulus operations are permitted? \$\endgroup\$ – Peter Taylor Apr 5 '16 at 13:35
  • \$\begingroup\$ @PeterTaylor Any modulus operations that don't bring the message back to itself and aren't the exact difference between lowercase and uppercase. \$\endgroup\$ – Daniel M. Apr 5 '16 at 15:42
0
\$\begingroup\$

Calculate the number of consecutive 0's at the end of n!


Simply put, write a program or function that takes n and returns the number of consecutive 0's at the end of n!


Examples

Input: 12
Output: 2

Input: 12345
Output: 3082

Input: 100000
Output: 24999
\$\endgroup\$
  • \$\begingroup\$ I think this might be a dupe. \$\endgroup\$ – Rɪᴋᴇʀ Apr 2 '16 at 21:45
  • \$\begingroup\$ @EasterlyIrk Do you have a link to the duplicate problem? \$\endgroup\$ – MrPublic Apr 4 '16 at 11:38
  • \$\begingroup\$ This is extremely similar. \$\endgroup\$ – FryAmTheEggman Apr 4 '16 at 17:20
  • 2
    \$\begingroup\$ This proposal would be similar to finding the position of the last nonzero digit, but it's not similar to the linked challenge, which finds the value of the last nonzero digit \$\endgroup\$ – Luis Mendo Apr 6 '16 at 11:14
0
\$\begingroup\$

How many pixels are in each ASCII char?

Write a program or function taking a single printable ASCII character as input that outputs how many pixels it takes to display that character to the screen.

Input can be taken by any reasonable method, including reading from a file, STDIN, or function argument. Input from a variable hardcoded into the program is not reasonable.

Output may by given by any reasonable method, including writing to a file and STDOUT. Extraneous output is permitted as long as the result remains unambiguous.

"Printable ASCII character" is defined as a character within the codepoints 32-126, inclusive.

A pixel counts as part of a character if the pixel is non-white after the character is written to a white screen.

The required font is Times New Roman, 20pt.

Do not hardcode the result.

Reference Solution: (JavaScript)

//create a canvas to display the character
var canvas = document.createElement("canvas")
canvas.width = 100
canvas.height = 100
document.body.appendChild(canvas)

var context = canvas.getContext("2d")

//make the canvas white
context.fillStyle = "white"
context.fillRect(0, 0, 100, 100)

//make the text black and set the font
context.fillStyle = "black"
context.font = "20pt Times New Roman"

//ask for the char
var char = prompt("Enter your ASCII char")
   
//draw the char
context.fillText(char,50,50)

//get the canvas pixel data
var pixelData = context.getImageData(0, 0, 100, 100).data
var pixelCount = 0
for(var i = 0; i < pixelData.length; i+=4) {

    //if the pixel isn't white, increment the counter
	if(pixelData[i] != 255 || pixelData[i+1] != 255 || pixelData[i+2] != 255) pixelCount++
}
alert(pixelCount)

\$\endgroup\$
  • \$\begingroup\$ Is there any specific font that should be used? \$\endgroup\$ – Downgoat Apr 3 '16 at 5:07
  • \$\begingroup\$ you should probably set a specified font (Times New Roman, Arial), to make answers more comparable. If not, you should probably say the font should have been made before this challenge was posted \$\endgroup\$ – Downgoat Apr 3 '16 at 5:13
  • \$\begingroup\$ @Downgoat actually on second thought, languages that can't output Times New Roman probably don't have the features to compete in this challenge anyway. I'll make 20pt Times New Roman the required font. \$\endgroup\$ – jrich Apr 3 '16 at 5:20
  • \$\begingroup\$ I wonder if any other algorithms exist that are more efficient. \$\endgroup\$ – Leaky Nun Apr 3 '16 at 5:48
0
\$\begingroup\$

Self-identification before golfing

Since golfed code is harder to read, answers often contain an less golfed version. There are a number of potential golfing transformations depending on the language, so you may be able to score more highly using a more traditional language. Some examples of golfing transformations:

  • Removal of spaces, tabs and/or newlines
  • Removal of disambiguating parentheses
  • Removal of braces around single controlled statements
  • Conversion from statements to comma operator
  • Removal of explicit return statements
  • Renaming identifiers

Your challenge is to write a program or function that can identify an ungolfed version of itself. Scoring is based on the number of golfing transformations that can be recognised. The submission must be capable of identifying all "original" code that is itself capable of self-identification (at least one such code must exist). Each supported transformation scores 1 point, but there are also bonus points available:

  • 1 bonus point if the transformation can be repeated multiple times
  • 1 bonus point of the program rejects at least one invalid transformation of itself (e.g. white space added inside a keyword)
  • 1 bonus point if the program only accepts valid transformations of itself
  • 1 bonus point if the transformation shortened the code (so if you only supported renaming a 1-letter variable to another letter, you would not qualify)
  • 1 bonus bonus point if in addition the transformed program recognises the original program as a transformation of itself

Example: A submission accepts the name of another program as a command-line parameter. It opens itself using its own name hard-coded into itself. It recognises the following transformations:

  • A change to the hard-coded file name (3 points, as there is only one file)
  • A change to the amount of space between words (5 points, as there are no invalid transformations to reject)
  • A change to the names of its variables (4 points, as it doesn't check whether the variables are renamed consistently or to keywords)

Total score: 12 points.

In the event of a tie on score, shortest code wins.

Tags: code-golf, quine

\$\endgroup\$
  • 4
    \$\begingroup\$ This is hopelessly subjective. \$\endgroup\$ – feersum Apr 5 '16 at 13:35
0
\$\begingroup\$

In this challenge you are supposed to output a grid 10x10 with numbers from 00 to 99 (each number once) following this rules:

  • Number 00 must be on the bottom row
  • Number 99 must be on the upper row
  • In the output each number must be sepparated by spaces and must have two digits (that is including 0's when needed for the first 10 numbers)
  • Output must be random
  • It must be solved within reasonable time

I'm having an issue trying to define random and reasonable time here and would like some help with it. Thanks.

\$\endgroup\$
  • \$\begingroup\$ Define random as 'Each of the possible permutations must have an equal probability of being the output'. For reasonable time I don't think you need a definition - especially since your challenge is only 100 numbers, so it should be perfectly doable unless your algorithm works in O(n!). \$\endgroup\$ – Sanchises Apr 7 '16 at 11:11
  • \$\begingroup\$ @sanchises I find that asking for equal probability is too strong, since there's no way to prove that one of those algorythm has equal probability. \$\endgroup\$ – Masclins Apr 7 '16 at 16:34
  • \$\begingroup\$ Of course, a formal proof is not always easy. However, an intuitive result should be enough for most applications, and if people have difficulty with that, you can always use one of the algorithms described at the Wikpedia page, e.g. Knuth shuffling. I was wondering though, is there a motivation behind the challenge, or is just something you cooked up? \$\endgroup\$ – Sanchises Apr 7 '16 at 17:57
0
\$\begingroup\$

Manual MD5

Given a string, calculate its MD5 sum without using any built-in MD5 library functions. An overview of the algorithm is here.

(I'm going to actually summarize the algorithm before I post it. Until then, it's still unfinished.)

Input is an ASCII string or byte stream with any reasonable length (I won't run an entire novel through your algorithm, for example).

Output the hex value of the resultant hash as a string.

Code golf, so shortest code wins. Standard loopholes are banned.

\$\endgroup\$
  • 1
    \$\begingroup\$ You add the tags by adding [tag:code-golf] (and the others) to the body of your post. \$\endgroup\$ – user45941 Apr 2 '16 at 5:41
  • 1
    \$\begingroup\$ To answer your question: yes, include a description of the algorithm in the challenge body. Requiring external resources for a challenge is discouraged. \$\endgroup\$ – user45941 Apr 6 '16 at 4:02
  • \$\begingroup\$ 1. "Given a string, calculate its MD5 sum" is underspecified. In many languages nowadays, a string is a sequence of Unicode characters; MD5 is defined over sequences of octets, so to talk about the MD5 sum of a string you first have to define its encoding in octets. 2. Output format? \$\endgroup\$ – Peter Taylor Apr 8 '16 at 7:28
  • \$\begingroup\$ I clarified as ASCII string now in the input section. Should I mention that at the top, as well? \$\endgroup\$ – Value Ink Apr 8 '16 at 7:38
  • \$\begingroup\$ I think so. It's a one word addition and it avoids people wandering mentally off track. \$\endgroup\$ – Peter Taylor Apr 10 '16 at 21:46
0
\$\begingroup\$

Matrix Multiplication

This is a challenge in which we will be multiplying matrices.

Input:

  • an n x m matrix, A
  • an m x p matrix, B
  • optional:
    • n, m, and p

Input may be in any convenient fashion in order to reduce/eliminate the need to parse input. In particular, it may be given via function argument. The matrix dimensions may be taken as input or may be deduced from the actual matrix input.

Output:

The product of the two matrices. That is, output the n x p matrix C such that A * B = C.

Scoring

Your score will be the average of the sum of times your program takes to multiply several test cases on my computer.

Basically, I:

  • Time your entry for each test case
  • Add up all the times
  • Repeat the above steps several/many times
  • Average all the sums
  • That average is your score

Rules and Restrictions

  • Built in array/vector/matrix multiplication functions are disallowed. If you have to ask if a built-in is allowed, it probably isn't (but please ask anyways).

    • However, once the test cases are up, I would like to see how MatLab compares to the given entries
  • Entries in A and B will be standard 16 bit signed integer. Entries in C will fit in 32 bit signed integers.

  • Matrix size/dimensions should be limited by mainly by my available memory.

  • The size of test cases is not yet determined. It will depend on the speed and memory requirements of entries. I will of course try my utmost to be fair.

  • I have 8G of RAM and an AMD64 cpu.

  • Languages must be freely available on linux. Please include instructions on how to compile/execute your code.

Notes

I'm really not sure how big the matrices will be, but I'm expecting dimensions in the 100's or 1000's.

\$\endgroup\$
  • \$\begingroup\$ I think at slightly above 10000x10000 matrices you will run out of RAM, considering you'd have to store three of these matrices. MATLAB can multiply matrices of that size on my machine (similar specs) with a time of still only about 45 seconds. So I think memory is probably going to be the main limiting factor=) (And I do not think that anything's going to be much faster than BLAS) \$\endgroup\$ – flawr Apr 8 '16 at 23:45
  • \$\begingroup\$ @flawr I think 45sec would be long enough to get accurate timings. Also my machine is probably slower than yours and I doubt any entries will beat MatLab's time. If you think memory will still be a problem, I have no problem using 16 bit integers instead of 32 bit. \$\endgroup\$ – Liam Apr 9 '16 at 0:00
  • 1
    \$\begingroup\$ 1. Without knowing more about the test cases and the CPU it's going to be hard to optimise, because the sizes you're talking are roughly where the cutoff for naïve being worse than Strassen lies. 2. Can assembly answers use SIMD instructions (SSE etc.) or are they banned built-ins? \$\endgroup\$ – Peter Taylor Apr 10 '16 at 21:41
0
\$\begingroup\$

Iterated Matrix Multiplication

Given an nxn matrix A, an nx1 matrix X, and a list L of ordered pairs in [0,n)x[0,n), determine if there exists some integer k>=0 such that, with B=A^k*X, for all (D,E) in L, B[D]<B[E].

Why it's possible: Every entry of the natural number power of a general matrix can be expressed via sums of multiples of powers of the matrix's eigenvalues, like 2^k+4*6^k-10*3^k, and for any two such expressions, there will always be some k beyond which one term dominates the expression, and the sign of their difference can no longer change, so one way to solve the problem would be to calculate that k.

Test cases:

[[1,2],[2,3]],[3,4],[(0,1)] -> Yes (k=0)
[[1,2],[2,3]],[3,4],[(1,0)] -> No
[[1,2],[2,3]],[4,3],[(1,0)] -> Yes (k=0)
[[1,2],[2,3]],[4,3],[(0,1)] -> Yes (k=1)
[[1,-2],[2,-3]],[3,4],[(1,0)] -> Yes (k=1)
[[-1,-2],[2,-3]],[3,4],[(1,0)] -> Yes (k=2)
[[-1,-2],[2,-3]],[3,4],[(1,0),(0,1)] -> No
\$\endgroup\$
  • 1
    \$\begingroup\$ 1. For fastest-code you need to describe how you will measure it, selecting a test size which is large enough to give meaningful differences but small enough to be feasible. That probably means that you need to write a reference implementation or three (trying difference approaches). 2. For floating point questions, you need to do some numerical analysis to determine on what range of input it's feasible to write a correct program, and then guarantee that the input will be within that range. 3. You need to think about what level of library support is fair. \$\endgroup\$ – Peter Taylor Apr 13 '16 at 8:54
0
\$\begingroup\$

Colorize!

In Ruby, the colorize gem allows you to output text to the terminal in pretty colors:

Blue, bold text saying "This is a box"

It uses the ANSI color standard to tell the terminal how to color things, then trusts that the terminal will do the right thing. For this challenge, you can too.

What you'll do is take a a pair of lidts of strings, in whatever format you want. For example, if you wanted comma-separated values:

+-----+,| box |,+-----+
red,blue,red

The first list is what you'll be colorizing. The second list is a list of color names that are the same as the ones in the Wikipedia article. You'll colorize each string from the first list with the respective color from the second. The two lists will always have the same number of items, and the second will only ever contain valid color names. The strings in the first will only contain valid, printable ASCII characters.

And apply those colors -- as given by the ANSI standard linked above -- to the text, printing each string on its own line. For example, with this (heavily ungolfed) code:

#to be written

you'd get this:

[picture of result]

You may not use any libraries built to do this, and the standard loopholes are disallowed.


I'm thinking of adding extra credit for bolding/doing multiple things at once. Is that a good idea?

Aside from that, how is the rest of the challenge?


To-do list:

  • Copy the list from Wikipedia to here
  • Add pictures, demo code
  • Add that you have to change the color back to default at the end
\$\endgroup\$
  • \$\begingroup\$ The comma separated thing seems unnecessary, in most languages this just adds a boring split(',') call. You also probably want to only allow printable ASCII in the body of the strings (or at least put some restriction otherwise stuff can get pretty hairy). In addition you should explain what is necessary to know from the ANSI standard in your question body. \$\endgroup\$ – FryAmTheEggman Apr 13 '16 at 13:03
  • \$\begingroup\$ @FryAmTheEggman I linked the relevant part and stated "ANSI color standard" when it was first mentioned. What input format would you suggest that can deliver a set of lines to colorized and a set of colors to use? \$\endgroup\$ – Fund Monica's Lawsuit Apr 13 '16 at 13:22
  • \$\begingroup\$ Just say what they are: a list of strings and a list of colours. The link doesn't matter: if Wikipedia is down or they change that page so it doesn't help here then I can't answer your question without guessing what you mean. Also, the reason I said printable ASCII is that some ASCII is still hard to deal with. What about control characters, etc.? \$\endgroup\$ – FryAmTheEggman Apr 13 '16 at 13:27
  • \$\begingroup\$ @FryAmTheEggman Oh, I see. I'll update it to have "input of two lists in whatever format you want" and "printable ASCII characters only". As for requiring Wikipedia to be up, I'll copy and paste it when I have time. However, note that ANSI's standards are available online, and Googling "ANSI color standard" yields their website as well. Wikipedia is far more readable. \$\endgroup\$ – Fund Monica's Lawsuit Apr 13 '16 at 13:32
0
\$\begingroup\$

Random Wikipedia Browsing

Here's a short one for you. Create a program or function prints or returns the title of a random Wikipedia page (similar to Alt + x functionality)

Rules:

  • Program or function will take no input
  • Program or function will print to STDOUT (or nearest equivalent) or return only the page name. I don't care about trailing spaces or newlines. Preceding spaces or new lines are disallowed
  • Program or function may not access a list of Wikipedia page names stored within a local file.
  • There is no requirement to use English language Wikipedia (en.wikipedia.org)
  • Page must be chosen (psuedo) randomly

For reference, here is a link to the Wikipedia API. Shortest program or function in bytes wins.

\$\endgroup\$
  • \$\begingroup\$ Bash: xdg-open http://bit.ly/19UDVJs (I think it's open). That Bitly link points to the Random Page link, which redirects to a random page. Wouldn't be hard to find a shorter URL, either. \$\endgroup\$ – Fund Monica's Lawsuit Apr 14 '16 at 17:10
  • \$\begingroup\$ Aww man, I had no idea that existed, guess it makes this pretty trivial \$\endgroup\$ – wnnmaw Apr 14 '16 at 17:11
  • \$\begingroup\$ Yep. Though if the language's builtins don't support automatic handling of redirects, it might be more challenging. \$\endgroup\$ – Fund Monica's Lawsuit Apr 14 '16 at 17:11
  • \$\begingroup\$ Could I disallow using that link? \$\endgroup\$ – wnnmaw Apr 14 '16 at 17:12
  • \$\begingroup\$ I dunno, to be honest. I'm not very good at writing challenges. \$\endgroup\$ – Fund Monica's Lawsuit Apr 14 '16 at 17:13
  • \$\begingroup\$ Relevant chat discussion, this challenge is trival \$\endgroup\$ – wnnmaw Apr 14 '16 at 17:21
  • \$\begingroup\$ @wnnmaw the Random Page is often used for wiki-racing. It's pretty fun. You can do either shortest distance (pages traversed), or fastest time. Maybe you could make this into a King of the Hill challenge to write a bot that wiki-races against other bots? \$\endgroup\$ – mbomb007 Apr 21 '16 at 18:15
0
\$\begingroup\$

I'm a Puzzle!

Your task is to print the string "I'm on OS!", where OS is the operating system that the program is run on without version numbers.

Standard loopholes apply.

In addition, programs with hardcoded values (e.g. print "I'm on AFakeOS") will be disqualified.

As this is Code Golf, your score will be the length of your full program.


Any suggestions?

Java example:

class A {
    public static void main(String[] args){
        System.out.println("I am a " + System.getProperty("os.name").replaceAll(" .*","")
                                     + "!");
    }
}
\$\endgroup\$
  • 5
    \$\begingroup\$ When making something in Java, "noncompetitive" is implicit. \$\endgroup\$ – Cyoce Feb 13 '16 at 7:31
  • 1
    \$\begingroup\$ :P I've been lurking and waiting for an idea long enough to know. \$\endgroup\$ – 0az Feb 13 '16 at 13:07
  • \$\begingroup\$ "If run in a browser (JavaScript and/or any other browser scripting languages), the browser should be output instead." Why is that? I'm pretty sure you can detect the operating system even if you're in a browser. \$\endgroup\$ – Martin Ender Feb 13 '16 at 17:40
  • \$\begingroup\$ And my suggestion for "other bonuses, penalties, ..." is drop all of them. \$\endgroup\$ – Martin Ender Feb 13 '16 at 17:40
  • \$\begingroup\$ Added Java example solution. Removed bonuses. Read the linked question. \$\endgroup\$ – 0az Feb 13 '16 at 21:32
  • 1
    \$\begingroup\$ Exactly what is acceptable output? If Windows 10, is Windows? Windows 10? Windows NT Version 10.[build n]? \$\endgroup\$ – lirtosiast Feb 14 '16 at 5:24
  • \$\begingroup\$ How portable does this need to be? E.g. would uname -o be acceptable? \$\endgroup\$ – Peter Taylor Feb 15 '16 at 12:46
  • \$\begingroup\$ Considering that uname prints Darwin on my MacBook, and -o is an illegal option, uname -o would not work. I guess a possible definition of portable would be "works correctly on OS X, Windows, and most of the more common Linux distros" \$\endgroup\$ – 0az Apr 18 '16 at 3:01
  • \$\begingroup\$ @alphadelta That entails unambiguously defining the operative words most of the and more common in the phrase most of the more common Linux distros, which is objectively impossible. \$\endgroup\$ – cat Apr 24 '16 at 2:14
  • \$\begingroup\$ Perl 5, fourteen bytes as a subroutine: {"I'm on $^O!"} (where ^O is actually the F byte). (Fifteen as a program that prints: say"I'm on $^O!".) I can only imagine that the golfing languages will get down to one or two bytes, then. :-) \$\endgroup\$ – msh210 Apr 26 '16 at 22:32
0
\$\begingroup\$

@Sandbox:

  • Not sure if is correct here.
  • Do I need test cases for this? They will make this very lengthy.

Tags:

Find the structs!

The Challenge

Given a piece of C-code, add a /* before and a */ after every top-level structure definition that you find. You may not do this for structures that are defined inside other structures.

  • A structure can be identified by the struct keyword followed by an identifier, an opening {, some alphanumeric characters inside the structure and a closing };.
  • A structure identifier will only consist of alphanumeric characters.
  • One structure may also contain other structures with an unlimited depth.
  • Comments and whitespaces may appear anywhere in the code and have no effect. // starts a single line comment and code enclosed in /* and */ is a multiline comment.
  • You can't rely on a specific indentation style.
  • A structure will not contain any braces {} that are not part of another structure definition.
  • There can be multiple top-level structures in the input. You have to consider them all.
  • The input will only contain printable ASCII and newlines.

Example

So the output for

int z;
struct example1 /* comment here */  {
    int x; // struct comment {int x;};
    struct nested
    {
        char* s;
        int* y;
    };
};
int y;

//struct { };

struct example2{int x;};

would be

int z;
/*struct example /* comment here */  {
    int x; // struct comment {int x;};
    struct nested
    {
        char* s;
        int* y;
    };
};*/
int y;

//struct { };

/*struct example2{int x;};*/

Rules

Happy Coding!

\$\endgroup\$
  • 1
    \$\begingroup\$ I think this has some problems, as most questions that say "Given some C code do...", with what counts as valid. What about things like trigraphs, or macros or... ? \$\endgroup\$ – FryAmTheEggman Apr 13 '16 at 17:56
  • \$\begingroup\$ @FryAmTheEggman So it would be fine, when I limit the possible code-contents to a certain subset of C like I did for the struct contents? \$\endgroup\$ – Denker Apr 13 '16 at 19:00
  • \$\begingroup\$ Yeah, but I'm not well versed enough in C grammar to be able to say for sure that that'll be enough. \$\endgroup\$ – FryAmTheEggman Apr 13 '16 at 19:05
  • \$\begingroup\$ @FryAmTheEggman Thought about this and I actually don't need all that C-syntax stuff. Just came from the origin of this, but it's no really needed. Should be clear now. \$\endgroup\$ – Denker Apr 13 '16 at 20:23
  • \$\begingroup\$ Please work on your spelling before posting this, if you do. \$\endgroup\$ – Fund Monica's Lawsuit Apr 14 '16 at 18:52
  • \$\begingroup\$ @QPaysTaxes You can't fault OP for speaking ESL; this is why anyone can edit posts on SE. \$\endgroup\$ – cat Apr 24 '16 at 1:20
  • \$\begingroup\$ @cat That's actually wrong. You can't suggest edits on meta, and this answer isn't CW, so I'm not able to edit this. If you'd like to confirm, take any of your accounts with less than the required rep, go to meta, and try to edit something. It doesn't let you. \$\endgroup\$ – Fund Monica's Lawsuit Apr 24 '16 at 2:04
  • \$\begingroup\$ @QPaysTaxes I'm aware there are no suggested edits on Meta, because that would mean more, more clogged review queues for popular sites. I meant when the challenge is posted which is the only time small grammar things will matter anyhow, and I tend to be the type to fix that stuff. \$\endgroup\$ – cat Apr 24 '16 at 2:08
  • \$\begingroup\$ @cat Oh, I see. I thought you meant I should edit the Sandbox post, which... I can't. I've been told several times to "just edit it!" on various Metas where I don't have permission; I have yet to be told "edit it when this is on main" :P \$\endgroup\$ – Fund Monica's Lawsuit Apr 24 '16 at 2:11
0
\$\begingroup\$

Spiral text

Write a function or program that given a text with one or more characters in it outputs the text as a square spiral. The first letter of the text must be the center of the spiral and then all the characters must follow a clockwise spiral pattern as follow, striping all white spaces:

           789[10]
           612[11]
           543[12]
              [13]

Example

Input: Hello World!
Output:

               ORLD
               WHE!
               OLL

The text could be any length. Please validate with the following texts:

Once upon a time

Expected output:

o   n   a   t
p   o   n   i
u   e   c   m
            e


Tyger Tyger, burning bright, In the forests of the night; 

Expected output:

g   h   t   ;           
i   i   g   h   t,  I   n
n   r   y   g   e   r   t
e   b   t   t   y   ,   h
h   g   r   e   g   b   e
t   n   i   n   r   u   f
f   o   t   s   e   r   o

The minimung length of the input text is one character.

Note: Somewhat similar to this question

\$\endgroup\$
  • \$\begingroup\$ Test cases are more useful if you also include the expected output. ;) \$\endgroup\$ – Martin Ender Apr 29 '16 at 9:16
  • \$\begingroup\$ @MartinBüttner yay! Doing that \$\endgroup\$ – Averroes Apr 29 '16 at 9:17
  • 1
    \$\begingroup\$ Also having to support the empty string seems like an annoying special case that isn't likely to add anything interesting to most answers, so I'd personally probably let the input have at least one character, but that's your call. \$\endgroup\$ – Martin Ender Apr 29 '16 at 9:18
  • \$\begingroup\$ When you say "somewhat similar": why should I not vote to close it as a duplicate? It seems that the only difference is a reflection in the leading diagonal, which I would class as trivial. \$\endgroup\$ – Peter Taylor Apr 29 '16 at 11:55
  • \$\begingroup\$ @PeterTaylor First of all the other question doesn't have any answer and it is a bit old so maybe now this question can get a little more audience now. Secondly the other question add "The characters can spiral into previous characters" that this doesn't add to the specs so I think they are different questions. \$\endgroup\$ – Averroes Apr 29 '16 at 12:39
  • \$\begingroup\$ Ok, the other question is horrible. This is actually more like various spiralling numbers questions, with the main difference being that it spirals outwards rather than inwards. \$\endgroup\$ – Peter Taylor Apr 29 '16 at 12:52
0
\$\begingroup\$

Is this a helpful starting layout?

My computer has a Patience-style card game installed on it. It takes two packs of cards, removes the Aces, shuffles them, and deals 8 cards.

In order to maintain my 100% perfect completion record, I want as helpful a starting layout as possible. Deuces are immediately playable, so they are helpful cards. However other cards can only be played on cards of descending rank and opposite colour, which means that cards of the same rank and colour unhelpfully clog up the layout.

The challenge is to write a program or function which accepts a string or list of eight cards and outputs a truthy or falsy value. Cards are identified by their rank, which is one of the characters 23456789TJQK, and their suit, which is one of the characters CDHS. (Note that using numbers 10-13 for the rank is not an acceptable input.) For a layout to be helpful there must be at least one Deuce of any rank, and (except Deuces) there must not be any pairs of cards with the same rank and colour. Examples:

4H7STHTD5C5D2HQS -> unhelpful because of two red Tens
TD8S4CKC4HKD5S5H -> unhelpful because of no Deuces
2H7SJH3S4HKS7H3H -> helpful layout

This is , so the shortest program wins.

\$\endgroup\$
  • \$\begingroup\$ At first I thought this was a request for help, not the setting for a problem. You'll want to add what those inputs mean, what "a helpful layout" means, in detail. \$\endgroup\$ – Fund Monica's Lawsuit May 2 '16 at 18:19
  • \$\begingroup\$ As I understand, this can be solved by checking if the string contains 2 and its chunks of two are distinct, which seems pretty straightforward. \$\endgroup\$ – xnor May 3 '16 at 11:46
  • \$\begingroup\$ @xnor Not quite distinct, since a) you have to ignore the chunks that contain 2 and b) H==D and S==C for the purposes of comparison. \$\endgroup\$ – Neil May 3 '16 at 11:57
0
\$\begingroup\$

Solve for the Operators

In this challenge, you will be given a bunch of numbers and an answer. Your job is to find a sequence of operators that will successfully solve this equation. Use the numbers in the order that they are given

Operators: +, -, *, /

For example,

Numbers given: 2, 6, 8, 4, 5

Answer: 9

2__3__8__4__5 = 9

The program should find which operators can be used in the blanks to make the equation true. Remember Order of Operations Matters (PEMDAS)

Output:

2*3-8/4+5 = 9

Only 1 solution is needed per problem

Rules

  1. No built-in math functions beyond operators.
  2. Must Follow Order of Operations
  3. Must give one correct output.
  4. Least Number of Bytes Wins.

Examples:

Numbers: 4, 4, 4, 4

Answer: 0

4 - 4 + 4 + 4 = 0

Numbers: 1, 8, 6, 4, 5, 2, 3, 3

Answer: -35

1*8+6-4*5*2-3*3 = -35

Numbers: 1, -2

Answer: 3

1--2 = 3
\$\endgroup\$
  • 2
    \$\begingroup\$ In many languages, this will just be "find the cartesian product of +-*/ repeated as many times as there are blanks with itself, insert them over the blanks and call eval". It's fine if you want that, but it seems somewhat, uh, boring? \$\endgroup\$ – FryAmTheEggman May 5 '16 at 13:26
  • 1
    \$\begingroup\$ 4 - 4 + 4 + 4 = 8 \$\endgroup\$ – trichoplax May 5 '16 at 13:30
0
\$\begingroup\$

Make a times table sheet

The challenge is to make an ascii art version of a times table sheet.

Look at the following:

times tables.

Your answer should have the same layout as this table:

  • You should not include the title or the footer or worry about colors. Black and white is fine.
  • The times tables lines in each box should be randomly ordered.
  • You should include all the horizontal and vertical lines in the image (except in the header and footer).
  • The equals signs should be aligned in each column as in the example above.
  • It should be in ASCII art.

I am not worried about the precise spacing as long as the layout is as specified.

\$\endgroup\$
  • \$\begingroup\$ no ascii art for me? \$\endgroup\$ – Leaky Nun May 6 '16 at 17:41
  • \$\begingroup\$ @KennyLau I could make it ASCII art if people love that. \$\endgroup\$ – user9206 May 6 '16 at 18:22
0
\$\begingroup\$

Challenge

Create a factor tree from a number. A factor tree will take a number > 1, n, and find 2 numbers that multiply together to equal n that are greater than 1. Then, it will repeat for the factors until every section reaches a number that does. Then it will output the last numbers.

For example:

enter image description here

Examples:

Input: n = 20

Graph(This is not the output):

enter image description here

Output: 2x2x2x3

Input: n = 54

Output:2x3x3x3

Input: n = 72

Output: 3x3x2x2x2

Input: n = 2

Output: 2

Scoring

Shortest bytes wins.

\$\endgroup\$
  • 1
    \$\begingroup\$ I think you mean a factor tree, not factorial. That is very different. \$\endgroup\$ – Rɪᴋᴇʀ May 7 '16 at 3:11
  • \$\begingroup\$ @EᴀsᴛᴇʀʟʏIʀᴋ yes that is what i meant. Thank you \$\endgroup\$ – JoshK May 7 '16 at 3:18
  • \$\begingroup\$ Would it be more interesting if i had the output be the tree instead of the numbers? \$\endgroup\$ – JoshK May 7 '16 at 3:20
  • \$\begingroup\$ yeah, I think the numbers is probably a dupe. Plus, it would be more fun/hard. (hard isn't bad) \$\endgroup\$ – Rɪᴋᴇʀ May 7 '16 at 3:20
  • \$\begingroup\$ I recommend having output be a image/ascii art, though that needs more specifications. \$\endgroup\$ – Rɪᴋᴇʀ May 8 '16 at 20:31
  • \$\begingroup\$ As it stands, this is a duplicate of codegolf.stackexchange.com/questions/1979/factorize-me \$\endgroup\$ – user45941 May 13 '16 at 5:27
0
\$\begingroup\$

Inverse Square Probability

It's a fairly well-known fact that the sum of the reciprocals of squares is equal to pi squared divided by 6. That is,

Basel Problem

This is the Basel problem and was solved by Euler in 1735. I was thinking about generating a random patchwork of squares and trying to decide how to weight the probabilities of different square sizes, when it occurred to me that I could use this fact and make the probability of choosing a square's size be the inverse of its size.

For instance, if I pick a random point on the interval [0..pi^2/6), then based on the point I pick, r, I can translate it to a square size in the following manner (all numbers rounded to 3 decimal places):

0     <= r < 1     => s = 1
1     <= r < 1.25  => s = 2
1.25  <= r < 1.361 => s = 3
1.361 <= r < 1.424 => s = 4
1.424 <= r < 1.464 => s = 5
...

Your program or function should work for any input within the limits of your language (for instance, floating point precision, lack of built-in bignum capabilities, etc). Input will always be 0 <= r < pi^2/6.

Test Cases

{to be added}
\$\endgroup\$
0
\$\begingroup\$

ASCII Hulls


Input

A string containing a rectangle made up of m rows of n characters, separated by newlines. Apart from an optional trailing newline (which you may choose), the string must contain nothing else.

All the characters will be printable ASCII (including space). So ASCII characters 32 to 176 inclusive.

The dimensions m and n will not be specified in the input. They will both be in the range 1 to 80 inclusive.

Output

A string containing the same rectangle but with the convex hull of each non-space character filled with that character, higher ASCII values overwriting lower ones.

Overwriting does not prevent a character from contributing to the convex hull. For each character, the convex hull is defined based on the locations of that character before any overwriting.

Details

The rectangle of characters forms a grid of m squares by n squares. The vertices of the convex hull for a given character are the centres of the squares containing that character (apart from any in the interior of the convex hull). All squares whose centre is on the convex hull or in its interior become that character (until any overwriting).

Outline showing convex hull Filled convex hull

Equivalently you can use the top left corner instead of the centre (or any other point in the square) provided it is consistent. This will give the same output.

Test cases

Input followed by output in a single code block

P    
   P
 P  

P    
 PPP
 P


C    C

      G    G
    C    C

   G    G

CCCCCC
  CCCCC
   CCCGGGGGG
    CGGGGGG
    GGGGGG
   GGGGGG


 W    Z
X      X


Y      Y
 W    Z

 W    Z
XXXXXXZX
 W    Z
 W    Z 
YYYYYYZY
 W    Z

Scoring

The shortest code in bytes wins.

\$\endgroup\$
  • \$\begingroup\$ I don't understand what the "convex hull" is here. Could you give an example? \$\endgroup\$ – Nathan Merrill May 10 '16 at 21:55
  • \$\begingroup\$ @NathanMerrill It's a convex hull I think. \$\endgroup\$ – Fund Monica's Lawsuit May 10 '16 at 22:02
  • \$\begingroup\$ @NathanMerrill I added some test cases to visualise it \$\endgroup\$ – trichoplax May 10 '16 at 22:08
  • \$\begingroup\$ @NathanMerrill I added a diagram which hopefully sums it up better \$\endgroup\$ – trichoplax May 10 '16 at 22:52
  • \$\begingroup\$ How do you decide if a letter is within the hull? For example, it seems like the first should be P / PPPP / _PP, because part of the square between the midpoints of each letter is crossed. \$\endgroup\$ – Fund Monica's Lawsuit May 10 '16 at 23:11
  • \$\begingroup\$ @QPaysTaxes All squares whose centre is on the convex hull or in its interior become that character so it isn't enough for part of the square to be crossed - the centre of the square has to be on or within the convex hull. \$\endgroup\$ – trichoplax May 10 '16 at 23:28
  • \$\begingroup\$ Oh, I see. That makes more sense.r \$\endgroup\$ – Fund Monica's Lawsuit May 10 '16 at 23:58
  • \$\begingroup\$ I'm having a bit of trouble deciding for this one, but apart from the fact that there's multiple hulls and ASCII parsing/writing involved, is the core of the challenge any different from existing convex hull challenges? \$\endgroup\$ – Sp3000 May 11 '16 at 5:09
  • \$\begingroup\$ @Sp3000 unless the need to keep track of where the initial characters were while doing the overwriting for other characters adds anything in terms of golfing challenge, then I guess this is a duplicate \$\endgroup\$ – trichoplax May 11 '16 at 14:35
0
\$\begingroup\$

Triangle Rasterization

I don't know if this is the right word for this, but here goes...

Given a triangle with a height and a width, you can convert it into squares by counting any square that the triangle occupies as a whole square. Your task is to calculate the area of this 'rasterized' triangle.

Your program should take two positive integers representing the height and width of a triangle and output the area of its 'rasterized' version. This should always be an integer.

No builtins are allowed, if there are any.

An example

What I'm actually talking about. This is a 6x4 triangle. The red area is the actual inside of the triangle, and the blue area is added on during the 'rasterization'. The total are of the red and the blue is 16. So, given 6 and 4 as inputs, your program must output 16, with or without a trailing newline.

Test cases

 input     output
 1, 1      1
 1, 2      2
 1, 3      3
 2, 2      3
 6, 4      16
 63, 47    1512

As you can probably tell, this is slightly larger than half the area of the enclosing rectangle, and gets more accurate for larger sizes.

Your program should preferably run in under a minute, but the answer with the shortest number of bytes will win.

\$\endgroup\$
  • 1
    \$\begingroup\$ Are you sure about the test case 63, 47? I make it 1535. \$\endgroup\$ – Peter Taylor May 12 '16 at 22:16
  • \$\begingroup\$ @PeterTaylor while fiddling around with a solution I made, I think this error comes from rounding poorly. When I tried adding 1 to each column with a non-integer value and then flooring (I believe this is equivalent to taking the ceiling) I got your answer, but when I tried adding .5 to each value and then flooring I got the value the OP got. For reference: ceil and flop \$\endgroup\$ – FryAmTheEggman May 13 '16 at 18:01
0
\$\begingroup\$

"45-degree rotation" of a square matrix


Introduction

Suppose we have a square matrix with odd sidelength, like this:

0 1 2 3 4
5 6 7 8 9
0 1 2 3 4
5 6 7 8 9
0 1 2 3 4

Let's divide it into nested layers as follows:

0 1 2 3 4
 +-----+
5|6 7 8|9
 | +-+ |
0|1|2|3|4
 | +-+ |
5|6 7 8|9
 +-----+
0 1 2 3 4

The nth layer, counting from the center, contains 8*(n-1) cells, and we rotate it n-1 steps in the clockwise direction:

0 5 0 1 2
 +-----+
5|1 6 7|3
 | +-+ |
0|6|2|8|4
 | +-+ |
1|7 8 3|9
 +-----+
2 3 4 9 4

Now our original matrix has been "rotated by 45 degrees", in a sense:

0 5 0 1 2
5 1 6 7 3
0 6 2 8 4
1 7 8 3 9
2 3 4 9 4

Namely, if this operation is applied twice, the result is a 90-degree rotation.

The task

Your input is an n×n matrix of single-digit integers, where n is odd, in any reasonable format. Your output is the 45-degree rotation of this matrix, as defined above.

Rules and scoring

You can write a full program or function. The lowest byte count wins, and standard loopholes are disallowed.

Test cases

[[3]] -> [[3]]
[[1,2,3],[4,5,6],[7,8,9]] -> [[4,1,2],[7,5,3],[8,9,6]]
[[0,1,2,3,4],[5,6,7,8,9],[0,1,2,3,4],[5,6,7,8,9],[0,1,2,3,4]] -> [[0,5,0,1,2],[5,1,6,7,3],[0,6,2,8,4],[1,7,8,3,9],[2,3,4,9,4]]
[[1,0,0,2,0,0,3],[0,1,0,2,0,3,0],[0,0,1,2,3,0,0],[4,4,4,5,0,0,0],[4,4,4,4,0,0,0],[4,4,4,4,0,6,7],[4,4,4,4,0,8,9]] -> [[4,0,0,1,0,0,2],[4,4,0,1,0,2,0],[4,4,4,1,2,0,0],[4,4,4,5,3,3,3],[4,4,4,0,0,0,0],[4,4,0,6,0,0,0],[4,0,8,9,7,0,0]]
\$\endgroup\$
0
\$\begingroup\$

KOTH Screeps Fighting AI

Screeps is an MMO for programmers (not a regular MMO, this is not modding, but rather the only way to play) where you program creeps. I want to make sure one more time: this is not hacking or modding, this is the only way you play the game. It has a builtin IDE that is always present.

This is your job: With 1550 energy, spawn an army of creeps to fight other player's armies. Your goal is to destroy the other team's spawn.

Specifications

  • Each team will start with 0 creeps and it's own spawn.
  • The team number will be hardcoded.
  • The spawns will be named Spawn1 and Spawn2, corresponding to each player's team
  • The room controller will be at level 8 and you will not have to worry about upgrading it.
  • Each creep will display an emoji chosen to represent it's team using creep.say(). This is so that members of the two teams can distinguished.

Rules

  • Not all creeps have to fight. Some can gather energy, build walls, etc.
  • Building structures is allowed. This includes walls, ramparts, towers, etc.

This is under construction! Please comment if you know how to improve this challenge!

\$\endgroup\$
  • \$\begingroup\$ I recall that in your purely energy gathering Screeps challenge, the example room could be used that did not require paying or creating an account. What is the situation with this new challenge? \$\endgroup\$ – trichoplax May 17 '16 at 19:20
0
\$\begingroup\$

Serialize and Deserialize a Binary Tree!

A coding website, leetcode.com, has a method to serialize a binary tree.

Serialize means making a binary tree linear.

For example, we have:

[1,[[2],[3,4,5]]]

    1
   / \
  2   3
     / \
    4   5

First, we fill the missing places with 0:

      1
     / \
    /   \
   /     \
  2       3
 / \     / \
0   0   4   5

Then read out all the lines from top to bottom:

->      1
       / \
      /   \
     /     \
->  2       3
   / \     / \
-> 0   0   4   5

[1,2,3,0,0,4,5]

Let's look at another example:

   1
    \
     2
    /
   3

Fill the missing places with 0:

   1
  / \
 0   2
    / \
   3   0

Note that 0 cannot have any child.

Therefore, this tree is serialized as [1,0,2,3,0].

Your task is to write two programs/functions, one to serialize, one to deserialize.

Specs

  • They may share code.
  • The binary tree will only contain positive integers.
  • A node in the binary tree is represented by [name,left_child,right_child].
  • You may not pre-fill the binary tree with 0s.
  • [1,0,2,3,0,0,0] is invalid.
  • Unlike the website given, [1,0,2,3] is invalid.

Notes

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

String covering

Given a target string and a list of fragment strings, determine whether the target string can be formed by concatenating fragments, allowing overlaps. Each fragment can be used any number of times.

Example:

cataract, [tar, car, tar, act, rat] -> True

cataract
cat
  tar
     act

Is this a dupe? It's hard to search for. Is it too similar to Imposters at the Zoo?

\$\endgroup\$
  • \$\begingroup\$ Related, related. \$\endgroup\$ – Leaky Nun May 22 '16 at 1:28
  • \$\begingroup\$ This challenge differs from zoo due to the fact that you can't "hide" mismatching parts, so I think it's fine. Not sure if there are any other potential dupes though. (also, I don't think Leaky's "related"s are that related) \$\endgroup\$ – Sp3000 May 22 '16 at 4:25
  • \$\begingroup\$ Just to double check, does "Each fragment can be used any number of times." mean that cancan, [can] -> True? \$\endgroup\$ – Sp3000 May 22 '16 at 6:45
  • \$\begingroup\$ I see a typo: "cat" isn't in the list but "tar" is twice \$\endgroup\$ – user46167 May 22 '16 at 20:18
0
\$\begingroup\$

Primary Chances

Write a program that lists all possible outcomes for a general election with any number of candidates.

Rules:

  • Your answer must output how many states each candidate won in any format.
  • Candidates can have any name.
  • This is , so standard loopholes are forbidden, and shortest code wins.
\$\endgroup\$
0
\$\begingroup\$

Sort 2D points by Sierpiński curve order


[ WORK IN PROGRESS]


Input

A collection of distinct 2D points in the range [0,1] X [0,1].

Output

An ordered collection of the same 2D points, meeting the criteria for Sierpiński curve order.

Sierpiński curve order

  • The points are in the order that the Sierpiński curve would pass through them.
  • The order is cyclic - it does not matter which point is first.
  • The order may be clockwise or anticlockwise/counterclockwise, provided it is consistent.
  • The point at the centre of the range, (0.5, 0.5), may fall into any triangular quarter of the range, provided it is in the correct order among other points in that quarter. Similarly for all other points where both coordinates have finite binary expansion.

Although the curve is infinitely long and fills the unit square, it is arranged in a convenient shape that allows ordering points by calculating only a finite number of iterations. For example, if there are 4 points, one in each triangular quarter of the square, then they can be ordered based only on this information as the curve fills one triangular quarter before moving on to the next so the exact position without that quarter is not relevant.


Sandbox questions

  • Should ambiguous points be allowed to fall in any direction, or should I impose that they always fall left rather than right and up rather than down? Or just insist that the solution choose a consistent direction rule?
  • Can I assume that any three points that can be described by floating point variables can be ordered in a finite number of subdivisions? I'm pretty sure but welcome a counterexample.
\$\endgroup\$
0
\$\begingroup\$

Find ALL Longest Common Substrings

Unlike "Longest Common Substring" algorithm which returns just one string, or the length of it. This algorithm returns a score after taking all separate longest common substrings into account.

This program returns the score of how similar one string is to another according to the following rules:

  1. isolate only the longest (non-overlaping) matching substrings.
  2. score every longest substring found with this formula: (substring.length / ((string1.length + string2.length) / 2)) * substring.length
  3. sum the scores and return.

STEP 1 Example:

string1 = ABCD

string2 = ZBCA

Deconstructing string1: (list of substring in order)

ABCD

ABC

AB

A (also found in string2)

BCD

BC (also found in string2)

B (also found in string2 but ignored - part of a longer substring)

CD

C (also found in string2 but ignored - part of a longer substring)

D

Matches: A, BC

STEP 2 Example: (substring.length / ((string1.length + string2.length) / 2)) * substring.length

A: (1/((4+4)/2)) * 1 = .25

BC: (2/((4+4)/2)) * 2 = 1

Step 3 Example:

.25 + 1 = 1.25, Return 1.25

Here's an example of longer strings of variable length:

string1 = Approximate This

string2 = Appropriate That Thing

Matches: Appro, i, ate Th,  Thi

Appro: (5/((16+22)/2)) * 5 = 1.3157894736842105263157894736842

ate Th: (6/((16+22)/2)) * 6 = 1.8947368421052631578947368421053

i: (1/((16+22)/2)) * 1 = 0.05263157894736842105263157894737

 Thi: (4/((16+22)/2)) * 4 = 0.47368421052631578947368421052632

Return: 4.1052631578947368421052631578948
\$\endgroup\$
1
60 61
62
63 64
102

You must log in to answer this question.

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