569
\$\begingroup\$

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

Sandbox FAQ

Posting

To post to the sandbox, scroll to the bottom of this page and click "Answer This Question". Click "OK" when it asks if you really want to add another answer.

Write your challenge just as you would when actually posting it, though you can optionally add a title at the top. You may also add some notes about specific things you would like to clarify before posting it. Other users will help you improve your challenge by rating and discussing it.

When you think your challenge is ready for the public, go ahead and post it, and replace the post here with a link to the challenge and delete the sandbox post.

Discussion

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

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

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

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

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

Other

Search the sandbox / Browse your pending proposals

The sandbox works best if you sort posts by active.

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

\$\endgroup\$
0

4562 Answers 4562

1
145 146
147
148 149
153
-2
\$\begingroup\$

The Tiniest Generic Evolutionary AI



Introduction

The smallest program you can make (measured in bytes) that builds evolving AIs that parses unknown text string A into unknown text string B that still evolves.

All languages are options. Internet connectivity is allowed (but not providing any specific links). The AI must have a choice of commands (allowing variables) from a Turing Complete instruction set.


Scoring

Scoring is two fold: N = Number of bytes of program (ignoring size of AIs generated)

T = The average generations (generations of 200 AIs or less) before your program can evolve an AI that can do the 5 test cases.

Score = 1000/(N*T)


Challenge

Rules: Using the fewest bytes possible, create a generic evolutionary AI that will evolve to parse one supplied but previously unknown string into another supplied but previously unknown string.

What qualifies as an evolutionary AI in this context:

Your Code
Takes an input string
Takes a seed AI Instruction Set(s)
Runs AI Instruction Sets
Rates Each AI Instruction Set against others and against test strings
Evolves AI to create a new set of AI Instruction Set(s) through random mutation and breeding of existing AIs.
=================
AI Code
Is not written by you (except for possibly a seed AI), to be created by your program instead.
Uses a set of *available* instructions that are or are inspired by a known Turing complete instruction set (such as RISC)
Should consist of references to the available instructions and values for them.
  1. The code you write does not parse the strings directly. Instead, it writes output that is a collection of instructions, and reads in a collection of instructions and applies these instructions. (Ugly as it may be, eval is allowed).

  2. It reads in multiple optional instruction sets.

  3. It rates those instruction sets based on which gets closest to parsing the input string into the target string.

  4. The best performing instructions sets are encouraged in some way.

  5. The worst performing instruction sets are discouraged and/or eliminated in some way.

  6. Using existing AI-oriented libraries is discouraged.

  7. Allowing evolutionary AIs to use develop using a turing-complete set of instructions is encouraged. (Example solution uses a modified RISC instruction set.)

  8. Instruction sets must be able to mutate (randomly change) between generations. They are allowed to breed (selectively change) between generations as well.

  9. Multiple iterations of comparing and evolving instructions sets is possible.

  10. How quickly your AIs evolve or how well they do the job doesn't matter so much as they can get better at the task over iterations.

  11. A seed starting instruction set is allowed. If your solution requires an inputed file for an initial instruction set, a functional example is required and counts towards the byte count.

  12. It handles if an instruction set it runs fails to complete, or times out if an AI instruction set goes on too long (default to 30 seconds).

  13. Program must accept in one arbitrary string from a source. (Your choice of a generic commonly used source, such as a web form, command line, or file). It outputs each AI instruction set's result in a similar format it took them in. It may also optionally accept a starter AI set of instructions.

  14. The AI code never gets to interact with the test string it's being graded against.

  15. Your program cannot do any string conversions on the input string on its own, only may act as it's instructed to by the AI.

  16. A seed AI is not allowed to have anything more than a start, end, or return call of some kind (it must evolve any processing steps on its own).


Test Cases:

Can the program evolve an AI that approaches being capable of string conversion of an unknown conversion? (It is recommended not to build the AI to these specific test cases, these are for the point of testing genericness. Do not specifically target these cases until reporting results, and others testing your program may test them against other string conversions and rate accordingly.)

Five examples follow -

abcdefghijklmnopqrstuvwxyz

will be converted into

zyxwvutsrqponmlkjihgfedcba

or possibly

1010101100110101011001

will be converted into

0101010011001010100110

or possibly

"Mary had a little lamb."

will be converted into

"Gary had a little ham."

or possibly

"Banana"

will be converted to

"Banananananananananananananananana."

Or maybe

The entire text of the Bible

will be converted to

The entire text of the Bible, but every instance of "sheep" is replaced with "codfish".


Short Diagram of interaction.

   STEP 1                         STEP 2                     STEP 3  ...

 Input String           ->
 Expected Output String ->   Your Code Starts  ->    Assorted AI Instruction sets. ->      ->        ->       ->      Your Code Processes AI Instruction Sets -> Your code compares, mutates, and breeds AIs to create new generation -> Return to Step 3
 Seed AI                ->                     (Example: AI1 -> Start(Input); Output(Input)
                                                         AI2 -> Start(Input); CP(Mem1, Mem2); Output (Mem2);)

Example

An on-a-whim project done that roughly followed these rules and inspired this challenge that ran <1000 lines of code (although short, it did not aim for minimal characters.)

myLittleAI

\$\endgroup\$
11
  • 1
    \$\begingroup\$ There are a lot of restrictions and rules, however there is no clear description of the task itself: What does "parse one string into another string" mean? About the rules: Overriding loop-holes such as allowing internet-connectivity is likely to create problems or allow boring answers. "Answer must evolve using options that are or are inspired by a Turing complete instruction set." seems like it's a non-observable requirement (and you override the rule in the second rule anyways). Why do you want to disallow libraries? \$\endgroup\$ Sep 22, 2018 at 23:01
  • \$\begingroup\$ Some of the other rules don't make sense to me, but it's likely to be caused by me not being able to understand the challenge itself. \$\endgroup\$ Sep 22, 2018 at 23:01
  • \$\begingroup\$ @BMO Reason to disallow libraries is that there are existing libraries that are AI libraries. Allowing them means you just call some monolithic AI library and you're done. I guess it'd make sense to just not allow AI libraries though? \$\endgroup\$
    – lilHar
    Sep 24, 2018 at 15:57
  • \$\begingroup\$ Maybe disallowing AI-libraries could be a sensible idea, but I wouldn't know how to put this (ie. what is an AI-library and what is a regular library) formally. Though the standard (this does not mean that it's always the case or that you need to follow it) is to not disallow such things but rather discourage it. If I'd use a library which is not part of the standard libraries it would count as a different language, eg. Python 3 + scikit and in a perfect world less interesting submissions would be given less upvotes. \$\endgroup\$ Sep 24, 2018 at 17:00
  • \$\begingroup\$ @BMO Rewrote it, does this look better? \$\endgroup\$
    – lilHar
    Sep 24, 2018 at 18:29
  • \$\begingroup\$ I think the rules do look more structured and clean, but I still don't understand the challenge itself. Some questions I think the challenge should answer for which I can't find an answer might help: Are you requiring a program, function or a set of functions? What is the input and output format? What makes a solution valid? What is parsing string A to string B? \$\endgroup\$ Sep 24, 2018 at 22:38
  • \$\begingroup\$ Also, keep in mind that golfed solutions might try to find some kind of weaknesses in your definitions to reduce the problem to the easiest way of solving it which might result in solutions that aren't very interesting from an AI perspective. This challenge might fit better test-battery (you can set a byte-limit motivated by your own code if you want). \$\endgroup\$ Sep 24, 2018 at 22:43
  • \$\begingroup\$ There are 2 critical pieces to this challenge that need to be clear before we can really make this post: 1. What are "Instructions"? 2. When an InstructionSet applies a string, what feedback does the AI get? \$\endgroup\$ Sep 25, 2018 at 16:37
  • 1
    \$\begingroup\$ Finally, realize that rule #10 simply means I can iterate over every possible program until I land on one that works, no AI needed. \$\endgroup\$ Sep 25, 2018 at 16:40
  • \$\begingroup\$ @NathanMerrill Did some clarifying randomness... better? \$\endgroup\$
    – lilHar
    Sep 27, 2018 at 18:49
  • \$\begingroup\$ Not really. Let's chat \$\endgroup\$ Sep 27, 2018 at 19:10
-2
\$\begingroup\$

Rotations Required

Given input 2 values:

\$x >= 0\$ :Distance to travel (float)

\$r>0\$ :Radius of wheel (float)

Output the number of rotations required by the wheel to travel that distance.

Constraints:

Your code must not contain any digits.

You cannot use pi functions (math.pi)

Output must be an integer.(In case exact int is not obtained, floor it) 1.0 is not a valid output, it should be 1.

Test Cases

x       r    o/p
50      1    7
0       34   0
50      0.3  26
44      33   0
5.5     5.5  0
105     5    3
155     5    4
6.28318 1    1 #This signifies that pi was approximated to 3.1419

Scoring:

Score= No. of bytes+20/number of digits taken for pi after decimal point

If you have taken more than 10 digits:

Score= No. of bytes

