# Sandbox for Proposed Challenges

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

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
• 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 needs more feedback, but it's been ignored, you can ask for feedback in The Nineteenth Byte. It's not only allowed, but highly recommended!

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".

Get the Sandbox Viewer to view the sandbox more easily!

(Now I don't know what the name should be)

# Intention

I want to create a challenge based on dependent typing, feature that exists in Idris, Coq, Agda and the similiar.

# Text

You should create a function in dependently typed language (Idris, Coq, Agda, etc) so that:

1. The function will receive a string that denotes format.
2. The format string will have s or n, s means it will receive a string, n means it will receive a number. You can assume that there is no other thing in the string
3. Arguments is received in order. If there is type mismatch, the error must be reported on compile-time.
4. After all arguments is received, the function will return a string, that is list of all passed argument

For example

formatf "sn" "goods" 25
> "goods 25"
> Type error in compile time
formatf "ak" "Akangka" 25
> You can do anything.
formatf "nnn" 24 25
> Either type error or return a function expecting a number and return string (currying is almost universal in these languages)
formatf "ss" "Akangka" "Martin Ender" "Adám"
> Type error on compile time


This challenge is similiar to printf-style string formatting, the difference that the function in this challenge has to be type safe.

Note that you cannot use build-in function or macro to do this

# Discussion

1. What should be the name of this challenge?
• Any reason why full programs are not allowed? May 2 '18 at 9:29
• What happens if the language is not compiled? May 2 '18 at 9:32
• (if you didn't realize, it's not just some languages can't solve it, but in some languages your requirements don't make any sense. There are languages without functions, language with only monadic functions, languages without integers, language without macros, language where macros have different meaning than C #define, language without string (C), etc.) May 2 '18 at 9:59
• If the string is possibly not known at compile time, how can it produce a type error at compile time?
– Angs
May 2 '18 at 10:04
• Personally I think it's a bit too similar to the challenge you linked.. The only difference is validating the input-type with the format.. In which case it would be better to have a challenge dedicated to that, as in: Given this format and a variable amount of other objects, check if the format and types of these objects match. In which case "%s: %i%%", "Percentage", 25 would be truthy, and "%s: %i%%", 123.45, 25 would be falsey. In addition, most languages are type independent, which can change during run-time based on their use.. 10.0 could be all three types in some languages.. May 2 '18 at 10:07
• Suggested re-working of the problem: Given a pattern using only %s and %n (for number), slot in the given list of strings and numbers in the given order, but return a distinct value or throw an error if the given list doesn't fit right.
May 2 '18 at 10:08
• @Angs dependent typing. In fact, this challenge is about dependent typing. May 2 '18 at 10:17
• @user202729 well, by compile-time, I mean about typechecking time. I specifically disallow dynamic typing, as one of the point of the challenge is to make the program fail to typecheck if %s format is supplied by integer, etc. May 2 '18 at 10:21
• @KevinCruijssen Indeed, not all language can do this challenge. After all the intention is on the dependent typing, which most programming language (but not Idris, Coq, etc) lack. May 2 '18 at 10:26
• @Adám nice suggestion. But the type-safe feature (i.e. all error is on type-checking time) is integral part of the challenge May 2 '18 at 10:28
• @Akangka I don't understand why my suggestion doesn't satisfy that. You get a list of strings and numbers and need to check against each tag in the format that you've been given the right tag.
May 2 '18 at 12:12
• I think you should limit to some languages (perhaps extend the language list if needed), as the challenge does not make sense in other languages anyway. May 3 '18 at 1:26
• @Adám I actually implement your suggestion, except the throw an error part. I make the challenge require the result is type error May 3 '18 at 2:03
• @Akangka I don't understand why you insist on language specific features like "type errors" and "compile time". Your examples do not show how to format ss, ns, and nn. You mention float dots, but floats are not part of the examples any more.
May 3 '18 at 5:46
• @Adám thanks about float dots. About language specific features, I just want to create a challenge about dependent typing. May 3 '18 at 6:50

# Challenge:

Your challenge is to write a quine-like program that takes a string from stdin and gives two outputs: Output A is the input string. Output B is your source code.

# Output Formats:

You can send your outputs to stdout, stderr, and/or files. If A and B go to the same output, they must be separated by a newline. Having a newline at the beginning of your source doesn't count. You'd need to print that newline from your source and then another newline to separate A and B.

# Examples:

source: print($stdin+"\n"+codeThatGeneratesSource) input: Hello, World! ### Both outputs on stdout: Hello, World! print($stdin+"\n"+codeThatGeneratesSource)


### Separate Outputs:

stdout: Hello, World!

$hiworld = new hiworld; echo$hiworld->$print; ?>  # Alternate Example Answer format # My Oh so wrong and totally fake Hello world - PHP - Alt.Points(53) <?php class hiworld{public$printme = "Hello World"}
$hiworld = new hiworld; echo$hiworld->\$print;
?>


Attempted with:

50 pts: PSR-2 Foo's Enforcement Hook: Foo-Checker [http://foo.example.com] (Broke)

3 pts: PSR-2 Bar's Enforcement Hook: Bar-Checker [http://bar.example.com]

Deleted Version

• That just makes it better. Mar 8 '19 at 23:29
• Hate as measured by votes, however, is a discrete value, and therefore objective. Mar 8 '19 at 23:37
• While I disagree that pop cons need an objective criterion for voting (anything objectively measurable wouldn't need votes), pop cons are out of favour for that very reason. It is rare for a pop con to be welcomed. Mar 10 '19 at 10:00
• @trichoplax Fair enough on that. I'll change encouragement to just be on coding style. Mar 10 '19 at 22:25
• The problem is mostly the popularity-contest tag, which are very hard to do correctly. For example, how do you define break as many coding conventions as possible? How do you define convention, especially for esoteric languages where there are no conventions? The amount of conventions broken also depends on the poster's and viewer's standards, and is therefore not objective.
– Jo King Mod
Mar 12 '19 at 21:38
• If a voter agrees it violates all the listed coding conventions, upvote the code that violates the most while still functioning is still subjective. All conventions are going to be subjective, e.g. Proper indentation, does that mean 4 spaces or a tab? One voter might think one way, and another might think another way. In general, I think you've chosen a very subjective winning criterion, and short of listing and defining the conventions yourself, it's not going to become objective again.
– Jo King Mod
Mar 13 '19 at 0:06
• I've removed my downvote and the related comment. Mar 13 '19 at 6:59
• The new scoring mechanism is still subjective, but a big improvement. What counts as a convention still seems like a grey area. Does it need to be from an official source, for some definition of official? Does it need to have been posted online prior to the posting of this challenge? Does it need to be stating that coders "must", "should", or something else? Mar 13 '19 at 7:05
• One way to make this objective would be as a language specific challenge, for example with something like JSLint. That way your score is the number of complaints triggered when running it through the linter, and highest wins. Only being able to compete in one language doesn't seem ideal, but I mention it as an example in case someone can come up with a more inclusive approach. Mar 13 '19 at 7:08
• "Whatever makes you feel dirty for having put it through your keyboard" and "Each answer should list and link to coding conventions it breaks" are mutually contradictory. Mar 13 '19 at 12:00
• @trichoplax I do like your idea of counting linter complaints to make it more objective, and feel that's on the right track. Maybe bringing some code-cleanup program into it, and seeing how much work it has to do? Mar 13 '19 at 15:33
• I feel like this could work if one language was selected, with associated style guide/linter, and an objective scoring system made for that. Otherwise, you're comparing a lot of apples and shoes. Mar 14 '19 at 16:36
• I know this probably isn't going anywhere, but the most 'official' python style guide is probably PEP 8. Apr 6 '19 at 18:17
• @liljoshu You've got my upvote for what it's worth, though I agree this needs some improvements. Apr 8 '19 at 22:35
• Something like codegolf.stackexchange.com/questions/172445/… might be ok Apr 10 '19 at 3:04

# Best Mile Time

## Introduction

Your friend has been trying to improve his mile time on. Unfortunately, he isn't very good at keeping a steady pace and constantly speeds up and then slows down. He usually runs for many miles at a time and wants to choose the fastest mile of his run to determine his mile time.

Given your friend's distance versus time, determine his fastest mile time for a contiguous mile stretch.

## Input

A list of distances (in miles) sampled at an even interval.

## Output

The length of the smallest interval during which a distance of at least one mile was traveled.

## Rules

• You may assume that the the total distance traveled is at least 1 mile.
• The mile time must be for a continuous time interval.
• Standard loop-holes are forbidden.
• Standard rules apply.
• This is , so the program with the smallest asymptotic time complexity wins!
• Ties will be broken by fastest run time.

## Example

### Python 3.7, O(n ^ 2)

Try it online!

from typing import List

def fastest_mile_time(distances):
"""Determines the fastest mile time from a list of distances.

Parameters
----------
distances : List[float]
The list of distances in miles.

Returns
-------
int
The length of the smallest interval during which at least one mile was traveled.
"""
intervals = []
for i in range(len(distances) - 1):
for j in range(i + 1, len(distances)):
if distances[j] - distances[i] >= 1:
intervals.append((i, j))
break

return min(map(lambda x: x[1] - x[0], intervals))

• @FryAmTheEggman how's this? Jul 19 '19 at 2:32
• Unless I'm missing something this is trivially O(n): keep two pointers into the list, advance them keeping them 1 mile apart, and keep track of the running minimum time. I'm downvoting, so ping me if I was mistaken or if this is updated so I can update my vote. Jul 19 '19 at 2:52
• @lirtosiast O(n) is trivial. I just gave O(n ^ 2) as an example. However it isn't clear to me that O(n) is the lower bound. I think the fact that the sequence is monotonically increasing may be of some use (although I've yet to show that to be the case). Jul 19 '19 at 3:20
• The optimal solution is O(n). You need to iterate two pointers through the entire list one time to ensure that you have found the minimum valid difference. The range of time this will take ranges from Ω(n) to O(2n) in the optimized case. for(i=j=0;j<length;i++){for(;array[j]-array[i]<1&&j<length;j++){}minTime=min(minTime , j-i)} Jul 20 '19 at 17:00
• Consider a list where every element at even index 2n is n, and every element at index 2n+1 is either n+.5 or n+1. If there is an integer at an odd index, the fastest mile time is 1, otherwise it's 2. But we have no way of determining this without reading all n/2 odd indices. Jul 20 '19 at 18:17
• @lirtosiast +1 thanks for such a clear example! Jul 21 '19 at 6:16

## Produce a self-reproducing data structure

Write the shortest code to produce a self-reproducing list, dictionary, array, and so on and so forth. That is, when you index any one of the logically-available items that belongs to the resulting data structure that you have produced, you get the same data structure when you compare the equality between the data structure before you indexed and the data structure after you indexed.

• In order to verify your code with automatically-provided constructions in programming languages, you should pick an operator that compares whether two values are equal (or does type-comparisons, if available).
• If your language does not provide an equality operator, you should simulate an equality operator yourself using operators like - or other operators that do the job of comparing values (as in Acc!, where an explicit comparison operator is not provided.)

## Example

This is an example of a validity/equality test of a possible solution in a Python REPL (when you have already produced a list, namely list, where it produces itself at its 0th item). This test simply compares the equality between the non-indexed list and the indexed list:

>>> list
[[...]]
>>> list[0]
[[...]]
>>> list==list[0]
True


However, if the result of the last line (the equality comparison) is not a truthy value in your language (for example False and 0 in Python), then your answer is invalid and should be improved.

## Rules

• Your program does not have to take input; neither does it have to explicitly output the data structure. However, your resulting data structure has to be accessible in some way.
• This is a contest; the shortest answer will win.
• In this challenge, the values on both operands in the equality check should have the same type.
• Your code (both your testing code and your producing code) should not produce any errors; any outputs to stderr are considered non-truthy values and demonstrates that your code is invalid.
• What does "compare it" mean? There are many many types of comparison one can perform, and they don't necessarily give the same result for the same values. Jul 24 '19 at 7:11
• @A__ For JavaScript, is it == or ===? Either way, people will be angry. Jul 24 '19 at 13:16
• @A__ Because either the challenge is trivial (['']) or you're arbitrarily restricting a language. Work on your definition of "equality operator". Jul 24 '19 at 13:46
• @A__ So, basically, you want (x=[])[0]=x? No clever tricks? Just a bog-standard recursive data structure? (Though, it might be interesting in languages where those aren't allowed.) Jul 24 '19 at 14:07
• @wizzwizz4 In fact, your program is a clever trick that I have not thought of. Mine is 13 bytes, yours is 11 bytes. Yes, what I want is a bog-standard recursive data structure, as long as it is not a duplicate of another question. (My program is a=[];a.push(a))
– user85052
Jul 24 '19 at 14:10
• @U10-Forward 0 bytes Jul 24 '19 at 14:32
• @tjjfvi I thought about that one, but I didn't think it'd be syntactically valid. It does, however, work. Jul 24 '19 at 15:19
• @wizzwizz4 How do you know which language? Jul 24 '19 at 15:31
• @tjjfvi I just assumed it was a language where the "null" / "undefined" singleton was indexable, returning the very same value. Jul 24 '19 at 15:34
• @wizzwizz4 No, JS: window.window === window :) Jul 24 '19 at 15:38
• @tjjfvi I read the challenge differently to you. I thought it meant "any one of the logically-available items". By this rule, (x={}).x=x is the shortest I can think of, other than the trivial case. Jul 24 '19 at 15:53
• @tjjfvi Well i do it in Python so no such a thing called 0 bytes in python Jul 25 '19 at 1:08
• Alternative: window["window"]===window
– user85052
Jul 25 '19 at 4:06

# Recursive Sum Up The Digits

Produce the shortest code that sums up all the digits in a number, and after if it still has more than one digit, sum it up again and again until it's with one digit, example: 987 would become 6 since 9 + 8 + 7 is 24, whereas 2 + 4 is 6.

• I have the feeling I've seen this challenge before, but I'm unable to find it. It could be that I'm confusing it with two similar loose challenges, since there are more challenges where we continue doing something until a single digit remains, and there are also loads of challenges summing the digits of an integer. I'm not 100% sure anymore whether there is already one with both combined. Aug 5 '19 at 6:37
• This is just "Given n output n % 9". Aug 5 '19 at 7:46
• @PeterTaylor Ah, now I remember where I've seen it before: here in the sandbox, and you (or someone else) made that same comment. :) Aug 5 '19 at 12:24
• Isnt this just a duplicate of codegolf.stackexchange.com/q/1775/87923? Aug 6 '19 at 8:19
• @EdgyNerd It's related, but not a dupe. That challenge takes multiple integers as input simultaneously, instead of a single input. And it outputs the amount of iterations for each of those integers to become a single digit, instead of the resulting digit itself. In addition, it has rather cumbersome output-format.. So that challenge would result in 987 2 for input [987]. The core part of both challenges is the same though: continue summing the digits of an integer until a single digit remains. Aug 6 '19 at 9:16

# Make it improbable... BUT NOT IMPOSSIBLE

You must make a program that outputs truly once in a while. However, making it have output falsy all the time is not acceptable.

## Rules

• Standard loopholes are forbidden.
• You may use any of accepted I/O formats.
• Your program must be possible to output a truly value.
• When not outputting a truly value, you may either output a falsy value or not output anything at all.
• You may output two or more values, however if it contains a truly value, then the output is considered truly.
• The probability of outputting a truly value must be at most 1/2.
• Your program must not take/use an input.
• Using non-deterministic but non-random(Such as getting the time) is prohibited. However, if date etc. is used in the builtin random function, it is allowed.
• The program must theoretically always terminate or stop outputting anything.
• You may assume that you have a fast enough computer and large enough memory.
• Your program should not be affected by raising the maximum value of a data type. You may still use unaffected constants.
• Data types must be following its spec: ie. for an unbounded arbituary precision integer type, you may assume that it can go as high as you want(but you are not allowed to increment until an error as in the rule above), but a double-precision floating-point format still has 22-bit fraction and 8-bit exponent.
• Score is calculated as: Pl-1.5l, where P is the probability and l is the byte length.

## Example(s)

JavaScript
P=0.1, l=24 => Score=23.534


The lowest score wins!

• So is it acceptable for just a program that always outputs truly? You need to define improbable. (I assume this probability must be at least lest than 1/2.) Providing a few examples will be helpful. So is there only output and no input? In addition, you need an objective winning criterion, which is a criterion that posts for this challenge will need to comply in order for it to be a valid answer. (Usually this criterion is making the source code shortest.)
– user85052
Sep 24 '19 at 13:37
• Sorry, I posted this incomplete. Sep 24 '19 at 16:14
• I don't think your scoring method works particularly well, unless I'm making an error. For any $l > 1$ your score cannot be less than 1. Achieving a score arbitrarily close to 1 is relatively easy. So the only way to beat that is to have a one or zero byte solution. It is easy to make the probability increase exponentially with linear code additions. It might be necessary to penalise length massively, like $P \times e^{l!}$, to avoid similar problems. Sep 24 '19 at 18:39
• I see. I guess P^l^k is too penalizing but Pk or Pe^k is too forgiving. Pe^l! looks simple enough but is is the middle so it may work. Sep 24 '19 at 20:11
• The problem with any of scoring methods for this challenge is that it is possible for any increasing computable function f, a program with length l can have P around 1/f(l). The only non-broken formula could be uncomputable, i.e. P/BB(l), where BB is the busy beaver function. Sep 24 '19 at 20:15

# I reverse the source code, you keep the output

Yet another blatant rip-off of a rip-off of a rip-off of a rip-off. Go upvote those!

Your task, if you wish to accept it, is to write a program/function that outputs/returns its own output. The tricky part is that if I reverse your source code, the output must be preserved.

# Examples

Let's say your code is ABC and the corresponding output is XYZ. If I run CBA, the output must also be XYZ

• What's to prevent a trivial solution of just 1 in many (many) languages? Sep 25 '19 at 18:30
• Or trivial comment abuse? Sep 25 '19 at 20:39
• @JL2210 This works in codegolf.stackexchange.com/questions/193315/… print("ABC")#("ABC")tnirp Sep 26 '19 at 15:21
• @AdmBorkBork This works in codegolf.stackexchange.com/questions/193315/… too: 1 is the reverse of 1 Sep 26 '19 at 15:22
• And to both of you: why did these not stop that code golf becoming a challenge? Sep 26 '19 at 15:23
• I didn't say it couldn't be a challenge. I just wanted to point out that this is trivial in many languages. And for what it's worth, I downvoted the challenge you linked for the same reason. Sep 26 '19 at 15:48
• @gadzooks02 That challenge requires you to reverse the input. The input can be anything in that challenge. Sep 26 '19 at 15:49
• @JL2210 Ah yes. Would preserve the input work better? Sep 26 '19 at 16:02
• No, then it would be trivial in Bash and BrainFuck and C and, well, you get the point. Sep 26 '19 at 16:26
• @JL2210 Yes, OK. Do I need to do something if I've decided against a challenge? Delete the post? Sep 26 '19 at 16:29
• No idea. Read over the guidelines, they might help. Sep 26 '19 at 16:31

## print 1000 digits of $$\\pi\$$ base 3

The question was on hold for "unclear what you're asking". Really? What was the real reason?

No input. We need to compute and print the values of $$\\pi\$$ and Euler constant $$\\gamma\$$
to $$\1000\$$ digits after decimal point
in base $$\3\$$ with digits $$\-1,0,1\$$ represented as -,0,+ respectively.

For $$\\pi\$$ output is likely starts with +0.0++-+++-000-0++-++0+-++++++00--++.
$$\\pi\$$ can be computed as series of $$\\tan^{-1}\$$, $$\\gamma\$$ -- like here, or any other method will do if fast enough to provide needed accuracy for at most $$\60\$$ seconds for both numbers.

Storing or using entire pre-computed values are forbidden.
One may though use wolframalpha regular-base-3 values for checking their output -- for $$\\pi\$$ and $$\\gamma\$$ (hit "More digits" some times to get $$\1000\$$).

Scoring method is code-golf, but TIO should run at most $$\60\$$ seconds.
Good luck. Please fell free to improve this post.

• "Storing or using entire pre-computed values are forbidden" is definitely one source of unclarity. What amount of pre-computation could be done? All but the last digit? All but two? Further there doesn't seem to be any reason to ask for two numbers, nor is there a on-site way to check the results. You shouldn't make your answerers have to go to an external site to verify their submission. Nov 21 '19 at 19:43

# Introduction

As programming languages reproduce are created, documentation is even more important for programmers. Your task is simple: output the esolangs.org documentation for your programming language.

With wikis being wikis, languages are heavily penalized in this challenge for being used often and for being interesting to write about, the goal here is to draw attention to languages that may not get utilized otherwise.

# Challenge

For this task, you will need to output the source for the article on esolangs.org for your language, with greater than or equal to 95% accuracy. Your score is your program length in bytes, as in other challenges.

Languages not on this multi-page list of languages as of the time of this posting are ineligible.

Standard loopholes are forbidden.

None

## Output

The source (as of this challenge being posted), for the esolangs wiki page for your language, with at least 95% accuracy.

# Example

Language: ///

Output:

{{featured language}}
'''///''' (pronounced "slashes") is a minimalist [[Turing-complete]] esoteric programming language, invented by Tanner Swett ([[User:Ihope127]]) in 2006 based on [[wikipedia:sed|the "s/foo/bar/" notation that everybody seemed to be using in IRC]]. The only operation is repeated string substitution, using the syntax <code>/''pattern''/''replacement''/</code>. Despite its extreme simplicity – there isn't even an obvious way to create a loop – it was proved [[Turing-complete]] by [[Ørjan Johansen]] in 2009, who created [[#Bitwise Cyclic Tag interpreter|an interpreter]] for the Turing-complete language [[Bitwise Cyclic Tag]].
...

• -1: Interesting idea, but I don't think it can work as a challenge. I'm not convinced that kolmogorov-complexity-ing a volatile data source is a good idea. What happens if the page is edited two weeks from now? Dec 13 '19 at 22:39
• Loophole. I blanked the esolangs.org documentation of my language. Therefore I can output nothing to achieve my goal.
– user85052
Dec 18 '19 at 4:07
• @A̲̲ nope, you have to output what it was at the time of posting Dec 18 '19 at 11:53
• Obviously, you blank the page and then post before it gets fixed. Dec 19 '19 at 13:55

# Background

"The finite element method (FEM), is a numerical method for solving problems of engineering and mathematical physics." -Wikipedia

One of the elementary formulations of fem in structural engineering is the truss. They are very basic, but have a lot of utility.

When one designs a truss, especially in the preliminary stages some assumptions are usually made to simplify the procedure. For instance, members are assumed to carry only tension or compression load. This means that we can only load the truss at the nodals points. Depending on how the connection is designed and detailed, these assumptions can be quite close to how the structure actually will behave in the real world.

So, what's so special about having a member with only axial loading? Well, there's a property of the material itself we can take advantage of. Most materials have a property of 'linear elasticity' when the material is stretched or compressed a very small amount. A material like steel is quite ductile, and so this range of linear elasticiticy is quite large, as compared to something like ceramics. This means if we push or pull on some steel with a small force, it will displace a proportional amount. If we double our applied force, its displacement will double as well. Also if we release our force, the material will go back to its original configuration. So as long as we deform the material elastically, we won't waste any energy deforming it plastically.

If you have ever taken a physics class, you may know that a spring has these exact same properties. Therefore, we can idealize all the members in our truss as just simple springs.

## Building up to direct stiffness method

A zero dimensional spring equation looks like this. $$K \cdot u = F$$ This relates the force required to any deformation of the spring. The force and deformation are linearly proportional by $$\K\$$, the spring constant. The constant $$\K\$$ has units of [force/distance] e.g. [pounds/in] or [kilograms/meter]. For example, if $$\K = 50 lb/in\$$, it would take $$\50lb\$$ of force to displace the spring $$\1\$$ inch, and $$\100lb\$$ to displace the spring $$\2\$$ inches. The stiffness in our truss members is similar:

$$K = \frac{EA}{L}$$

$$\E\$$ is Young's Modulus, $$\A\$$ is the cross sectional area, and $$\L\$$ is the length of the bar. The only scary thing here is probably $$\E\$$, but it's not too crazy. It's kind of like stiffness, but it's normalized. Instead of [force/distance] we have [stress/strain]. Stress is like the normalized force, it's the amount of force over the area of the element. Strain is like the normalized displacement, it's calculated by (change in length/original length) or percent elongation.

Let's develop this a bit more and put it in matrix form. This will allow us to relate the force on one side of the bar to force on the other.

$$\frac{EA}{L} \left[\begin{array}{cc} 1 & -1\\ -1 & 1 \\ \end{array}\right] \cdot \left[\begin{array}{c} u_1 \\ u_2 \\ \end{array}\right] = \left[\begin{array}{c} f_1 \\ f_2 \\ \end{array}\right]$$

Now we have our one dimensional spring equation. Instead of a single displacement, we have a displacement vector. We can displace both sides of the spring independently and find what the resultant forces on each side will be.

Examples:

Displace the right node 1 unit to the right $$\frac{EA}{L} \left[\begin{array}{cc} 1 & -1\\ -1 & 1 \\ \end{array}\right] \cdot \left[\begin{array}{c} 0 \\ 1 \\ \end{array}\right] = \left[\begin{array}{c} f_1 \\ f_2 \\ \end{array}\right]\\ f_1 = \frac{-E A}{L}, f_2 = \frac{E A}{L}$$

This makes sense, because if we displace the right side by a unit, we need a force in the equal and opposite direction on the left side to not drag that side along.

Displace both nodes $$\1\$$ unit to the right $$\frac{EA}{L} \left[\begin{array}{cc} 1 & -1\\ -1 & 1 \\ \end{array}\right] \cdot \left[\begin{array}{c} 1 \\ 1 \\ \end{array}\right] = \left[\begin{array}{c} f_1 \\ f_2 \\ \end{array}\right]\\ f_1 = 0, f_2 = 0$$

This makes sense, because if we displace both sides at the same time, the distance between them does not change. It would be as if we just translated the spring across the table and did not strech it. We don't need some force holding it in a deformed configuration.

That's cool, but one dimensional structures are lame. I want a two dimensional structure to build a bridge! Well, it's not that much more difficult. We just need to add a $$\y\$$ degree of freedom (dof) on each side of the spring. We can also couple our $$\x\$$ and $$\y\$$ dofs into one angle from the $$\+x\$$ direction to simplify our matrix. And so with some magic (rotational matrix) we can get the following:

## Step 1 - Local Stiffnes Matrix

This is our local stiffness matrix, also known as $$\K^e\$$. It has all the same properties as our one dimensional stiffness matrix, but it takes into account $$\(x,y)\$$ displacements at each side of the spring. This gives us a total of four degrees of freedom.

You may begin to see how powerfull this method can be. We can now iterate through all of our elements and just calculate the angle and length from its nodes. This will give us $$\i\$$ local stiffness matrices, where $$\i\$$ is the number of elements. For example if we have $$\3\$$ elements in our truss, we can calculate our $$\3\$$ local matrices for each element.

Let's go through an example.

If we calcualted the local stiffness matrices for the figure above ($$\EA = 1\$$, $$\L(1,2)=1\$$), you would find: $$\hspace{50pt}\begin{array}{cccc}1 & 2 & 3 & 4\\\end{array} \\ K(1) = \begin{array}{c} 1 \\ 2 \\ 3 \\ 4 \\ \end{array} \left[\begin{array}{cccc} 1 & 0 & -1 & 0\\ 0 & 0 & 0 & 0\\ -1 & 0 & 1 & 0\\ 0 & 0 & 0 & 0\\ \end{array}\right]$$ $$\hspace{50pt}\begin{array}{cccc}3 & 4 & 5 & 6\\\end{array} \\ K(2) = \begin{array}{c} 3 \\ 4 \\ 5 \\ 6 \\ \end{array} \left[\begin{array}{cccc} 0 & 0 & 0 & 0\\ 0 & 1 & 0 & -1\\ 0 & 0 & 0 & 0\\ 0 & -1 & 0 & 1\\ \end{array}\right]$$ $$\hspace{50pt}\begin{array}{cccc}1 & 2 & 5 & 6\\\end{array} \\ K(3) = \begin{array}{c} 1 \\ 2 \\ 5 \\ 6 \\ \end{array} \left[\begin{array}{cccc} 0.64 & 0.48 & -0.64 & -0.48\\ 0.48 & 0.36 & -0.48 & -0.36\\ -0.64 & -0.48 & 0.64 & 0.48\\ -0.48 & -0.36 & 0.48 & 0.36\\ \end{array}\right]$$

Where the numbers outside the array correspond to the global matrix indicies.

## Step 2 - Assemble local matrices into the global matrix

These local matricies are uncoupled, and so they don't really tell us much about the global system of the truss, or how to solve for the displacements with given forces. However, we can do something called matrix assembly to put them all into one big global stiffness matrix. This will couple all of our local element equations so we can solve our system of equations.

We do this by matching the local degrees of freedom to our global degrees of freedom, then add our local to our global matrix.

Since our global truss has 3 nodes and each node has $$\2\$$ dofs $$\(x,y)\$$, our global matricies are of size 6. $$\K \in \mathbb R^{6 \times 6}, F \in \mathbb R^{6 \times 1}, u \in \mathbb R^{6 \times 1}\$$. If we layed out the dof number for each row/column of our stiffness matrix we would get the following:

$$\hspace{35pt}\begin{array}{cccccc}1 & 2 & 3 & 4 & 5 & 6\\\end{array} \\ K = \begin{array}{c} 1 \\ 2 \\ 3 \\ 4 \\ 5 \\ 6 \\ \end{array} \left[\begin{array}{cccccc} 0 & 0 & 0 & 0 & 0 & 0\\ 0 & 0 & 0 & 0 & 0 & 0\\ 0 & 0 & 0 & 0 & 0 & 0\\ 0 & 0 & 0 & 0 & 0 & 0\\ 0 & 0 & 0 & 0 & 0 & 0\\ 0 & 0 & 0 & 0 & 0 & 0\\ \end{array}\right]$$

From step 1, the global dofs of $$\k(1)\$$ were $$\1,2,3,4\$$. This means we just add them index by index into our global stiffness matrix.

$$\hspace{35pt}\begin{array}{cccc}1 & 2 & 3 & 4\\\end{array} \\ k(1) = \begin{array}{c} 1 \\ 2 \\ 3 \\ 4 \\ \end{array} \left[\begin{array}{cccc} k_{11} & k_{12} & k_{13} & k_{14}\\ k_{21} & k_{22} & k_{23} & k_{24}\\ k_{31} & k_{32} & k_{33} & k_{34}\\ k_{41} & k_{42} & k_{43} & k_{44}\\ \end{array}\right]$$

If we match up the indicies, we can just add: $$K_{11} += k_{11}\\ K_{12} += k_{12}\\ K_{13} += k_{13}\\ K_{14} += k_{14}\\ K_{21} += k_{21}\\ ...$$

We can see if we do this for all three elements, we can match up where they will go in the global matrix with colors. This is shown in the figure below.

## Step 3 - Add bounds on the stiffness matrix, and modify the force vector

We are almost done! But there is one final important step. If we were given an arbitrary force vector and tried to find the displacements, our truss would just fly away to infinity. This is because there are no boundary conditions! There is nothing yet holding on to it, resisting the forces. But guess what? There's another neat trick we can use. This will keep everything in matrix form and give us the answers we want when we solve our system of equations.

All we do is remove the influence of the node on the force vector. For this example, we will assume the constraint on dof1 is set to $$\g\$$.

For the general case, we just set $$\dof1 = g\$$ in the force vector, and subtract g* the column of $$\K\$$ with dof1 = 0. If $$\g=0\$$, we just need to set $$\dof1 = 0\$$ in the force vector.

$$F = \left[\begin{array}{c} F_1\\ F_2\\ F_3\\ \vdots\\ F_n\\ \end{array}\right] \Rightarrow \left[\begin{array}{c} g\\ F_2\\ F_3\\ \vdots\\ F_n\\ \end{array}\right] - g \left[\begin{array}{c} 0\\ K_{21}\\ K_{31}\\ \vdots\\ K_{n1}\\ \end{array}\right]$$

Then we just restrain our stiffness matrix. This can be done by zeroing out the row and column of $$\dof1\$$, then setting $$\(dof1,dof1)=1\$$ as shown below.

$$K = \left[\begin{array}{cccc} K_{11} & K_{12} & \cdots & K_{1n}\\ K_{21} & K_{22} & \cdots & K_{2n}\\ \vdots & \vdots & \ddots & \vdots\\ K_{n1} & K_{n2} & \cdots & K_{nn}\\ \end{array}\right] \Rightarrow \left[\begin{array}{cccc} 1 & 0 & \cdots & 0\\ 0 & K_{22} & \cdots & K_{2n}\\ \vdots & \vdots & \ddots & \vdots\\ 0 & K_{n2} & \cdots & K_{nn}\\ \end{array}\right]$$

## Step 4 - Solve with linear algebra

Now we are finally back to our equation of a spring. However, in this case each variable below is an array or vector of size $$\n\$$, where $$\n\$$ is the number of $$\nodes \times 2\$$.

$$\mathbf{K} \cdot \mathbf{u} = \mathbf{F}$$

We can simply solve this system of equations by taking the inverse of the stiffness matrix. This gives us:

$$\mathbf{u} = \mathbf{K}^{-1} \cdot \mathbf{F}$$

This can be easily solved by a computer. For example Python:

    u = np.linalg.solve(K, F)


# Rules

• Input data type can for the most part be changed for your needs. However, it should be human-readable, or at least reasonable to be able to change the input for a new structure easily.

Example input

E = .
A = .
nodes = [., ., ...]
elements = [., ., ...]
forces = [., ., ...]
bounds = [., ., ...]


Example output

[., ., ...]

• Output can be in any form, as long as it's in order of dof.
• Inbuilt FEM functions not allowed. You must construct and assemble your matrices yourself. Inbuilt linear algebra is fine.

# Test Cases

From UNM example in references:

E = 29500
A = 1
nodes = [[0,0],[40,0],[40,30],[0,30]]
elements = [[1,2],[2,3],[1,3],[3,4]]
forces = [[0,0],[20,0],[0,-25],[0,0]]
bounds = [[0,0],[None,0],[None,None],[0,0]]


Output:

[0.0 0.0 0.027 0.0 0.006 -0.022 0.0 0.0]


Large Truss Input:

E = 29000
A = 25
nodes = [[0,0],[100,0],[200,0],[300,0],[0,100],[100,100],[200,100],[300,100],[400,100]]
elements = [[1,2],[1,5],[1,6],[2,3],[2,6],[2,7],[3,4],[3,7],[3,8],[4,8],[4,9],[5,6],[6,7],[7,8],[8,9]]
forces = [[0,-10],[0,-10],[0,-10],[0,-10],[0,0],[0,0],[0,0],[0,0],[0,-10]]
bounds = [[0,0],[None,None],[None,None],[None,None],[-0.01,0],[None,None],[None,None],[None,None],[None,None]]


Output:

[ 0.     0.    -0.008 -0.025 -0.012 -0.061 -0.014 -0.1   -0.01   0.     0.004 -0.019  0.012 -0.057  0.016 -0.098  0.018 -0.136]


Here is what the geometry and displacement looks like for the test cases so you can visualize it.

# References

Here are some references that may be useful if you are looking for some more in-depth information.

http://www.unm.edu/~bgreen/ME360/Finite%20Element%20Truss.pdf

https://engineering.purdue.edu/~aprakas/CE474/CE474-Ch5-StiffnessMethod.pdf

http://people.duke.edu/~hpgavin/cee421/truss-method.pdf

http://ocw.ump.edu.my/pluginfile.php/9806/mod_resource/content/2/7_Plane_Truss_Example.pdf

https://nptel.ac.in/content/storage2/courses/105105109/pdf/m4l24.pdf

And lastly, here is some working python 3 code that I wrote. It should lay out all the steps cleanly.

import numpy as np
from math import sqrt,sin,cos,acos

def ex_unm():
"""Example - Verification from UNM"""
print("Example UNM")
# Material Properties
E = 29500 # (units = ksi)
A = 1 # (units = in^2)
# Node locations (units = in)
nodes = {1:(0,0), 2:(40,0), 3:(40,30), 4:(0,30)}
# Element connections
elements = {1:(1,2), 2:(3,2), 3:(1,3), 4:(4,3)}
# Nodal forces (units = kips)
forces = {2:(20,0), 3:(0,-25)}
# Nodal Boundaries (units = in)
bounds = {1:{'x':0,'y':0},2:{'y':0},4:{'x':0,'y':0}}
# Run Analysis
displacements = analyze(E,A,nodes,elements,forces,bounds)
for i,disp in enumerate(displacements):
print("Node {},{}: {}".format(int(i/2)+1,['x','y'][i%2],round(disp,5)))

plot_truss(nodes, elements, displacements, 200)

def ex_big_boi():
"""Example - Large Truss"""
print("Example BIG BOI")
# Material Properties
E = 29000 # (units = ksi)
A = 25 # (units = in^2)
# Node locations (units = in)
nodes = {1:(0,0), 2:(100,0), 3:(200,0), 4:(300,0),
5:(0,100), 6:(100,100), 7:(200,100), 8:(300,100), 9:(400,100)}
# Element connections
elements = {1:(1,2), 2:(1,5), 3:(1,6),
4:(2,3), 5:(2,6), 6:(2,7),
7:(3,4), 8:(3,7), 9:(3,8),
10:(4,8), 11:(4,9),
12:(5,6), 13:(6,7), 14:(7,8), 15:(8,9)}
# Nodal forces (units = kips)
forces = {1:(0,-10), 2:(0,-10), 3:(0,-10), 4:(0,-10), 9:(0,-10)}
# Nodal Boundaries (units = in)
bounds = {1:{'x':0,'y':0}, 5:{'x':-0.01,'y':0}}
#bounds = {1:{'x':0,'y':0}, 5:{'x':0,'y':0}}
# Run Analysis
displacements = analyze(E,A,nodes,elements,forces,bounds)
for i,disp in enumerate(displacements):
print("Node {},{}: {}".format(int(i/2)+1,['x','y'][i%2],round(disp,5)))

plot_truss(nodes, elements, displacements, 500)

"""Visualization, not really needed but may be good to see"""
import matplotlib.pyplot as plt

def plot_truss(nodes, elements, u, scale):
"""A very simple plot to show geometry and displacements of nodes"""
x = [coords[0] for node,coords in nodes.items()]
y = [coords[1] for node,coords in nodes.items()]
ux = x + u[::2] * scale
uy = y + u[1::2]* scale

fig,ax = plt.subplots()
# Plot original Points
ax.plot(x,y,'o',color=(0.5,0.5,0.5))
# Plot original Elements (Theres probably a better way to do this)
for element,eleNodes in elements.items():
ex = [x[i-1] for i in eleNodes]
ey = [y[i-1] for i in eleNodes]
ax.plot(ex,ey,color=(0.5,0.5,0.5))

# Plot displaced Points
ax.plot(ux,uy,'o',color=(0,0,1))
# Plot displaced Elements (Theres probably a better way to do this)
for element,eleNodes in elements.items():
ex = [ux[i-1] for i in eleNodes]
ey = [uy[i-1] for i in eleNodes]
ax.plot(ex,ey,color=(0,0,1))

# Make plot have same xy scale
ax.axis('equal')
#fig.tight_layout()
ax.set_title("Truss Geometry and Displacement, Scale = {}".format(scale))

def analyze(E, A, nodes, elements, forces, bounds):
"""Analyze a given system and return the nodal displacements"""
# Assemble global matricies
K = gen_global_K(E,A,nodes,elements)
F = gen_global_F(nodes,forces)
#F = restrain_stiffness(K, F, bounds)
restrain_stiffness(K, F, bounds)
# Solve K*u=F -> u=K^-1*F
u = np.linalg.solve(K, F)
# return the nodal displacements
return u

def gen_global_K(E, A, nodes, elements):
"""Generate the Global stiffness Matrix"""
# Initialize Global Stiffness Matrix
size = len(nodes)*2
K = np.zeros([size,size])

# Itterate through each element and add its local stiffness to global stiffness
for element,(node_1,node_2) in elements.items():
node_1_xy = nodes[node_1]
node_2_xy = nodes[node_2]
# Element length
L = sqrt((node_2_xy[0]-node_1_xy[0])**2 + (node_2_xy[1]-node_1_xy[1])**2)
# Get this element's local stiffness roated into global plane
K_local = (E*A/L) * gen_local_K(node_1_xy, node_2_xy)
# Assemble local matrix into global
assemble(K, K_local, node_1, node_2)
return K

def gen_local_K(n1, n2):
"""Create a local stiffness matrix from two nodes' angle"""
angle = gen_angle(n1,n2)
c  = cos(angle)**2
s  = sin(angle)**2
cs = cos(angle) * sin(angle)
# Create the local K matrix
K_local = np.array([[ c , cs,-c ,-cs],
[ cs, s ,-cs,-s ],
[-c ,-cs, c , cs],
[-cs,-s , cs, s ]])
return K_local

def gen_angle(n1, n2):
"""Find angle between two nodes and +x axis"""
v1 = np.array([n2[0]-n1[0],n2[1]-n1[1]])
v2 = np.array([1,0])
return acos(np.dot(v1,v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)))

def assemble(K, K_local, n1, n2):
"""Assemble a local element stiffness matrix into the global stiffness"""
# Degrees of freedom of our local element
dofs = [2*(n1-1), 2*(n1-1)+1, 2*(n2-1), 2*(n2-1)+1]
# Go element by element to add matrix
for i_local,i_global in enumerate(dofs):
for j_local,j_global in enumerate(dofs):
K[i_global,j_global] += K_local[i_local,j_local]

def gen_global_F(nodes, forces):
"""Generate the global force vector"""
F = np.zeros(2*len(nodes))
for node,(f_x,f_y) in forces.items():
dof = 2*(node-1)
F[dof] = f_x
F[dof+1] = f_y
return F

def restrain_stiffness(K, F, bounds):
"""Use a given displacement bound to modify matricies"""
dir = {'x':0, 'y':1}
for node,this_bound in bounds.items():
for coord,disp in this_bound.items():
# Get what dof the bound is
dof = (node-1)*2 + dir[coord]

"""Move the fixed displacement over to F (since it's constant)"""
# Get displaced F by reducing by given displacement * stiffness column
# Must use -= to ensure python evaluates in-place
#   We don't need to return the array if it's passed by reference
F -= disp * K[:,n]
# Set the Force value at that dof to the given displacment
F[n] = disp
# Clear stiffness matrix dof row & col

"""Zero out row and col of dof, then make [n,n] = 1"""
for i in range(np.size(K,0)):
K[n,i] = 0
K[i,n] = 0
K[n,n] = 1

if __name__ == "__main__":
# Set print options if you want to print an array nicely (easier for debug)
np.set_printoptions(precision=2, suppress=True, linewidth=np.inf)
ex_unm()
ex_big_boi()

plt.show()


Good Luck!

• Really cool introduction to FEM! I allowed myself to make some corrections and convert some more equations to mathjax, I hope you are ok with that. Some points I noticed that I would suggest improving: If you introduce a new variable, always describe what it is: It doesn't seem clear from the start what $u$ is (displacement?) or how $\beta$ is defined. Then I'd also try to make the indexing consistent: I'd always use the indices like $K_i$ insetad of $K(i)$. Dec 28 '19 at 14:32
• Similarly I'd avoid reusing the same symbol: For example for $k(1)$ you reuse the symbol $k$ for its entries, so I'd recommend rewriting it as maybe $\vec k_1$. Dec 28 '19 at 14:35
• You talk about the degrees of freedom "dofs", aren't these just the entries of $u$? Dec 28 '19 at 14:37
• And what type of challenge is it anyway? code-golf or something else? Dec 28 '19 at 14:37
• Thanks! Yea, the u vector is the displacement of each node. It is common to have it in the form {node1 x, node1 y, node2 x, node2 y.,,,}. Each element of the vector would be a degree of freedom, and together they would be the degrees of freedom of the entire structure. However, the u vector is not the actual degrees of freedom, it is just the displacements at each degree of freedom. For instance, the force vector would have a force at each degree of freedom. I think it wold be standard code-colf, least bytes wins, however I'm not sure if there's a better challenge it should go into. Dec 29 '19 at 4:21

# 101 Hello Worlds

I have a project where I'm trying to collect 101 versions of "Hello, World" using obscure and over-engineered approaches in JavaScript/Node.js:

https://github.com/georgemandis/101-hello-worlds

We're up to 38 so far and I've really enjoyed the community contributions.

I recognize the way this is phrased at the moment isn't compatible with the way Code Golf is setup, but I feel like there could be a large overlap with people who might be interested and this community.

Does this seem like something that would be welcome here? Would others have suggestions for how I might re-word this to create a suitable entry for Code Golf?

If it's not suitable or welcome here I respect being downvoted into oblivion and can remove the answer.

Thanks!

• Thanks for using the Sandbox. The answer is that no, this isn't really suited to the Code Golf site. The closest winning criterion to use would be popularity-contest, but that was retired a while ago, since it wasn't really objective. If you want inspiration though, you can look at the hello-world tag, which has a lot of interesting restrictions on hello world programs. For example, there's no repetition, radiation-hardened, polyglots, palindromes etc.
– Jo King Mod
Feb 11 '20 at 4:52
• Thanks @JoKing. I'll take a look at that tag. I think I'll add a tag to it in my project's README as well to give other people inspiration. Feb 11 '20 at 14:28

# Hello, World, but looong

I couldn't find out that this challenge exists

If this challenge exists, let me know

Write a simple Hello, World! program.

The winner is the person who has the longest code.

However, any subsequence except itself cannot be the answer.

## Input

You can have input in which way.

## Output

Hello, World!

Feb 13 '20 at 13:07

# Write an if/else statement from scratch code-golfrestricted-source

I am new to this community, so please do not hesitate to point out edits and clarifications in this post. Also note that this is just a loose draft for the question. There are several improvements to be made..

We all use if/else statements in our daily programming life (except the oldies who write Machine code). However, put your feet in a young programmer's shoes. If you wanted to write the if/else statement, what would you do?

So basically you have to re-design or recreate the if/else statement in any language of your choice.

The if/else statement should obviously not use if/else from any other language. This does not mean that we can use a statement that has some other name in other languages, no function/statement that produces if/else statement behavior can be used.

So this means that functions like case etc. which can be used in substitution with if-else cannot be used. Neither can you use while loops to simulate an if/else....

### Ideas:-

On posting this as a question there were a lot of people saying that the challenge was not clear. Can anyone edit or point the mistakes in the lines or think that they can make the question a bit more clear?

In the simplest words, it is a challenge to write the if/else statement without using any of its counterparts (like in other languages it has other names) which can be used with a syntax for general cases. For example, it should be able to compare:-

arrays
lists
dicts
other data types (heap, stack,tree)
strings


Everything a normal if/else can do.

• Apr 26 '20 at 13:49
• 1+ have the command #, which pops a stack and jump to the nth # in the program. Is using # allowed?
– null
Apr 26 '20 at 13:57
• Some languages do not have conditional statements, and some have only a while loop. Some languages may not have any of your listed data types. You don't know, so it's suggested that you don't write a challenge based on that assumption. Apr 26 '20 at 13:57
• @HighlyRadioactive # is a kind of goto, so it's definitely allowed.
– user92069
Apr 26 '20 at 14:15
• @petStorm Okay then, but I guess we are still waiting for the OP to clarify. Is it allowed to assume there are no #s before the snippet?
– null
Apr 26 '20 at 14:19
• I think that # can be allowed as long as it works for most of the data types. Atleast commmon types like string, integers, array should work with it.... Apr 26 '20 at 14:51
• @S.S.Anne I think that languages that have only a have a while loop are automatically disqualified. So any answerer should not use them. What about making esoteric languages compulsory? I am sure it will be very tough and feel like a real challenge! Apr 26 '20 at 14:54
• From the same page, this is also discouraged: Explicitly disallowing or disadvantaging arbitrary (classes of) languages. Going against the things to avoid guidelines will generally mean that your question will be downvoted and/or closed. Try to write a challenge that doesn't do anything that's listed there and it will be more likely that your question will get upvotes and will stay open. Apr 26 '20 at 14:56
• How can you tell what's an if/else/switch/loop and what's not? This fulfills your requirements, for example: ,[.[-]]+[-[.]]. I could argue that this contains none of these but you'd never know if it did or not. Apr 26 '20 at 15:03
• @S.S.Anne So what do you think is the best course of action to take? I don't want to scrap this question because it is really good at its core (but not the best in a practical scenario) Could anyone suggest a very innovative fix so that this question remains a good one? Apr 26 '20 at 15:16
• You should also look at this. I think you should define more clearly what do you want the if-else statement to allow doing. should it allow executing code that can be substituted, given as input based on an input falsy/truthy value? Apr 26 '20 at 16:10
• I agree that this is far from clear. One additional question I have, is what must we be able to do within our if/else replacement. Do we have to be able to run arbitrary sequences of lines of code? Or is just producing a value enough? Note that some languages make a distinction between statements and expressions, and may have if/else constructs for one or both situations.
– xnor
Apr 26 '20 at 20:15
• @neelg As far as I know most Esolangs does not have string and array (as an object). For example, there is only one type in 1+, that is, unsigned integer.
– null
Apr 26 '20 at 23:58

# Produce the next Italy number code-golfintegersequence

This is the third post for the second RGS's Golfing Showdown.

Italy is a Southern European country that was greatly devastated by the impact of the coronavirus crisis in its fairly aged population. As of the 27th of April, Italy was roughly 600 cases short of hitting 200.000 total confirmed cases.

Your task is to produce the total number of confirmed cases on day n+1 given the total number of confirmed cases on day n, with n going from the 21st of February 2020 to the 10th of April 2020, as per Wikipedia's data, obtained at 19:38 27/04/2020 UTC.

For your convenience, these are the 20 numbers involved; the first 19 are inputs and the last 19 are outputs.

[20, 79, 150, 229, 322, 445, 650, 888, 1128, 1694, 2036, 2502, 3089, 3858, 4636, 5883, 7375, 9172, 10149, 12462]


# I/O

I/O should be integers or reasonable representations of those, with the restriction that your code must accept as input its own output.

# Test cases:

20 -> 79
79 -> 150
150 -> 229
229 -> 322
322 -> 445
445 -> 650
650 -> 888
888 -> 1128
1128 -> 1694
1694 -> 2036
2036 -> 2502
2502 -> 3089
3089 -> 3858
3858 -> 4636
4636 -> 5883
5883 -> 7375
7375 -> 9172
9172 -> 10149
10149 -> 12462


Python reference implementation

• Can we use ResourceObject["Epidemic Data for Novel Coronavirus COVID-19"] for Mathematica? (it involves fetching the data from a server, but 1) it's still built-in 2) so do many SomethingData functions for the first time). Apr 28 '20 at 1:47
• @mypronounismonicareinstate if that is not against some loophole, sure. Just make sure the numbers coincide with the numbers I posted
– RGS
Apr 28 '20 at 6:00
• How is this not a hard-code the data challenge? Is there any possible relation? Because otherwise, it seems really boring. Apr 29 '20 at 0:54
• @S.S.Anne thank you for your feedback; I changed the task and reduced the total amount of days we are dealing with. Please let me know if this looks more sensible.
– RGS
Apr 29 '20 at 18:40
• It's better, but I still don't see how this couldn't be solved without just a big array. Apr 29 '20 at 19:06
• @S.S.Anne someone will think of something! Hopefully :)
– RGS
Apr 29 '20 at 19:15
• You can't just hope that someone will find some interesting way to solve your challenge to make a boring challenge interesting. The shortest way I see to solve this right now is to hard-code the data, which is probably what everybody will do. Apr 29 '20 at 19:22
• Just graph your data, see how much it deviates from only a simple parabola? Apr 29 '20 at 19:29
• Maybe you could allow some small error bound on the output (say 10%)? Then the challenge would become about finding a model that approximates the data well, rather than hardcoding values Apr 29 '20 at 20:16

