Print your char count in words, in many languages This challenge is inspired by my earlier challenge "Create a program that prints the amount of characters it has, in words".

This challenge's rules are simple: make a program that prints its character count, in words, which works in as many languages as possible.

Each programming language the program works in must make the program print its char count in a different natural language.

E.g. you can make a polyglot which prints "fifty" (suppose this is its char count) in one language and "pedeset" (Serbocroatian for 50) in another, but not a polyglot printing "fifty" in both languages.

An extension to the "don't invent languages to solve the task" rule also applies here: don't make a constructed language just to validate your otherwise nonsense output in some language.

If the polyglot printing "fifty" in one language was tested in another and printed (prant?) "Aijsisdjdsl", it's illegal to make a conlang using "Aijsisdjdsl" as the word for "fifty".

Capitalization is ignored: in case you're printing "one" (somehow) you can print "one", "oNe", "ONE" or anything else.

Base ten is required.

Proper spacing is also required.

In the (unlikely but just for specification) case your program reaches one billion characters or more, use the American number scale. A billion here is 10^9 and a million is 10^6.

Do not use "one hundred and one": use "one hundred one".

Do not use the hyphen. Print forty four, not forty-four.

If the language you use has another script, use it instead of the romanization of it. If your program prints Arabic in some language, it should print (yet again, example with 50) "خمسون" and not "khamsun".

Use the grammatically correct translation.

For our purposes, we use Ethnologue to determine what is and isn't a language in this challenge. It's the most widely used so we'll just go with that.

For simplicity, any languages with identical numerals will be considered the same for this challenge. Using any Japanese/Chinese numeral gives you a score of 1.

If a word is spelled the same in multiple languages, e.g. English and French's "six", it counts as one point toward your score.

Dialects Ethnologue differentiates will be considered different languages as long as they don't fall in the two rules above.

Different compilers of the same programming languages are not differentiated here.

Your score is the amount of languages your program works in, per standard rosetta-stone rules.

If the two (or more) best answers are tying, the one with the lowest byte count wins.

The encoding used to determine byte count for tiebreakers is UTF-8.

The highest score wins (in case of tie see above). Have fun.

9 10 12 13 16 18 21 23 languages, 1000 bytes

Bash (prints "duizend", Dutch)
Zsh (prints "een Dausend", Luxembourgish)
Dash (and other true POSIX shells) (prints "nje mije", Albanian)
C (prints "et tusind", Danish)
C++ (prints "ib txhiab", Hmong)
brainfuck (prints "mille", Italian)
boolfuck (prints "afe", Samoan)
Brainlove (prints "mil", Spanish)
2DFuck (prints "sewu", Javanese)
Python 1 (prints "one thousand", English)
Python 2 (prints "eintausend", German)
Python 3 (prints "hal kun", Somali)
Asar (prints "tuhat", Estonian)
><> (prints "jedna hiljada", Bosnian)
Gol><> (prints "eenduisend", Afrikaans)
Befunge-98 (prints "o mie", Romanian)
Befunge-96 (prints "otu puku", Igbo)
Labyrinth (prints "elf", Maltese)
Hexagony (prints "ett tusen", Swedish)
GNU Make (prints "isang libo", Filipino)
A Pear Tree (prints "hezar", Kurdish)
Octave (prints "tūkstantis", Lithuanian)
Whispers (prints "seribu", Malay)

#ifdef    warnings //[[^
#_ if 0
#{
#(________ )
'''''echo' -n<<"'''+r'''":
    @echo   "isang libo"
define N #
1_801_201_
0
1...@
endif
print "tuhat"
macro _()
#}
disp("t\xc5\xabkstantis")
quit
#{
> "seribu"
>> Output 1
'''+r''':
[ -n "$ZSH_VERSION" ]&&echo een Dausend||([ -n "$BASH_VERSION" ]&&echo duizend||echo nje mije)
:<<"endmacro;\"^*///]\"\"\"#/t#"
#endif
#include<stdio.h>
int main(){puts(sizeof('1')-1?"et tusind":"ib txhiab");}
/*
print"hezar";exit;<<'/*';#NJ@G@GMCI
1234567890123456789012345678901234567890123|u;ts;6ie$;;tn;e@$<
]+[+++[[<+>->+++++>+<<]+>]<<<.<.+++.(.<.)>>+;+;;;;+;;+;;+;;+;;+;;+;+;+;+;+;;+;;+;[-]]![!.!...!..!..!.!..!..!.!.!.!.!...!.!...!.!...!.!.!.!.!][
'''
print(["hal kun","eintausend","one thousand"][(type(1==1)==type(1))+(3/2==1)])
r""""
01234567891234567890123456789012                               1
                       >"ukup uto">:#,_@
                H"eenduisend"\
        >o<"jedna hiljada"~\ u
#}
endef #   >"eim o"4k,@ /"`"/"/"\
endmacro;"^*///]"""#/t#

There should be a hard tab at the start of line 6.

Try it online! (use the switch languages button to try them all)

Length is exactly 1000 ASCII characters, and also 1000 bytes.

Asar is a SNES assembler that has quite sloppy input parsing and thus accepts a lot of  inputs that one may consider invalid. I used version 1.71 for this, downloadable here, and depended on quite a few bugs, so there is a chance this will break in later versions.

All of the other languages are well-known enough to be on TIO.

I used Google Translate for the translations, so they may not be perfectly grammatically accurate. If anyone knows some of the languages better, please suggest improvements, I've got some wiggle room here :)

Credits: @JoKing for some minor optimizations regarding brainfuck, befunge, (gol)><>, hexagony, and python. @flawr for suggesting and helping with octave. @caird coinheringaahing for suggesting whispers.