\$\endgroup\$
12
  • 3
    \$\begingroup\$ "You cannot use pi functions" is an unobservable requirement, which is not allowed. You need some test cases. The no-digits rule won't actually make this problem harder for most golflangs. \$\endgroup\$ Oct 16, 2018 at 12:43
  • \$\begingroup\$ @NathanMerrill The latter is less problematic (and more objective) than the former. \$\endgroup\$
    – DELETE_ME
    Oct 16, 2018 at 14:21
  • \$\begingroup\$ Test cases are not strictly required, but it would make it easier to check if a solution is definitely incorrect. \$\endgroup\$
    – DELETE_ME
    Oct 16, 2018 at 14:22
  • 3
    \$\begingroup\$ Info: Adding constraints just "because the challenge is too easy" usually doesn't make it more interesting (unless the constraints are the main difficulty of the challenge, for example for radiation-hardened challenges) \$\endgroup\$
    – DELETE_ME
    Oct 16, 2018 at 14:24
  • \$\begingroup\$ I will add test cases. @NathanMerrill, there just shouldn't be any inbuilt functions that give pi directly is what I want to say. \$\endgroup\$ Oct 17, 2018 at 5:35
  • \$\begingroup\$ @VedantKandoi I understand what you want, but we allow any language on this site, and it's impossible to define what a "pi-giving function" is to work for all possible languages. \$\endgroup\$ Oct 17, 2018 at 6:26
  • \$\begingroup\$ Is there any other way I could word it then, as I don't want python, java etc. users to use math.pi or should I just remove it? \$\endgroup\$ Oct 17, 2018 at 7:15
  • \$\begingroup\$ Also, since pi is in the formula, exact int will never be obtained, and if anyone uses approximate value of pi, they may get exact int at certain value or 1 less than desired answer. What can I add for this? \$\endgroup\$ Oct 17, 2018 at 7:48
  • \$\begingroup\$ I changed the scoring method for the above issue, so should be okay now. \$\endgroup\$ Oct 17, 2018 at 8:15
  • \$\begingroup\$ Why would the output be floored? Surely you should use ceiling so that the wheel is actually travelling that distance. \$\endgroup\$
    – Jo King Mod
    Oct 17, 2018 at 8:26
  • \$\begingroup\$ I was thinking of something like how many full rotations need to be completed. \$\endgroup\$ Oct 17, 2018 at 8:31
  • 2
    \$\begingroup\$ "Not using a pi function" is a non-observable program requirement, which is one of the things to avoid when writing a challenge. I don't see any way to fix this challenge: fundamentally what it's asking is too trivial to be interesting. My advice would be to delete the body of this answer and then delete the answer (to keep the sandbox tidy) and then to try to come up with a challenge which is inherently interesting enough that it doesn't need that kind of restriction. \$\endgroup\$ Oct 17, 2018 at 14:06
-2
\$\begingroup\$

Write a Self-Hosting Ouroboros: each quine produces the next quine AND its interpreter

My meta-questions, please give feedback and/or add your own:

  • Too elaborate or long post?
  • Rules too strict? Too lax?
  • Not having a deadline: good or bad idea?

A Quine is a program that prints its own source code as output when it is run.