# Make an Anti-compressor (WIP)

Create an algorithm that reversibly and losslessly makes files bigger. You must create the anti-compressor. The de-anti-compressor can be your own creation or something that already exists. The two programs do not need to be written in the same language.

### Objective Validity Criteria

• Inputs into the anti-compressor can be binary files using any or all byte values.
• All inputs into your anti-compressor must produce outputs that are at least one byte longer.
• The anti-compressor is losslessly reversible by either an existing program or your own.
• The de-anti-compressor must work on (at least) all possible outputs of the anti-compressor.
• Both the anti-compressor and de-anti-compressor can be executed on an actual computer. Keep execution time within reason (e.g. no $$\O(n!)\$$ programs, please)

This will be a unless I get a good suggestion for an objective scoring system.

My only idea so far is that the score could be based on the decompression ratio, cancelled out by how well gzip compresses the output. Unfortunately, this could be abused easily by inserting arbitrarily large amounts of random padding between significant bits of information, leading to an unbounded score that can always be beaten with trivial modification.

• Besides the usual issues with pop-cons, I'd really have no idea how to vote because the task is so broad and I don't know what's meant to be interesting in an answer.
– xnor
May 11 '20 at 20:00
• @xnor that's fair. I'm not entirely sure if this challenge is a good idea in the first place, but I got an upvote earlier, so I thought it might be worth it to refine it and see where it goes. I could see the subjective criteria being along the lines of the funniest or most clever way of anti-compressing a file. Injecting filler data, random or not, is not very clever, but having it output an overly verbose java program that outputs the original file when executed is both humorous and clever- but perhaps not as much as other ideas I haven't even thought of. May 11 '20 at 23:09
• @Λ̸̸ The issue with that scoring system is that you can always make a file more bloated. Someone doubles every byte? I can just triple every byte. That kind of oneupmanship is not interesting. I can try to put limits on exactly what kind of bloating is allowed so that there is some sort of soft upper bound, but then the challenge becomes one of abusing the rules and finding clever interpretations and loopholes- also not very interesting. May 12 '20 at 15:08
• I have an idea: make the answerer choose an existing compression algorithm, and then create an anti-compression program given an input string.The anti-compressed string, when compressed with the chosen algorithm, must produce the exact same output as the input. That way, the anti-compressing method of randomly inserting characters in the input string can be avoided, since there isn't a way to un-double speak a given input character, and for a string with randomly inserted characters, the compressor will not know which characters to leave out during the compression.
– user92069
May 13 '20 at 2:36
• Given that, the scoring criterion can now be simply code-golf, since there isn't a way to create boring answers, and the only possible way to score answers left is just code-golf.
– user92069
May 13 '20 at 2:38
• @Λ̸̸ At that point, it would make more sense to make a jillion different code-golf challenges since this essentially defines an entire class of golfing challenges. May 13 '20 at 16:32