Fun fact: I made most of this polyglot months ago. It included the first 10 languages mentioned here. (edit: I've since shuffled the language list around a bit so it makes more sense, but check the 2nd oldest version of this polyglot in the edit history and add hexagony to get that list).

Explanation (slightly outdated)

This explanation was made for an older revision. It's hard enough keeping track of all the natural language shuffling (to make more difficult programming languages use shorter natural language words) and Hexagony's constant grid shifting, let alone update the explanation every single revision. I'm leaving this here since it still gives a good overview of how what path most of these languages take.

Asar

Asar is a SNES assembler written by Alcaro in 2011, intended to be backwards-compatible with xkas (written by byuu in around 2006). It doesn't have the nicest code. The first line begins with a special kind of label definition, the label is called ifdef. Then follows a warnings command, which is supposed to control when warnings are thrown. Usually it's followed by either push or pull, but it doesn't reject other words following it. So that's the first line: a label-definition followed by a no-op. The 2nd line is a similar label definition (this time the label is called simply _) followed by an if statement. The condition is 0, so the contents of the if are ignored. This means we can pretty much go wild inside it, the only rule we have to follow is that all double-quotes must be paired. The end of that if statement is at the endif on line 10. After that comes a simple print statement which prints the output. Then comes a macro declaration. Declaring a macro that isn't used is pretty much equivalent to an if 0. The end of the macro declaration is on the very last line. In Asar, comments are started with ;, so the rest of the last line is ignored.

Bash, Zsh, Dash

The first 3 lines are just regular comments. The 4th line is equivalent to echo -n <<"'''+r''':". This is an echo without a linebreak following it. Then we have a heredoc that ends at any occurrence of '''+r''':. The contents of the heredoc are piped to the stdin of that echo command, but that doesn't matter since echo ignores its stdin. After the end of the heredoc on line 14, we have regular shell code that checks whether the variables for either zsh or bash are defined and chooses what to print based on that. After that, we have the null command :, which does nothing, into which we pipe the rest of the script using another heredoc. The heredoc ends with endmacro;"^*///]"""#/t#, which just happens to be the very last line of the script.

C, C++

The first line is a preprocessor directive which checks whether the define "warnings" is defined. There's also a comment after the directive. warnings isn't defined, so the contents of the block are skipped. There are a bunch more garbage preprocessor directives inside the skipped if branch, but they are ignored too. The #endif is on line 18. After that we have a standard C program. It checks whether the size of a character literal is greater than 1 or not. If it's greater, we are in C, because in C character literals are actually of int type, which has a size of at least 2 bytes on literally every platform in use today. In C++, however, the type of a character literal is char, which is defined to have a size of 1, so a different branch is taken.
The rest of the code is a single comment, started with /* at line 21. It's terminated in the middle of the last line, but followed immediately by a single line comment.

Brainfuck

On the first line, we have 2 open brackets. This is because one of them is eaten by the heredoc that ends the shell part, which is before the brainfuck part. There are some balanced brackets within the skipped part too, but they don't matter because they are balanced. The next closing bracket is on line 21, which is also the start of the brainfuck code. I used this text-to-brainfuck converter, because somehow it generated even better output than BF-Crunch. Then follows the boolfuck code, which is mostly ignored due to ; not being defined. The increments don't matter either, we just switch to the next cell which has never been written to so the next open bracket is a guaranteed jump. The next closing bracket after that is on the very last line, and there are no brainfuck instructions after it.

Boolfuck

The boolfuck control flow is quite similar. However, once the brainfuck code is reached, most of it is ignored as - isn't defined in boolfuck. The area with + and ; is where the output is actually printed. It just prints the string "mil" bit by bit, with + negating the current bit and ; outputting it. The rest of the control flow is identical to brainfuck.

Python 1, 2, 3

The first 3 lines are regular comments. The 4th line starts with a triple-quoted string literal, delimited by single quotes. This string literal is often closed and reopened because I needed to get a backslash in somewhere (I've forgotten where), so I needed the string literal to be raw, but I couldn't put the r before the first quotes. Anyways, the first place where the string literal is closed and not immediately followed by another string literal is on line 23, which is the start of the Python code. This code uses a few simple tests to determine which version of Python it's running on: in Python 1.6, there was no separate boolean type, so the results of comparisons were just ints. The first condition checks that. The second condition checks whether division rounds down or not. In Python 2, division on integers rounded the result down, whereas in Python 3, it results in a floating point answer. After the Python code, we have another raw string literal that lasts until the last line, where it is immediately followed by a comment.

><>, Gol><>

Now we get to the 2D languages. Gol><> is almost perfectly backwards compatible with fish, so they start execution the same way. In fish, execution starts from the north east ("top left") corner of the program, with the instruction pointer pointing west. In fish, # is a mirror which reflects the instruction pointer back in the direction it came from. The # causes the IP to point west instead. In fish, program space is topologically a torus, so going off the western edge results in reappearing at the eastern edge of the program. There it encounters ^, which changes the instruction pointer's direction to north. Execution then continues from the very bottom of the script. The IP goes right past the very last character of the program and hits the / on line 31. The / reflects the IP like a mirror, so it'll go east again. Here is where we determine if we are running fish or golfish. In golfish, quotes inside string literals can be escaped with `. So in golfish, the string literal is only terminated on the 3rd quote on that line. In regular fish, however, the backtick escape doesn't exist, so the string literal ends after the 2nd quote. (The 4th quote is needed to keep Asar happy about paired quotes). Then, both IPs are reflected upwards. The fish one goes west on line 30 and follows a pretty simple text printing program. The golfish one goes west on line 29, after switching to a different stack with the u in its path on line 30. There, it follows a very simple string printing code too (just push the string on the stack and call H, which exits and dumps the whole stack as ASCII text).

Befunge-98

In Befunge-98, execution starts out in the north west ("top left") corner of program space, pointing east. # is a trampoline command, it skips the next instruction. The letters a-f just push their hex value on the stack. Spaces are no-ops. w pops 2 items from the stack, compares them, and turns left or right depending on which one is larger. here, f is larger than e (15 is larger than 14), so we turn left, with the IP pointing north. Now we jump to the bottom of the program, like in fish, and follow the path of arrows to line 31. This uses a simple string printing code with the k operator, which repeats the next instruction (print character) some number of times, 5 in this case.

Hexagony

This was the one language that probably costed me the most time while writing this thing. This explanation is a bit oversimplified, go look at Hexagony's README or wiki page if you want to learn more. Hexagony reformats your program into a hexagon. Then execution starts at the north-west corner. The first command, #, switches to the IP with the index of the current memory cell (there are 6 IPs, each one starting at a different corner of the hexagon). Memory is initialized to all 0's though, so this switches to the first IP, which is the one that is already executing. All alphabetic characters simply set the current memory cell to their value, so most of the rest of the 1st line is just no-ops. Then there's a mirror, /, which makes the IP point north-west (as if it got reflected off the mirror). This means the IP will wrap around to the very bottom of the hexagon. There, it happens to hit the / at the very end of the script. This is also a mirror and makes the IP go east again. Then we set the current memory cell to t and use the "switch IP" command again. Since there are only 6 IPs, the current memory cell is taken modulo 6 when switching, so it goes to the 3rd IP, which starts at the eastern corner of the hexagon. This IP starts out moving southwest and it executes some useless operations before reaching the end of line 23 in the original code. There it uses the $ operator to skip over some characters the first time around, then encounters | which turns it around and prints some more characters.

Labyrinth

In labyrinth, control flow is determined by the program's layout. All spaces and alphabetic characters are considered walls. The # command pushes the number of items on the stack, which is 0, to the stack. Then execution continues in the only possible direction, south. Here, the number of items on the stack is pushed again, this time pushing a 1. Now there's 2 directions to go: south again or east. Since the topmost value on the stack is positive, execution would try to go west, but that path is blocked, so it goes east instead. _ pushes a 0. Now there's again 2 directions to go, but we came from one direction and unless nothing else is possible, the IP will never flip around and go back the direction it came from, so we continue south. Here we have a (, which decrements the top of the stack. This means the topmost item is now -1. Excluding the direction we came from, there's 3 directions to go, but since the top of the stack is negative, we go east. Here we push 0 a bunch of times, which means we continue east for as long as possible. In the end, we go south because that's the only other place to go. There we find a ', which is a no-op if debugging output isn't enabled. Now, labyrinth treats tabs as a single space, so the character south of the ' is actually " from the start of the echo's parameters. Execution continues there. Below that, there is only one path to follow, which leads to the 4th character of line 9. There, we simply construct the ascii values corresponding to "elf" and print them.

Make

The first 3 lines are comments. The 4th line is somehow a valid target name. (To be honest, I have no idea either about why this works.) Since this is the first target in the makefile, it's what gets executed when no argument is given to make. The rule just prints the character count. Then we define a variable called N which contains the rest of the script. It ends on the 2nd-to-last line with the endef command. Following it is a comment that ends with a backslash. This causes make to interpret the next line as part of the comment too.

A Pear Tree

A Pear Tree starts execution by finding the longest substring of the program whose CRC32 is 0. Then it shifts the whole program so that said substring is at the start of the program. This long substring with a CRC32 of 0 is print"hezar";exit;<<'/*';#NJ@G@GMCI, which just happens to be valid Perl code. No, actually I used a tool called crchack to generate some letters to add to a comment so that the string's CRC is 0. So this Perl program is shifted to the very beginning of the program. It contains a print statement, an exit statement and a heredoc. The heredoc is terminated by the line that was right before the perl script originally, and thus is at the very end of the program now. So the heredoc skips the entire rest of the script and all of the syntax errors that would arise from not doing so.


Binary Reduce a List By Addition With a Right Bias Given a list of 2 or more strictly positive integers, sum the first and last half of the list, with the middle element being counted only in the right half if the list has an odd number of elements

Some examples of the middle element being counted in the right half:

[1, 2, 3, 4]       -> Left: [1, 2];    Right: [3, 4]
[1, 2, 3]          -> Left: [1];       Right: [2, 3]
[1, 2, 3, 4, 5]    -> Left: [1, 2];    Right: [3, 4, 5]
[1, 2, 3, 4, 5, 6] -> Left: [1, 2, 3]; Right: [4, 5, 6]

Test Cases

Input

[1, 9]
[9, 5, 5, 7]
[6, 7, 5, 1, 3, 9, 7, 1, 6]
[2, 8, 10, 9, 9, 3, 7, 8, 9, 8, 6, 1, 2, 9, 8, 3, 8, 9, 5]
[2, 3, 1, 8, 6, 2, 10, 6, 7, 6]

Output

[1, 9]
[14, 12]
[19, 26]
[65, 59]
[20, 31]

Reference Program With Two Output Methods

Rules

Input/Output can be Taken/Given in any convenient and reasonable format.
Functions and full programs are both acceptable.

Python 2, 40 bytes

Takes as input a list \$ l \$, and outputs the two sums in reverse order ([right, left]).

lambda l:[sum(l.pop()for x in l),sum(l)]

Explanation

In sum(l.pop()for x in l), we pop the last element, in each iteration, and sum the popped elements. Surprisingly, the loop only runs \$ \lceil{\frac{|l|}{2}}\rceil \$ times, since for every element we iterate from the left, we are removing an element from the right, resulting in the loop terminating somewhere in the middle. Therefore it gives us the sum of the right portion of the list. The sum of the remaining elements make up the left portion.

Try it online!


Find all a, b, c, d, e, such that a + b + c + d + e = 1000 with no more than 3 loops The rule is:

a, b, c, d, e is an integer from 0 to 1000, no relation between a, b, c, d, e so a can equal to b or c, ...
can not use more than 3 loops (it can be 3 nested loops or 3 normal loops, or 2 nested loops + 1 normal loop, ...)
you need to find all the answers for (a, b, c, d, e) that is:

a + b + c + d + e = 1000

Your answer can be any format: line by line, array, object, ... but it must be clear so anyone can see it.
Shortest bytes will be win for each language!

For example here is when I used 5 loops to solve this puzzle and it violates the rules:

https://repl.it/repls/BestKnobbyDonateware

APL (Dyalog Unicode), 23 16 bytesSBCS

Full program. No loops. Prints a list of quintuplets with two spaces between them. Each quintuplet has the variables separated by single spaces. Requires 0-indexing (⎕IO←0) which is default on many systems.

⍸1E3=⊃∘.+/5⍴⊂⍳1001

Since the above code requires more memory than available on TIO, here's exactly the same, but with a + b + c + d + e between 0 and 10 and a sum of 10:

⍸1E1=⊃∘.+/5⍴⊂⍳11.0

Try it online!

⍳1001 the ɩntegers 0…1000

⊂ enclose to treat as a unit

5⍴ reshape that to length 5

∘.+/ reduction by outer-sum (like outer product, but with plus)
this creates a 5D array with all dimensions being 1000 elements long

⊃ disclose (the reduction had to enclose the result to reduce the rank from 1  to 0)

1E3 5D Boolean mask where equal to 1000

⍸ list of ɩndices where true


Tips for golfing in INTERCAL What general tips do you have for golfing in INTERCAL? I'm looking for ideas which can be applied to code golf challenges and are also at least somewhat specific to INTERCAL (i.e. "remove comments" is not a useful answer).

I know exotic languages can be really useful to win golf contests, but I don't see much INTERCAL code around here. Do you have any advice that can help people get competitive code sizes with INTERCAL? Could this language ever be competitive?

INTERCAL is so underutilized that it doesn't even have a tag. So sad...

Focus on doing as much work as possible in one statement

INTERCAL's statement identifiers are rather verbose; DO is two noise characters on every statement, the statement's name itself also tends to be quite long, and you have to throw in a PLEASE every now and then to keep the parser happy. (The best you can do is a ratio of four DO to one PLEASE, meaning you're using 14 characters in identifiers for every 5 commands.) On the other hand, the expression syntax is fairly terse (ridiculous, but terse). This means that it's often worthwhile fitting part of your program into a single expression even when using multiple statements would be a more "natural" way to do things.

For example, if you want to assign #1 to .1 and #2 to .2, instead of doing it in the obvious INTERCAL-72 way:

DO.1<-#1DO.2<-#2

it's strongly worth considering overloading a random variable to allow you to assign both at once:

DO:1<-#1$#2

(with :1/!1$.2' thrown in somewhere earlier in the program; note that this notation postdates INTERCAL-72 by quite a way, so you'll need to use a modern INTERCAL for this to work). This is only slightly longer even if you take the setup into account, and becomes shorter if you ever need to, or can arrange to, simultaneously assign to .1 and .2 more than once.

It's not just calculate commands where this trick works. If you need to stash a variable twice, don't do it like this:

DOSTASH.1DOSTASH.1

but like this:

DOSTASH.1+.1

(The + notation works for most commands where it could conceptually make sense.)


Determine if a grid contains another grid Challenge

Create a function takes in two 2-dimensional arrays of characters (or strings if the programming language does not have characters as a datatype) as inputs: a and b. If your language does not support these inputs, you may use any other standard one-byte variable.

Your task is to determine if b contains a. If this is so, return true. Otherwise, return false.

Sample Test Cases

a:

123
456
789

b:

123
456
789

should return true.

a:

code
golf

b:

thisis
code!!
golf!!
ohyeah

should return true.

a:

abcd
efgh
ijkl

b:

abcdef
ghijkl
mnopqr

should return false.

a:

abc
def

b:

1abc2
3def4
5ghi6

should return true

a:

ab
cd

b:

#ab##
##cd#

should return false

This is code-golf so least bytes wins.

Brachylog (v2), 4 bytes

s\s\

Try it online!

Most easily run as a full program, as usual for a decision-problem, with a specified as a command-line argument, b on standard input. The question asks for a function, and the program also works as a function, with b on the left, a on the right, and output via producing an exception if and only if the decision is  false.

Explanation

s\s\
s     a substring of rows of {the left input}
 \…\  assert rectangular; swap row and column operations
  s   a substring of <s>rows</s> columns of {the above matrix}
      {implicit} assert that the result can be {the right input}

The "assert rectangular" is, obviously, pointless, as the question guarantees that already. The rest of the program does the grid-finding for us by identifying a substring of the rows and of the columns, i.e. a submatrix.

Meta-discussion

We've had a very similar question before; I'd expect most answers to one question to be modifiable into answers to the other. I think this is the neater version of it, though.


Longest Non-Repeating Substring Given a string as input find the longest contiguous substring that does not have any character twice or more.  If there are multiple such substrings you may output either.  You may assume that the input is on the printable ASCII range if you wish.

Scoring

Answers will first be ranked by the length of their own longest non-repeating substring, and then by their total length.  Lower scores will be better for both criteria.  Depending on the language this will probably feel like a code-golf challenge with a source restriction.

Triviality

In some languages achieving a score of 1, x (lenguage) or 2, x (Brain-flak and other turing tarpits) is pretty easy, however there are other languages in which minimizing the longest non-repeating substring is a challenge.  I had a lot of fun getting a score of 2 in Haskell, so I encourage you to seek out languages where this task is fun.

Test cases

"Good morning, Green orb!" -> "ing, Gre"
"fffffffffff" -> "f"
"oiiiiioiiii" -> "io", "oi"
"1234567890"  -> "1234567890"
"11122324455" -> "324"

Scoring submission

You can score your programs using the following snippet:

input.addEventListener("input", change);

// note: intentionally verbose :)
function isUnique(str) {
  var maxCount = 0;
  var counts = {};
  for(var i = 0; i < str.length; i++) {
    var c = str.charAt(i);
    counts[c] |= 0;
    counts[c]++;
    if(maxCount < counts[c]) {
      maxCount = counts[c];
    }
  }
  return maxCount <= 1;
}

function maximizeSubstring(str, pred, cost) {
  var mostExpensive = -1;
  // iterate over substrings
  function iterate(start, end) {
    var slice = str.slice(start, end);
    if(pred(slice)) {
      var profit = cost(slice);
      if(profit > mostExpensive) {
        mostExpensive = profit;
      }
    }
    end++;
    if(start >= str.length) {
      return;
    }
    else if(end > str.length) {
      start++;
      iterate(start, start);
    }
    else {
      iterate(start, end);
    }
  }
  iterate(0, 0);
  return mostExpensive;
}

function size(x) {
  return x.length;
}

function longestNonRepeatingSize(str) {
  return maximizeSubstring(str, isUnique, size);
}

function change() {
  var code = input.value;
  output.value = "Your score is: " + longestNonRepeatingSize(code);
}

change();
* {
  font-family: monospace;
}
Input code here:

<textarea id="input"></textarea>

<textarea id="output"></textarea>

C, score 2,  747   720  662 bytes

L  [  1  <<  7  ]  ,  *  q  ,  *  r  ,  l  ,  d  ,  i  ,  c  ,  j  ,  s  ,  t  ,  k  =  1  <<  7  ;  h  (  )  {  q  =  s  +  i  +  j  ++  ;  *  q  %  k  &&  !  L  [  *  q  %  k  ]  ++  &&  h  (  ++  c  )  ;  }  g  (  )  {  q  =  s  +  i  ;  *  q  %  k  ?  z  (  k  )  ,  h  (  j  =  c  =  0  )  ,  c  >  d  &&  (  d  =  c  )  &&  (  l  =  i  )  ,  g  (  ++  i  )  :  0  ;  }  f  (  S  ,  T  )  {  s  =  S  ;  l  =  i  =  d  =  0  ;  g  (  t  =  T  )  ;  p  (  i  =  0  )  ;  }  p  (  )  {  q  =  s  +  l  +  i  ;  r  =  t  +  i  ;  i  ++  <  d  ?  p  (  *  r  =  *  q  )  :  (  *  r  =  0  )  ;  }  z  (  i  )  {  L  [  --  i  ]  =  0  ;  i  &&  z  (  i  )  ;  }

Works at least on 32-bit MinGW (with optimizations disabled). Doesn't use a single keyword.

Works apparently on TIO with gcc and clang, too: Try it online! (Thanks @Dennis!)

Call with:

int main()
{
    char str[1024];

    f("Good morning, Green orb!", str);
    puts(str);

    f("fffffffffff", str);
    puts(str);

    f("oiiiiioiiii", str);
    puts(str);

    f("1234567890", str);
    puts(str);

    f("L  [  1  <<  7  ]  ,  *  q  ,  *  r  ,  l  ,  d  ,  i  ,  c  ,  j  ,  s  ,  t  ,  k  =  1  <<  7  ;  h  (  )  {  q  =  s  +  i  +  j  ++  ;  *  q  %  k  &&  !  L  [  *  q  %  k  ]  ++  &&  h  (  ++  c  )  ;  }  g  (  )  {  q  =  s  +  i  ;  *  q  %  k  ?  z  (  k  )  ,  h  (  j  =  c  =  0  )  ,  c  >  d  &&  (  d  =  c  )  &&  (  l  =  i  )  ,  g  (  ++  i  )  :  0  ;  }  f  (  S  ,  T  )  {  s  =  S  ;  l  =  i  =  d  =  0  ;  g  (  t  =  T  )  ;  p  (  i  =  0  )  ;  }  p  (  )  {  q  =  s  +  l  +  i  ;  r  =  t  +  i  ;  i  ++  <  d  ?  p  (  *  r  =  *  q  )  :  (  *  r  =  0  )  ;  }  z  (  i  )  {  L  [  --  i  ]  =  0  ;  i  &&  z  (  i  )  ;  }");
    puts(str);
}

Output:

The code with slightly more readable formatting:

L[1<<7],
*q, *r, l, d, i, c, j, s, t, k=1<<7;

h()
{
    q = s+i+j++;
    *q%k && !L[*q%k]++ && h(++c);
}

g()
{
    q = s+i;
    *q%k ? z(k), h(j=c=0), c>d && (d=c) && (l=i), g(++i) : 0;
}

f(S, T)
{
    s = S;
    l = i = d = 0;
    g(t=T);
    p(i=0);
}

p()
{
    q = s+l+i;
    r = t+i;
    i++<d ? p(*r=*q) : (*r=0);
}

z(i)
{
    L[--i] = 0;
    i && z(i);
}

And this can be used to generate proper spacing to get to the formatting with score 2: Try it online!

C, score 3, 309 bytes

i
,
j
,
l
,
c
,
d
;
f
(
\
c\
\
h\
\
a\
\
r
*
s
)
{
\
f\
\
o\
\
r
\
(
i
=
l
=
d
=
0
;
s
[
i
]
;
c
>
d
&&
(
d
=
c
)
&&
(
l
=
i
)
,
++
i
)
\
f\
\
o\
\
r
(
\
c\
\
h\
\
a\
\
r

L
[
\
1\
\
2\
\
8
\
]
=
{
j
=
c
=
0
}
;
s
[
i
+
j
]
&&
!
L
[
s
[
i
+
j
++
]
]
++
;
++
c
)
;
\
w\
\
r\
\
i\
\
t\
\
e
(
1
,
s
+
l
,
d
)
;
}

Try it online!


26 Singers, 26 Letters According to RollingStone, below are the 26 greatest singers of all time:
Aretha Franklin         Al Green
Ray Charles             Robert Plant
Elvis Presley           Mick Jagger
Sam Cooke               Tina Turner
John Lennon             Freddie Mercury
Marvin Gaye             Bob Marley
Bob Dylan               Smokey Robinson
Otis Redding            Johnny Cash
Stevie Wonder           Etta James
James Brown             David Bowie
Paul McCartney          Van Morrison
Little Richard          Michael Jackson
Roy Orbison             Jackie Wilson

You can get this as a list of strings here.
Task
Given a singer name, print or return a letter from A to Z which uniquely identifies this singer. (If your code returns A for Bob Dylan, then it cannot return A for any other singer.)
As opposed to other similar challenges, the mapping is up to you as long as it's collision-free.
Rules

The input is guaranteed to be one of the 26 singer names listed above with this exact spelling and without any leading or trailing whitespace.
You may output the letter in either lowercase or uppercase. But it must be consistent.
You are encouraged to provide a test suite for all 26 possible inputs.
This is code-golf, so the shortest answer in bytes wins!


Detect what programming language a snippet is Your challenge is to take some source code as input, and output which programming language it is written in.

For example, you could have the input

class A{public static void main(String[]a){System.out.println("Hello, World!");}}

And output

Java

Your two main goals are diversity (how many programming languages you can detect) and accuracy (how good you are at detecting these languages).

For polyglots (programs valid in more than one language), you can decide what to do. You could just output the language that your program thinks is more likely, or you could output an error, or you could output an array of possible choices (which would probably get more upvotes than just an error!).

This is a popularity-contest, because it would be very difficult to specify a different objective winning criterion. Voters, please vote on how many languages it can detect and how accurate it is.

234 text formats - Unix Shell
(not all of them languages - I need to count them carefully)
file $1

I hesitate to post this somewhat smart-a$$ answer, but I don't see anything in the rules banning it and the file shell utility really does do a good job of this.  e.g:
$ file golfscript.rb
golfscript.rb: Ruby module source, ASCII text
$ file template.c
template.c: ASCII C program text
$ file adams.sh
adams.sh: Bourne-Again shell script, ASCII text executable
$

Furthermore you can use the -k option to "keep going" when testing a polyglot:
 -k, --keep-going
         Don't stop at the first match, keep going.  Subsequent matches
         will be have the string ‘\012- ’ prepended.  (If you want a new‐
         line, see the -r option.)

Also, the -l option will give you an idea of how good the algorithm is for differing languages:

$ file -l | grep shell
unknown, 0: Warning: using regular magic file `/etc/magic'
Strength = 280 : shell archive text [application/octet-stream]
Strength = 250 : Tenex C shell script text executable [text/x-shellscript]
Strength = 250 : Bourne-Again shell script text executable [text/x-shellscript]
Strength = 240 : Paul Falstad's zsh script text executable [text/x-shellscript]
Strength = 240 : Neil Brown's ash script text executable [text/x-shellscript]
Strength = 230 : Neil Brown's ae script text executable [text/x-shellscript]
Strength = 210 : Tenex C shell script text executable [text/x-shellscript]
Strength = 210 : Bourne-Again shell script text executable [text/x-shellscript]
Strength = 190 : Tenex C shell script text executable [text/x-shellscript]
Strength = 190 : Bourne-Again shell script text executable [text/x-shellscript]
Strength = 180 : Paul Falstad's zsh script text executable [text/x-shellscript]
Strength = 150 : Tenex C shell script text executable [text/x-shellscript]
Strength = 150 : Bourne-Again shell script text executable [text/x-shellscript]
Strength = 140 : C shell script text executable [text/x-shellscript]
Strength = 140 : Korn shell script text executable [text/x-shellscript]
Strength = 140 : Paul Falstad's zsh script text executable [text/x-shellscript]
Strength = 130 : POSIX shell script text executable [text/x-shellscript]
Strength = 130 : Plan 9 rc shell script text executable []
$

This is file-5.09 (on Ubuntu 12.04)


Validating a Battleship board Do you know the game Battleship? Well, I want to play with my little brother, but before we can begin we need to set up our ships on the board. This is your input.
Now, we need to check that the ships that we set up are valid. This is where you come in to help. Your task is to write a program or function which checks whether the given 2d array (your board/input) is a valid board or not.
The input will be a 2d array, where 1 represents part of a ship and 0 represents part of the ocean.
The rules:

There must be:

One battleship (size 4)
Two cruisers (size 3)
Three destroyers (size 2)
Four submarines (size 1)

Any additional ships are not allowed, and neither are missing ships
Each ship must be either vertical or horizontal (aside from submarines, which are a single grid space)
The ships cannot overlap, but may be adjacent

in addition, you must solve this with a BF function (naturally the class will be called BF) which receives the 2d array(input) and uses a validate function. Afterward, you are free to manipulate the 2d array however you want and add any functions that you want.

here are some more examples(inputs) that your code must pass:
is valid:
 {1,1,1,1,0,0,0,0,0,0},
 {1,1,1,1,0,0,0,0,0,0},
 {1,1,1,1,0,0,0,0,0,0},
 {1,1,1,1,0,0,0,0,0,0},
 {1,1,1,1,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},
 {0,0,0,0,0,0,0,0,0,0},
 {0,0,0,0,0,0,0,0,0,0},

InvalidShapeOfBoat which is invalid->
 {1,0,0,0,0,1,1,0,0,0},
 {1,0,0,0,0,0,0,0,1,0},
 {1,1,0,0,1,1,1,0,1,0},
 {0,0,0,0,0,0,0,0,0,0},
 {0,0,0,0,0,0,0,0,1,0},
 {0,0,0,0,1,1,1,0,0,0},
 {0,0,0,0,0,0,0,0,1,0},
 {0,1,0,1,0,0,0,0,0,0},
 {0,1,0,0,0,0,0,1,0,0},
 {0,0,0,0,0,0,0,0,0,0},

wrong ships, result is false-
 {1,0,0,0,0,1,1,0,0,0},
 {1,0,1,0,0,0,0,0,1,0},
 {1,0,1,0,1,1,1,0,1,0},
 {1,0,0,0,0,0,0,0,0,0},
 {0,0,0,0,0,0,0,0,1,0},
 {0,0,0,0,1,1,1,0,0,0},
 {0,1,0,0,0,0,0,0,1,0},
 {0,0,0,1,0,0,0,0,0,0},
 {0,0,0,0,0,0,0,1,0,0},
 {0,0,0,0,0,0,0,0,0,0},

missing ships, is false->
 {0,0,0,0,0,1,1,0,0,0},
 {0,0,1,0,0,0,0,0,1,0},
 {0,0,1,0,1,1,1,0,1,0},
 {0,0,0,0,0,0,0,0,0,0},
 {0,0,0,0,0,0,0,0,1,0},
 {0,0,0,0,1,1,1,0,0,0},
 {0,0,0,0,0,0,0,0,1,0},
 {0,0,0,1,0,0,0,0,0,0},
 {0,0,0,0,0,0,0,1,0,0},
 {0,0,0,0,0,0,0,0,0,0},

check contact, is true->
 {1,1,1,0,0,0,0,0,0,0},
 {1,1,0,0,0,0,0,0,1,0},
 {1,1,0,0,1,1,1,0,1,0},
 {1,0,0,0,0,0,0,0,0,0},
 {1,0,0,0,0,0,0,0,1,0},
 {0,0,0,0,1,1,1,0,0,0},
 {0,0,0,0,0,0,0,0,1,0},
 {0,0,0,0,0,0,0,0,0,0},
 {0,0,0,0,0,0,0,1,0,0},
 {0,0,0,0,0,0,0,0,0,0},

check another one with contact->
 {1,1,1,0,0,0,0,0,0,0},
 {1,1,0,0,0,0,0,0,1,0},
 {1,1,0,0,1,1,1,0,1,0},
 {1,0,0,0,0,0,0,0,0,0},
 {1,0,0,0,0,0,0,0,1,0},
 {0,0,0,0,1,1,1,0,0,0},
 {0,0,0,0,0,0,0,0,1,0},
 {0,0,0,0,0,0,0,0,0,0},
 {0,0,0,0,0,0,0,1,0,0},
 {0,0,0,0,0,0,0,0,0,0},

check invalid, is false->
 {0,1,1,1,0,0,0,0,0,0},
 {0,0,0,1,1,1,0,0,0,0},
 {0,1,1,1,0,0,0,0,0,0},
 {0,0,0,1,1,1,0,0,0,0},
 {0,1,1,1,0,1,1,0,0,0},
 {0,1,0,0,0,0,1,1,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,0,0,0,0,0,0},

random board which is false->
{0,1,0,0,0,0,0,0,0,0},
 {1,1,1,1,0,0,0,0,0,0},
 {1,0,1,1,1,0,0,0,0,0},
 {1,1,0,0,0,0,0,0,0,0},
 {1,1,0,0,0,0,0,0,0,0},
 {0,1,0,0,0,0,0,0,1,0},
 {0,0,1,0,0,0,0,0,1,0},
 {0,0,0,0,0,0,0,0,0,0},
 {0,0,0,0,1,0,0,0,0,0},
 {0,0,0,0,1,0,0,0,0,0},

Who's code will be the shortest byte solution that passes all these examples successfully?! Good luck. ;)
Any language is allowed.
on the 16th I will award the winner with a nice green tick:)

JavaScript (ES6),  162  158 bytes
Returns 0 if the grid is invalid, or a positive integer otherwise.

m=>(o=0,g=u=>m.some((r,y)=>r.some((v,x)=>v&&[0,1].map(d=>(r=(w,X=x+!d*w,R=m[y+d*w]||0)=>R[X]&&R[R[X]--,u&(k=1<<w*3)*7&&g(u-k),r(-~w),X]++)``)))|u||++o)(668)*o

Try it online!
Commented
m => (                       // m[] = input matrix
  o = 0,                     // o = result
  g = u =>                   // g is a recursive function taking a bit mask u
                             // holding the ship counters on 4 x 3 bits
  m.some((r, y) =>           //   for each row r[] at position y in m[]:
    r.some((v, x) =>         //     for each value v at position x in r[]:
      v &&                   //       abort if v is not set
      [0, 1].map(d =>        //       otherwise, look for a horizontal ship (d = 0)
        (                    //       or a vertical ship (d = 1):
          r = (              //         r is a recursive function taking:
            w,               //           w = ship width - 1
            X = x + !d * w,  //           X = position of the cell in ...
            R = m[y + d * w] //           ... R[] = row of the cell
                || 0         //           (force it to 0 if undefined)
          ) =>               //
          R[X] &&            //           abort if R[X] is not set
          R[                 //
            R[X]--,          //           otherwise, set the cell to 0
            u & 7 *          //           if there's still at least one ship of
            (k = 1 << w * 3) //           width w to be found in the grid:
            && g(u - k),     //             do a recursive call to g with u updated
            r(-~w),          //           do a recursive call to r with w + 1
            X                //
          ]++                //           restore the cell afterwards
        )``                  //         initial call to r with u zero'ish
      )                      //       end of map()
    )                        //     end of some()
  )                          //   end of some()
  | u || ++o                 //   increment o if the grid has been cleared and all
                             //   boats have been found
)(668)                       // initial call to g with u = 668 (001 010 011 100)
* o                          // multiply by o


Shifting-Oriented Programming A string can be shifted by a number n by getting the byte value c of each character in the string, calculating (c + n) mod 256, and converting the result back to a character.

As an example, shifting "ABC123" by 1 results in "BCD234", shifting by 10 in "KLM;<=", and shifting by 255 in "@AB012".

The Task

Pick as many numbers n with 0 < n < 256 as you dare and write a program or function that takes a string as input and

returns the string unchanged when the source code is unchanged, but
returns the string shifted by n when the source code is shifted by n.

Rules

The score of your submission is the number of supported n, with a higher score being better. The maximum score is thus 255.
Your submission must support at least one shift, so the minimal score is 1.
In case of a tie the shorter program wins.
All shifted programs need to be in the same language.

Brainfuck, score: 31 (2208 bytes)

Base64-encoded program:

[encoded data, 5160 characters]

Works for shifts 0, 4, 8, 12, 32, 36, 40, 44, 64, 68, 72, 76, 96, 100, 104, 108, 128, 132, 136, 140, 160, 164, 168, 172, 192, 196, 200, 204, 224, 228, 232 and 236.

For every value between 0 and 255, there is exactly one of those shifts that sends that character to a valid brainfuck instruction.

The program relies on 8-bit cells with wrapping on overflows.
This could probably be golfed quite a bit, as the shift just consists of a repeated + or - (whichever is shorter).

Python code used to generate this:

l = [0, 4, 8, 12, 32, 36, 40, 44, 64, 68, 72, 76, 96, 100, 104, 108, 128, 132, 136, 140, 160, 164, 168, 172, 192, 196, 200, 204, 224, 228, 232, 236]
shift = lambda s,n:"".join(chr((ord(i)+n)%256) for i in s)
code = ""
for i in l:
    code += shift(",[{}.,]".format(i*"+" if i<=128 else (256-i)*"-"),-i)


Counting Eisenstein primes Introduction

Eisenstein integers are complex numbers of the form

a+bω

Where a,b are integers, and

ω = e^(2πi/3)

The Eisenstein integers form a triangular lattice in the complex plane:

We say that an Eisenstein integer z=a+bω is prime if it cannot be written as the product of two non-unit (not 1,-1,ω,-ω,ω^2, or -ω^2) Eisenstein integers

Program

Input: A natural number n.

Output: The number of Eisenstein primes which are of the form a+bω for which a,b are natural numbers (including zero) less than or equal to n

Test Cases

0 → 0

1 → 0

2 → 5

3 → 9

4 → 13

5 → 20

Scoring

This is code-golf, so least amount of bytes wins

Julia, 66 62 60 bytes

!n=sum(isprime,[a<1<b%3?b:a^2-a*b+b^2for a=[0;0;0:n],b=0:n])

Try it online!

Explanation

We’re interested in the primes in this parallelogram on the complex plane (example for n = 4):

We can split them into primes on the green lines, and on the gray lines.

Wikipedia tells me an Eisenstein number z is a green line Eisenstein prime iff |z| is a natural prime equal to 2 mod 3.

It also says z is a gray line Eisenstein prime iff |z|² = a² − ab + b² is a natural prime.

So we loop over a = 0…n and b = 0…n, and check:

If (a = 0 or b = 0 or a = b) and max(a, b) % 3 = 2, then count whether max(a, b) is a prime.
Else, count whether a² − ab + b² is a prime.

However, we can abuse the distribution’s symmetry. Instead of counting each green line once, we can just count one green line thrice! That is, only check a = 0 and increment the counter by three when we find a green line prime. The a=[0;0;0:n] achieves exactly this.

Since we know we’re only considering the green line a = 0, we can replace max(a, b) by b.

The “green line condition” is nicely expressed in Julia using operator chaining: a<1<b%3.

(For the remaining green lines, we will never return a false positive: if a = b or b = 0 then a² − ab + b² = a², which can’t be prime.)

Ideas

Maybe, instead of writing a^2-a*b+b^2, I can conditionally replace the exponent at b by 1 when a<1<b%3 – then the expression reduces to b. This doesn’t seem to be shorter, but it’s neat!


List *all* the tuples! Write a program, given an input n, will generate all possible n-tuples using natural numbers.

n=1
(1),(2),(3),(4),(5),(6)...

n=2
(1,1),(1,2),(2,1),(2,2),(1,3),(3,1),(2,3),(3,2),(3,3)...

n=6
(1,1,1,1,1,1) (1,1,1,1,2,1) (1,1,1,2,1,1)...

The output may be in any order that does not break any other rules.
The program must be written to run forever and list all applicable tuples exactly once, in theory.

In reality, your program will reach your integer type's limit and crash. This is acceptable as long the program would run infinitely long if only your integer type was unlimited.
Each valid tuple must be listed within finite time, if only the program were allowed to run that long.

The output may, at your option, include zeroes in addition to the natural numbers.
You may choose your program's output format for your convenience, as long as the separation between tuples and numbers inside each tuple is clear and consistent. (For example, one tuple per line.)
The input (n) is an integer from one to six. Required behavior is undefined for inputs outside of this range.
Code-golf rules apply, shortest program wins.

Thanks to "Artemis Fowl" for feedback during the sandbox phase.

Husk, 2 bytes

πN

Try it online!

Explanation

N is the infinite list of natural numbers [1,2,3,4,...
π is Cartesian power.
Result is an infinite list of lists.
Each list of the desired length occurs exactly once because π is cool like that.
Input and output are implicit.


Grids can be curvy. How long is yours? Consider depicting a simple, open, two-dimensional curve on a W wide by H high grid of text where X represents part of the curve and . represents empty space and no other characters are used.

Every grid space has 8 neighboring grid spaces, its Moore neighborhood. Grid spaces beyond the borders are considered empty.

A grid contains a curve if it has exactly one X OR if it has more than one X where:

Exactly two Xs have only one neighboring X. These are the curve's endpoints.
Every X besides the endpoints neighbors exactly two Xs. These form the bulk of the curve.

  For example, this grid where W = 9 and H = 4 contains a curve:

....X....
.X.X.X.X.
X..X..X.X
.XX.....X

  Likewise, these grids (W = 4, H = 3) have curves:

....  .X..  ....  ....  .X.X
....  X..X  ..X.  XX..  X.X.
..X.  .XX.  .X..  ....  ....

  These grids, however, do not contain a curve:

....  .XX.  ...X  XX..  ....  X.X.
....  X..X  ..XX  XX..  .X.X  .X..
....  .XX.  .X..  ....  ...X  X.X.

We can find the length of a curve by summing the distances between all neighboring pairs of Xs:

The distance between two orthogonally neighboring Xs is 1 unit.

XX

X
X
The distance between two diagonally neighboring Xs is √2 units.

X.
.X

.X
X.

  For example, the length of the curve in the grid

XXX.
...X
..X.

  can be visualized as

  so we can see it is 1 + 1 + √2 + √2 = 4.828427...

The length of a curve with only one X is zero.

When a grid does not form a curve its length is not well defined.

Challenge

Given a grid of text of Xs and .s, output the length of the curve it contains, or else output something such as -1 or Null to indicate the grid has no curve.

For input you may use other characters than X and . if desired, and H and W may be taken as input if needed. Input as a nested list or matrix filled with 1s and 0s instead of a string is also fine.

You may output a float for the curve length or alternatively two integers A and B where length = A + B*√2.

The shortest code in bytes wins.

Test Cases

XXX.
...X
..X.
2 + 2*√2 = 4.828427...

....X....
.X.X.X.X.
X..X..X.X
.XX.....X
3 + 8*√2 = 14.313708...

....
....
..X.
0 + 0*√2 = 0

.X..
X..X
.XX.
1 + 3*√2 = 5.242640...

....
..X.
.X..
0 + 1*√2 = 1.414213...

....
XX..
....
1 + 0*√2 = 1

.X.X
X.X.
....
0 + 3*√2 = 4.242640...

....
....
....
....
-1

.XX.
X..X
.XX.
-1

...X
..XX
.X..
-1

....
.X.X
...X
-1

X.X.
.X..
X.X.
-1

MATL, 52 51 bytes
t2Y6~Z+*ssGt3Y6Z+*tt1=z2=wssGzqE=*Gz1=+?}_q]ssy-h2/

Input is a matrix of zeros and ones.
Output is B, then A. Non-curves give a negative A.
Try it online! Or verify all test cases.
Explanation
Computing the length of the curve uses two 2D convolutions1: one with the Moore mask, and another with a mask containing only the diagonal neighbours. The results are two matrices with the same size of the input, which will be denoted as M and D respectively. M gives the total number of neighbours for each point, whereas D gives the number of diagonal neighbours.
The results in M and D must be filtered to discard points that don't belong to the curve. Also, they must be divided by 2, because "being neighbour of" is a a symmetric relation, so each point in the curve is counted twice.
Determining if the curve is valid is more cumbersome than I expected. To do this, the code tests three conditions:

Does the number of ones in M equal 2? (That is, are thre exactly two points with a single neighbour?)
Does the total sum of M equal the number of points in the input curve times 2 minus 2? (Together with condition 1, this tests if all non-zero values in M except two of them equal 2)
Does the input curve contain a single point?

The curve is valid if conditions 1 and 2 are true, or if condition 3 is.
t       % Implicit input matrix of zeros and ones. Duplicate
2Y6~    % Push [1 0 1; 0 0 0; 1 0 1]
Z+      % 2D convolution, keeping size
*       % Multiply to zero out results for non-curve points. Gives matrix D
ss      % Sum of matrix D
Gt      % Push input again wtice
3Y6     % Push [1 1 1; 1 0 1; 1 1 1]
Z+      % 2D convolution, keeping size
*       % Multiply to zero out results for non-curve points. Gives matrix M
tt      % Duplicate twice
1=z     % Number of ones
2=      % Does it equal 2? This is condition 1
wss     % Swap. Sum of matrix
G       % Push input again
zqE     % Number of nonzeros values minus 1, and then multiplied by 2
=       % Are they equal? This is condition 2
*       % Multiply. This is a logical AND of conditions 1 and 2
G       % Push input again
z1=     % Does it contain exactly one nonzero value? This is condition 3
+       % Add. This is a logical OR with condition 3
?}      % If result was false
  _q    %   Negate and subtract 1. This makes sure we get a negative value
]       % End
ss      % Sum of matrix M
y       % Duplicate sum of matrix D from below
-       % Subtract
h       % Concatenate horizontally
2/      % Divide by 2. Implicitly display

1 Convolution is the key to success.


Largest Error Message in 100 bytes The goal is to raise the error message with the most bytes! The error message may not be generated by the program itself, such as Python's raise. errors that do not terminate the program are not allowed unless they do not show an error message.
Here is an example in python that raises 243041 bytes of error code:
def a(m):
    try:-''
    except:
        if m>0:
            a(m-1)
        else:-''
a(900)

you can try it here.

Python 3, \$\approx\$A(A(A(9,9),A(9,9)),A(A(9,9),A(99,99))) where A is the Ackermann function,or limited by RAM

A=lambda m,n:m and A(m-1,n<1or A(m,n-1))or-~n
a='.'*(A(A(A(9,9),A(9,9)),A(A(9,9),A(99,99))))
exec(a)

Don't try it online!
Stole the Ackermann function from here.
More manageable version to demonstrate:

A=lambda m,n:m and A(m-1,n<1or A(m,n-1))or-~n
a='.'*(9999)
exec(a)

Try it online!
Admittedly I'm not certain this approach is arbitrarily extendible in practice.


Hexagonify™ a String Block Sandbox

What is Hexagonification™?

Hexagonification™ is a transformation that creates a hexagon with 3 copies of a rectangle block, each skewed to the right by 30 degrees and then rotated by 0, 120 and 240 degrees respectively, as shown in the following image. A triangle hole may appear in the middle, but that isn't a great deal.

Challenge

Write a program or function that receives a block of string as an input and outputs the hexagonified™ input. You may assume that the input consists of only ASCII characters and new lines, and each line of the input has been padded so that all lines are of equal length. Empty spaces should be filled with space characters.

The input and output formats are flexible. You may receive a single string, a list of lines or a 2D array as input, and output a single string or a list of lines. You may have leading/trailing spaces on each line and leading/trailing newlines, provided that the hexagon is properly formed. See Sample IO for how the blocks should be positioned.

Sample IO

Input:

3x3
squ
are

Output:

   3 x 3
  e s q u
 u r a r e
3 q a a s 3
 x s r q x
  3 e u 3

Input:

longer.....
rectangular
block......

Output:

   l o n g e r . . . . .
  . r e c t a n g u l a r
 r . b l o c k . . . . . .
. a .                 b r l
 . l .               l e o
  . u .             o c n
   . g .           c t g
    . n k         k a e
     r a c       . n r
      e t o     . g .
       g c l   . u .
        n e b . l .
         o r . a .
          l . r .

Input:

vb
el
ro
tc
ik
c2
ax
l8

Output:

        v b
       8 e l
      x l r o
     2 a   t c
    k c     i k
   c i       c 2
  o t         a x
 l r           l 8
b e l a c i t r e v
 v 8 x 2 k c o l b

Input:

1.line

Output:

 1 . l i n e
e           1
 n         .
  i       l
   l     i
    .   n
     1 e

Input:

1
.
l
i
n
e

Output:

      1
     e .
    n   l
   i     i
  l       n
 .         e
1 e n i l . 1

Scoring

Your score will be the area of the hexagonified™ source code (including the triangle hole). Assuming your code can just fit inside a rectangle of width \$w\$ and height \$h\$, the score will be:

$$3wh+\frac{(w-h)(w-h+1)}{2}$$

Winning Criteria

The submission with the lowest score in each language wins. No standard loopholes.

Charcoal, score 235 168

→ＷＳ⊞υιＦυＦ
«Ｐ↙ιＭ²←»Ｆ
Ｍ⊖⌈ＥυＬκ↙Ｆ
Ｆυ«Ｐ↖κ↗»Ｆ
Ｍ⊖⌈ＥυＬκ↖Ｆ
Ｆυ«Ｐ⪫κ ↘»

Try it online! Takes input as a newline-terminated list. Charcoal's problem here is that a newline is a command, so I can't just throw newlines in arbitrarily. Instead, I'm passing them as arguments to the For command, which loops over each character in the string, which here is just the one character, therefore not modifying the behaviour of the program (except to change the implicit loop variables). As such, these dummy For instructions are not included in the explanation. Explanation:

→

Another no-op, just to make the code exactly rectangular.

ＷＳ⊞υι

Input the list.

Ｆυ«Ｐ↙ιＭ²←»

Print the lower right diagonal side.

Ｍ⊖⌈ＥυＬκ↙

Move to the bottom.

Ｆυ«Ｐ↖κ↗»

Print the lower left diagonal side.

Ｍ⊖⌈ＥυＬκ↖

Move to the top left.

Ｆυ«Ｐ⪫κ ↘»

Print the top side.


ASCII Pizza (no pineapple) I like pizza!

Task

Given the radius of a pizza and a list of ingredients, create the corresponding ascii pizza!

Example size 4 pizza with mozzarella cheese, olives and ham:

  #####
 #@@@@M#
#H@O@@@@#
#M@@@H@@#
#@OO@@@@#
#@@H@@@@#
#M@M@@@@#
 #O@@@H#
  #####

Input

A positive integer r for the size of the pizza and a (possibly empty) list of ingredients (non-empty strings). The list of ingredients can be given in a series of convenient formats, including but not limited to:

a list of ingredients, such as ["tomato", "ham", "cheese"];
a list of the initials, such as ["t", "h", "c"];
a list of left- or right-padded ingredients, such as ["tomato", "ham   ", "cheese"] or ["tomato", "   ham", "cheese"];
a string with the initials, such as "thc".

Output specs

The pizza is built on a square of size 2r+1 characters, with the centre character having coordinates (0,0) for the purposes of this explanation. All characters in the square have integer coordinates. Then,

a position is crust # if its coordinates x,y satisfy \$r+1 > \sqrt{x^2 + y^2} \geq r\$;
a position is dough @ if its coordinates x,y satisfy \$ r > \sqrt{x^2+y^2}\$.

Then, the ingredients must be put randomly on the pizza. Each ingredient will be represented by its initial and you must place r of each ingredient randomly in the dough characters. You can assume there will be enough space in the pizza. Ingredients cannot be placed on top of eachother, so in the final pizza there must be exactly rl non-dough symbols, in groups of r, if the ingredients list has size l.

For the randomness in the distributions of ingredients on top of the pizza, it suffices that for a fixed r and ingredient list, all ingredient distributions obeying the specs have non-zero probability of occurring.

Examples

r = 1, no ingredients

###
#@#
###

r = 2, no ingredients

#####
#@@@#
#@@@#
#@@@#
#####

r = 5, no ingredients

  #######
 ##@@@@@##
##@@@@@@@##
#@@@@@@@@@#
#@@@@@@@@@#
#@@@@@@@@@#
#@@@@@@@@@#
#@@@@@@@@@#
##@@@@@@@##
 ##@@@@@##
  #######

r = 4, ingredients = ["bacon", "mozzarela", "tomato"]

  #####
 #@@b@m#
#@@@@@b@#
#@@@btb@#
#@@@@@@t#
#@@@@@@@#
#@mt@@@@#
 #t@mm@#
  #####

Reference implementation

Please include one or two of your favourite pizzas in your answer :)

This is code-golf so shortest submission in bytes, wins! If you liked this challenge, consider upvoting it... And happy golfing!

APL (Dyalog Extended), 55 bytesSBCS

Anonymous infix lambda. Takes r as left argument (⍺) and ingredient initials as right argument (⍵).

{i@((≢i←⍺/⍵)?≢⍸1=n)@{1=n}'@# '[n←(0⍺,⍺+1)⍸⍤1|∘.⌾⍨⍺…-⍺]}

Try it online!

{…} "dfn"; left argument ⍺ (leftmost Greek letter), right argument ⍵ (rightmost Greek letter)

'@# '[…] index the string with:

  -⍺ negate r

  ⍺… generate integer range from r to -r

  ∘.⌾⍨ generate table of complex coordinates

  | magnitudes

  (…)⍸⍤1 for each row's elements, find ɩndex the [a,b) ɩnterval in which the magnitude falls:

   ⍺+1 increment r

   0⍺, prepend [0,r]

   n← store in n (1: dough; 2: crust; 3: outside pizza)

 i@(…)@{1=n} place the characters of i (to be defined) at the following subset of positions at which n is 1 (i.e. we have dough):

  1=n mask where n is 1

  ⍸ ɩndices of trues

  ≢ count them

  (…)? pick the following number of random indices from 1 to that:

   ⍺/⍵ replicate each ingredient initial letter to r copies

   i← store in i

   ≢ tally that


Compute the result of an equation, but with selectable operator precedence Forget BIDMAS! Write a program that takes an equation and an operator precedence order, and prints the result.

Example input format:

1.2+3.4*5.6/7.8-9.0 */+-

Rules & guidelines:

The only operators that are defined are addition (+), subtraction (-), multiplication (*), and division (/). No parentheses, no exponentiation.
Associativity is always left-to-right. For example, 10/4/2 is to be interpreted as (10/4)/2 with a result of 1.25, rather than 10/(4/2).
The input format is as follows:

An equation, followed by a space, followed by the operator precedence specification (or two string arguments, one for the equation and the other for the precedence).
The equation comprises base-10 decimal numbers separated by operators, with no spaces. Integer values do not have to contain a period character, i.e. both 5 and 5.0 are to be accepted values.
For simplicity, negative numbers may not be included in the input, e.g. 6/3 is valid but 6/-3 is not. Input also may not contain a leading or trailing operator, so -6/3 isn't considered valid, nor is 6-3+.
The precedence specification string is always 4 characters long and always contains the characters +, -, /, and * once each. Precedence is read as left-to-right, e.g. */+- specifies multiplication with the highest precedence, division next, then addition, and finally subtraction. EDIT: It is acceptable to take the precedence string in reverse order (lowest to highest) as long as you specify this in your answer.

Input is a string to be taken via command line arguments, STDIN, or the default input format in programming languages that do not support these input methods.
You are free to assume that the given input will be in the correct format.
Output is via STDOUT or your language's normal output method.
The printed result should be in base-10 decimal.
Results must be computed to at least 4 decimal points of accuracy when compared to a correct implementation that uses double precision (64-bit) floating point arithmetic. This degree of freedom is designed to allow for the use of fixed-point arithmetic in languages that have no floating-point support.
Divide by zero, overflow, and underflow are undefined behaviour. Your code is free to assume that no inputs will be given that will trigger these cases.
You may not call out to any external services (e.g. Wolfram Alpha)
You may not call out to any programs whose primary function is to solve these types of problems.

Test cases:

6.3*7.8 followed by any operator precedence specification prints 49.14
2.2*3.3+9.9/8.8-1.1 */+- is parsed as ((2.2*3.3)+(9.9/8.8))-1.1 and should print 7.285
2.2*3.3+9.9/8.8-1.1 +*/- is parsed as ((2.2*(3.3+9.9))/8.8)-1.1 and should print 2.2
10/2+5-1 +-/* is parsed as 10/((2+5)-1) and the printed result should be 1.6666666...
2147480/90+10*5 +/-* is parsed as (2147480/(90+10))*5 and the printed result should be 107374
3*55-5/8/4+1 -/+* is parsed as 3*((((55-5)/8)/4)+1) should print 7.6875
An input containing one thousand instances of the number 1.015 separated by multiplier operators (i.e. the expanded multiplicative form of 1.015^1000), followed by any operated precedence specification, should print a number within 0.0001 of 2924436.8604.

Code golf, so shortest code wins.

JavaScript (ES6), 94 bytes

Not particularly short, but fun. Adding parentheses all over the place...

s=>([e,o]=s.split` `,[...o].map(x=>e=e.split(x).join((a+=')')+x+(b+='(')),a=b=''),eval(b+e+a))

Test cases

let f =

s=>([e,o]=s.split` `,[...o].map(x=>e=e.split(x).join((a+=')')+x+(b+='(')),a=b=''),eval(b+e+a))

console.log(f("6.3*7.8 +-*/"))              // 49.14
console.log(f("2.2*3.3+9.9/8.8-1.1 */+-"))  // 7.285
console.log(f("2.2*3.3+9.9/8.8-1.1 +*/-"))  // 2.2
console.log(f("10/2+5-1 +-/*"))             // 1.6666
console.log(f("2147480/90+10*5 +/-*"))      // 107374
console.log(f("3*55-5/8/4+1 -/+*"))         // 7.6875

Historical note

A similar method was used in early FORTRAN compilers. Here is a link from archive.org to a relevant article written by Donald E. Knuth in a 1962 book called Computers and automation.

Examples

Let's consider the expression 2.2*3.3+9.9/8.8-1.1.

With operator precedence */+-, it will expand to:

((((2.2)*(3.3)))+(((9.9))/((8.8))))-((((1.1))))

With operator precedence +*/-, it will now expand to:

((((2.2))*((3.3)+(9.9)))/(((8.8))))-((((1.1))))

Removing all redundant parentheses, we get:

((2.2*3.3)+(9.9/8.8))-1.1 = 7.285

and:

((2.2*(3.3+9.9))/8.8)-1.1 = 2.2


Is it an arithmetico-geometric sequence? An arithmetico-geometric sequence is the elementwise product of an arithmetic sequence and a geometric sequence. For example, 1 -4 12 -32 is the product of the arithmetic sequence 1 2 3 4 and the geometric sequence 1 -2 4 -8. The nth term of an integer arithmetico-geometric sequence can be expressed as

$$a_n = r^n \cdot (a_0 + nd)$$

for some real number \$d\$, nonzero real \$r\$, and integer \$a_0\$. Note that \$r\$ and \$d\$ are not necessarily integers.

For example, the sequence 2 11 36 100 256 624 1472 3392 has \$a_0 = 2\$, \$r = 2\$, and \$d = 3.5\$.

Input

An ordered list of \$n \ge 2\$ integers as input in any reasonable format. Since some definitions of geometric sequence allow \$r=0\$ and define \$0^0 = 1\$, whether an input is an arithmetico-geometric sequence will not depend on whether \$r\$ is allowed to be 0. For example, 123 0 0 0 0 will not occur as input.

Output

Whether it is an arithmetico-geometric sequence. Output a truthy/falsy value, or two different consistent values.

Test cases

True:

1 -4 12 -32
0 0 0
-192 0 432 -1296 2916 -5832 10935 -19683
2 11 36 100 256 624 1472 3392
-4374 729 972 567 270 117 48 19
24601 1337 42
0 -2718
-1 -1 0 4 16
2 4 8 16 32 64
2 3 4 5 6 7
0 2 8 24

False:

4 8 15 16 23 42
3 1 4 1
24601 42 1337
0 0 0 1
0 0 1 0 0
1 -1 0 4 16

Wolfram Language (Mathematica), 55 bytes

{}!=Solve[i=Range@Tr[1^#];(a+i*d)r^i==#,{r,a,d},Reals]&

Try it online!

Solve return all solution forms. The result is compared with {} to check if there is any solution.


Match strings whose length is isolated prime Isolated prime definition from Wikipedia:

  An isolated prime is a prime number p such that neither p − 2 nor p + 2 is prime. In other words, p is not part of a twin prime pair. For example, 23 is an isolated prime since 21 and 25 are both composite.

Consider strings which consists of character x repeated n times, where n ≥ 0. You shall write a regex which matches strings whose length is an isolated prime, and rejects strings whose length is not an isolated prime.

Same rule as my previous question Match strings whose length is a fourth power:

Any (ir)regular expression syntax is allowed, except for arbitrary code execution (to Perl users).
Your solution should logically1 work correctly for large number. This means that an answer that lists out all the lengths within certain range is disqualified.
Please also include a short explanation about your approach to the problem (something like this).

1 Some engine implements * with an upper limit. This question assumes that * doesn't have an upper limit (and the only limit is the length of the input string).

This question on SO might be useful as a starting point. How to determine if a number is a prime with regex?

Do you know?

If you can solve this problem, with trivial modification, you can check whether a number is part of a twin prime, since isolated prime has opposite definition of a twin prime.

Perl, 54
/^(?!(..+)\1+$)(?=..(?:|(..+)\2+)$)(?=(..(.*))\4\3*$)/

I think this is not possible without the Perl look-ahead expression... Firstly, there is no positive regex to match the prime number. You can only match a non-prime by simulating multiplication: (..+)\1+. To negate it, I use negative look-ahead: /^(?!(..+)\1+$)/ matches prime numbers (neglecting the 0, 1 case).
The beauty of the look-ahead is that it is zero-width, i.e. eats no characters. This means you can actually AND those conditions! My regex is composed of 3 look-aheads, corresponding to AND-ing 3 conditions:

(?!(..+)\1+$) - N (length of the string) is the prime number
(?=..(?:|(..+)\2+)$) - N-2 is a non-prime - this is a trival modification of the basic non-prime expression - (..+)\1+) - just add two characters. The (?:|...) is included to also match an empty string (case N=2 should match too).
(?=(..(.*))\4\3*$) - N+2 is a non-prime - again, trivial modification of the basic non-prime expression - cut two characters out of one repetition.

Test:
$ perl -E'($"x$_)=~/^(?!(..+)\1+$)(?=..(?:|(..+)\2+)$)(?=(..(.*))\4\3*$)/&&say for(2..200)'
2
23
37
47
53
67
79
83
89
97
113
127
131
157
163
167
173


Island Golf #2: The Eccentric Hermits This is the second in a series of Island Golf challenges. Previous challenge

Two hermits have arrived on a desert island. Since they came seeking solitude, they wish to live as far away from each other as possible. Where should they build their huts to maximize the walking distance between them?

Related reading

Input

Your input will be a rectangular grid consisting of two characters, representing land and water. In the examples below, land is # and water is ., but you may substitute any two distinct characters you wish.

...........
...##......
..#####....
..#######..
.#########.
...#######.
...#####.#.
....####...
...........

There will always be at least two land tiles. The land tiles will all be contiguous (i.e. there's only one island). The water tiles will also be contiguous (i.e. there are no lakes). The outer border of the grid will all be water tiles. Land tiles will not be connected diagonally: i.e., you will never see something like

....
.#..
..#.
....

Output

Your code must output the same grid, with two hut locations marked on it. In the examples below, the hut locations are marked with X, but you may substitute any character as long as it is distinct from your land and water characters.

The hut locations must be two land tiles, chosen so as to maximize the walking distance between them. We define walking distance as the length of the shortest path, entirely on land, between the two points. Land tiles are considered adjacent horizontally or vertically, but not diagonally.

A possible solution for the above island:

...........
...X#......
..#####....
..#######..
.#########.
...#######.
...#####.X.
....####...
...........

The walking distance between these two points is 11, which is the greatest distance between any two points on this island. There is another distance-11 solution:

...........
...##......
..X####....
..#######..
.#########.
...#######.
...#####.X.
....####...
...........

Details

Your solution may be a full program or a function. Any of the default input and output methods are acceptable.

Your input and output may be a multiline string, a list of strings, or a 2D array/nested list of characters/single-character strings. Your output may (optionally) have a single trailing newline. As mentioned above, you may use any three distinct characters in place of #.X (please specify in your submission which characters you're using).

Test cases

A. Islands with unique hut placements:

....
.##.
....

....
.XX.
....

......
......
..##..
...#..
......
......

......
......
..X#..
...X..
......
......

........
.#####..
.##..##.
.#..###.
.##..##.
........

........
.#####..
.##..##.
.#..###.
.#X..#X.
........

.........
.#####.#.
.#...#.#.
.#.###.#.
.#.....#.
.#######.
.........

.........
.#####.X.
.#...#.#.
.#.X##.#.
.#.....#.
.#######.
.........

B. Example of an island with multiple possible solutions:

........
....##..
...####.
..###...
.#####..
.#####..
..##....
........

Possible outputs:

........
....#X..
...####.
..###...
.#####..
.X####..
..##....
........

........
....#X..
...####.
..###...
.#####..
.#####..
..X#....
........

........
....##..
...###X.
..###...
.#####..
.X####..
..##....
........

........
....##..
...###X.
..###...
.#####..
.#####..
..X#....
........

C. Large test case as a Gist

This is code-golf: the shortest code in each language wins.

Python 3, 249 246 bytes

Shaved off 3 bytes, thanks DLosc.

Input and output are single strings, with '.', '@', and 'X' representing water, huts, and land, respectively.

A='@'
def f(s):
 w=s.find('\n')+1;d=u={(k,k):0for k,c in enumerate(s)if A<c}
 while u:d.update(u);u={(k,j):d[(k,i)]+1for k,i in d for j in{i+1,i+w,i-1,i-w}if A<s[j]and(k,j)not in d}
 k,j=sorted(max(d,key=d.get))
 return s[:k]+A+s[k+1:j]+A+s[j+1:]

Prior version:

Input is a single string, with '.' and '#' representing water and land, respectively.  'X' represents the huts in the output.

def f(s):
 w=s.find('\n')+1;d=u={(k,k):0for k,c in enumerate(s)if'#'==c}
 while u:d.update(u);u={(k,j):d[(k,i)]+1 for k,i in d for j in{i+1,i+w,i-1,i-w}if'#'==s[j]and(k,j)not in d}
 k,j=sorted(max(d,key=d.get))
 return s[:k]+'X'+s[k+1:j]+'X'+s[j+1:]

Explanation:

It's basically doing a breadth first search from every possible starting point at the same time.  Keep a dictionary, d, of path lengths keyed by the start and end of the path, e.g., d[(k,i)] is the distance from k to i.  Then iterate over the keys in the dictionary, d, and create a new dictionary, u, with paths that are 1 unit longer by moving the end point 1 unit to the N,S,E,W, e.g., u[(k, i+1)] = d[(k,i)] + 1.  Don't include paths that are already in d.  If u is not empty, then add the new longer paths to d and repeat.  When u is empty, that means no more paths could be made.  Now d contains all the possible paths and their lengths.  So its just a matter of getting the key with the longest path.

Less golfed, commented version:

def f(s):
  w=s.find('\n')+1                    # width of a row, or a move N or S

  d = {}                              # dictionary of all the paths.
                                      # The key is a tuple (k,j) and the
                                      # value is the distance from k to j.
  for k,c in enumerate(s):            # Initialize. Distance from k to k is 0
    if'#'==c:                         # Only do land.
      d[(k,k)] = 0

  u = d                               # dictionary of new paths. initialize it to d
                                      # so loop is entered. first d.update is
                                      # basically a NOP

  while u:                            # while there are new paths
    d.update(u)                       # add the new paths to the dict of old paths
    u={}                              #
    for k,i in d:                     # iterate over the known paths. k is the start, i is the end
      for j in{i+1,i+w,i-1,i-w}:      # iterate over squares 1 move to the E,S,W,N from i
        if'#'==s[j]and(k,j)not in d:  # if it's still land, and the path (k,j) isn't already in d,
          u[(k,j)] = d[(k,i)]+1       # then add the new path to u

  k,j=sorted(max(d,key=d.get))        # find the longest path

  return s[:k]+'X'+s[k+1:j]+'X'+s[j+1:]  # X marks the endpoints.


Complex Fibonacci numbers The Binet formula is a closed form expression for the \$n\$'th Fibonacci number:
$$F_n = \frac {\phi^n - (1-\phi)^n} {\sqrt 5}$$
where \$\phi = \frac {1 + \sqrt 5} 2\$ is the golden ratio. This formula works even when \$n\$ is negative or rational, and so can be a basis to calculating "complex Fibonacci numbers".
For example, by setting \$n = \frac 1 2\$, we can calculate \$F_\frac 1 2\$ as:
$$F_\frac 1 2 = \frac 1 {\sqrt 5} \left( \sqrt \frac {1+\sqrt 5} 2 - \sqrt \frac {1-\sqrt 5} 2 \right) \\
\approx 0.56886-0.35158i$$
You are to take a floating point, \$-10 \le n \le 10\$, with up to 3 decimals after the point, and output \$F_n\$, accurate to at least 5 decimal places. You may either round or truncate, so long as it is consistent. You may also choose to input as a rational number if you wish, or as a (numerator, denominator) pair. You may also choose whether integers should be suffixed with .0 or not, so long as it is consistent across all 21 integer inputs.
As the output will be a complex number in all but 21 cases, you may output in any reasonable format for such a type, including outputting as a (real, imag) pair. For the integer inputs, the imaginary part will be \$0\$. You may choose whether to output the imaginary part in this case (and returning an integer  or float is perfectly fine).
This is code-golf, so the shortest code in bytes wins
Test cases
These all round their output, rather than truncate.

  n       Re(Fn)     Im(Fn)
-10      -55         0
  1        1         0
 -7       13         0
  3        2         0
  0.5      0.56886  -0.35158
  5.3      5.75045   0.02824
  7.5     16.51666   0.01211
 -1.5      0.21729  -0.92044
 -9.06    34.37587  -6.55646
  9.09    35.50413   0.00157
 -2.54     0.32202   1.50628
  5.991    7.96522   0.00071
 -6.033   -8.08507   0.84377
  8.472   26.36619  -0.00756

And a script to output all possible outputs in the same format (gets cut off on TIO due to the length).

Wolfram Language (Mathematica), 30 bytes
(h=2/--√5;h^#-(1-h)^#)√.2&

Try it online!
Uses \$\frac{\sqrt 5+1}{2}=\frac{2}{\sqrt 5-1}\$. Mathematica's pre-increment/decrement operators still return the desired value when used on (non-variable) non-atoms.
The built-in Fibonacci is a continuous real function, the real part of the Binet formula: \$F_n=\frac{\phi^n-\cos(\pi n)\phi^{-n}}{\sqrt 5}\$.


Can this knot be colored with 3 colors? In this challenge you will be asked to take a knot and determine if it can be colored in a particular way.

First we draw a diagram of the knot.  We use the standard way of drawing knots where we put gaps in strands where they pass under each other.  Here is an example of some knots drawn this way:

Taken with permission from wikimedia user Jkasd

Once we have drawn the knot we want to color the knot with three colors such that:

Every contiguous length of string in the knot's diagram is colored with the same color (String on the opposite ends gaps where we pass under do not need to be the same color)
The three strands that meet at an intersection are either

all the same color
or all different colors

At least two colors must be used in total

Some knots can be drawn in this way for example:

Taken with permission from wikimedia user n4nojohn

and some cannot for example

Taken with permission from wikimedia user n4nojohn

Your task is to take a knot as input and determine whether or not it can be colored.  You may take a knot in any reasonable format (some examples listed below) and you may output two distinct consistent values one indicating that it can be colored one that it cannot.

This is code-golf so answers will be scored in bytes with fewer bytes being better.

Example input formats

Some nice ways of taking knots as input:

Dowker Notation, A list of pairs of positive integers
Gauss Code, A list of positive integers

Haskell, 249 246 bytes

(i#x)a=[head$[x|j==i]++[s]|(j,s)<-zip[0..]a]
(s%i)[]=i<2&&elem 2(concat s)
(s%i)((l,a):b)|l,[]<-s!!a=or[(a#[i,x]$s)%x$b|x<-[1..3]]|[]<-s!!a=(a#[i]$s)%i$b|[x]<-s!!a,x==i=s%i$b|[x]<-s!!a=s%(6-i-x)$b|u<-s!!a=mod(sum$i:u)3<1&&(s%i)b
f x=(x>>[[]])%1$x

Try it online!

Takes input as a Gauss Code, ([(Bool, Int)]) where False represents crossing over and True represents under

Explanation

This algorithm works by stepping though each intersection and trying to resolve the colors of that intersection.  It keeps track of what color the strand is and branches if multiple colors are possible at a given point.

The function that we build to do this is called r.  It takes, 3 arguments:

The Gauss Code of the knot we are working on (which it will consume in order)
A list of "intersections" and what colors we have already filled in
The color of the strand where we are currently processing.

Our intersections are represented as a list of colors (Int), which we know to be at that intersection.  There are three possible states for this:

It is empty, meaning we have not visited this intersection yet.
It has one element, meaning we visited the intersection going over.
It has two elements (possibly equal), meaning we visited the intersection going under.

We can't have 3 elements because when we visit an intersection the second time we don't have to add the third element since we are never coming back.  Since we don't have to and this is code-golf, we don't.

At each step of the way we can use a very simple case analysis to determine how to branch.  Here is a diagram showing each case and the possible outputs (no possible outputs is a contradiction and return False if we reach it).  Incoming color and location are indicated with the small arrow.

Here are some sample paths of execution on the granny knot and the figure 8 knot as shown in the question.  I skip over steps where we went over a unvisited intersection, since they are quite trivial and the diagrams are quite large even without them.

Since Haskell is lazy we only ever evaluate two of these paths, the left-most path, and when that fails because the result doesn't have two colors we evaluate the second left-most.  Since that one passes we exit without further evaluation.

Here the only branch that does not encounter an error colors everything the same way.

Here is my code ungolfed a bit and commented.  I will expand this a little bit shortly.

-- Update an element of a list
q i x a=[head$[x|j==i]++[s]|(j,s)<-zip[0..]a]
-- Perform the algorithm
-- Iterates through the intersections in order
-- It records colors at each intersection and searches for a contradiction
r[]s i=i<2&&elem 2(concat s)
r((l,a):b)s i
  -- If we reach a new intersection passing under
  -- Branch on the three possible colors
  -- label the intersection with the incoming and outgoing colors
  |l,[]<-s!!a=or[r b(q a[i,x]s)x|x<-[1..3]]
  -- If we reach a new intersection passing over
  -- label the intersection with the incoming color
  |[]<-s!!a=r b(q a[i]s)i
  -- If we reach an intersection going under where the over strand is the same color as the incoming
  -- The outgoing strand is the same color
  |[x]<-s!!a,x==i=r b s i
  -- If we reach an intersection going under where the over strand is different from the incoming
  -- The outgoing strand is the third color
  |[x]<-s!!a=r b s(6-i-x)
  -- If we reach an intersection going under
  -- Check that the three strands have either all the same or all different colors
  -- Since we use 1,2 and 3 for the colors this is the same as checking if their sum is divisible by 3
  |u<-s!!a=mod(sum$i:u)3<1&&r b s i
f x=r x(x>>[[]])1


Maximal number of regions obtained by joining n points around a circle by straight lines Let's define f(n) as the aximal number of regions obtained by joining n points around a circle by straight lines. For example, two points would split the circle into two pieces, three into four, like this:

Make sure when you are drawing the lines, you don't have an intersection of more than two lines.

Your task

Given a number n, print f(n).

Test cases:

 n | f(n)
---+-----
 1 |   1
 2 |   2
 3 |   4
 4 |   8
 5 |  16
 6 |  31
 7 |  57
 8 |  99
 9 | 163

You can see more here.

Using built-in sequence generators is not allowed.

Remember, this is code-golf, so the code with the smallest number of bytes wins.

If you guys want the formula, here it is:

Mathematica, 23 bytes
Tr@Binomial[#,{0,2,4}]&

Uses the formula in the question.


Find top student from three test marks First save the following text into a file called marks.csv

Smith,6,9,24
Jones,9,12,20
Fred,5,9,20

Each line contains a students name and three marks they scored. Find the top student by simply summing the three marks and then output their name. In this case the output is:

Jones

I would like to see somebody beat my Python solution but any language will be allowed :) If anybody beats my Python solution I will accept their answer but for now I will just accept the shortest code.


Reproduce an image using lines Write a program that takes in a true-color RGB image I, the maximum number of lines to draw L, and the minimum m and maximum M length of each line. Output an image O that looks as much as possible like I and is drawn using L or fewer straight lines, all of which have Euclidean length between m and M.

Each line must be one solid color, have both endpoints in the bounds of O, and be drawn using Bresenham's line algorithm (which most graphics libraries will already do for you). Individual lines can only be 1-pixel thick.

All lines, even those of length 0, should take up at least one pixel. Lines may be drawn on top of one another.

Before drawing any lines you may initialize the background of O to any solid color (that may depend on I).

Details

O should have the same dimensions as I.
L will always be a nonnegative integer. It may be greater than the area of I.
m and M are nonnegative floating point numbers with M >= m. The distance between two pixels is the Euclidean distance between their centers. If this distance is less than m or greater than M, then a line between those pixels is not allowed.
The lines should not be antialiased.
Opacity and alpha should not be used.
Your program should not take more than an hour to run on a decent modern computer on images with less than a million pixels and L less than 10,000.

Test Images

You should of course show us your most accurate or interesting output images (which I expect will occur when L is between 5% and 25% of the number of pixels in I, and m and M are around one tenth of the diagonal size).

Here are some test images (click for originals). You may also post your own.

Simpler images:

This is a popularity contest. The highest voted submission wins.

Notes

It may be helpful to let L be derived from a percentage of total pixels in I as well as an absolute value. e.g. >>> imageliner I=img.png L=50% m=10 M=20 would be the same thing as >>> imageliner I=img.png L=32 m=10 M=20 if img.png were an 8 by 8 pixel image. Something similar could be done for m and M. This is not required.
Since lines cannot go out of bounds, the longest lines possible will be the diagonal length of I. Having M higher than this should not break anything though.
Naturally, if m is 0 and L is greater than or equal to the number of pixels in I, O could be identical to I by having length 0 "lines" at each pixel location. This behavior is not required.
Arguably, reproducing the shape of I is more important than reproducing the color. You may want to look into edge detection.

C++ - somewhat random lines and then some

First some random lines

The first step of the algorithm randomly generates lines, takes for the target image an average of the pixels along this, and then calculates if the summed up square of rgb space distances of all pixels would be lower if we would paint the new line (and only paint it, if it is). The new lines color for this is chosen as the channel wise average of the rgb values, with a -15/+15 random addition.

Things that I noticed and influenced the implementation:

The initial color is the average of the complete image. This is to counter funny effects like when making it white, and the area is black, then already something as a bright green line is seen better, as it is nearer to black than the already white one.
Taking the pure average color for the line is not so good as it turns out to be unable to generate highlights by being overwritten by later lines. Doing a little random deviation helps a bit, but if you look at starry night, it fails if the local contrast is high at many places.

I was experimenting with some numbers, and chose L=0.3*pixel_count(I) and left m=10 and M=50. It will produce nice results starting at around 0.25 to 0.26 for the number of lines, but I chose 0.3 to have more room for accurate details.

For the full sized golden gate image, this resulted in 235929 lines to paint (for which it took a whopping 13 seconds here). Note that all images here are displayed in reduced size and you need to open them in a new tab/download them to view the full resolution.

Erase the unworthy

The next step is rather expensive (for the 235k lines it took about an hour, but that should be well within the "an hour for 10k lines on 1 megapixel" time requirement), but it is also a bit surprising. I go through all the previously painted lines, and remove those that do not make the image better. This leaves me in this run with only 97347 lines that produce the following image:

You probably need to download and compare them in an appropriate image viewer to spot most differences.

and start over again

Now I have a lot of lines that I can paint again to have a total of 235929 again. Not much to say, so here is the image:

short analysis

The whole procedure seems to work like a blurring filter that is sensitive to local contrast and object sizes. But it is also interesting to see where the lines are painted, so the program records these too (For each line, the pixel color will be made one step whiter, at the end the contrast is maximized). Here are the corresponding ones to the three colored above.

animations

And since we all love animations, here are some animated gifs of the whole process for the smaller golden gate image. Note that there is significant dithering due to gif format (and since creators of true color animation file formats and browser manufacturers are in war over their egos, there is no standard format for true color animations, otherwise I could have added an .mng or similar).

Some more

As requested, here are some results of the other images (again you might need to open them in a new tab to not have them downscaled)

Future thoughts

Playing around with the code can give some intresting variations.

Chose the color of the lines by random instead of being based on the average. You might need more than two cycles.
The code in the pastebin also contains some idea of a genetic algorithm, but the image is probably already so good that it would take too many generations, and this code is also too slow to fit into the "one hour" rule.
Do another round of erase/repaint, or even two...
Change the limit of where lines can be erased (e.g. "must make the image at lest N better")

The code

These are just the two main useful functions, the whole code doesn't fit in here and can be found at http://ideone.com/Z2P6Ls

The bmp classes raw and raw_line function do access pixels and lines respectively in an object that can be written to bmp format (It was just some hack lying around and I thought that makes this somewhat independent from any library).

The input file format is PPM

std::pair<bmp,std::vector<line>>  paint_useful( const bmp& orig, bmp& clone, std::vector<line>& retlines, bmp& layer, const std::string& outprefix, size_t x, size_t y )
{
        const size_t pixels = (x*y);
        const size_t lines = 0.3*pixels;
//      const size_t lines = 10000;

//      const size_t start_accurate_color = lines/4;

        std::random_device rnd;

        std::uniform_int_distribution<size_t> distx(0,x-1);
        std::uniform_int_distribution<size_t> disty(0,y-1);
        std::uniform_int_distribution<size_t> col(-15,15);
        std::uniform_int_distribution<size_t> acol(0,255);

        const ssize_t m = 1*1;
        const ssize_t M = 50*50;

        retlines.reserve( lines );

        for (size_t i = retlines.size(); i < lines; ++i)
        {
                size_t x0;
                size_t x1;

                size_t y0;
                size_t y1;

                size_t dist = 0;
                do
                {
                        x0 = distx(rnd);
                        x1 = distx(rnd);

                        y0 = disty(rnd);
                        y1 = disty(rnd);

                        dist = distance(x0,x1,y0,y1);
                }
                while( dist > M || dist < m );

                std::vector<std::pair<int32_t,int32_t>> points = clone.raw_line_pixels(x0,y0,x1,y1);

                ssize_t r = 0;
                ssize_t g = 0;
                ssize_t b = 0;

                for (size_t i = 0; i < points.size(); ++i)
                {
                        r += orig.raw(points[i].first,points[i].second).r;
                        g += orig.raw(points[i].first,points[i].second).g;
                        b += orig.raw(points[i].first,points[i].second).b;
                }

                r += col(rnd);
                g += col(rnd);
                b += col(rnd);

                r /= points.size();
                g /= points.size();
                b /= points.size();

                r %= 255;
                g %= 255;
                b %= 255;

                r = std::max(ssize_t(0),r);
                g = std::max(ssize_t(0),g);
                b = std::max(ssize_t(0),b);

//              r = acol(rnd);
//              g = acol(rnd);
//              b = acol(rnd);

//              if( i > start_accurate_color )
                {
                        ssize_t dp = 0; // accumulated distance of new color to original
                        ssize_t dn = 0; // accumulated distance of current reproduced to original
                        for (size_t i = 0; i < points.size(); ++i)
                        {
                                dp += rgb_distance(
                                                                                orig.raw(points[i].first,points[i].second).r,r,
                                                                                orig.raw(points[i].first,points[i].second).g,g,
                                                                                orig.raw(points[i].first,points[i].second).b,b
                                                                        );

                                dn += rgb_distance(
                                                                                clone.raw(points[i].first,points[i].second).r,orig.raw(points[i].first,points[i].second).r,
                                                                                clone.raw(points[i].first,points[i].second).g,orig.raw(points[i].first,points[i].second).g,
                                                                                clone.raw(points[i].first,points[i].second).b,orig.raw(points[i].first,points[i].second).b
                                                                        );

                        }

                        if( dp > dn ) // the distance to original is bigger, use the new one
                        {
                                --i;
                                continue;
                        }
                        // also abandon if already too bad
//                      if( dp > 100000 )
//                      {
//                              --i;
//                              continue;
//                      }
                }

                layer.raw_line_add(x0,y0,x1,y1,{1u,1u,1u});
                clone.raw_line(x0,y0,x1,y1,{(uint32_t)r,(uint32_t)g,(uint32_t)b});
                retlines.push_back({ (int)x0,(int)y0,(int)x1,(int)y1,(int)r,(int)g,(int)b});

                static time_t last = 0;
                time_t now = time(0);
                if( i % (lines/100) == 0 )
                {
                        std::ostringstream fn;
                        fn << outprefix + "perc_" << std::setw(3) << std::setfill('0') << (i/(lines/100)) << ".bmp";
                        clone.write(fn.str());
                        bmp lc(layer);
                        lc.max_contrast_all();
                        lc.write(outprefix + "layer_" + fn.str());
                }

                if( (now-last) > 10 )
                {
                        last = now;
                        static int st = 0;
                        std::ostringstream fn;
                        fn << outprefix + "inter_" << std::setw(8) << std::setfill('0') << i << ".bmp";
                        clone.write(fn.str());

                        ++st;
                }
        }
        clone.write(outprefix + "clone.bmp");
        return { clone, retlines };
}

void erase_bad( std::vector<line>& lines, const bmp& orig )
{
        ssize_t current_score = evaluate(lines,orig);

        std::vector<line> newlines(lines);

        uint32_t deactivated = 0;
        std::cout << "current_score = " << current_score << "\n";
        for (size_t i = 0; i < newlines.size(); ++i)
        {
                newlines[i].active = false;
                ssize_t score = evaluate(newlines,orig);
                if( score > current_score )
                {
                        newlines[i].active = true;
                }
                else
                {
                        current_score = score;
                        ++deactivated;
                }
                if( i % 1000 == 0 )
                {
                        std::ostringstream fn;
                        fn << "erase_" << std::setw(6) << std::setfill('0') << i << ".bmp";
                        bmp tmp(orig);
                        paint(newlines,tmp);
                        tmp.write(fn.str());
                        paint_layers(newlines,tmp);
                        tmp.max_contrast_all();
                        tmp.write("layers_" + fn.str());
                        std::cout << "\r i = " << i << std::flush;
                }
        }
        std::cout << "\n";
        std::cout << "current_score = " << current_score << "\n";
        std::cout << "deactivated = " << deactivated << "\n";

        bmp tmp(orig);

        paint(newlines,tmp);
        tmp.write("newlines.bmp");
        lines.clear();
        for (size_t i = 0; i < newlines.size(); ++i)
        {
                if( newlines[i].is_active() )
                {
                        lines.push_back(newlines[i]);
                }
        }
}


Rotate Cartesian coordinates. Write a program rotates some Cartesian coordinates through an angle about the origin (0.0,0.0). The angle and coordinates will be read from a single line of stdin in the following format:

angle x1,y1 x2,y2 x3,y3 ...

eg.

3.14159265358979 1.0,0.0 0.0,1.0 1.0,1.0 0.0,0.0

The results should be printed to stdout in the following format:

x1',y1' x2',y2' x3',y3' ...

eg.

-1.0,-3.23108510433268e-15 -3.23108510433268e-15,-1.0 -1.0,-1.0 -0.0,-0.0

Perl, 112 80 78

s/\S*//;$c=cos$&;$s=sin$&;s/([^ ,]*),(\S*)/($1*$c-$2*$s).",".($1*$s+$2*$c)/ge

Run on command-line as perl -pe 'code here', p option counted in code size.
For reference, here's my previous approach.  But regexes are too damn powerful.
split/[ ,]/,<>;$_='A;Y,print$x*cos($a)-$y*sin$a,",",$x*sin($a)+$y*cos$a,$"whileX';s/[AXY]/\$\l$&=shift\@_/g;eval


Binary to Hexadecimal Convert a binary number (of any size) into a hexadecimal number.

Input
A POSITIVE binary number with just the 0s and 1s. A valid input will always match the following regex: [0-1]+. If the input is not a valid binary number, that is, anything not matching this regex, the output should be 0 or the program should exit, or error. The output does not need the leading 0x nor does it need to be capitalized.

Output
The binary number converted to hexadecimal.

Winning
Original Code-Golf Rules, Lowest amount of bytes.

Examples

IN: [101]
OUT: [0x5] OR [5]

IN: [10000000010100100000]
OUT: [0x80520] OR [80520]

IN: [1010101]
OUT: [0x55] OR [55]

IN: [1111111111111111]
OUT: [0xFFFF] OR [FFFF] OR [0xffff] OR [ffff]

IN: [1012101]
OUT: [0]

IN: [a]
OUT: [0]

IN: [-1010101]
OUT: [0]

IN: [abcdef]
OUT: [0]

IN: [2]
OUT: [0]

MY, 8 6 5 bytes
⍞PrH↵

Try it online!
How?

⍞ line of raw input
P basify
r convert from binary
H convert to hex
↵ output

Errors if input isn't correct.