A Self-Hosting Quine (which is something I just made up, although I'm sure it exists already) is a quine that also produces an interpreter/compiler/emulator/whatever for itself (from now on I will just say "interpreter").

I believe this actually means that a lot of essential functionality must be "circularly defined" - for example, to print output, the interpreter must rely on the parent interpreter's ability to print output. So maybe we should call this a Von Munchausen Quine?

An Ouroboros Program or Quine Relay is a quine that prints a different quine, which then prints yet another program, and so on, until the last quine produces the original quine. See this famous example that cycles through over a hundred languages.

A Self-Hosting Ouroboros, then, is quine that produces a program in another language, and also produces an interpreter for that language. The interpreter should be in the current language, so that the next quine can immediately be run and produce the quine after that.

Tangent: obviously, the idea can also be extended to interpreter multiquines but that can be another challenge. Let's make Von Munchausen's Ouroboros first!

Rules

  • The ouroboros must be able to make a complete cycle
  • Score by total quines in chain / shortest source code (in bytes) in the chain (bytes to allow non-textual outputs)
  • Empty quines and interpreters do not count - two character minimum
  • Code-golf languages allowed
  • No languages defined just for this challenge - no "I define language x to always produce quine y in C plus the complete GCC compiler when fed any input"-stuff please
  • Quines must be valid code in their programming languages
  • Interpreters that are partial language implementations are fine, however:
    • it must be able to run the quine, and produce the next quine (obviously).
    • it should be able to run any other correct code that is limited to the same language subset¹. No hyperfitting²!
    • for the sake of code golfing it may accept incorrect code that a normal interpreter should not (the quine is already restricted to correct code anyway)

Clarifications

Yes, you can make a quine that produces itself and its own interpreter

Counts as a 1-chain ouroboros.

What would an "interpreter" for machine code be?

An emulator. Which of course needs some way to load a program and produce the output. You may define a fictional simplified, minimal hardware set-up to do so. For example: a (partial) Z80 emulator where:

  • two hardware ports are connected to send output bytes to (one for interpreter, one for quine). Are those bytes interpreted as raw bytes/ASCI/UTF8 text/whatever? Up to you!
  • the program is already loaded in memory, at whatever address is most convenient (quine too big to fit in the addressable memory space? Define an input port to scan bytes from I guess :P)
  • the PC (program counter), and SP (stack pointer) registers initiate at whatever value is most convenient for creating a quine in Z80 opcode

Obviously, no set-ups with fictional ROM that just happens to contain a new quine, or stuff like that (even though this would be hard to really abuse, since that ROM would still need to be implemented in the emulator).

Am I seriously expecting anyone to create an emulator like this? No, but let's keep the possiblity open (some stack machines might be code golf-friendly enough for the challenge).

"Borrowing" snippets from each other is encouraged, but give accreditation and link to sources!

Because we all really just want to see how long this can get, no? Besides, whatever you take probably has to be heavily modified to fit it in your existing ouroboros chain anyway. Sharing is caring, and accreditation is the decent thing to do.

No dead-line, nor will a winner be selected. Just make as long a chain as possible.


¹ You wrote an interpreter for a subset of Rust, but it doesn't feature the borrow checker? That is fine long as:

  • it works with correct Rust code limited to the language subset
  • it works with the quine itself
  • the quine itself is correct rust code

² Example of what I do and do not consider hyperfitting: if your interpreter can deal with for(var i; i < 10; i++) { a[i] = i; } but crashes without the enclosing {} because it expects them to designate code blocks, that counts as a partial implementation. If var only expects i, or < only expects i and 10? Hyperfitting. If var only accepts single letter names, and < only expects variables on the left and literals on the right? Probably hyperfitting but debatable.

\$\endgroup\$
4
  • \$\begingroup\$ What would the interpreter of a program written in machine code be? \$\endgroup\$
    – DELETE_ME
    Oct 19, 2018 at 15:14
  • \$\begingroup\$ How should we separate the quine output and the interpreter output? \$\endgroup\$
    – Jo King Mod
    Oct 21, 2018 at 0:10
  • \$\begingroup\$ @user202729: an emulator \$\endgroup\$
    – Job
    Oct 21, 2018 at 13:01
  • \$\begingroup\$ @JoKing: hmm, good question. Two separate calls to whatever output method is chosen? (print or its equivalent) \$\endgroup\$
    – Job
    Oct 21, 2018 at 13:03
-2
\$\begingroup\$

Unicode encoder

Do Invent your own Unicode 7.0.0 encoding (as efficient as possible) with score 317754(the lowest possible score). Shortest encode+decode program win.

You can either write two programs doing encode and decode, or write one with argument/input method difference deciding whether it's encoding or decoding

As you may know, the Unicode standard has room for 1,114,111 code points, and each assigned code point represents a glyph (character, emoji, etc.).

Most code points are not yet assigned.

Current Unicode implementations take a lot of space to encode all possible code points (UTF-32 takes 4 bytes per code point, UTF-16: 2 to 4 bytes, UTF-8: 1 to 4 bytes, etc.)


Task
-

Today, your task is to implement your own Unicode implementation, with the following rules:

- Write an encoder and a decoder in any language of your choice
- The encoder's input is a list of code points (as integers) and it outputs a list of bytes (as integers) corresponding to your encoding.
- The decoder does the opposite (bytes => code points)
- Your implementation has to cover all Unicode 7.0.0 assigned code points
- It has to stay backwards-compatible with ASCII, i.e. encode Basic latin characters (U+0000-U+007F) on one byte, with 0 as most significant bit.
- Encode all the other assigned code points in any form and any number of bytes you want, as long as there is no ambiguity (i.e. two code points or group of code points can't have the same encoding and vice versa)
- Your implementation doesn't have to cover UTF-16 surrogates (code points U+D800-U+DFFF) nor private use areas (U+E000-U+F8FF, U+F0000-U+10FFFF)
- Your encoding must be context-independant (i.e. not rely on previously encoded characters) and does NOT require self-synchronization (i.e. each byte doesn't have to infer where it's located in the encoding of a code point, like in UTF-8).

To sum up, here are the blocks that you have to cover, in JSON:

[
  [0x0000,0x007F], // Basic Latin
  [0x0080,0x00FF], // Latin-1 Supplement
  [0x0100,0x017F], // Latin Extended-A
  [0x0180,0x024F], // Latin Extended-B
  [0x0250,0x02AF], // IPA Extensions
  [0x02B0,0x02FF], // Spacing Modifier Letters
  [0x0300,0x036F], // Combining Diacritical Marks
  [0x0370,0x03FF], // Greek and Coptic
  [0x0400,0x04FF], // Cyrillic
  [0x0500,0x052F], // Cyrillic Supplement
  [0x0530,0x058F], // Armenian
  [0x0590,0x05FF], // Hebrew
  [0x0600,0x06FF], // Arabic
  [0x0700,0x074F], // Syriac
  [0x0750,0x077F], // Arabic Supplement
  [0x0780,0x07BF], // Thaana
  [0x07C0,0x07FF], // NKo
  [0x0800,0x083F], // Samaritan
  [0x0840,0x085F], // Mandaic
  [0x08A0,0x08FF], // Arabic Extended-A
  [0x0900,0x097F], // Devanagari
  [0x0980,0x09FF], // Bengali
  [0x0A00,0x0A7F], // Gurmukhi
  [0x0A80,0x0AFF], // Gujarati
  [0x0B00,0x0B7F], // Oriya
  [0x0B80,0x0BFF], // Tamil
  [0x0C00,0x0C7F], // Telugu
  [0x0C80,0x0CFF], // Kannada
  [0x0D00,0x0D7F], // Malayalam
  [0x0D80,0x0DFF], // Sinhala
  [0x0E00,0x0E7F], // Thai
  [0x0E80,0x0EFF], // Lao
  [0x0F00,0x0FFF], // Tibetan
  [0x1000,0x109F], // Myanmar
  [0x10A0,0x10FF], // Georgian
  [0x1100,0x11FF], // Hangul Jamo
  [0x1200,0x137F], // Ethiopic
  [0x1380,0x139F], // Ethiopic Supplement
  [0x13A0,0x13FF], // Cherokee
  [0x1400,0x167F], // Unified Canadian Aboriginal Syllabics
  [0x1680,0x169F], // Ogham
  [0x16A0,0x16FF], // Runic
  [0x1700,0x171F], // Tagalog
  [0x1720,0x173F], // Hanunoo
  [0x1740,0x175F], // Buhid
  [0x1760,0x177F], // Tagbanwa
  [0x1780,0x17FF], // Khmer
  [0x1800,0x18AF], // Mongolian
  [0x18B0,0x18FF], // Unified Canadian Aboriginal Syllabics Extended
  [0x1900,0x194F], // Limbu
  [0x1950,0x197F], // Tai Le
  [0x1980,0x19DF], // New Tai Lue
  [0x19E0,0x19FF], // Khmer Symbols
  [0x1A00,0x1A1F], // Buginese
  [0x1A20,0x1AAF], // Tai Tham
  [0x1AB0,0x1AFF], // Combining Diacritical Marks Extended
  [0x1B00,0x1B7F], // Balinese
  [0x1B80,0x1BBF], // Sundanese
  [0x1BC0,0x1BFF], // Batak
  [0x1C00,0x1C4F], // Lepcha
  [0x1C50,0x1C7F], // Ol Chiki
  [0x1CC0,0x1CCF], // Sundanese Supplement
  [0x1CD0,0x1CFF], // Vedic Extensions
  [0x1D00,0x1D7F], // Phonetic Extensions
  [0x1D80,0x1DBF], // Phonetic Extensions Supplement
  [0x1DC0,0x1DFF], // Combining Diacritical Marks Supplement
  [0x1E00,0x1EFF], // Latin Extended Additional
  [0x1F00,0x1FFF], // Greek Extended
  [0x2000,0x206F], // General Punctuation
  [0x2070,0x209F], // Superscripts and Subscripts
  [0x20A0,0x20CF], // Currency Symbols
  [0x20D0,0x20FF], // Combining Diacritical Marks for Symbols
  [0x2100,0x214F], // Letterlike Symbols
  [0x2150,0x218F], // Number Forms
  [0x2190,0x21FF], // Arrows
  [0x2200,0x22FF], // Mathematical Operators
  [0x2300,0x23FF], // Miscellaneous Technical
  [0x2400,0x243F], // Control Pictures
  [0x2440,0x245F], // Optical Character Recognition
  [0x2460,0x24FF], // Enclosed Alphanumerics
  [0x2500,0x257F], // Box Drawing
  [0x2580,0x259F], // Block Elements
  [0x25A0,0x25FF], // Geometric Shapes
  [0x2600,0x26FF], // Miscellaneous Symbols
  [0x2700,0x27BF], // Dingbats
  [0x27C0,0x27EF], // Miscellaneous Mathematical Symbols-A
  [0x27F0,0x27FF], // Supplemental Arrows-A
  [0x2800,0x28FF], // Braille Patterns
  [0x2900,0x297F], // Supplemental Arrows-B
  [0x2980,0x29FF], // Miscellaneous Mathematical Symbols-B
  [0x2A00,0x2AFF], // Supplemental Mathematical Operators
  [0x2B00,0x2BFF], // Miscellaneous Symbols and Arrows
  [0x2C00,0x2C5F], // Glagolitic
  [0x2C60,0x2C7F], // Latin Extended-C
  [0x2C80,0x2CFF], // Coptic
  [0x2D00,0x2D2F], // Georgian Supplement
  [0x2D30,0x2D7F], // Tifinagh
  [0x2D80,0x2DDF], // Ethiopic Extended
  [0x2DE0,0x2DFF], // Cyrillic Extended-A
  [0x2E00,0x2E7F], // Supplemental Punctuation
  [0x2E80,0x2EFF], // CJK Radicals Supplement
  [0x2F00,0x2FDF], // Kangxi Radicals
  [0x2FF0,0x2FFF], // Ideographic Description Characters
  [0x3000,0x303F], // CJK Symbols and Punctuation
  [0x3040,0x309F], // Hiragana
  [0x30A0,0x30FF], // Katakana
  [0x3100,0x312F], // Bopomofo
  [0x3130,0x318F], // Hangul Compatibility Jamo
  [0x3190,0x319F], // Kanbun
  [0x31A0,0x31BF], // Bopomofo Extended
  [0x31C0,0x31EF], // CJK Strokes
  [0x31F0,0x31FF], // Katakana Phonetic Extensions
  [0x3200,0x32FF], // Enclosed CJK Letters and Months
  [0x3300,0x33FF], // CJK Compatibility
  [0x3400,0x4DBF], // CJK Unified Ideographs Extension A
  [0x4DC0,0x4DFF], // Yijing Hexagram Symbols
  [0x4E00,0x9FFF], // CJK Unified Ideographs
  [0xA000,0xA48F], // Yi Syllables
  [0xA490,0xA4CF], // Yi Radicals
  [0xA4D0,0xA4FF], // Lisu
  [0xA500,0xA63F], // Vai
  [0xA640,0xA69F], // Cyrillic Extended-B
  [0xA6A0,0xA6FF], // Bamum
  [0xA700,0xA71F], // Modifier Tone Letters
  [0xA720,0xA7FF], // Latin Extended-D
  [0xA800,0xA82F], // Syloti Nagri
  [0xA830,0xA83F], // Common Indic Number Forms
  [0xA840,0xA87F], // Phags-pa
  [0xA880,0xA8DF], // Saurashtra
  [0xA8E0,0xA8FF], // Devanagari Extended
  [0xA900,0xA92F], // Kayah Li
  [0xA930,0xA95F], // Rejang
  [0xA960,0xA97F], // Hangul Jamo Extended-A
  [0xA980,0xA9DF], // Javanese
  [0xA9E0,0xA9FF], // Myanmar Extended-B
  [0xAA00,0xAA5F], // Cham
  [0xAA60,0xAA7F], // Myanmar Extended-A
  [0xAA80,0xAADF], // Tai Viet
  [0xAAE0,0xAAFF], // Meetei Mayek Extensions
  [0xAB00,0xAB2F], // Ethiopic Extended-A
  [0xAB30,0xAB6F], // Latin Extended-E
  [0xABC0,0xABFF], // Meetei Mayek
  [0xAC00,0xD7AF], // Hangul Syllables
  [0xD7B0,0xD7FF], // Hangul Jamo Extended-B
  [0xF900,0xFAFF], // CJK Compatibility Ideographs
  [0xFB00,0xFB4F], // Alphabetic Presentation Forms
  [0xFB50,0xFDFF], // Arabic Presentation Forms-A
  [0xFE00,0xFE0F], // Variation Selectors
  [0xFE10,0xFE1F], // Vertical Forms
  [0xFE20,0xFE2F], // Combining Half Marks
  [0xFE30,0xFE4F], // CJK Compatibility Forms
  [0xFE50,0xFE6F], // Small Form Variants
  [0xFE70,0xFEFF], // Arabic Presentation Forms-B
  [0xFF00,0xFFEF], // Halfwidth and Fullwidth Forms
  [0xFFF0,0xFFFF], // Specials
  [0x10000,0x1007F], // Linear B Syllabary
  [0x10080,0x100FF], // Linear B Ideograms
  [0x10100,0x1013F], // Aegean Numbers
  [0x10140,0x1018F], // Ancient Greek Numbers
  [0x10190,0x101CF], // Ancient Symbols
  [0x101D0,0x101FF], // Phaistos Disc
  [0x10280,0x1029F], // Lycian
  [0x102A0,0x102DF], // Carian
  [0x102E0,0x102FF], // Coptic Epact Numbers
  [0x10300,0x1032F], // Old Italic
  [0x10330,0x1034F], // Gothic
  [0x10350,0x1037F], // Old Permic
  [0x10380,0x1039F], // Ugaritic
  [0x103A0,0x103DF], // Old Persian
  [0x10400,0x1044F], // Deseret
  [0x10450,0x1047F], // Shavian
  [0x10480,0x104AF], // Osmanya
  [0x10500,0x1052F], // Elbasan
  [0x10530,0x1056F], // Caucasian Albanian
  [0x10600,0x1077F], // Linear A
  [0x10800,0x1083F], // Cypriot Syllabary
  [0x10840,0x1085F], // Imperial Aramaic
  [0x10860,0x1087F], // Palmyrene
  [0x10880,0x108AF], // Nabataean
  [0x10900,0x1091F], // Phoenician
  [0x10920,0x1093F], // Lydian
  [0x10980,0x1099F], // Meroitic Hieroglyphs
  [0x109A0,0x109FF], // Meroitic Cursive
  [0x10A00,0x10A5F], // Kharoshthi
  [0x10A60,0x10A7F], // Old South Arabian
  [0x10A80,0x10A9F], // Old North Arabian
  [0x10AC0,0x10AFF], // Manichaean
  [0x10B00,0x10B3F], // Avestan
  [0x10B40,0x10B5F], // Inscriptional Parthian
  [0x10B60,0x10B7F], // Inscriptional Pahlavi
  [0x10B80,0x10BAF], // Psalter Pahlavi
  [0x10C00,0x10C4F], // Old Turkic
  [0x10E60,0x10E7F], // Rumi Numeral Symbols
  [0x11000,0x1107F], // Brahmi
  [0x11080,0x110CF], // Kaithi
  [0x110D0,0x110FF], // Sora Sompeng
  [0x11100,0x1114F], // Chakma
  [0x11150,0x1117F], // Mahajani
  [0x11180,0x111DF], // Sharada
  [0x111E0,0x111FF], // Sinhala Archaic Numbers
  [0x11200,0x1124F], // Khojki
  [0x112B0,0x112FF], // Khudawadi
  [0x11300,0x1137F], // Grantha
  [0x11480,0x114DF], // Tirhuta
  [0x11580,0x115FF], // Siddham
  [0x11600,0x1165F], // Modi
  [0x11680,0x116CF], // Takri
  [0x118A0,0x118FF], // Warang Citi
  [0x11AC0,0x11AFF], // Pau Cin Hau
  [0x12000,0x123FF], // Cuneiform
  [0x12400,0x1247F], // Cuneiform Numbers and Punctuation
  [0x13000,0x1342F], // Egyptian Hieroglyphs
  [0x16800,0x16A3F], // Bamum Supplement
  [0x16A40,0x16A6F], // Mro
  [0x16AD0,0x16AFF], // Bassa Vah
  [0x16B00,0x16B8F], // Pahawh Hmong
  [0x16F00,0x16F9F], // Miao
  [0x1B000,0x1B0FF], // Kana Supplement
  [0x1BC00,0x1BC9F], // Duployan
  [0x1BCA0,0x1BCAF], // Shorthand Format Controls
  [0x1D000,0x1D0FF], // Byzantine Musical Symbols
  [0x1D100,0x1D1FF], // Musical Symbols
  [0x1D200,0x1D24F], // Ancient Greek Musical Notation
  [0x1D300,0x1D35F], // Tai Xuan Jing Symbols
  [0x1D360,0x1D37F], // Counting Rod Numerals
  [0x1D400,0x1D7FF], // Mathematical Alphanumeric Symbols
  [0x1E800,0x1E8DF], // Mende Kikakui
  [0x1EE00,0x1EEFF], // Arabic Mathematical Alphabetic Symbols
  [0x1F000,0x1F02F], // Mahjong Tiles
  [0x1F030,0x1F09F], // Domino Tiles
  [0x1F0A0,0x1F0FF], // Playing Cards
  [0x1F100,0x1F1FF], // Enclosed Alphanumeric Supplement
  [0x1F200,0x1F2FF], // Enclosed Ideographic Supplement
  [0x1F300,0x1F5FF], // Miscellaneous Symbols and Pictographs
  [0x1F600,0x1F64F], // Emoticons
  [0x1F650,0x1F67F], // Ornamental Dingbats
  [0x1F680,0x1F6FF], // Transport and Map Symbols
  [0x1F700,0x1F77F], // Alchemical Symbols
  [0x1F780,0x1F7FF], // Geometric Shapes Extended
  [0x1F800,0x1F8FF], // Supplemental Arrows-C
  [0x20000,0x2A6DF], // CJK Unified Ideographs Extension B
  [0x2A700,0x2B73F], // CJK Unified Ideographs Extension C
  [0x2B740,0x2B81F], // CJK Unified Ideographs Extension D
  [0x2F800,0x2FA1F], // CJK Compatibility Ideographs Supplement
  [0xE0000,0xE007F], // Tags
  [0xE0100,0xE01EF]  // Variation Selectors Supplement
]

Total: 116,816 code points.

Scoring
--

Your score is the number of bytes that your encoder outputs when you feed it with all the 116,816 possible code points (in one time or separately).

\$\endgroup\$
3
  • \$\begingroup\$ I suppose 317754 is the optimal score, right? \$\endgroup\$
    – DELETE_ME
    Oct 22, 2018 at 9:37
  • \$\begingroup\$ @user202729 Yes if there are 116,816 code points \$\endgroup\$
    – l4m2
    Oct 22, 2018 at 9:38
  • 1
    \$\begingroup\$ p.s. I think you should expand it while it is on the sandbox, just in case somebody don't understand the specification. \$\endgroup\$
    – DELETE_ME
    Oct 22, 2018 at 9:38
-2
\$\begingroup\$

Forcing a kernel panic from a mountaintop

This is a thought resulting from a curious incident where C# code opening file apparently caused a BSOD. In the conclusion, it was due to a faulty driver, but from that a thought came up --- can one cause a kernel panic (or BSOD) using managed code exclusively?

Why?

Typically in such environment, there are many compile-time and run-time checks that safeguard the code from doing something that would cause a kernel panic. For a mature managed environment, it should be impossible to cause the operating system to arrive into a bad state. In the case, though it was C# code, the fact that a faulty driver was involved breached the walled garden. But can we breach it from within?

Rules

  • The code must be managed in some fashion (e.g. Java, C#, VB.NET), and normally comes with both compile-time and run-time checks.
  • The code should be running in a virtual machine or equivalent. (e.g. Java's JVM or .NET's AppDomain)
  • The code should NOT rely on any external anything. No extern declarations, no networking, no dodgy APIs.
  • The code should NOT use any construct which allow direct access to resources (e.g. unsafe in C#)
  • The code should use only the native libraries & API available as part of its usual environment.
  • Throwing an exception is not sufficient. To qualify, the code must result in a kernel panic.

Criteria

Essentially a code-golf -

  • The less code to kernel panic, the better
  • The fewer dependencies the code uses to make it happen, the better
  • The code that consistently causes a kernel panic is better than one that only does it sometimes
\$\endgroup\$
3
  • 2
    \$\begingroup\$ Is the code considered malicious code? \$\endgroup\$
    – DELETE_ME
    Nov 10, 2018 at 15:26
  • \$\begingroup\$ What is "managed code"? \$\endgroup\$
    – DELETE_ME
    Nov 10, 2018 at 15:26
  • \$\begingroup\$ While it can be used with malicious intent, the goal is more toward proving whether it's possible to unintentionally break through the walled garden. RE: "managed code" --- it might be a .NET-specific term but I use it in general sense to refer to any programming language that usually run in a some kind of sandbox -- I cited Java's JVM or .NET's AppDomain as such examples. Those usually enforce runtime checks in addition to compile-time checks to prevent doing stupid thing like passing a null pointer which usually is a trappable exception. \$\endgroup\$
    – this
    Nov 10, 2018 at 19:06
-2
\$\begingroup\$

Play snake on a 50*50 grid. The snake will start at length 3, heading (2,0) with body (1,0) and (0,0). It shouldn't bump into wall or itself. There is always one food, which increases the length of snake by 1 when eaten.

Smallest amount of steps till there's no space to place food win. Flexible I/O, anyway it doesn't matter.

Vote on whether the food placer is transparent and allow food manipulation(Up for yes, down for no)

\$\endgroup\$
4
  • \$\begingroup\$ I think there are already quite a few snake challenges. You need to flesh out some more details here. How do you determine where the food will spawn? Will you be given some sampling of the game state (vision?) on each step? \$\endgroup\$
    – Beefster
    Dec 28, 2018 at 19:22
  • \$\begingroup\$ @Beefster If "food placer is transparent and allow food manipulation", you just know how it spawns; If not, you get access to the location of current food \$\endgroup\$
    – l4m2
    Dec 29, 2018 at 3:44
  • \$\begingroup\$ If food manip. is allowed, is the optimal score achievable by finding an Hamiltonian path starts with the snake? \$\endgroup\$
    – DELETE_ME
    Dec 29, 2018 at 8:55
  • \$\begingroup\$ @user202729 It depends on how strong the manipulation is \$\endgroup\$
    – l4m2
    Dec 29, 2018 at 10:54
-2
\$\begingroup\$

No-alphanumeric code exec

\$\endgroup\$
6
  • 4
    \$\begingroup\$ -1 for winning entries must be written in one of the 25 top languages. \$\endgroup\$
    – Jo King Mod
    Jan 19, 2019 at 9:28
  • \$\begingroup\$ I'm trying to exclude golfing languages with that - this only seems like an interesting challenge to me if you don't allow languages where it's excessively trivial. Any suggestions for how to do that in a more permissive way or other thoughts about that goal? \$\endgroup\$
    – lahwran
    Jan 19, 2019 at 22:13
  • \$\begingroup\$ actually, I think this will be quite difficult in many code golf languages as well, as they usually try to get brevity by cramming things into single letters and numbers. there are of course languages where it'll be excessively trivial, but that's fine, those solutions most likely just won't be upvoted. \$\endgroup\$
    – lahwran
    Jan 19, 2019 at 22:21
  • \$\begingroup\$ Most golfing languages won't be able to pull sth. from the interconnected-webs afaik, so there's no real need to invent arbitrary restrictions to ban them. \$\endgroup\$ Jan 21, 2019 at 16:25
  • 1
    \$\begingroup\$ Also "but that's fine, those solutions most likely just won't be upvoted" is too optimistic, usually it's the other way around :( \$\endgroup\$ Jan 21, 2019 at 16:26
  • \$\begingroup\$ dang, good to know. \$\endgroup\$
    – lahwran
    Jan 21, 2019 at 22:55
-2
\$\begingroup\$

HTML-tac-toe

Build a one-player tic-tac-toe game with only HTML and CSS.

Introduction

You can do just about anything with a fully-featured programming language, but how much can you accomplish on a Neopets petpage? Inspired by http://www.neopets.com/~vuh

Challenge

Build a one-player tic-tac-toe game with only HTML and CSS.

  • Use no more than one file.
  • GIFs (including animations), PNGs, and JPEGs are allowed.
  • Flash, embedded scripts, iframes, and JavaScript are not allowed.
  • It must work in the at least two standard browsers (FF, Chrome, Safari, Opera, IE)

Inputs: The player will click on a space when it's their turn to move there.

Outputs: The page will show the current board state at all times. The page will play an optimal move whenever the player moves, unless the game is over.

You're free to decide who starts and who has X or O.

Scores

  • -10 per image
  • -1 per opening bracket or brace (< / { )

Brownie points for design, flair, and new tricks!

Example Input and Output

Input:

Click on the top left of an empty grid

Output:

Grid shows my mark where I clicked and the opposite mark in the left middle or top middle.

\$\endgroup\$
11
  • \$\begingroup\$ I'd recommend against restricting languages, and against score bonuses too \$\endgroup\$
    – ASCII-only
    Jan 22, 2019 at 4:15
  • \$\begingroup\$ @ASCII-only I can drop the bonuses without much consequence, but it's not a new challenge without a language or host restriction. Any suggestions? \$\endgroup\$
    – Qaz
    Jan 22, 2019 at 4:45
  • \$\begingroup\$ True, but... language restrictions are pretty frowned upon \$\endgroup\$
    – ASCII-only
    Jan 22, 2019 at 4:47
  • 1
    \$\begingroup\$ Welcome to PPCG! You may want to check this post out, it certainly helped me when starting with writing my own challenges. Also, your post does not have a well-defined objective winning criterion. It seems like it is atomic code-golf or code-challenge [1/2] \$\endgroup\$ Jan 22, 2019 at 19:32
  • \$\begingroup\$ , but you will need to define how answers are scored (in this case lower is worse) and how ties are treated. Also why do you disallow GIFs but JPGs not? I know most will know, but maybe explain or at the very least link to somewhere where the rules for tic-tac-toe are explained. What counts as an X, what as an O? There are a lot of open question atm. [2/2] \$\endgroup\$ Jan 22, 2019 at 19:36
  • \$\begingroup\$ JPGs are allowed. (That's the same format as JPEG, just a different extension.) I can change it to 'images', but I'm worried about some image format I don't know of that makes the challenge trivial. More points, more better! That seems clear enough, but I can certainly spell it out. Are ties forbidden? Two entries with the same number of points seem equally good to me, but the first posted could be the winner. If I link to tic-tac-toe rules, does that answer "What counts as an X, what as an O?" or are you asking something else? \$\endgroup\$
    – Qaz
    Jan 23, 2019 at 0:13
  • 4
    \$\begingroup\$ "Standard exceptions are allowed IF they work on Neopets.com." How do we know what works on Neopets.com? If we have to create accounts on a random third party site to test answers and know whether they're valid or not, the question should and probably will end up closed with a lot of downvotes. \$\endgroup\$ Jan 24, 2019 at 15:34
  • 1
    \$\begingroup\$ This isn't very interesting in general. It essentially amounts to creating every possible layout of a tic-tac-toe board and linking them together with clever CSS and HTML hacks so it fits in 25 pages. I think it could be made a bit more interesting by making it atomic code golf scoring on the total number of html files used, lowest scores win rather than limiting the total number of pages. \$\endgroup\$
    – Beefster
    Jan 25, 2019 at 20:36
  • \$\begingroup\$ @PeterTaylor very well, dropped that altogether \$\endgroup\$
    – Qaz
    Jan 25, 2019 at 22:53
  • \$\begingroup\$ @Beefster The page I link to as the inspiration (neopets.com/~vuh) uses only one html file, and the source isn't too hard to understand, so perhaps I should link to the creator of the page instead, limit the solutions to one page, or both. \$\endgroup\$
    – Qaz
    Jan 25, 2019 at 22:53
  • 1
    \$\begingroup\$ I highly suggest looking through current codegolf questions to see which are well-received by the community. This question seems highly arbitrary and leaves too much under-specified. \$\endgroup\$
    – qwr
    Jan 27, 2019 at 20:28
-2
\$\begingroup\$

Bit flipper

Given a string s and a positive number n, return the string s with n random bits flipped. (A random number can be generated in any way, including pseudo-random number generators)

Example:

Before:

Hello World

After (n = 2, 2 bits flipped):

Hello wOrld
\$\endgroup\$
16
  • 2
    \$\begingroup\$ How exact are the bytes being 'flipped'? Are we changing the bits? Is the output deterministic? It doesn't look like you're modifying any specific bit of the byte, or reversing it, or doing bitwise negation. \$\endgroup\$
    – Riker
    Mar 21, 2019 at 1:55
  • 1
    \$\begingroup\$ @Riker well changing from uppercase to lowercase is just xor 32. But they'rem saying byte flipper not bit flipper which is a bit confusing \$\endgroup\$
    – ASCII-only
    Mar 21, 2019 at 6:09
  • \$\begingroup\$ @Riker The bits are flipped \$\endgroup\$ Mar 21, 2019 at 9:42
  • \$\begingroup\$ @JoKing No, that was an example because I didn’t wanted binary non-unicode characters in the post. \$\endgroup\$ Mar 21, 2019 at 9:44
  • \$\begingroup\$ What is n? On the basis of what little is specified in the question, I would be tempted to write an implementation for n=0 which consists of the empty program in GolfScript... \$\endgroup\$ Mar 21, 2019 at 16:44
  • \$\begingroup\$ @PeterTaylor A user defined count of how many bytes will be flipped \$\endgroup\$ Mar 21, 2019 at 18:12
  • 1
    \$\begingroup\$ I think the confusion here is that "bytes" doesn't mean what you think it means. From the lone test case I think what you're trying to ask us is: given a string s and a number n, change the case of n random letters in s - would that be correct? \$\endgroup\$
    – Shaggy
    Mar 22, 2019 at 0:41
  • \$\begingroup\$ I assume case was just an example of bit 5 flipping. I'd recommend writing it like Given a string s and a positive number n, return the string s with n random bits flipped. Though from there you run into problems about invalid unicode sequences in the output \$\endgroup\$
    – Jo King Mod
    Mar 22, 2019 at 3:45
  • \$\begingroup\$ @JoKing I replaced with your example. \$\endgroup\$ Mar 22, 2019 at 7:47
  • \$\begingroup\$ What do you mean by Default n = 3? Also, how should programs handle invalid unicode sequences? \$\endgroup\$
    – Jo King Mod
    Mar 22, 2019 at 9:14
  • \$\begingroup\$ @JoKing By default, n should be 3. And invalid unicode sequences should not be handled, and the data should be directly printed out to stdout or any output file. \$\endgroup\$ Mar 22, 2019 at 12:35
  • \$\begingroup\$ When you say random, do you mean of our choice? pseudo-random? fetched from random.org? \$\endgroup\$
    – Miriam
    Mar 26, 2019 at 23:16
  • \$\begingroup\$ @ArtemisFowl It is selected by the program. \$\endgroup\$ Mar 27, 2019 at 10:45
  • \$\begingroup\$ @smileycreations15 It's gonna be hard to make that 100% random \$\endgroup\$
    – Miriam
    Mar 27, 2019 at 15:46
  • 1
    \$\begingroup\$ @smileycreations15 Maybe you should add that to the question. \$\endgroup\$
    – Miriam
    Mar 27, 2019 at 20:35
-2
\$\begingroup\$

You can't tell me what to do!!!

Intentionally break as many coding conventions as possible while crafting a working Hello World

For each language, a coding convention standard will be selected. The following is the current list:

javascript -> Google's Style Guide

PHP -> PSR-2

C++ -> ISO C++ Style Guide

Python -> PEP-8

The maximum file length is 6000 characters. Any code beyond the first 6000 will not count towards broken conventions. (Using conventions that you have set to break after the 6000 point, however, will count against you.)

If you do not see your language, you may choose one of the most common coding standards for your language, and use that, and (hopefully) it will be noticed and added to the list. Each language is its own competition. (For example: If your code is in Ruby, you're not competing against C++ code)

This is the coding equivalent of an ugly baby contest, and pushes you to think outside the box (possibly way too far outside the box). The goal is to write a 'simple' Hello World program. However, you have to do it while breaking as many coding conventions as possible, and being as ugly as possible (but still working!)

The advantages of this puzzle are multi-purpose. This is to challenge the coder to separate long-standing habits (which generally follow coding conventions) from functionality - to encourage creativity. Further, it also serves as a reverse example to demonstrate when coding conventions are a help vs a hindrance.

Remember, ugly doesn't have to mean gibberish or unnecessarily long or poorly running. In fact, code length or runtime do not factor into the evaluation.

For example, you could write procedural code using only classes, use an eval() to declare constants, or use only use variable names using characters that have nothing to do with what the variable does, reverse indentation, or rely exclusively on gotos in an interpreted language. The only thing your code has to do is output "Hello World" to the command line or an equivalent.

Each answer should list and link to coding conventions it breaks and receives 1 point for each broken code convention (but instant total of zero points the code follows any coding convention it says its breaking). If a voter agrees it violates all the listed coding conventions, upvote the code that violates the most while still functioning. (Accidentally violating coding conventions, however, does not count. Each one violated coding convention must be documented and intentional.)

Note: For each coding convention taken on, it must be consistently broken across the entire program. Following the convention even once invalidates your entire code. Habits are your enemy. Further note: If you declare you're breaking a convention, you MUST break it. If it's not applicable, it doesn't count.

Alternate Scoring method:

Don't like the "call your shot and then try to make it" scoring method? Do you have a readily available git functionality? Does the coding convention have a convenient git-hook for code style enforcement? Fear not, you have the option for an alternate scoring method: 1. Write up your code. 2. Run it through the git commit with the hook active. 3. If your hook auto-changes code, commit it, and do step 4. If it gives you coding style errors and rejects the commit, count the errors; you get one point for each error and skip to step 5. If you break git due to the hook crashing, list the broken code enforcement, add 50 points, and try again with a different code-enforcement hook. (You CANNOT be an author or contributor to any git-hook before you test against it. This is considered cheating and will be disqualify you.) 4. If your hook auto-changes code to fit style enforcement, do a git-diff between your code and the code it committed. Each change is one point. 5. Total your points. List your points as an alternate score in your answer's header. List the code-enforcement hooks you tested it against.

I'm personally not a fan of this scoring method as it allows accidental points and becomes more like it's testing the enforcement hook rather than creative code style breaking, but some like the more computer-controlled scoring method... so there ya go.

Sandbox Reminder: Sandbox is a place for constructive criticism. Saying, "I don't like it" or "I wouldn't do it" isn't constructive criticism. Last time I had this in the sandbox, most criticism was built on disliking the type of challenge, not actually building it properly. If you don't like the challenge concept, then just don't do it. If you have legitimate suggestions on how to make the challenge better then do so. I will do my best to address legitimate points.

Standard Example Answer format


My Oh so wrong Hello world - PHP - Attempting 2 points

Breaking conventions in PSR-2:

  • breaking "Opening braces for classes MUST go on the next line, and closing braces MUST go on the next line after the body."
  • breaking "All PHP files MUST end with a single blank line."

--

<?php
class hiworld{public $printme = "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

\$\endgroup\$
24
  • \$\begingroup\$ That just makes it better. \$\endgroup\$
    – lilHar
    Mar 8, 2019 at 23:29
  • \$\begingroup\$ Hate as measured by votes, however, is a discrete value, and therefore objective. \$\endgroup\$
    – lilHar
    Mar 8, 2019 at 23:37
  • \$\begingroup\$ 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. \$\endgroup\$ Mar 10, 2019 at 10:00
  • \$\begingroup\$ @trichoplax Fair enough on that. I'll change encouragement to just be on coding style. \$\endgroup\$
    – lilHar
    Mar 10, 2019 at 22:25
  • 3
    \$\begingroup\$ 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. \$\endgroup\$
    – Jo King Mod
    Mar 12, 2019 at 21:38
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – Jo King Mod
    Mar 13, 2019 at 0:06
  • 2
    \$\begingroup\$ I've removed my downvote and the related comment. \$\endgroup\$ Mar 13, 2019 at 6:59
  • 2
    \$\begingroup\$ 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? \$\endgroup\$ Mar 13, 2019 at 7:05
  • 4
    \$\begingroup\$ 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. \$\endgroup\$ Mar 13, 2019 at 7:08
  • 5
    \$\begingroup\$ "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. \$\endgroup\$ Mar 13, 2019 at 12:00
  • 2
    \$\begingroup\$ @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? \$\endgroup\$
    – lilHar
    Mar 13, 2019 at 15:33
  • 2
    \$\begingroup\$ 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. \$\endgroup\$ Mar 14, 2019 at 16:36
  • 2
    \$\begingroup\$ I know this probably isn't going anywhere, but the most 'official' python style guide is probably PEP 8. \$\endgroup\$
    – Miriam
    Apr 6, 2019 at 18:17
  • 1
    \$\begingroup\$ @liljoshu You've got my upvote for what it's worth, though I agree this needs some improvements. \$\endgroup\$
    – Miriam
    Apr 8, 2019 at 22:35
  • 2
    \$\begingroup\$ Something like codegolf.stackexchange.com/questions/172445/… might be ok \$\endgroup\$
    – Gymhgy
    Apr 10, 2019 at 3:04
-2
\$\begingroup\$

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.
  • Please provide a link to test your code as well as an explanation.
  • 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))
\$\endgroup\$
6
  • \$\begingroup\$ @FryAmTheEggman how's this? \$\endgroup\$ Jul 19, 2019 at 2:32
  • 2
    \$\begingroup\$ 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. \$\endgroup\$
    – lirtosiast
    Jul 19, 2019 at 2:52
  • \$\begingroup\$ @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). \$\endgroup\$ Jul 19, 2019 at 3:20
  • 3
    \$\begingroup\$ 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)} \$\endgroup\$ Jul 20, 2019 at 17:00
  • 2
    \$\begingroup\$ 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. \$\endgroup\$
    – lirtosiast
    Jul 20, 2019 at 18:17
  • \$\begingroup\$ @lirtosiast +1 thanks for such a clear example! \$\endgroup\$ Jul 21, 2019 at 6:16
-2
\$\begingroup\$

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.
  • No standard loopholes, please.
  • 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.
\$\endgroup\$
13
  • 4
    \$\begingroup\$ 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. \$\endgroup\$ Jul 24, 2019 at 7:11
  • 5
    \$\begingroup\$ @A__ For JavaScript, is it == or ===? Either way, people will be angry. \$\endgroup\$
    – wizzwizz4
    Jul 24, 2019 at 13:16
  • 2
    \$\begingroup\$ @A__ Because either the challenge is trivial (['']) or you're arbitrarily restricting a language. Work on your definition of "equality operator". \$\endgroup\$
    – wizzwizz4
    Jul 24, 2019 at 13:46
  • 2
    \$\begingroup\$ @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.) \$\endgroup\$
    – wizzwizz4
    Jul 24, 2019 at 14:07
  • \$\begingroup\$ @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)) \$\endgroup\$
    – user85052
    Jul 24, 2019 at 14:10
  • 3
    \$\begingroup\$ @U10-Forward 0 bytes \$\endgroup\$
    – tjjfvi
    Jul 24, 2019 at 14:32
  • 1
    \$\begingroup\$ @tjjfvi I thought about that one, but I didn't think it'd be syntactically valid. It does, however, work. \$\endgroup\$
    – wizzwizz4
    Jul 24, 2019 at 15:19
  • 1
    \$\begingroup\$ @wizzwizz4 How do you know which language? \$\endgroup\$
    – tjjfvi
    Jul 24, 2019 at 15:31
  • 1
    \$\begingroup\$ @tjjfvi I just assumed it was a language where the "null" / "undefined" singleton was indexable, returning the very same value. \$\endgroup\$
    – wizzwizz4
    Jul 24, 2019 at 15:34
  • 1
    \$\begingroup\$ @wizzwizz4 No, JS: window.window === window :) \$\endgroup\$
    – tjjfvi
    Jul 24, 2019 at 15:38
  • 2
    \$\begingroup\$ @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. \$\endgroup\$
    – wizzwizz4
    Jul 24, 2019 at 15:53
  • 1
    \$\begingroup\$ @tjjfvi Well i do it in Python so no such a thing called 0 bytes in python \$\endgroup\$ Jul 25, 2019 at 1:08
  • \$\begingroup\$ Alternative: window["window"]===window \$\endgroup\$
    – user85052
    Jul 25, 2019 at 4:06
-2
\$\begingroup\$

Recursive Sum Up The Digits

Tags:

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.

\$\endgroup\$
5
  • 2
    \$\begingroup\$ 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. \$\endgroup\$ Aug 5, 2019 at 6:37
  • 5
    \$\begingroup\$ This is just "Given n output n % 9". \$\endgroup\$ Aug 5, 2019 at 7:46
  • \$\begingroup\$ @PeterTaylor Ah, now I remember where I've seen it before: here in the sandbox, and you (or someone else) made that same comment. :) \$\endgroup\$ Aug 5, 2019 at 12:24
  • \$\begingroup\$ Isnt this just a duplicate of codegolf.stackexchange.com/q/1775/87923? \$\endgroup\$
    – EdgyNerd
    Aug 6, 2019 at 8:19
  • 1
    \$\begingroup\$ @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. \$\endgroup\$ Aug 6, 2019 at 9:16
-2
\$\begingroup\$

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
alert(Math.random()<0.1)
P=0.1, l=24 => Score=23.534

The lowest score wins!

\$\endgroup\$
5
  • \$\begingroup\$ 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.) \$\endgroup\$
    – user85052
    Sep 24, 2019 at 13:37
  • \$\begingroup\$ Sorry, I posted this incomplete. \$\endgroup\$
    – Naruyoko
    Sep 24, 2019 at 16:14
  • \$\begingroup\$ 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. \$\endgroup\$ Sep 24, 2019 at 18:39
  • \$\begingroup\$ 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. \$\endgroup\$
    – Naruyoko
    Sep 24, 2019 at 20:11
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – Naruyoko
    Sep 24, 2019 at 20:15
-2
\$\begingroup\$

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

\$\endgroup\$
11
  • 3
    \$\begingroup\$ What's to prevent a trivial solution of just 1 in many (many) languages? \$\endgroup\$ Sep 25, 2019 at 18:30
  • \$\begingroup\$ Or trivial comment abuse? \$\endgroup\$
    – S.S. Anne
    Sep 25, 2019 at 20:39
  • \$\begingroup\$ @JL2210 This works in codegolf.stackexchange.com/questions/193315/… print("ABC")#("ABC")tnirp \$\endgroup\$
    – gadzooks02
    Sep 26, 2019 at 15:21
  • \$\begingroup\$ @AdmBorkBork This works in codegolf.stackexchange.com/questions/193315/… too: 1 is the reverse of 1 \$\endgroup\$
    – gadzooks02
    Sep 26, 2019 at 15:22
  • \$\begingroup\$ And to both of you: why did these not stop that code golf becoming a challenge? \$\endgroup\$
    – gadzooks02
    Sep 26, 2019 at 15:23
  • 2
    \$\begingroup\$ 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. \$\endgroup\$ Sep 26, 2019 at 15:48
  • \$\begingroup\$ @gadzooks02 That challenge requires you to reverse the input. The input can be anything in that challenge. \$\endgroup\$
    – S.S. Anne
    Sep 26, 2019 at 15:49
  • \$\begingroup\$ @JL2210 Ah yes. Would preserve the input work better? \$\endgroup\$
    – gadzooks02
    Sep 26, 2019 at 16:02
  • \$\begingroup\$ No, then it would be trivial in Bash and BrainFuck and C and, well, you get the point. \$\endgroup\$
    – S.S. Anne
    Sep 26, 2019 at 16:26
  • \$\begingroup\$ @JL2210 Yes, OK. Do I need to do something if I've decided against a challenge? Delete the post? \$\endgroup\$
    – gadzooks02
    Sep 26, 2019 at 16:29
  • \$\begingroup\$ No idea. Read over the guidelines, they might help. \$\endgroup\$
    – S.S. Anne
    Sep 26, 2019 at 16:31
-2
\$\begingroup\$

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.

\$\endgroup\$
1
  • 3
    \$\begingroup\$ "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. \$\endgroup\$ Nov 21, 2019 at 19:43
-2
\$\begingroup\$

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.

Inputs

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

\$\endgroup\$
4
  • 4
    \$\begingroup\$ -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? \$\endgroup\$
    – Beefster
    Dec 13, 2019 at 22:39
  • \$\begingroup\$ Loophole. I blanked the esolangs.org documentation of my language. Therefore I can output nothing to achieve my goal. \$\endgroup\$
    – user85052
    Dec 18, 2019 at 4:07
  • \$\begingroup\$ @A̲̲ nope, you have to output what it was at the time of posting \$\endgroup\$
    – iPhoenix
    Dec 18, 2019 at 11:53
  • \$\begingroup\$ Obviously, you blank the page and then post before it gets fixed. \$\endgroup\$ Dec 19, 2019 at 13:55
-2
\$\begingroup\$

Finite Elements from Scratch


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)
    # Add bounds to matricies
    #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]
            add_disp(K, F, disp, dof)

def add_disp(K, F, disp, n):
    """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
    add_bound(K, n)

def add_bound(K, n):
    """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!

\$\endgroup\$
5
  • \$\begingroup\$ 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)\$. \$\endgroup\$
    – flawr
    Dec 28, 2019 at 14:32
  • \$\begingroup\$ 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\$. \$\endgroup\$
    – flawr
    Dec 28, 2019 at 14:35
  • \$\begingroup\$ You talk about the degrees of freedom "dofs", aren't these just the entries of \$u\$? \$\endgroup\$
    – flawr
    Dec 28, 2019 at 14:37
  • 2
    \$\begingroup\$ And what type of challenge is it anyway? code-golf or something else? \$\endgroup\$
    – flawr
    Dec 28, 2019 at 14:37
  • \$\begingroup\$ 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. \$\endgroup\$ Dec 29, 2019 at 4:21
-2
\$\begingroup\$

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!

\$\endgroup\$
2
  • 2
    \$\begingroup\$ 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. \$\endgroup\$
    – Jo King Mod
    Feb 11, 2020 at 4:52
  • \$\begingroup\$ 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. \$\endgroup\$ Feb 11, 2020 at 14:28
-2
\$\begingroup\$

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!
\$\endgroup\$
1
-2
\$\begingroup\$

Write an if/else statement from scratch

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

Task:-

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.

\$\endgroup\$
13
  • \$\begingroup\$ See Things to avoid when writing challenges, in particular Making assumptions about language features. \$\endgroup\$
    – S.S. Anne
    Apr 26, 2020 at 13:49
  • \$\begingroup\$ 1+ have the command #, which pops a stack and jump to the nth # in the program. Is using # allowed? \$\endgroup\$ Apr 26, 2020 at 13:57
  • \$\begingroup\$ 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. \$\endgroup\$
    – S.S. Anne
    Apr 26, 2020 at 13:57
  • \$\begingroup\$ @HighlyRadioactive # is a kind of goto, so it's definitely allowed. \$\endgroup\$
    – user92069
    Apr 26, 2020 at 14:15
  • \$\begingroup\$ @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? \$\endgroup\$ Apr 26, 2020 at 14:19
  • \$\begingroup\$ 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.... \$\endgroup\$
    – neel g
    Apr 26, 2020 at 14:51
  • \$\begingroup\$ @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! \$\endgroup\$
    – neel g
    Apr 26, 2020 at 14:54
  • \$\begingroup\$ 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. \$\endgroup\$
    – S.S. Anne
    Apr 26, 2020 at 14:56
  • \$\begingroup\$ 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. \$\endgroup\$
    – S.S. Anne
    Apr 26, 2020 at 15:03
  • \$\begingroup\$ @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? \$\endgroup\$
    – neel g
    Apr 26, 2020 at 15:16
  • 1
    \$\begingroup\$ 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? \$\endgroup\$ Apr 26, 2020 at 16:10
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – xnor
    Apr 26, 2020 at 20:15
  • \$\begingroup\$ @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. \$\endgroup\$ Apr 26, 2020 at 23:58
-2
\$\begingroup\$

Produce the next Italy number

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.

Task

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

\$\endgroup\$
9
  • \$\begingroup\$ 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). \$\endgroup\$ Apr 28, 2020 at 1:47
  • \$\begingroup\$ @mypronounismonicareinstate if that is not against some loophole, sure. Just make sure the numbers coincide with the numbers I posted \$\endgroup\$
    – RGS
    Apr 28, 2020 at 6:00
  • 1
    \$\begingroup\$ How is this not a hard-code the data challenge? Is there any possible relation? Because otherwise, it seems really boring. \$\endgroup\$
    – S.S. Anne
    Apr 29, 2020 at 0:54
  • \$\begingroup\$ @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. \$\endgroup\$
    – RGS
    Apr 29, 2020 at 18:40
  • \$\begingroup\$ It's better, but I still don't see how this couldn't be solved without just a big array. \$\endgroup\$
    – S.S. Anne
    Apr 29, 2020 at 19:06
  • \$\begingroup\$ @S.S.Anne someone will think of something! Hopefully :) \$\endgroup\$
    – RGS
    Apr 29, 2020 at 19:15
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – S.S. Anne
    Apr 29, 2020 at 19:22
  • 1
    \$\begingroup\$ Just graph your data, see how much it deviates from only a simple parabola? \$\endgroup\$
    – S.S. Anne
    Apr 29, 2020 at 19:29
  • 6
    \$\begingroup\$ 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 \$\endgroup\$ Apr 29, 2020 at 20:16
-2
\$\begingroup\$

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.

\$\endgroup\$
6
  • \$\begingroup\$ 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. \$\endgroup\$
    – xnor
    May 11, 2020 at 20:00
  • \$\begingroup\$ @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. \$\endgroup\$
    – Beefster
    May 11, 2020 at 23:09
  • \$\begingroup\$ @Λ̸̸ 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. \$\endgroup\$
    – Beefster
    May 12, 2020 at 15:08
  • \$\begingroup\$ 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. \$\endgroup\$
    – user92069
    May 13, 2020 at 2:36
  • \$\begingroup\$ 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. \$\endgroup\$
    – user92069
    May 13, 2020 at 2:38
  • \$\begingroup\$ @Λ̸̸ 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. \$\endgroup\$
    – Beefster
    May 13, 2020 at 16:32
-2
\$\begingroup\$

Print all sequenced variants of the SARS-CoV-2 (COVID-19) genome in FASTA format

https://www.ncbi.nlm.nih.gov/genbank/sars-cov-2-seqs/

The FASTA format has the name of the sequence data following a >, a newline, 60 characters of As, Ts, Cs, and Gs, a newline, 60 characters of As, Ts, Cs, and Gs, and so on.

You need only print the name of the, not the location it came from. For example:

>XX-NNNNNN.N
GENOMIC DATA GOES HERE
>XX-NNNNNN.N
MORE GENOMIC DATA GOES HERE
\$\endgroup\$
1
  • \$\begingroup\$ I can't imagine what good does requiring newlines every 60 characters do to the challenge. That site also has very many files linked, and you have not specified which ones we need to use, nor you provided us with the expected output (a plain link to a random website where we have to scrape and parse several thousands of files you haven't told us about is not enough). Since there are thousands of them, I strongly suspect suspect that zpaq will win this time. \$\endgroup\$ Jun 14, 2020 at 8:13
-2
\$\begingroup\$

Wuhan Xi Estimates

Challenge
Create a program that takes two base-ten integer number inputs (w,x). The program should output the closest integer number that is x order of magnitude smaller than w, rounded downwards. The output should be zero if the result is less than 1.

Test cases

f(10,1) = 1
f(10,2) = 0
f(1000000, 3) = 1000
f(888, 2) = 8
f(99999, 4) = 9
f(7777777, 8) = 0
f(123455, 5) = 1
f(123455, 4) = 12345
f(123455, 0) = 123455

Example Code
Here's an ungolfed example in Lua:


b=io.read()
a,b=b:match("([^,]+),([^,]+)")

if (b+0 > #a) then 
    print(0)
else 
    d = (a+0)/(10^b)
    print (math.floor(d))
end

Try it online!

General rules

  • This is , so shortest code in bytes in its respective language wins.

  • Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN (with the specification above)/STDOUT, functions/method with the proper parameters and return-type, full programs.

  • Default Loopholes are forbidden.

  • If possible, please add a link with a test for your code (TIO).

\$\endgroup\$
8
  • \$\begingroup\$ Can we take input as string where the two numbers are separated by "E-" ? \$\endgroup\$
    – Adám
    Jun 22, 2020 at 21:52
  • \$\begingroup\$ @Adám, Is "E-" executable code? If so, I guess that's fine, but it has to be part of the byte count. If it is just a glorified separator, or a switch of some kind, then yes and doesn't have to be included in the byte count. \$\endgroup\$
    – ouflak
    Jun 23, 2020 at 5:55
  • \$\begingroup\$ My idea what that one could do something like floor(input) where input is e.g. 888E-2 thus trivialising the challenge. \$\endgroup\$
    – Adám
    Jun 23, 2020 at 5:57
  • \$\begingroup\$ @Adám, That would be fine, and the challenge will have many 'trivial' answers in several languages. I'd be surprised if there isn't atleast a few 2/3 byte solutions. \$\endgroup\$
    – ouflak
    Jun 23, 2020 at 6:00
  • \$\begingroup\$ Maybe mention in the challenge text that this amounts to computing \$⌊w×10^{-x}⌋\$? \$\endgroup\$
    – Adám
    Jun 23, 2020 at 6:10
  • \$\begingroup\$ @Adám, There are other ways to look at it. My Turing Machine Code solution certainly won't be computing any powers. \$\endgroup\$
    – ouflak
    Jun 23, 2020 at 6:34
  • \$\begingroup\$ Is that integers or positive integers? ;) \$\endgroup\$
    – Trebor
    Jun 23, 2020 at 16:07
  • 1
    \$\begingroup\$ The wording 'closest integer number that is \$x\$ order of magnitude smaller than \$w\$' is ambiguous. I initially interpreted it to mean, e.g., f(1000000, 3) = 9999 (closest integer to 1000000 that is 3 orders of magnitude smaller). As Adám said above, it seems that you're just asking for \$\lfloor w\times 10^{-x}\rfloor\$. \$\endgroup\$
    – Dingus
    Jun 25, 2020 at 0:22
-2
\$\begingroup\$

Meta-golfing Numbers

The Esolangs Wiki has a page here cataloging the shortest known programs in Brainf*** to generate a given number. A similar catalog could exist for any language: it would simply be a list of the shortest known programs in that language outputting a given constant. By extension, we can assume that for any given language, a catalog like this could be generated programmatically, by creating a program that given a constant outputs another program outputting that constant.

The Challenge

Your challenge is to create a program in any language \$A\$, such that when that program is given an input \$N\$, it outputs a program in language \$B\$ that will ouput \$N\$.

  • Languages \$A\$ and \$B\$ need not be different; you can output a program in the same language as your source code.
  • All outputted programs must be in the same language \$B\$.
  • \$N\$ is guaranteed to be a positive integer. It may be \$0\$.

I/O

  • Input and output can be done with any of the default I/O methods.
  • \$N\$ should be inputted as an integer, the string representation of an integer, or an array of digits. Programs should be outputted as a string or a list of characters.

Restrictions

  • Your program must handle values of \$N\$ at least up to \$255\$.
  • Trailing whitespace and newlines are allowed, as long as they do not make any program invalid; ie., I can have trailing newlines and whitespace as long as the implementation of \$B\$ allows them in programs.

Scoring

This question is a , so the answer with the most votes wins!

\$\endgroup\$
6
  • 2
    \$\begingroup\$ A critique of the scoring system (and possibly the challenge as a whole): In some languages, the empty program outputs its input, and in some languages, a numeric literal outputs itself. So the optimal submission will be program A, 0 bytes, for a score of 0. But even if the scoring system is changed to prevent the multiplying-by-zero exploit, I don't see how any other approach will be better than the empty-identity-program approach. So as it stands, this challenge will gather multiple trivial answers--and probably some interesting ones, but with worse scores. \$\endgroup\$
    – DLosc
    Aug 21, 2020 at 1:52
  • \$\begingroup\$ I don't think lowest score wins is a good idea for a contest where you have the flexibility to choose how difficult the task it. Might be better as a popularity contest, or maybe it would be better with a list of difficult languages to print constants in. \$\endgroup\$
    – Razetime
    Aug 21, 2020 at 2:09
  • \$\begingroup\$ @Razetime yeah, I actually hadn't realized the multiplying by zero exploit, so this seems like the best course of action - I've updated the answer. \$\endgroup\$
    – sugarfi
    Aug 21, 2020 at 12:09
  • \$\begingroup\$ Righ now, this is not metagolf, this is just... meta? \$\endgroup\$ Aug 22, 2020 at 3:10
  • \$\begingroup\$ I guess so, yeah... But metagolf is a bit catchier, isn't it? \$\endgroup\$
    – sugarfi
    Aug 22, 2020 at 13:23
  • \$\begingroup\$ Program: any implementation of cat in any language A. Language B: cat. \$\endgroup\$
    – user253751
    Aug 24, 2020 at 17:46
-2
\$\begingroup\$

Feedback Wanted

  • Is this too vague? should I change it to something like "create a quine with the fewest unique bytes", or perhaps adapt another existing challenge that might otherwise use lots of repeated bytes?
  • Maybe the idea is just too boring on its own and I should create a new proper challenge based around it?
  • Should I change the scoring system (votes - unique_bytes) - should it be divided instead, or use a more complex formula?

Introduction

This is , but not as you know it. Instead of every byte, This is sort-of also a question.

Challenge

Write an interesting program that uses the fewest unique bytes. This is not really about what the program does, but what you can do with a limited set of characters.

Rules

  • Your program must run on Try It Online
  • Programming languages with only a few permissible bytes anyway like Brainfuck's +-.,[]<>, are allowed, but officially considered boring

Apart from this, you can write anything.

Scoring

  • Hybrid of and "fewest-unique-bytes". Score is calculated as votes - unique_bytes
  • Unique bytes is based on bytes, not characters or whatever. You can calculate unique bytes using this Python snippet: len(set(b"your code here"))
\$\endgroup\$
4
  • 4
    \$\begingroup\$ It's definitely too vague. "Interesting" could mean anything, and you'd have to argue with several people over whether their ignore-input-and-print-0 program counts as interesting before the challenge is closed as too broad or unclear. [popularity-contest] is also a dangerous tag, in that it's very hard to do well and has fallen out of favor long ago. This extends to all scoring systems that involve votes. \$\endgroup\$
    – Zgarb
    Aug 21, 2020 at 19:33
  • 1
    \$\begingroup\$ I think this idea has been largely covered by Fewest (distinct) characters for Turing Completeness. Many languages require surprisingly few characters to run arbitrary code, so I expect there's not much interesting room for specific programs that use fewer characters than needed for that. \$\endgroup\$
    – xnor
    Aug 21, 2020 at 22:39
  • 1
    \$\begingroup\$ As far as I remember, there exists a Lenguage quine (that uses only 1 unique byte). I think combining popularity-contest with something else is even worse than simply using popularity-contest. \$\endgroup\$ Aug 22, 2020 at 3:00
  • 1
    \$\begingroup\$ For future reference, start your sandbox entries with the title of your challenge rather than a generic "feedback wanted". It's the prevailing convention and doing something different is a little confusing to scroll past. \$\endgroup\$
    – Beefster
    Aug 24, 2020 at 16:18
-2
\$\begingroup\$

Solving P=NP!

Today, we are going to solve P=NP, kinda...

Input

A guaranteed prime positive integer, P.

Output

The smallest composite number (NonPrime,NP) which sum of digits equals P.

Examples

Input (P)    Output (NP)      Why? (for reference)
  2              20          2+0=2 and 11 is prime
  3              12                 1+2=3
  5              14                 1+4=5
  7              16                 1+6=7
  11             38          3+8=11 and 29 is prime
  13             49                 4+9=13
  17             98          9+8=17 and 89 is prime

Check OEIS A073868 for more results.

Challenge

Write a function or program that, given a positive prime number P as input, calculates NP, the smallest composite number which sum of digits equals P.

  • Range of input: any integer prime number greater than 1, up to the limit of the chosen language.
  • Range of output: also according to the limits of the chosen language.
  • Means of input/output: free to choose.

Winning condition

This is a challenge. The shortest code wins!

Tags

Meta

I have searched if this was already posted, but with no success.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ To me, this isn't all that interesting of a challenge because it's a mash-up of "find a number whose digit sum is X" and "check if a number is prime." If a language has a built-in for primality, it's done. If not, it's still been done over and over again. The fact that the input is prime doesn't really add anything here for me. And skipping over primes as possible answers doesn't either. Why not do "find the smallest number whose digits add to X?" or "Find the Yth number whose digits add to X" where both x and y are inputs? \$\endgroup\$
    – Xcali
    Dec 23, 2020 at 20:37
  • \$\begingroup\$ The challenge itself looks to be well specified but I dislike the title. I'm all for using clever/controversial titles to attract attention, but not at the expense of accurately conveying what the challenge is about. \$\endgroup\$
    – Dingus
    Jan 1, 2021 at 1:38
-2
\$\begingroup\$

English Grammar Checker

Being tired of checking English grammar, I decided to write an English grammar regular expression.

Notations

  1. All capital letters denote an expression.
  2. Quoted strings (like "a") and lower-case letters denotes literals.
  3. AB means concatenating expressions / literals A and B together.
  4. (...) groups the expression inside the parentheses, as a whole expression.
  5. A* means repeating the expression A zero or more times.
  6. A? means the expression A is optional here.
  7. A|B means either A or B can be placed here.
  8. A=B means all expression A should be replaced by B.

Grammatical Rules

Parts of Speech

For simplicity, all parts of speech are substituted using symbols.

Symbol Part of Speech
a article
b verb
j adjective
m numeral
n noun
r pronoun
v adverb

Rules

There's a whole bunch of rules in English grammar. For simplicity, I only chose a tip of the iceberg. Your RegEx should only match all valid S's.

  1. S=N+V
  2. N=((a|m)?j*n(pN)?)|r
  3. V=b((pN)*|N)?v?

Examples

These should be matched Real-life example
anb The man runs
rbpajjnv He dives into the deep blue sea quickly
anpanbpr The wave on the sea came towards me
mnpambv Two friends of the man walks slowly
anpmjjnbajjnv The robot of two tall thin girls greets the young handsome man repeatedly
These shouldn't be matched Real-life "wrong" sentences example
nn Man child
nabr Student a told me
arbv The you laughed happily
anbvv The woman sang slowly beautifully
rbvj He is very funny

Notice that the last example is a valid English sentence, but it doesn't match our simplified rules. You shouldn't match them.

Tips

You can assume that there's no whitespaces and line feeds in the input.

You can assume that you only need to match 1 input per time.

You can use any RegEx dialects no newer than this challenge.

Scoring

Your score is the bytes in your RegEx. Flags are not counted.

The least score wins!

\$\endgroup\$
18
  • 3
    \$\begingroup\$ Are you sure that this grammar is really decidable with a regex? \$\endgroup\$
    – DELETE_ME
    Feb 19, 2021 at 9:12
  • \$\begingroup\$ YES @user202729 and I've already made one; but not decided to make it public yet. \$\endgroup\$
    – atzlt
    Feb 19, 2021 at 9:14
  • \$\begingroup\$ It's better if you explain what format the rules are specified in. (while I can understand it, it isn't obvious) The standard is Backus-Naur form I guess? \$\endgroup\$
    – DELETE_ME
    Feb 19, 2021 at 9:20
  • \$\begingroup\$ Any dialect restriction? \$\endgroup\$
    – DELETE_ME
    Feb 19, 2021 at 9:21
  • \$\begingroup\$ I wrote the format for rules in Notation section; is it unclear? \$\endgroup\$
    – atzlt
    Feb 19, 2021 at 9:22
  • \$\begingroup\$ Originally I overlook that = can be recursive and I can't find capital N in the table. \$\endgroup\$
    – DELETE_ME
    Feb 19, 2021 at 9:24
  • \$\begingroup\$ Err, yes, but I don't have good ideas about how to explain ='s. It's just kind of, substitution? But it can be recursive? Anyone have ideas? \$\endgroup\$
    – atzlt
    Feb 19, 2021 at 9:26
  • \$\begingroup\$ Perhaps you can show an example of a simple (recursive) pattern matching a simple string. \$\endgroup\$
    – DELETE_ME
    Feb 19, 2021 at 9:30
  • \$\begingroup\$ Not sure if you're asking an example regex matching a recursive rule. For A=(yA)|x using the same notation, regex: y*x. \$\endgroup\$
    – atzlt
    Feb 19, 2021 at 9:37
  • \$\begingroup\$ Does "without flags" mean ", flags are not counted"? That sentence can be interpreted as "regex flags are not allowed" too. \$\endgroup\$
    – DELETE_ME
    Feb 20, 2021 at 8:44
  • 2
    \$\begingroup\$ English grammar is not regular and cannot be matched with a regular expression. At best, you can tease out some subset that is context-free, but realistically, this is not a good challenge as it is written. Natural languages tend to be riddled with all sorts of crazy complexity that makes them highly context-sensitive and possibly undecidable. \$\endgroup\$
    – Beefster
    Feb 22, 2021 at 16:55
  • 1
    \$\begingroup\$ @Beefster As I wrote in the challenge you should only match the simplified "rules", as in section Rules. There're only 3 rules. As I commented before I already wrote a regex that can match these rules, so the challenge is absolutely solvable. \$\endgroup\$
    – atzlt
    Feb 23, 2021 at 2:54
  • \$\begingroup\$ @Beefster And op did do that. (op claim that the chosen subset is context-free, but I didn't verify it) \$\endgroup\$
    – DELETE_ME
    Feb 24, 2021 at 3:52
  • \$\begingroup\$ @user202729 if you want to verify, <S> ::= <N><V>, <J> ::= "j"<J> | "", <N> ::= "r" | "a"<J>"np"N | "a"<J>"n" | "m"<J>"np"N | "m"<J>"n" | <J>"np"N | <J>"n", <P> ::= "p"N<P> | "", <V> ::= "b" | "bv" | "b"<N> | "b"<N>"v" | "b"<P> | "b"<P>"v". Really verbose. \$\endgroup\$
    – atzlt
    Feb 24, 2021 at 4:08
  • \$\begingroup\$ Even with this limited subset, reducing it to a regex really only has one optimal approach and isn't particularly interesting in lending itself to many different approaches. \$\endgroup\$
    – Beefster
    Feb 24, 2021 at 16:31
-2
\$\begingroup\$

Given a positive even integer \$n\$, generate a random Brainfuck snippet of length \$n\$, containing only +-<>, that do no modify to the tape or tapehead.

To avoid random generation and try again or fallback into a trivial nop for invalid nops, your solution should run in polynomial time, and the ratio of possibility returning any two nops should be below polynomial.

\$\endgroup\$
1
145 146
147
148 149
153

You must log in to answer this question.

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