Print the time in a digital watch Write a program that prints the current time in a digital watch.

Rules:

The program must use the local timezone.
Time is expressed between 00:00 to 23:59 (with only hours and minutes).
The program must follow the output rules.
The smallest program wins.

Output (see example):

Each digit is represented by 4×3 matrix of the characters ␣ (space), | (pipe) and _ (underscore).
There are two spaces between two digits.
The : (column) is represented with a 1x3 matrix [␣,.,.] and is separated with the digits on both sides by 2 spaces.
A newline at the end of the output is tolerated.

List of digits:

 __           __    __          __    __    __    __    __
|  |     |    __|   __|  |__|  |__   |__      |  |__|  |__|
|__|     |   |__    __|     |   __|  |__|     |  |__|   __|

Example output: (for 21:08)

 __             __    __
 __|     |  .  |  |  |__|
|__      |  .  |__|  |__|

Go!

EDIT: corrected the spaces for : and 1

PHP, 229 174

<?php $s=" |.. w\$km<]_d\x7F}";for($r=3;$r--;print'
')foreach(str_split(date('H:i'))as$c)echo$c>'9'?$s[$r+2]:$s[($d=ord($s[$c+5])>>$r*3)/2&1].($d&1?@__:'  ').$s[$d/4&1],'  ';

$s is a lookup table that encodes several things. The first two characters are the vertical segments, when off or on. The next three characters are the characters of the colon on each of the three rows. The character codes of the remaining characters encode in binary the state of the segments of each digit.

Old version, 229 chars:

<?php foreach([strtr(decbin(735),['    ',' __ ']).' ','|  |   | __| __||__||__ |__    ||__||__|.','|__|   ||__  __|   | __||__|   ||__| __|.']as$r){foreach(str_split(date('H:i'))as$c)echo substr($r,ord($c)-48<<2,4).'  ';echo'
';}

Useful fact: the ASCII code of : is one greater than the ASCII code of 9, so 0123456789: are contiguous.


Bouncey-edged XY box with a marker at Z Long time lurker first time poster here.

Write a program which takes 3 inputs: X, Y and Z.

X = across (columns)
Y = down (rows)
Z = Location Marker

The program should then print a visual grid X across and Y down. This grid will can be made of any character except "+". Each 'location' is given an index number, counting up from 1 at coordinate 1, 1 across and then down until the end.

X and Y will always be at least 3, and Z will never be bigger than X * Y.

Z will represent the location which is printed as a "+", on the location as well as 1 character left, right, up and down. For example:

 +
+++
 +

Finally, if the + characters would intercept the edges (top most, left most, right most and/or down most edge), then the + should bounce back along the same axis and overflow the other side.

Examples:
Input = 5, 5, 13

-----
--+--
-+++-
--+--
-----

Input = 10, 10, 10

-------+++
---------+
---------+
----------
----------
----------
----------
----------
----------
----------

Input = 10, 10, 21

----------
+---------
+++-------
+---------
----------
----------
----------
----------
----------
----------

Edit : non square example
16,3,32

---------------+
-------------+++
---------------+

I think I've covered everything.
There should be no limit to the input, but if your program requires, cap it off at 64 * 64.

Bonus point (can I do that?): Input Z should not be > X * Y, but if it is larger than Y * Z, then output the center + to the middle of the grid.
EDIT: Input Z cannot be greater than X * Y

Edit 2:. Made some changes to X and Y to hopefully be clearer

This is code golf, shortest code wins.


Repeat every other character in string starting with second character Requirements:

Take a single word as input with only lowercase alphabetical characters (a-z)
Output a string where every other character is repeated, with the first repeated character being the second character in the string

Example:

Input: abcde

Output: abbcdde

Winning Criteria:
Standard code golf. Shortest number of bytes in program wins.

Clarification:
For languages with 1-based indexing the output must still match the above, aabccdee is not an acceptable solution.


Difference should make no difference Your company lately hired a new bunch of extremely dedicated sysadmins. They feel that just watching computer screens is quite limiting (I mean, 60Hz refresh rate is just NOT enough), so they hooked up the CPU data bus to an DAC and play that on a speaker through the server room so that they can hear up to 20kHz. One problem: they're sysadmins, not electrical engineers, and their speaker setup keeps breaking. They figured that this is caused by too abrupt changes in byte values in the code that the software engineers compile on the mainframe. The sysadmins are now hosting a little competition to see who can make code that is the most gentle to their speaker setup.
Challenge
Your mission is to create a program or function in a language of choice that has as little difference as possible between consecutive bytes (see the Calculation section). This program will have the task of calculating its own score.
Input
An ASCII string on stdin or your language's closest equivalent, or as a function input if you're creating a function. Since your program will have to take itself as input to calculate your score, your program should support Unicode if it contains any Unicode. Otherwise, ASCII is sufficient. Input can be assumed to be at least 2 bytes long.
Calculation
Each character of the string will be converted to it's numerical equivalent, using the ASCII standard. Then, the difference between all characters will first be squared and then summed. For example, the string abd will get a score of 1²+2²=5.
Output
Output will be the title to your entry. This means that it should be prepended by a # or appended by a newline and a - (dash). Then, it should output the name of your programming language, followed by a comma, a space and then an integer representing the result of the calculation. For example
#C++, 98

would be valid output. Output should be given on stdout or your language closest equivalent, or as a return value to your function.
Scoring
Your score will be the calculated value by your program, with the program itself as input.
Edit: Should handle newlines now, sorry for before, folks
Here is a Pyth script to verify the score calculation.


Sorted Lexical Partition of a Number The challenge is really simple: given a number, you split its digits into an array of smaller numbers such that the resulting numbers are non-decreasing. The catch is that you have to split it such that the array length is maximal.

Confused?

You are given a positive integer via STDIN (or closest alternative), command-line argument or function argument in any convenient, unambiguous input format.
You have to partition the number's decimal digits into contiguous, disjoint groups.
The array of numbers represented by these digit groups should be sorted (in the usual, non-decreasing order) without rearranging the groups.
In cases where more than one such partition exists, you have to partition the input into as many numbers as possible. In the case of ties, return one such result.
You can output the array to STDOUT (or closest alternative) or as a function return value. In case of STDOUT (or closest alternative), the array should be printed in any convenient, unambiguous list format.
The split numbers should not have leading zeroes. So for instance 1002003 cannot be printed as either [1, 002, 003] or [1, 2, 3] and the only valid answer for it is [100, 2003].

Test cases:

123456 -> [1, 2, 3, 4, 5, 6]
345823 -> [3, 4, 5, 8, 23]
12345678901234567890 -> [1, 2, 3, 4, 5, 6, 7, 8, 90, 123, 456, 7890]
102 -> [102]
302 -> [302]
324142 -> [3, 24, 142] OR [32, 41, 42]
324142434445 -> [32, 41, 42, 43, 44, 45]
1356531 -> [1, 3, 5, 6, 531]
11121111111 -> [1, 1, 1, 2, 11, 11, 111]
100202003 -> [100, 202003]

Scoring

This is code-golf so shortest code in bytes wins.

Pyth, 34

FNyUz#aYmv:zhdedC,+0N+NlzB)efqSTTY

Try it online here. Notice, this has a time (and space) complexity of O(n). Therefore the test case 12345678901234567890 takes too long in the online compiler. Use the offline one instead (1 minute on my laptop).

This is only my first attempt. There might be some room for improvements.

First some ideas how my algorithm works.

I interpret the input as string and not as a number.
Then I create all possible subsets of [0, 1, 2, ..., len(n-1)]
For each of these subsets (lets take [1, 4, 5]), I split the input string into part using these numbers. [input[0:1], input[1, 4], input[4,5], input[5,len(input)]].
Afterwards I try to convert these numbers into strings. There can be two problems. Pyth (or Python) throws an exception for an empty string, and for a string of numbers starting with 0. Therefore I use a try - catch block (actually infinity loop with an immediate break). If converting was successfully, I add the result to a list Y.
After I handled all subsets, I filter the list Y for results, that are already sorted and print the last one (the last one has the most groups).

Now the detailed explanation:

                            Implicit: z = input() (z is a String!)
                                      Y = empty list
FNyUz                       for each subset N of [0, 1, 2, ..., len(z)-1]:

     #                         start try-catch block (actually an infinite loop,
                               but the Python implementation uses a try catch.

      aY                          append to Y:
                C,+0N+Nlz            zip([0] + N, N + [len(z)])
        m                            map each element d to
          :zhded                     z[d[0]:d[-1]]
         v                           evaluated
                         B        if this didn't throw an exception already, end the infinite loop
                          ) end for loop

 f    Y      filter Y for elements T, for which
  qSTT           sorted(T) == T
e            and print the last one (the subsets generated with yUz are sorted
             by length, so the last one has the most groups)


Is it a Lynch-Bell number? You will be given a positive, whole number (that will never contain a 0) as input. Your task is to check whether it is a Lynch-Bell number or not.

A number is a Lynch-Bell number if all of its digits are unique and the number is divisible by each of its digits.

In fact, there are actually only 548 Lynch-Bell numbers, so hard-coding is a possibility, but will almost certainly be longer.

126 is a Lynch-Bell number because all of its digits are unique, and 126 is divisible by 1, 2, and 6.

You can output any truthy and falsy value.

Examples:

7 -> truthy
126 -> truthy
54 -> falsy
55 -> falsy
3915 -> truthy

This is OEIS A115569.

Mathematica, 42 bytes

0!=##&@@d&&##&@@((d=IntegerDigits@#)∣#)&

I think 0!=##&@@d&&##&@@ is a new low in readability for Mathematica...

Explanation

Some of the basic syntactic sugar used here:

& has very low precedence and turns everything left of it into an unnamed function.
&& is just the And operator.
# is the argument of the nearest enclosing unnamed function.
## is a sequence of all of the function's arguments.
@ is prefix notation for function calls, i.e. f@x == f[x].
@@ is Apply, which passes the elements of a list as individual arguments to a function, i.e. f@@{a,b,c} == f[a,b,c].

With that out of the way...

(d=IntegerDigits@#)

This should be fairly self-explanatory: this gives us a list of the input's decimal digits and stores the result in d.

(...∣#)

This tests the input for divisibility by each of its digits (because the divisibility operator is Listable). This gives us a list of Trues and Falses.

...&@@...

We apply the function on the left-hand side to the list of booleans, such that each boolean is a separate argument.

...&@@d

We apply another function to d, so that the individual digits are given as separate arguments. The function is 0!=##&, i.e. Unequal[0, d1, d2, ...]. It checks that all the digits are distinct (and that they are distinct from 0 but that's given by the challenge, and if it wasn't, it wouldn't be a divisor anyway). 0!=##& is really just a 1-byte saver on using Unequal itself, and it works because there's a 1-byte element (0) that we know is not present. So this first thing checks that the digits are unique. Let's call this result U

...&&##

Again, this is really just shorthand for And[U, ##]. With ## being a sequences, the individual booleans from the initial divisibility check are expanded into the And, so we get And[U, d1∣n, d2∣n, ...] which checks that both the digits are unique and each digit divides the input.


The alphanumeric spiral The task is very simple, when given an input, output one of the following spirals:

Input = 1 gives a spiral with the letter A beginning in the top left corner:

A B C D E F
T U V W X G
S 5 6 7 Y H
R 4 9 8 Z I
Q 3 2 1 0 J
P O N M L K

Input = 2 gives a spiral with the letter A beginning in the top right corner:

P Q R S T A
O 3 4 5 U B
N 2 9 6 V C
M 1 8 7 W D
L 0 Z Y X E
K J I H G F

Input = 3 gives a spiral with the letter A beginning in the bottom right corner:

K L M N O P
J 0 1 2 3 Q
I Z 8 9 4 R
H Y 7 6 5 S
G X W V U T
F E D C B A

Input = 4 gives a spiral with the letter A beginning in the bottom left corner:

F G H I J K
E X Y Z 0 L
D W 7 8 1 M
C V 6 9 2 N
B U 5 4 3 O
A T S R Q P

As you can see, the spiral always goes clockwise and moves from the outside to the inside.

The rules are simple:

You need to provide a full program using STDIN and STDOUT, or the nearest equivalent if not possible.
Given an input (1, 2, 3, 4), output the related spiral.
Trailing whitespaces are allowed
Leading whitespaces are allowed when used consistently
You need to use uppercase letter for the output, lowercase letters are not allowed.
This is code-golf, so the program with the least amount of bytes wins!

Japt, 53 bytes 58 59 60

Saved 5 bytes thanks to @ETHproductions

"FGHIJK EXYZ0L DW781M CV692N BU543O ATSRQP"¸zU ®¬¸} ·

This uses the rotate command which I never thought would be so useful

Explanation && Ungolfed

"FGHIJK EXYZ0L DW781M CV692N BU543O ATSRQP"qS zU m_q qS} qR

             // Implicit: U = input
"FGH...SRQP" // String, " " represent newlines
qS           // Split   " "
zU           // Rotate
m_           // Loop the lines
  q qS}      // Insert spaces
qR           // Join by newlines

Try it online


Generate a map for a roguelike Today, we'll be generating a map for a roguelike RPG!
Example Map:
##########
####    F#
####    ##
##    C#C#
#     ## #
# C   #E #
####  #  #
#        #
#P       #
##########

# are walls, P is the player's starting location, F is the finish that must be reached, C are coins that can be collected, and E are enemies that can be fought.
Map specifications:

Height and Width should both be between 10 and 39, inclusive. Height does not have to equal width.
The maps borders should be filled in with walls.
P should be placed in the bottom left corner.
F should be placed in the top right corner.
There should be between 1 and 3 enemies.
There should be between 2 and 4 coins.
There should be some amount of walls in the middle. There should be a path to get from P to Every C, E, and F, keeping in mind that the player cannot move diagonally.
Every possible combination should have some chance of occurring.

Rules

Fewest byte program wins.
Your program should not take any input.
Your program may not exit with an error (non-fatal output is STDERR is ok, but we can't have our rogue-like crash after map generation!)
A single trailing newline is allowed and trailing space is allowed.
No other output is allowed.


Ordered sequence of ascending integer combinations Write a program or function to produce the following output in the correct order.

EDIT: The symbols are not mathematical! The numbers just represent unique data and the + and - could be any two arbitrary symbols.

Take an non-negative integer input n. The first line is always -, even for n=0.

If the current line is -, the next line is 1+2+ ... (n-1)+n-

n=4: - => 1+2+3+4-

If the last integer is equal to n, remove all integers from the end that are immediately followed by a -, then change the last + to a -

n=4: 1-2+3-4- => 1-2-
EDIT: When the string is full (all the integers from 1 to n are included), remove all integers from the end that are followed by a -, until you reach an integer followed by a +. Leave that integer but change its following + to a -
Using the same example as immediately above (which does not follow -), remove 4-, remove 3-, change 2+ to 2-. 1- doesn't change since we stop at 2. Result:  1-2-

If the last integer is less than n, append the remaining integers with a + after each one, except the final integer which should have a - appended

n=4: 1+2- => 1+2-3+4-
EDIT: If the current string is not full (does not contain all the integers from 1 to n), add each integer not already included in ascending order up to n-1 with a + after each one, and then append the last integer n followed by a -
If the current line is 1-, append 2+, append 3+ which is n-1 if n=4. Then append 4-. Result: 1-2+3+4-

If the current line contains all the integers and each one is immediately followed by a -, exit the code

n=4: 1-2-3-4- => END

There must be no leading or trailing spaces on any line. There must be a line break between each line. There may or may not be a line break on the last line.

EDIT: You should test your code up to at least n=10 (over 1000 lines of output so I can't include it here). Any number that doesn't cause your code to run out of resources should (eventually!) produce the correct output but you don't have to wait for the universe to end!

This is code-golf, so shortest code in bytes wins!

Input n=0:

-

Input n=1:

-
1-

Input n=2:

-
1+2-
1-
1-2-

Input n=4:

-
1+2+3+4-
1+2+3-
1+2+3-4-
1+2-
1+2-3+4-
1+2-3-
1+2-3-4-
1-
1-2+3+4-
1-2+3-
1-2+3-4-
1-2-
1-2-3+4-
1-2-3-
1-2-3-4-

Haskell, 89 bytes

g takes an integer and returns a string.

g n=unlines$max"-".foldr(\(s,i)r->id=<<[show i++s:r|s:r>"+"])""<$>mapM(mapM(,)"+-")[1..n]

Try it online!

How it works

Loosely speaking, the algorithm constructs a list of all 2^n combinations 1+2+...n+, 1+2+...n- up to 1-2-...n-, strips away the final +-terminated numbers, and if the result is empty, replaces it with -.
mapM(,)"+-" is a shorter way (using the function monad) to write \i->[('+',i),('-',i)].
mapM(mapM(,)"+-")[1..n] generates (using the list monad for the outer mapM) a list with all combinations as lists of tuples e.g. [(1,'+'),(2,'-'),...,(n,'+')].
foldr ... <$> ... combines each of these lists of tuples into a string, using the lambda expression to build it from the right.

(s,i) is a tuple of a sign and a number, and r is the string constructed from the tuples to its right.
id=<<[show i++s:r|s:r>"+"] prepends i and s to the string r constructed so far, but not if the sign s is positive and r is empty.

This is tested by comparing s:r to "+". By luck this is the lexicographically smallest string that can result from concatenating them, so the comparison can use > rather than /=.

Also by luck, "-" is smaller than any nonempty string that can be constructed by the fold, so the empty string can be replaced with it by using max.
Finally unlines turns the strings into a single string of lines.


Count the number of cyclic words in an input Cyclic Words

  Problem Statement

  We can think of a cyclic word as a word written in a circle. To
  represent a cyclic word, we choose an arbitrary starting position and
  read the characters in clockwise order. So, "picture" and "turepic"
  are representations for the same cyclic word.

  You are given a String[] words, each element of which is a
  representation of a cyclic word. Return the number of different cyclic
  words that are represented.

Fastest wins (Big O, where n = number of chars in a string)

Python

Here's my solution. I think it might still be O(n2), but I think the average case is much better than that.

Basically it works by normalizing each string so that any rotation will have the same form. For example:

'amazing' -> 'mazinga'
'mazinga' -> 'mazinga'
'azingam' -> 'mazinga'
'zingama' -> 'mazinga'
'ingamaz' -> 'mazinga'
'ngamazi' -> 'mazinga'
'gamazin' -> 'mazinga'

The normalization is done by looking for the minimum character (by char code), and rotating the string so that character is in the last position. If that character occurs more than once, then the characters after each occurrence are used. This gives each cyclic word a canonical representation, that can be used as a key in a map.

The normalization is n2 in the worst case (where every character in the string is the same, e.g. aaaaaa), but most of the time there's only going to be a few occurrences, and the running time will be closer to n.

On my laptop (dual core Intel Atom @ 1.66GHz and 1GB of ram), running this on /usr/share/dict/words (234,937 words with an average length of 9.5 characters) takes about 7.6 seconds.

#!/usr/bin/python

import sys

def normalize(string):
   # the minimum character in the string
   c = min(string) # O(n) operation
   indices = [] # here we will store all the indices where c occurs
   i = -1       # initialize the search index
   while True: # finding all indexes where c occurs is again O(n)
      i = string.find(c, i+1)
      if i == -1:
         break
      else:
         indices.append(i)
   if len(indices) == 1: # if it only occurs once, then we're done
      i = indices[0]
      return string[i:] + string[:i]
   else:
      i = map(lambda x:(x,x), indices)
      for _ in range(len(string)):                       # go over the whole string O(n)
         i = map(lambda x:((x[0]+1)%len(string), x[1]), i)  # increment the indexes that walk along  O(m)
         c = min(map(lambda x: string[x[0]], i))    # get min character from current indexes         O(m)
         i = filter(lambda x: string[x[0]] == c, i) # keep only the indexes that have that character O(m)
         # if there's only one index left after filtering, we're done
         if len(i) == 1:
            break
      # either there are multiple identical runs, or
      # we found the unique best run, in either case, we start the string from that
      # index
      i = i[0][0]
      return string[i:] + string[:i]

def main(filename):
   cyclic_words = set()
   with open(filename) as words:
      for word in words.readlines():
         cyclic_words.add(normalize(word[:-1])) # normalize without the trailing newline
   print len(cyclic_words)

if __name__ == '__main__':
   if len(sys.argv) > 1:
      main(sys.argv[1])
   else:
      main("/dev/stdin")


Golf the Chinese 9*9 multiple table Output the following table:
一一得一
一二得二 二二得四
一三得三 二三得六 三三得九
一四得四 二四得八 三四十二 四四十六
一五得五 二五一十 三五十五 四五二十 五五二十五
一六得六 二六十二 三六十八 四六二十四 五六三十 六六三十六
一七得七 二七十四 三七二十一 四七二十八 五七三十五 六七四十二 七七四十九
一八得八 二八十六 三八二十四 四八三十二 五八四十 六八四十八 七八五十六 八八六十四
一九得九 二九十八 三九二十七 四九三十六 五九四十五 六九五十四 七九六十三 八九七十二 九九八十一

Or you can use the first three letters in its English word, in case that some languages don't support Chinese characters:
OneOneGetOne
OneTwoGetTwo TwoTwoGetFou
OneThrGetThr TwoThrGetSix ThrThrGetNin
OneFouGetFou TwoFouGetEig ThrFouTenTwo FouFouTenSix
OneFivGetFiv TwoFivOneTen ThrFivTenFiv FouFivTwoTen FivFivTwoTenFiv
OneSixGetSix TwoSixTenTwo ThrSixTenEig FouSixTwoTenFou FivSixThrTen SixSixThrTenSix
OneSevGetSev TwoSevTenFou ThrSevTwoTenOne FouSevTwoTenEig FivSevThrTenFiv SixSevFouTenTwo SevSevFouTenNin
OneEigGetEig TwoEigTenSix ThrEigTwoTenFou FouEigThrTenTwo FivEigFouTen SixEigFouTenEig SevEigFivTenSix EigEigSixTenFou
OneNinGetNin TwoNinTenEig ThrNinTwoTenSev FouNinThrTenSix FivNinFouTenFiv SixNinFivTenFou SevNinSixTenThr EigNinSevTenTwo NinNinEigTenOne

You can output in any reasonable format, e.g. plain text separated with space/comma/tab and newline, 2D array where empty places are empty or don't exist (The 2*1 place is empty so there shouldn't be anything in the array).
Code golf, shortest code in bytes win. GBK encoding is allowed, where each Chinese character use 2 bytes.
Converting Table:

Character
Number

一
One

二
Two

三
Thr

四
Fou

五
Fiv

六
Six

七
Sev

八
Eig

九
Nin

十
Ten

得
Get

Stax, 66 characters
9mYF"得一二三四五六七八九"cacy*~@ny@\p;11AH:b!n;A/X@]z?px'十z?p,A%sn@]z?' +qD

Number of bytes depends on the encoding used for Chinese characters.
Run and debug online!
Explanation
9mYF...D    Loop `n` times and print a newline after each loop, `n`=1..9

"..."cay*~@ny@\p
"..."c              Push the string and duplicate it
      ay            Fetch the outer loop variable
        *           Multiply with the inner loop variable
         ~          Move the product to input stack for later use
          @         Take character at the index specified by inner loop variable
           ny@      Take character at the index specified by outer loop variable
              \p    Print the two characters

;11AH:b!n;A/X@]z?p
;11AH:b!        ?p    Is the product not in range [11,20)?
                      Output (*) if true, (**) if false.
        n;A/X@        Character at the index of the "ten" digit of product
              ]       Convert character to string (*)
               z      Empty string (**)

x'十z?p,A%sn@]z?' +q
x'十z?p                Print "十" if the "ten" digit is non-zero, nothing otherwise
       ,A%sn@]z?       Get the character specified by the last digit if that digit is non-zero, empty string otherwise
                ' +q   Append a space and print

Alternative version (Stax 1.0.6), 59 bytes (by @recursive)
This uses a feature that is inspired by this challenge and is only included in Stax 1.0.6 which postdates the challenge.
éz░╖▐5à{│`9[mLùÜ•ëO╞îπl▼Γ─§╥|▒╛Δ◙Φµ'r╠eƒÿQ╫s♪Ω]£ï♪D3╚F◙δÿ%‼

The ASCII version is
9mX{x\_x*YA/]yA-y20<*!*+y9>A*+yA%]0-+"NT|,,t.%,p&()(!'^pq kzi !X6"!s@mJ

This version constructs the index array and then uses it to index the string of Chinese characters to avoid redundant stack operations (c,a,n) and multiple @s.
Explanation
9mX{...m    Loop `n` times and map `1..n` to a list of strings, `n`=1..9
        J   Join the strings with space and print with a newline

x\_x*YA/]yA-y20<*!*+y9>A*+yA%]0-+"..."!s@
x\                                           A pair: (inner loop variable, outer loop variable)
  _x*Y                                       Product of inner and outer loop variable
      A/                                     floor(product/10)
        ]                                    [floor(product/10)]
         yA-                                 Product does not equal 10
            y20<                             Product is less than 20
                *!                           `Nand` of them
                                             This is true (1) if the product is in the range {10}U[20,81]
                  *                          Repeat [floor(product/10)] this many times
                                             This results in itself if the predicate above is true, or empty array if it is false
                   +                         Add it to the list of [inner loop var, outer loop var]
                                             This list will be used to index the string "得一二三四五六七八九十"
                    y9>A*                    Evaluates to 10 if the product is larger than 9, 0 otherwise
                                             When indexed, they become "十" and "得", respectively
                         +                   Append to the list of indices
                          yA%                Product modulo 10
                             ]0-             [Product modulo 10] if that value is not zero, empty array otherwise
                                +            Append to the list of index
                                 "..."!      "得一二三四五六七八九十"
                                       s@    Index with constructed array


Attack, Decay, Sustain, Release Sound synthesizers use envelope generators to control how certain parameters of the sound (such as overall loudness) change with time. In many synthesizers an envelope is defined by four parameters, as represented in the following figure from Wikipedia:

Attack time (A): time taken for the envelope to reach its maximum level, starting from zero, when the key is first pressed.
Decay time (D): time taken for the envelope to reach the specified sustain level.
Sustain level (S): level which is maintained, after the initial attack and decay, for as long as the key is being pressed.
Release time (R): time taken for the envelope to reach zero when the key is released.

The challenge
Input the four parameters A, D, S, R and plot the envelope.
Parameters will be integer values from 0 to 127.
The maximum level (reached at the end of the attack phase) will be assumed to be 127.
The horizontal segment at the sustain level will be assumed to have duration 64 (in the actual sound this duration is not fixed, but is determined by the amount of time that the key is held).
Format and further details
The output should be an image in raster or vector format. If it's raster, the polygonal line should occupy at least 50 pixels vertically an horizontally.
The image can be either displayed or produced as a file in a standard image format. The file can be written to disk, or its exact contents can be output, either to STDERR or as function return argument.
The graph need only contain the polygonal line that defines the envelope. The scale of each axis can be freely chosen. Other elements such as axis lines, numeric labels or line colors are optional.
Input means and format are flexible as usual. For example, you can take the four numbers in any order, or an array containing them. A program or a function can be provided. Standard loopholes are forbidden.
Shortest code in bytes wins.
Test cases
Input is in the format [A D S R]. Note that the scale is different in each figure (in accordance with the rule that scale can be freely chosen)
[15 30 70 40]

[64 64 64 64]

[0 10 50 80]

[0 0 90 80]

[5 50 0 0]

[5 50 0 80]

[24 32 127 48]

TikZ, 195 193 181 177 172 167 163 160 159 bytes

Thanks to David Carlisle for his helpful answer here

\documentclass[tikz]{standalone}\begin{document}\tikz\def~#1{\typein[#1];}~\a~\s~\d~\r\def\u{)--(\a+\d}\draw(,)--(\a,127\u,\s\u+64,\s\u+\r+64,);\end{document}

Yes, you heard right TikZ.

Explanation

This uses a couple of techniques to achieve its goal.  The first thing is input.  Most people might not know that LATEX can take input.  Well it can.  This is achieved with the command \typein.  This will halt the compiler and request input from the user as assign it to a variable.

The other main technique is the use of \def.  \def in Tikz is absurdly powerful.  It essentially defines a piece of code and pastes it everywhere you call the variable.  In this code we define two things \typein[#1]{} so that we can assign our variables golfily and )--(\a+\d because this code shows up a bunch of times in the ungolfed version.

Here are two versions of the code (without the wrapper):

Golfed:

\documentclass[tikz]{standalone}\begin{document}\tikz\def~#1{\typein[#1];}~\a~\s~\d~\r\def\u{)--(\a+\d}\draw(,)--(\a,127\u,\s\u+64,\s\u+\r+64,);\end{document}

Ungolfed:

\typein[\a]{}\typein[\s]{}\typein[\d]{}\typein[\r]{}\draw(0,0)--(\a,127)--(\a+\d,)--(\a+\d+64,)--(\a+\d+\r+64,0);

Image:

Since I cannot upload a pdf image directly, and converting it to any other format seems to cause the line to disappear altogether, here is what an image might look like when opened in Preview (input for this image is [64 64 64 64]):

As you can see it is very thin.  However because it is a PDF image and not a raster image does not have to comply with thickness requirements.


solve puzzle with a tweet? javascript (fun challenge) the question is "complete this subtraction by replacing the asterisks with digits so the numbers 1-9 only appear once each"

 9**
-*4*
____
 **1

my code tries random numbers until it works, and displays the answer.  here is the entire html app.  I want one to fit in a tweet at 140 characters  (not counting  tags)

<script>
function r(){return Math.random()*9+1^0}
do{a=900+r()*10+r(),b=r()*100+40+r(),c=a-b,s=''+a+b+c
}while(c%10!=1||eval('for(i=0;i++<9;)if(s.indexOf(i)<0)1'))alert(s)
</script>

Is there any way to make this shorter, including with a different solution?

SOLVED!:
Thanks Peter, Shmiddty and copy, currently I have 91 chars!

for(x=1;++x<999;)for(y=1;y<x;)/(?!.*0|.*(.).*\1)9...4...1/.test(s=''+x+y+(x-y++))&&alert(s)


Frame this nice ASCII-Art Introduction
I think everyone agrees that nice pictures have to have a nice frame. But most challenges on this site about ASCII-Art just want the raw picture and don't care about it's preservation.
Wouldn't it be nice if we had a program that takes some ASCII-Art and surrounds it with a nice frame?
The Challenge
Write a program that takes some ASCII-Art as input and outputs it surrounded by a nice frame.
Example:

*****
 ***
  *
 ***
*****

becomes

╔═══════╗
║ ***** ║
║  ***  ║
║   *   ║
║  ***  ║
║ ***** ║
╚═══════╝

You have to use the exact same characters for the frame as in the example: ═ ║ ╔ ╗ ╚ ╝
The top and the bottom of the frame get inserted before the first and after the last line of the input.
The left and rights parts of the frame have to have exact one space padding to the widest line of the input.
There may be no leading or trailing whitespaces in the output. Only a trailing newline is allowed.
You may assume that the input has no unnecessary leading whitespaces.
You may assume that the input has no trailing whitespaces on any line.
You don't have to handle empty input.
The input will only contain printable ASCII-characters and newlines.

Rules

Function or full program allowed.
Default rules for input/output.
Standard loopholes apply.
This is code-golf, so lowest byte-count wins. Tiebreaker is earlier submission.

Happy Coding!
Using some great ASCII-Art, that was produced in any challenge on this site, as input to your program and showing it with a nice frame is highly encouraged!

Haskell, 139 bytes

q=length
g x|l<-lines x,m<-maximum$q<$>l,s<-[-1..m]>>"═"='╔':s++"╗\n"++(l>>= \z->"║ "++z++([q z..m]>>" ")++"║\n")++'╚':s++"╝"

As an example I'm framing snowman "12333321".

*Main> putStrLn $ g " _===_\n (O.O)\n/(] [)\\\n ( : )"
╔═════════╗
║  _===_  ║
║  (O.O)  ║
║ /(] [)\ ║
║  ( : )  ║
╚═════════╝

How it works:

bind
  l: input split into lines
  m: maximum line length
  s: m+2 times ═

build top line
prepend left frame to each line, pad with spaces, append right frame
build bottom line.


Golf Me A Bubble Sort Your task is to create a program that performs a bubble sort on a given array until it is sorted.

Algorithm

In order to qualify as a bubble sort, the program must operate as follows:

Each pass goes through the array, looks at every two adjacent elements in turn, and potentially swaps them.
Each pass goes through the array in the same direction and without gaps. There are no partial passes - each pass must go through the whole array.
The program must never compare or swap array elements that aren't adjacent.
A sufficient (and finite) number of passes must be performed, such that the output array is guaranteed to be sorted. (E.g. you can safely stop if there was a whole pass without any swaps, or after len(array) passes have been made, etc.)

Rules

You must provide a sufficient explanation for how your answer does a bubble sort.
You may not use built-in or standard library sorting algorithms. You must make your own code.
Your program should take an array of numbers as input and output them in the correct order.

Input: 10 5 9 2 . . . (and so on)
The program should always output the sorted array.
Output can be an array returned by the program when run, or it can modify the input array in-place.
Output can also be the correctly ordered values separated by whitespace.

Speed does not matter as much as if the program functions.

Test Cases

10 5 9 2 1 6 8 3 7 4 (you can format it differently depending on your language)
1 2 5 4 3

This is code-golf, so the shortest answer in bytes wins.

Haskell, 55 53 bytes

f(a:b:c)=min a b:f(max a b:c)
f x=x
foldr(\_->f)=<<id

Usage example: foldr(\_->f)=<<id $ [3,1,6,4,3,8,3,1,1,2] -> [1,1,1,2,3,3,3,4,6,8]. Try it online!.

How it works: f does one iteration by keeping the minimum of the first two elements and appending a recursive call with the maximum of the first two elements and all the other elements. It stops when there are less than two  elements in the list. The main function calls f length <input> times by iterating over the input list via fold but ignoring the elements.


Find the Squarish Root Write code that when given a positive number \$x\$ as input, outputs the largest positive divisor of \$x\$ less than or equal to the square root of \$x\$.

In other words find the largest \$n > 0\$ such that

\$\exists m\geq n:m\cdot n=x\$

(Exists \$m\$ greater than or equal to \$n\$ such that \$m\$ times \$n\$ is \$x\$)

For example if the input were \$12\$ the divisors are \$1\$, \$2\$, \$3\$, \$4\$, \$6\$, and \$12\$.  \$1\$, \$2\$ and \$3\$ all multiply by larger numbers to get \$12\$, but \$3\$ is the largest so we return \$3\$.

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

Test Cases

(1,1)
(2,1)
(3,1)
(4,2)
(5,1)
(6,2)
(7,1)
(8,2)
(9,3)
(10,2)
(11,1)
(12,3)
(13,1)
(14,2)
(15,3)
(16,4)
(17,1)
(18,3)
(19,1)
(20,4)
(21,3)
(22,2)
(23,1)
(24,4)
(25,5)
(26,2)
(27,3)
(28,4)
(29,1)
(30,5)
(31,1)
(32,4)
(33,3)
(34,2)
(35,5)
(36,6)
(37,1)
(38,2)
(39,3)
(40,5)
(41,1)
(42,6)
(43,1)
(44,4)
(45,5)
(46,2)
(47,1)
(48,6)
(49,7)
(50,5)

OEIS A033676

Python3, 49 47 bytes

def f(x):
 l=x**.5//1
 while x%l:l-=1
 return l

Explanation

l=x**.5//1 → Assign l the largest integer less than equal to the square root of x
while x%l:l-=1 → While l does not evenly divide x, decrement l.

Edits

Mention Python3, not Python2
Use ...//1 to save two bytes.  (Decimals are okay!  Thanks @Rod)


Addition/Multiplication table generator Given a number and either "+" or "*", return an addition or multiplication table with the dimensions of that number.

Specifications

The input will be formatted as dimension, operation.
The program should not return anything if the operation input is not + or *.
The program should not return anything if the dimension input is less than 1.

(4,*):
1 2 3 4
2 4 6 8
3 6 9 12
4 8 1216

(4,+):
1234
2456
3567
4678

The spaces between the numbers in the table should be equal to one less than the number of digits in dimension^2 for multiplication, and for addition one less than the number of digits in dimension * 2.

Bash + BSD Utils, 62 bytes

l=$[$1*$1-1]
eval echo \$[{1..$1}$2{1..$1}]|rs -g${#l} $[$1+1]

This calculates the number of spaces as per "number of digits in (dimension^2)-1", and not as shown in the example output, as currently written.
This answer is very similar to this one.
Works out-of-the-box on macOS.  rs may need to be installed on Linux systems:
sudo apt-get install rs


Mutual Negative Quines This was inspired by Print a Negative of your Code and Golf a mutual quine.

Consider a rectangle of characters, that meet the following restrictions:

Consists solely of printable ASCII characters
Dimensions both greater than 1
Each row and each column contains at least one space.
Each row and each column contains at least one non-space character.

For example, the following is a valid 6x4 rectangle:

%n 2e
1  g 3
 &* __
 3

A negative for this rectangle is defined to be a rectangle of equal dimensions, with all spaces replaced by non-space characters, and all non-space characters replaced by spaces. A negative of the above rectangle could be:

  f  ^
 33 >
9  $
^ }|Q'

Any non-space printable ASCII character may be used to replace a space.

Task

Your task is to write a program with rectangular source code, that outputs a valid negative to itself. The negative outputted must also be a valid program, in the same language as the original, and it must output the source of the original.

No trailing whitespace may be added or removed, except for a single trailing newline at the end of either output, which is optional.

Neither program is permitted to read the source code of either; nor may REPL environments be assumed.

Scoring

Your score is the product of the dimensions of your code (i.e. if your source code is in a 12 by 25 rectangle, your score is 12*15=180). Additionally, for each character used in a comment, your score increases by 2 (If you use /* .. */ once in your code, and your code is in a 10 by 10 rectangle, your score would be 10*10+8*2=116).

The lowest score wins.

If there is a tie, the submission with the least number of spaces in the program (either the original or the negative, whichever has fewer spaces) wins.

If there still remains a tie, the earlier answer shall win.

There is a bonus of -52%, if combining the original and the negative together produces a normal quine. For example:

Original   Negative   Combined
 A A       B B        BABA
A A         B B       ABAB


Permutation? Permutatino! Specifications

Your program must can take in an integer n, then take in n more strings (containing only alphanumeric characters) in your preferred method (separated by whitespace, file input, hash table etc.). You must then find the permutation before the inputted strings when sorted in lexicographical order, and output that in your preferred method.

If it is already sorted in lexicographical order, output the permutation in reverse regular lexicographical order.

Rules

1) Code can be just a function

2) If you pipe in from a file, you can to exclude the file name's length from your program (just the filename, not full path)

3) If there are repeated characters, take the permutation before the first occurrence of the repeats

Test cases

3 abc hi def

The possible permutations of this (in lexicographical order) are:

abc def hi
abc hi def
def abc hi
def hi abc
hi abc def
hi def abc

Now see that abc hi def is the 2nd permutation, so we output abc def hi.

If instead we pick abc def hi(the first permutation), then output abc def hi.

Another test case is in the title: your function should map Permutation to Permutatino

Scoring:

The winner is the code with the smallest score, which is the length of the code multiplied by the bonus.

Bonus:

20% -90% (to keep non-esolangs in the fight) of your byte count if you can do this in O(N) time.

-50% (stacks with the above -90% to give a total of -95%) if your solution isn't O(N!) which is listing out permutations, finding the element and getting the index, subtracting 1 from the index (keep it the same if the index is 0) and outputting the element with the subtracted index

With the above 2 bonuses, I won't be surprised if there's a 2 byte answer.

Hint: there is definitely a faster way to do this apart from listing all the permutations and finding the supposed element in the general case

Congrats to @Forty3 for being the first person to get the O(N) solution!

Here's some (C based) pseudocode:

F(A) { // A[0..n-1] stores a permutation of {1, 2, .., n}
  int i, j;
  for (i = n - 1; i > 0 && (A[i-1] < A[i]); i--)
    ; // empty statement
  if (i = 0)
    return 0;
  for (j = i + 1; j < n && (A[i-1] > A[j]); j++)
    ; // empty statement
  swap(A[i-1], A[j-1]); // swap values in the two entries
  reverse(A[i..n-1]); // reverse entries in the subarray
  return 1;
}

If you want to test if your program is O(N), try with n=11 and the strings being the individual letters of Permutation. If it takes longer than a second, it's most definitely not O(N).

Python 2, 118 96 - 50% = 48 bytes

Takes input in the form ['abc','def','ghi']. Note that this solution returns the list reversed if the input is sorted, as per a previous spec.

def f(n):m=n[1:];S=sorted;a=S(n);return[a.pop(a.index(n[0])-1)]+a[::-1]if m==S(m)else[n[0]]+f(m)

Try it Online!

Seems to be the O(n) solution more efficient than computing all permutations.

Explanation: Recursively checks if everything after the current element is in sorted order. If so, returns the string immediately lexicographically before (a.index(n[0])-1)) the first element + the rest of the list reversed (a[::-1]).

Runtime: O(n^2 logn) In the worst case (list is reversed), the function will call sorted, which has a runtime of nlogn, for each element in the list (n times).


Create a sudoku solution CHECKER Create a Sudoku solution CHECKER

There are oodles of Sudoku SOLVERS here, but I want you to create a solution CHECKER as small as humanly possible (code-golf).

A valid entry will be able to either take a 9x9 array as an argument (passed by reference, serialized on the command line, or however you want to take it) or accept an input file that is nine lines of nine numbers for the final grid.  See examples of input below.
Valid input should be base-10 numbers (1-9)
Missing, empty, extra, non-numeric positions, or positions with numbers outside of 1-9 should be rejected as invalid input by returning a non-zero result, printing an error, or both.
Your program needs to test whether each number appears once per column, once per line, and once per 3x3 sub-grid.  If it passes, return "0" and if not, return a non-zero result.
Use of external resources (websites, etc.) is to be avoided.
If your solution is a stand-alone program, exiting with a exit status of, or printing, "0" or non-zero for "Pass" or "Fail", respectively, is ok.

Let the smallest answer win!

Input Examples:

c array:

int input[9][9]={{1,2,3,4,5,6,7,8,9},
                 {4,5,6,7,8,9,1,2,3},
                 {7,8,9,1,2,3,4,5,6},
                 {2,3,1,5,6,4,8,9,7},
                 {5,6,4,8,9,7,2,3,1},
                 {8,9,7,2,3,1,5,6,4},
                 {3,1,2,6,4,5,9,7,8},
                 {6,4,5,9,7,8,3,1,2},
                 {9,7,8,3,1,2,6,4,5}
                };

file:

123456789
456789123
789123456
231564897
564897231
897231564
312645978
645978312
978312645

The 9 sub-grids:

+---+---+---+
|123|456|789|
|456|789|123|
|789|123|456|
+---+---+---+
|231|564|897|
|564|897|231|
|897|231|564|
+---+---+---+
|312|645|978|
|645|978|312|
|978|312|645|
+---+---+---+

Python, 103

I hate sudoku.

b = [[1,2,3,4,5,6,7,8,9],
     [4,5,6,7,8,9,1,2,3],
     [7,8,9,1,2,3,4,5,6],
     [2,3,1,5,6,4,8,9,7],
     [5,6,4,8,9,7,2,3,1],
     [8,9,7,2,3,1,5,6,4],
     [3,1,2,6,4,5,9,7,8],
     [6,4,5,9,7,8,3,1,2],
     [9,7,8,3,1,2,6,4,5]]

e=enumerate;print 243-len(set((a,t)for(i,r)in e(b)for(j,t)in e(r)for a in e([i,j,i/3*3+j/3]*(0<t<10))))

How it works: each row, column, and block must have each number from 1 to 9.  So for each 0 <= i, j < 9, the cell i,j is in block 3*floor(i/3) + floor(j/3).  Thus, there are 243 requirements to satisfy.  I make each requirement a tuple ((item index,item type number),symbol) where item index is a number between 0 and 8 (inclusive), item type number is 0,1, or 2 to denote row, column or block respectively, and symbol is the entry b[i][j].

Edit: I mistakenly didn't check for valid entries.  Now I do.


Golfing Newton's Method I have the following code which I've written to emulate Newton's method for deriving the square root of a number:

r=(x,y)=>
  (z=((y=y||x)*y-x)/(2*y)>1e-15)?
r(x,y-(y*y-x)/(2*y)):y

Where r(37) would result in 6.08276253029822 which is great given the limitations of my browser.

I'd like to golf this code further seeing there's some repetition here, not to mention, I'd also like to reduce my error limit (the 1e-15). This is the furthest I've gotten. Can anyone help? If possible I'd love to eliminate the need of the error limit without resulting in a "maximum stack call size exceeded" error...

This is for a blog post I'm working on JavaScript and alternatives to native methods. I'll give a special shout out on the blog post to the persons who can help me out.

Thanks in advance.

Golfed only, -23 bytes
ES6 supports default parameters.

Default function parameters allow formal parameters to be initialized
with default values if no value or undefined is passed.

So, we can replace y=y||x with just r=>(x,y=x).
(y*y-x)/(2*y) can be rewritten as y/2-x/2/y. And since this expression appears twice in the code, we can assign it to a new variable z.
We get:
r=(x,y=x)=>(z=y/2-x/2/y)>1e-15?r(x,y-z):y

As suggested by ETHproductions in the comments, we now can save 2 more bytes by multiplying z by 2:
r=(x,y=x)=>(z=y-x/y)>2e-15?r(x,y-z/2):y

r=(x,y=x)=>(z=y-x/y)>2e-15?r(x,y-z/2):y

console.log(r(37))

Alternate version, -26 bytes
To save more bytes, another approach is to just iterate enough times rather than using a test on the result.
That could be done that way:
r=(x,y=k=x)=>(k/=2)?r(x,y/2+x/2/y):y

r=(x,y=k=x)=>(k/=2)?r(x,y/2+x/2/y):y

console.log(r(37))

We start with k = x and divide it by 2 at each iteration. No matter the initial value of x, we will eventually reach 0 because of arithmetic underflow.
The good thing about this method is that the number of iterations doesn't heavily rely on the value of x. For instance, we'll get 1142 iterations for x = 1020 and 1009 iterations for x = 10 -20. In both cases, we iterate far too many times than necessary, without exceeding the default maximum number of iterations of common browsers.
Some more notes:

The error is negligible for x > 10 -215 and quickly grows below this bound.
For the same byte count and less iterations, we can divide by 9 instead. In that case, a safe bound is x > 10 -124.
Unlike Math.sqrt(), this method does not return NaN for negative numbers or ±Infinity (and neither does the original code).


Alex the Truck Driver Alex is a Truck Driver who wants to find the quickest way to deliver goods to multiple cities. He knows the distances between his destinations, but you need to write a program to help him find the quickest way to deliver goods to them.

Input

The first line of input gives the number of cities Alex needs to deliver goods to. Every line that follows gives the distance between the cities. The second line of input is always the distance between the first and second cities. If there is a third city, the third line of input is the distance between the first and third city. When to distance to the first city has been given for all cities, the next lines of input gives the distance between the the second city and every other city (except the first, as that information as already been given). This continues until every combination has been given. Sample inputs:

//Number of cities
4
//A -> B
2
//A -> C
4
//A -> D
3
//B -> C
5
//B -> D
1
//C -> D
3

3
6
4
2

Output

The output should print the quickest way to deliver goods to every destination in the form A -> C -> D -> C -> A (For every output, the reverse of will also work. You only need to print one solution). Alex ALWAYS starts at A and must always return to A at the end (as A is where he lives). Here are the outputs for the sample inputs above:

A -> B -> D -> C -> A

A -> C -> B -> A

Rules

The shortest code wins.

Happy Golfing!

Python 2, 210 205

from itertools import*
r=range(input())
d={t:input()for t in combinations(r,2)}
n=0,
print" -> ".join(chr(65+c)for c in n+min(permutations(r[1:]),key=lambda p:sum(d[min(t),max(t)]for t in zip(n+p,p+n)))+n)

Edit: Shortened according to Volatility's suggestion.
I'm amazed that it gets more readable and Pythonic the shorter it gets.


Indent your code according to Fibonacci Okay, so I saw this in a meme and decided it'd be the perfect code golf challenge:
I prefer to increase the side of my indents according to the Fibonacci sequence:
class Kls
 def method
  t = Time.now
  if t.hour >= 12
    puts "It's afternoon"
    if t.hour == 18
       puts "It's time for your meal of:"
       %w(bread sausage brocolli milk).each do |food|
            "Some #{food}"
       end
    end
  else
    puts "It's not afternoon"
  end
 end
end

This means each line is indented by the sum of the spaces indented in the previous indentation-level. The first indention-level is indented by one space, then subsequent indention-levels are indented by 1, 2, 3, 5, 8, 13, 21, etc additional spaces.
The challenge
Given a multi-line string with multiples of 2 spaces as indentation, convert it to a Fibonacci indented multi-line string instead.
This means every line with 0 indented spaces will remain 0 spaces; every line with 2 indented spaces will become 1 instead (sum of the first two Fibonacci numbers 0+1 = 1); every line with 4 indented spaces will becomes 2 instead (sum of the first three Fibonacci numbers 0+1+1 = 2); etc. So the number of indentations can be calculated as follows:

Get the current amount of leading spaces (guaranteed to be a multiple of 2, so [0,2,4,6,8,...])
Divide this by 2, so we have our 0-indexed numbers (let's call it n)
Get the first [0,n] (0-indexed) Fibonacci numbers
Sum that sub-sequence together, and use that amount of leading spaces instead in the output

For example, for the output above, the input would have been:
class Kls
  def method
    t = Time.now
    if t.hour >= 12
      puts "It's afternoon"
      if t.hour == 18
        puts "It's time for your meal of:"
        %w(bread sausage brocolli milk).each do |food|
          "Some #{food}"
        end
      end
    else
      puts "It's not afternoon"
    end
  end
end

If we take a look at the line containing "Some #{food}":
In the input it has 10 amount of leading spaces, so n will be 10/2 = 5. The first [0,5] Fibonacci numbers are: [0,1,1,2,3,5]. When we take the sum of that list (0+1+1+2+3+5) the new amount of leading spaces in the output would be 12.
The amount of indented spaces in the output for every 2 indented spaces in the input will be [0, 1, 2, 4, 7, 12, 20, 33, 54, 88, ...] A000071 on oeis.org (except for the first 0).
Challenge rules:

The space-indentation of the input is guaranteed to be multiples of 2 ([0,2,4,6,8,...])
The input is guaranteed to not contain more than 1 consecutive space elsewhere (except for the leading indentation of course)
Use whatever language you like
Please include a link to an online interpreter
Input should be a multi-line string (so no, string-lists/arrays aren't allowed)
Output should also be a multi-line string (either printed or returned as string)
Your method should work for deeper-indented Fibonacci indented multi-line strings than the example
This is code-golf, so try to do it in the fewest bytes possible.

Additional test cases:
Input:
this
  is
    one
      of
        the
          tests
            !

Output:
this
 is
  one
    of
       the
            tests
                    !

Input:
      And
  how
               about
        this ?

Output:
    And
 how
                                 about
       this ?

Input:
                    20 spaces?

Output:
                                                                                20 spaces?

05AB1E (legacy), 22 21 bytes

|εDgsðÛ©g-;LÅfOð*®J}»

Try it online.

21 bytes alternative using the formula \$Fib(\frac{n}{2}+2)-1\$ instead of \$\sum_{i=1}^{i=\frac{n}{2}}{Fib(i)}\$ :
(Credit to @JonathanAllan's Jelly answer for this formula.)

|εDgsðÛ©g-;ÌÅf<ð*®J}»

Try it online.

Explanation:

|                        # Take the input split by newlines
 ε                  }    # Map each line to:
  Dg                     #  Duplicate the line and take its length
    s                    #  Swap so the duplicated line is at the top of the stack again
     ðÛ                  #  Remove all leading spaces
       ©                 #  Store the result in the register (without popping)
        g                #  Take its length as well
         -               #  Subtract both lengths from each other
          ;              #  Halve it, because they are multiples of 2 indented spaces
           L             #  Create a list in the range [1, n]
            Åf           #  Get the i'th Fibonacci number for each
              O          #  And sum them together
               ð*        #  Have that many space characters
                 ®J      #  And join them with the saved string from the register
                    »    # And finally print the mapped list with new-lines


Find a binary needle in a decimal haystack The challenge

You're given:

a non-empty, unsorted list h of positive integers (the haystack)
a positive integer n (the needle)

Your task is to return the list of all unique decimal concatenations of permutations of h whose binary representation contains the binary representation of n.

Examples

h = [ 1, 2, 3 ]
n = 65

There's only one matching concatenation, so the expected output is [321].
h = [ 1, 2, 3 ]
n = 7

This time, there are three concatenations which contain the binary pattern 111. The expected output is [123, 231, 312].
h = [ 12, 3 ]
n = 7

Only two permutations are available and both are matching. The expected output is [123, 312].
h = [ 1, 2, 2 ]
n = 15

The only matching concatenation is 122 (1111010 in binary, which contains 1111), so the expected output is [122]. Note that two permutations actually lead to 122 but you are not allowed to output [122, 122].

Clarifications and rules

You may take the needle as an integer (65), a string representing a decimal value ("65") or a string representing a binary value ("1000001").
You may take the haystack as a native array/object/set of integers ([11,12,13]), a native array/object/set of strings representing decimal values (["11","12","13"]), or a delimited string of decimal values ("11 12 13" or "11,12,13"). You may also opt for a variant using arrays of digits (like [[1,1],[1,2],[1,3]]).
The output must follow one of the formats described above for the haystack, but not necessarily the same one.
You're not supposed to handle haystacks whose highest decimal concatenation is greater than the highest representable unsigned integer in your language.
Apart from that, your code should theoretically support any input -- assuming it's given enough time and memory.
This is SPARTA! code-golf, so the shortest answer in bytes win!

Test cases

Haystack             | Needle   | Output
---------------------+----------+-----------------------------------
[ 1, 2, 3 ]          | 65       | [ 321 ]
[ 1, 2, 3 ]          | 7        | [ 123, 231, 312 ]
[ 12, 3 ]            | 7        | [ 123, 312 ]
[ 1, 2, 2 ]          | 15       | [ 122 ]
[ 1, 2 ]             | 7        | []
[ 12, 34, 56 ]       | 21       | [ 125634, 341256, 345612, 563412 ]
[ 1, 2, 3, 4, 5 ]    | 511      | [ 53241 ]
[ 1, 3, 5, 7, 9 ]    | 593      | [ 37519, 51793, 75913, 75931 ]
[ 11, 12, 13, 14 ]   | 12141311 | [ 12141311 ]
[ 1, 2, 1, 2, 1, 2 ] | 1015     | [ 221112 ]

05AB1E, 10 8 bytes

Takes the needle in binary to save 1 byte.

-2 bytes thanks to Emigna

œJÙʒbŒIå

Try it online!

œJÙʒbŒIå   Arguments: a, n
œJÙ        Get all unique permutations of a
   ʒ       Filter: Keep if following code returns true
    b      Convert to binary
     Œ     Get all substrings
      Iå   Check if substrings contain n
           Implicit output of filtered list


Save money with price rounding In Canada, the penny is no longer circulated.  Cash payments are rounded to the nearest 5 cents.

Money can be saved by splitting purchases.  For example, two $1.02 items cost $2.04 which rounds up to $2.05, but when buying the items in separate purchases, each price rounds to $1.00 for a total of $2.00.  However, when buying two items at $1.03 each, it is better to buy them in a single purchase.

Another way to save money is using a credit card when rounding is unfavourable, because credit payments are not rounded.  If we want two $1.04 items, the total price will round up to $2.10 regardless of how we split the purchases.  Therefore, we should pay for these items with a credit card.

Write a function or program which accepts a list of prices of items as integers in cents and outputs the lowest possible total price (in cents) for those items which can be achieved through a sequence of purchases, each either by cash or by credit.

Shortest code wins.

Test cases

[] : 0
[48] : 48
[92, 20] : 110
[47, 56, 45] : 145
[55, 6, 98, 69] : 225
[6, 39, 85, 84, 7] : 218
[95, 14, 28, 49, 41, 39] : 263
[92, 6, 28, 30, 39, 93, 53] : 335
[83, 33, 62, 12, 34, 29, 18, 12] : 273
[23, 46, 54, 69, 64, 73, 58, 92, 26] : 495
[19, 56, 84, 23, 20, 53, 96, 92, 91, 58] : 583
[3, 3, 19, 56, 3, 84, 3, 23, 20, 53, 96, 92, 91, 58, 3, 3] : 598
[2, 3, 4, 4, 4, 4, 4] : 19

Ruby, 119 105 characters (93 body)

def f s
a,b,c,d=(1..4).map{|i|s.count{|x|x%5==i}}
s.reduce(0,:+)-a-(c-m=c>d ?d:c)/2-2*(b+m+(d-m)/3)
end

Two characters may be saved if the algorithm is allowed to crash when fed an empty shopping list.


To count the sum of all Unicode characters of a given input under an interesting constraint Program: To count the sum of all Unicode characters of a given input.
(No need to display the output. The final answer can be calculated in any base no need to convert back to hexadecimal.)
Test case : XyZ= 0058+0079+005A=012B
Condition: If the program is inputted, then its output must be an integral multiple of 1729 (hex 06C1). (Sum of all characters (Unicode) in the code must be equal to an integral multiple of 1729.)
Winning criterion: code golf.

Sandbox

Haskell, 20 18 bytes
Sheer luck!

sum.fmap(fromEnum)

Try it online!


Judge Some Titrations In chemistry class, we were learning about titrations, and attempting one as a lab. We were using phenolphthalein as the indicator for the titration, so on top of grading the lab normally, my teacher held a little contest to see who had the lightest shade of pink, and thus the most accurate transition.
Your task is to write a program that acts like the teacher and judges the titrations.
Specs
As input, you take a list of RGB triples in any sane format representing the titration of each student. ex: ["D966FF", "ECB3FF", "AC00E6"]. You will be guaranteed that if converted to HSL, the hue is 285 and the saturation is 100.
The conversion for RGB to HSL lightness is the average of the max and min of the normalized RGB components (*100 for a percentage).
Now the teacher is a human being and therefore cannot measure the lightness of the solution perfectly, so before you do any of the things described below, randomly change the lightness value of each of the titrations by ±3, uniformly distributed.
If a titration has a lightness value greater than 94, it is too light to  visibly see that all the acid has neutralized. Therefore, the first output is a list, sorted in descending order, of all the titrations whose RGB triples, when converted to HSL, yield a lightness value less than 94. This represents the results of the contest.
The other output is a list of all the people who have failed the lab. This includes the people with the lightness values greater than 94, but also people whose lightness values are less than or equal to 65 because these people's titrations are too inaccurate.
This is code-golf, so shortest code in bytes win.
Test Cases
These test cases all assume that the error is always 0 for ease in checking if your program is correct. The results from your program should be different each time you run it.
["D966FF", "ECB3FF", "AC00E6"] -> ["ECB3FF", "D966FF", "AC00E6"], ["AC00E6"]
["EDB8FF", "D761FF", "9100C2", "FBEFFF"] -> ["EDB8FF", "D761FF", "9100C2"], ["FBEFFF", "9100C2"]
["F5D6FF"] -> ["F5D6FF"], []

Pyth, 35 34 bytes
Input already converted to decimal.
L+O32+eSbhSbf<yTJ495Qf|gyTJ<yT347Q

Test suite.
Previous 35-byte version:
Input already converted to decimal.
L+O32+eSbhSbf<yT495Qf|gyT495<yT347Q

Test suite.
Verify that the third testcase is not the same for each run.
Sample input/output:
input:
[[217, 102, 255], [236, 179, 255], [172, 0, 230]]
output:
[[217, 102, 255], [236, 179, 255], [172, 0, 230]]
[[172, 0, 230]]

Explanation
(max/255 + min/255)/2 + random[-0.03 .. 0.03] >= 0.94
(max/255 + min/255) + random[-0.06 .. 0.06] >= 1.88
max + min + random[-15 .. 15] >= 479.4
max + min + random[0 .. 31] >= 494.4
max + min + random[0 .. 31] >= 495

(max/255 + min/255)/2 + random[-0.03 .. 0.03] <= 0.65
(max/255 + min/255) + random[-0.06 .. 0.06] <= 1.30
max + min + random[-15 .. 15] <= 331.5
max + min + random[0 .. 31] <= 346.4
max + min + random[0 .. 31] < 347

L+O32+eSbhSbf<yT495Qf|gyT495<yT347Q
                                     @memoized
L                                    def y(b):
 +O32                                    return random(range(32)) +
     +eSb                                b.sort[-1] +
         hSb                             b.sort[0]
            f      Q                 filter for elements in Q as T:
             <yT495                      y(T) < 495
                                     (implicitly printed)
                    f             Q  filter for elements in Q as T
                     |gyT495             y(T) >= 495 or
                            <yT347       y(T) < 347
                                     (implicitly printed)

Before you complain that it calls random three times, hence having inconsistent outputs from the function, note that the function is memoized.
Before you complain that different students with the same colour always produce the same outcome, note that the question never said that the random generator must be independent. It must only be uniform.


Inverse regex of compound interest Koronkorko is the Finnish word for compound interest. We don't want compound interest in our strings, so let's find the shortest possible regular expression to exclude it.

Given a string consisting only of the uppercase alphabetic characters A-Z, determine the shortest possible regular expression that matches the string if it does not contain the substring KORONKORKO. Any string that contains KORONKORKO as a substring should not be matched by the regex.

Only the characters A-Z, [, ], -, ^, , ?, *, +, |, (, and ) should be used in the expression.

I think this can be done with 118 characters in the expression. Can you make it shorter?

Note: This challenge is from Ohjelmointiputka (in Finnish).

204 characters

(K((O(R(O(NKORO)*(NK(O(RK)?)?)?)?)?)?K)*(O(R(O(NKORO)*(N(K(O(RK?[^KO]|[^KR])|[^KO])|[^K])|[^KN])|[^KO])|[^KR])|[^KO])|[^K])*(K((O(R(O(NKORO)*(NK(O(RK)?)?)?)?)?)?K)*(O(R(O(NKORO)*(N(K(O(RK?)?)?)?)?)?)?)?)?

Generated by turning .*KORONKORKO.* into a finite state machine, inverting the finite state machine, and turning it back into a regex.


HelolW rdlo (A threading challenge) I have a challenge for you:

Print "Hello World" using any language.
Each character must be printed from its own, unique thread

That's it. Obviously, as there's no guarantee that the threads will operate in the order you start them, you have to make your program thread safe to ensure the output is printed in the right order.

And, because this is code golf, the shortest program wins.

Update:

The winner is Marinus' APL entry, at 34 characters. It also wins the prize for the least readable entry.

C, 61 62 chars

i;main(){write(1,"Hello World\n"+i++,1);i>13||fork()||main();}

The pthread library functions all have loooooong names, so instead I fired up an entire separate process for each character. fork() is so much shorter.

It was necessary to use write() instead of putchar() because the stdio buffering functions are not thread-safe.

Edited: Back up to 62 chars. In my zeal, dropping down to 61 chars also dropped the thread-safety.


The eruption of Eyjafjallajökull? Year of 2010, an Icelandic Vulcano, concisely named Eyjafjallajökull  erupted, resulting in my long-planned flight being canceled.

In case this ever happens again, I would really like to know in advance, so please help me build a simple visual alert system !

Input

Take the Icelandic Meteorological Office volcanic activity alert code, as an input (string):

GREEN - Volcano is in normal, non-eruptive state.

YELLOW - Volcano is experiencing signs of elevated unrest above known background levels.

ORANGE - Volcano is exhibiting heightened unrest with increased likelihood of eruption.

RED - Eruption is forecasted to be imminent with significant emission of ash into the atmosphere likely.

Output

The graphic (ASCII art) alert, illustrating the state of Eyjafjallajökull.

GREEN (Eyjafjallajökull is resting)

      al   la
     j       j
  jaf         öku
 y               l
E                 l
-------------------

YELLOW (some smoke appears !)

       ~   ~
         ~
      al   la
     j       j
  jaf         öku
 y               l
E                 l
-------------------

ORANGE (more smoke !)

      ~  ~  ~
       ~   ~
         ~
      al   la
     j       j
  jaf         öku
 y               l
E                 l
-------------------

RED (even more smoke and some ash, too !)

   `~ ~ ~ ~ ~ ~`
    ` ~  ~  ~ `
     ` ~   ~ `
       ` ~ `
      al   la
     j       j
  jaf         öku
 y               l
E                 l
-------------------

Rules

You may output to the screen (stdout), or return a string
This is code-golf ! The shortest answer (in bytes), wins
Feel free to replace ö with o
Trailing spaces are allowed, but not required
At most one trailing newline is allowed
At most 4 leading newlines are allowed (in place of smoke)

Batch, 284 bytes

@set e=echo
@%e%off
set s=
set t=
goto %1
:RED
set t= `
%e%   `~ ~ ~ ~ ~ ~`
:ORANGE
%e%   %t%~  ~  ~%t%
:YELLOW
%e%    %t%~   ~%t%
%e%%s%%t%~%t%
:GREEN
%e%%s%al   la
%e%     j%s% j
%e%  jaf %s%  oku
%e% y %s%%s%  l
%e%E%s%%s%%s%l
%e%--------------------

Note: Lines 1 and 7 have one trailing space, line 3 has six and line 4 has three.


Which Go rank is higher? Players of the traditional board game Go measure their skill in a system of ranks:

Players new to the game are ranked 30th kyū (written 30k) and progress counting down to 1st kyū (written 1k). These are considered the student ranks.
A player may promote from 1st kyū to 1st dan rank (written 1d), and then progress counting up to 7th dan rank (written 7d). These are the master ranks.
Exceptionally skilled players past 7d may promote to the 1st professional dan rank 1p, and progress counting up to 9th professional dan rank (written 9p). This is the highest rank.

In short: ranks are ordered 30k < 29k < ··· < 1k < 1d < 2d < ··· < 7d < 1p < 2p < ··· < 9p.

Task

Given two strings among {30k, …, 1k, 1d, …, 7d, 1p, …, 9p} as input, output the higher rank of the two. (If they are equal, simply output either input.)

(As usual, I/O is flexible — your answer may be a function or a full program, reading input in any reasonable fashion and producing output in any reasonable fashion.)

This is code-golf: the objective is to minimize your code's byte count.

Test cases

(Format: input1 input2   output.)

29k 9k    9k
21k 27k   21k
6d 1p     1p
5d 17k    5d
1k 1d     1d
1d 1d     1d
1d 2d     2d
9p 1d     9p
2d 30k    2d
1p 1k     1p
1d 1p     1p
1p 2d     1p
7p 8p     8p
30k 30k   30k

JavaScript (ES7), 58 bytes

Takes the two strings in currying syntax (a)(b).

a=>b=>(g=s=>parseInt(s)*'_dp'.search(s[1])**3)(a)>g(b)?a:b

Try it online!

How?

The helper function g() translate the input string s into a score.

1) We look for s[1] into the string "_dp". This gives:

1 for a dan rank "xd"
2 for a professional dan rank "xp"
-1 for a kyū rank "xk" or "xxk" because s[1] is either "k" or a digit

2) We cube this result, which leaves 1 and -1 unchanged but gives 8 for a professional dan rank.

3) We multiply by the decimal part of the rank.


Find the sortable years The year 2013 had an interesting property: the digits are consecutive when sorted (0123). Let's call this type of number a sortable number: a non-negative integer whose base-10 digits are consecutive after sorting. Unfortunately, this won't happen again until 2031, and after that, not until 2103. Your challenge is to write a program or function that, when given a non-negative integer through any standard method, outputs or returns the next sortable number.

Rules

Input and output must be in base 10.
Output may be in any reasonable format (number literal, string literal, single-item array, ...).
Your code must produce the proper output within 1 minute for all inputs up to 98764.

Test cases

    0 -> 1
    1 -> 2
    9 -> 10
   10 -> 12
   11 -> 12
   99 -> 102
  233 -> 234
  234 -> 243
  243 -> 312
 2016 -> 2031
 2031 -> 2103
 2103 -> 2130
 2130 -> 2134
 2134 -> 2143
 9876 -> 10234
98764 -> 98765

The sortable numbers form A215014. A list of all entries up to 98765 can be found here.

Scoring

This is code-golf, so the shortest code in bytes wins.

Python 2, 61 bytes

f=lambda n:-~n*(`sorted(`n+1`)`[2::5]in'0123456789')or f(n+1)

Try it online!


Codegolf: Quine and Antiquine This challenge is similar to Can you Meta Quine?

A quine is a program that produces itself on STDOUT. This challenge is to produce a program A which when run produces a program B on STDOUT. Program B when run produces program A on STDOUT. Programs A and B must be written in (and run in) the same language. The linked question constrained A != B. That looked too easy. So for this question, we insist A and B are antiquines, using the following rules:

Programs A and B may not use any of the same characters, save for whitespace and statement separators, and punctuation characters.
Programs A and B must each contain at least one character that is neither whitespace nor a statement separator, nor a punctuation character.
For the purpose of rules 1 and 2, the term 'whitespace' excludes any symbol or sequence of symbols which itself is a statement, operator or symbol that is interpreted (as opposed to a separator). Therefore in the Whitespace language, there is no whitespace.
A statement separator is a syntactic element conventionally used within the language to separate statements. This would include the newline in python, or the semicolon in Java, perl or C.
A punctuation character is an ASCII character which is neither whitespace nor in the POSIX word character class (i.e. an underscore is not punctuation for this purpose) - i.e ispunct() would return true, and it's not _.
Program A when run must produce a program (Program B) on its STDOUT, which when run in turn produces Program A.
Programs A and B must be in the same programming language.
The programming language used must actually be a programming language. Unless you make a good case otherwise, I'll suggest it must be Turing complete.
At least one of A and B must execute at least one statement within the language.

This is code golf, so the shortest answer wins, the score being the length of program A in bytes (i.e. the length of program B is not relevant).


Force an Average on an Image Write a program that takes in a standard truecolor image and a single 24-bit RGB color (three numbers from 0 to 255). Modify the input image (or output a new image with the same dimensions) such that its average color is exactly the single color that was input. You may modify the pixels in the input image in any way you like to achieve this, but the goal is to make the color changes as visually unnoticeable as possible.
The average color of an RGB image is really a set of three arithmetic means, one for each color channel. The average red value is the sum of the red values across all the pixels in the image divided by the total number of pixels (the image area), rounded down to the nearest integer. The green and blue averages are calculated in the same way.
This Python 2 (with PIL) script can compute the average color of most image file formats:
from PIL import Image
print 'Enter image file'
im = Image.open(raw_input()).convert('RGB')
pixels = im.load()
avg = [0, 0, 0]
for x in range(im.size[0]):
    for y in range(im.size[1]):
        for i in range(3):
            avg[i] += pixels[x, y][i]
print 'The average color is', tuple(c // (im.size[0] * im.size[1]) for c in avg)

(There are similar average color programs here, but they don't necessarily do the exact same calculation.)
The main requirement for your program is that for any input image, its corresponding output's average color must exactly match the color that was input - as judged by the Python snippet or some equivalent code. The output image must also have the exact same dimensions as the input image.
So you could technically submit a program that simply colors the entire input the specified average color (because the average would always be that color), but this is a popularity contest - the submission with the highest number of votes will win, and such a trivial submission will not get you many upvotes. Novel ideas like taking advantage of quirks in human vision, or shrinking the image down and drawing a colored border around it will (hopefully) get you votes.
Note that certain combinations of average colors and images necessitate extremely noticeable color changes. For example, if the average color to match were black (0, 0, 0), any input image would need to be made completely black because if any pixels had non-zero values, they would make the average non-zero as well (barring round-off errors). Keep such limitations in mind when voting.
Test Images
Some images and their default average colors to play around with. Click for full sizes.
A. average (127, 127, 127)
 From fejesjoco's Images with all colors answer. Found original on his blog.
B. average (62, 71, 73)
 Yokohama. Provided by Geobits.
C. average (115, 112, 111)
 Tokyo. Provided by Geobits.
D. average (154, 151, 154)
 Escher's Waterfall. Original.
E. average (105, 103, 102)
 Mount Shasta. Provided by me.
F. average (75, 91, 110)
 The Starry Night
Notes

The exact input and output formats and image file types your program uses does not matter much. Just make sure it is clear how to use your program.
It is probably a good idea (but not technically a requirement) that if an image already has the goal average color, it should be output as is.
Please post test images with the average color input as either (150, 100, 100) or (75, 91, 110), so voters can see the same inputs across different solutions. (Posting more examples than this is fine, even encouraged.)

Python 2 + PIL, simple colour scaling

from PIL import Image
import math

INFILE = "street.jpg"
OUTFILE = "output.png"
AVERAGE = (150, 100, 100)

im = Image.open(INFILE)
im = im.convert("RGB")
width, height = prev_size = im.size
pixels = {(x, y): list(im.getpixel((x, y)))
          for x in range(width) for y in range(height)}

def get_avg():
    total_rgb = [0, 0, 0]

    for x in range(width):
        for y in range(height):
            for i in range(3):
                total_rgb[i] += int(pixels[x, y][i])

    return [float(x)/(width*height) for x in total_rgb]

curr_avg = get_avg()

while tuple(int(x) for x in curr_avg) != AVERAGE:
    print curr_avg
    non_capped = [0, 0, 0]
    total_rgb = [0, 0, 0]

    for x in range(width):
        for y in range(height):
            for i in range(3):
                if curr_avg[i] < AVERAGE[i] and pixels[x, y][i] < 255:
                    non_capped[i] += 1
                    total_rgb[i] += int(pixels[x, y][i])

                elif curr_avg[i] > AVERAGE[i] and pixels[x, y][i] > 0:
                    non_capped[i] += 1
                    total_rgb[i] += int(pixels[x, y][i])

    ratios = [1 if z == 0 else
              x/(y/float(z))
              for x,y,z in zip(AVERAGE, total_rgb, non_capped)]

    for x in range(width):
        for y in range(height):
            col = []

            for i in range(3):
                new_col = (pixels[x, y][i] + 0.01) * ratios[i]
                col.append(min(255, max(0, new_col)))

            pixels[x, y] = tuple(col)

    curr_avg = get_avg()

print curr_avg

for pixel in pixels:
    im.putpixel(pixel, tuple(int(x) for x in pixels[pixel]))

im.save(OUTFILE)

Here's a naïve approach which should serve as a good baseline. At each iteration, we compare our current average with the desired average, and scale the RGB of each pixel by the according ratio. We have to be a bit careful though, for two reasons:

Scaling 0 still results in 0, so before we scale we add something small (here 0.01)
RGB values are between 0 and 255, so we need to adjust the ratio accordingly to make up for the fact that scaling capped pixels doesn't do anything.

The images save as PNG because saving as JPG seems to mess up the colour averages.

Sample output

(40, 40, 40)

(150, 100, 100)

(75, 91, 110), Starry Night palette


HyperNeutrino is back! Today, @HyperNeutrino succeeded merging his two accounts, and finally got the reputation he lost back. Now, it's time to celebrate! Your task is to output this exact text:

                /\
               /  \
              /    \
             /      \
            /        \
           /          \
          /            \
         /              \
        /                \
       /                  \
      /                    \
     /                      \
    /                        \
   /                          \
  /                            \
 /                              \
/                                \
|                                |
|                                |
|  @HyperNeutrino Welcome back!  |
|                                |
|                                |
\                                /
 \                              /
  \                            /
   \                          /
    \                        /
     \                      /
      \                    /
       \                  /
        \                /
         \              /
          \            /
           \          /
            \        /
             \      /
              \    /
               \  /
                \/

Rules:

Your program must not take input.
The output must be exactly as shown above.
Trailing and leading spaces / newlines are allowed.
Defaults Loopholes apply.
You can provide output by any standard method.
This is a code-golf celebration, hence the shortest code in each language wins! Have fun!

V, 64 bytes

i/\
\/16ñH>GMÙXppjÄXppñ5O|³² |M3lR@HyperNeutrino Welcome back!

Try it online!

Hexdump:

00000000: 692f 5c0a 5c2f 1b31 36f1 483e 474d d958  i/\.\/.16.H>GM.X
00000010: 7070 6ac4 5870 70f1 354f 7cb3 b220 7c1b  ppj.Xpp.5O|.. |.
00000020: 4d33 6c52 4048 7970 6572 4e65 7574 7269  M3lR@HyperNeutri
00000030: 6e6f 2057 656c 636f 6d65 2062 6163 6b21  no Welcome back!

Explanation:

i                             " Insert:
 /\<cr>\/                     "   '/\<newline>\/'
         <esc>                " Return to normal mode
16ñ             ñ             " 16 times:
   H                          "   Move to the beginning of the buffer
    >G                        "   Indent every line
      M                       "   Move to the middle of the buffer (the last downward facing part)
       Ù                      "   Duplicate this line downwards
        X                     "   Delete one of the leading spaces
         pp                   "   And paste it between the slashes twice
           j                  "   Move down a line (the first upward facing part)
            Ä                 "   Duplicate this line upwards
             X                "   Delete one of the leading spaces
              pp              "   And paste it between the slashes twice
5O                            " On the five lines above us, insert:
  |³² |                       "   A bar followed by 32 spaces, followed by a bar
       <esc>                  " Return to normal mode
            M                 " Move to the middle line of the buffer
             3l               " Move 3 characters to the right
               R              " And write the following over the existing text:
@HyperNeutrino Welcome back!  "   Welcome back!


Dames, do some math! The order of operations, PEMDAS, is a basic rule in mathematics telling us which order operations should be performed:

"Parentheses, Exponents, Multiplication and Division, and Addition and Subtraction"

The problem is, PEMDAS is not very versatile! What if you wanted to do it in another order? We won't mess with the parentheses, so we keep them where they are (first).

Create a program that takes two arguments:

A string, telling which order the operations should follow. Some examples are "DAMES", "SAD, ME", "ME SAD", "MEADS". Yes, spaces and commas are OK, as it makes the order easier to remember.

Following suggestions in chat: Supporting spaces and commas is now optional.
If one of the letters is missing, or if there are additional letters that shouldn't be there, you can consider the input invalid and treat it however you like.

A string, or an expression containing the expression that should be evaluated.

Return the result of the expression as either a decimal number, or an integer. If the answer is not an integer, it has to be returned as a decimal number.

Rules:

It's OK to combine the two input arguments into one, if that's easier in your language.
It doesn't have to be a string, but it has to have letters. You can't substitute Addition with 1, Division with 2, etc.
You can choose which input is first.
The expression is evaluated right to left left to right. (Change of rule. Any submissions poster the first 12 hours that have this the other way around are accepted).
The operations use the symbols: ( ) ^ * / + -. For instance, you can't use ¤ instead of + for addition.
Spaces in the input expression is not valid as input
Unary +/- is not valid as input if it directly follows + or -. Consider 3+-2 as invalid input. It can be treated however you like (doesn't have to produce an error). If + or - follows any other operator than plus or minus, it's treated the usual way: 3*-3 = -9, sin(-2)=-0.909
The program must strictly follow the letters, so "EMDAS", 1-3+4 => -6, and "EMDSA", 1-3+4 => 2.

Examples:

Input:   "EMDAS", "3+6*2/4-1"   // -> 3+12/4-1 -> 3+3-1 -> 6-1 -> 5
Output:  5

Input:   "DAMES", "3+6*2/4-1"   // -> 3+6*0.5-1 -> 9*0.5-1 -> 4.5-1 -> 3.5
Output:  3.5

Input:   "SAD, ME", "3+6*2/4-1"  // -> 3+6*2/3 -> 9*2/3 -> 9*0.66667 -> 6
Output:  6

Input:   "ME ADS", "3+5^4/2-3*2 // -> 3+5^4/2-6 -> 3+625/2-6 -> 628/2-6 -> 314-6 -> 308
Output:  308

Input:   "AM EDS", "4*3-sin(0.5^2)*3+1" // -> 4*3-sin(0.5^2)*4 -> 12-sin(0.5^2)*4 -> 4*3-(4*sin(0.5^2)) -> 12-(4*sin(0.5^2)) -> 12-(4*sin(0.25)) -> 12-(4*0.24740) -> 12-0.98961 -> 11.01038
Output:  11.01038

Input:   "DAMES", "4-5-6"   // -> (4-5)-6 -> = -7
Output:  -7                  // NOT: -> 4-(5-6) -> 4-(-1) -> 5

Note, the parentheses where added to show that the multiplication 4*sin(0.5^2) is evaluated before the exponentiation.

This is code golf, so the shortest code in bytes win.


Fixing a Froot Loop Necklace Suppose you are stringing a strand of Froot Loops for a necklace, bracelet, shoelace, or whatever. There are 6 loop colors: red, orange, yellow, green, blue, and purple. You want your strand to start with red at the very left and cycle in rainbow order going right, ending with purple. That is, you want to make it so your strand could be represented by the string roygbp repeated some number of times (possibly 0).

The problem is, you've already strung your loops, and not in any particular order. Which loops should you eat and not eat so that you can maximize the number of correct rainbow cycles going from left to right, with the very first loop red and the very last loop purple?

Write a program or function that takes in an arbitrary string of the characters roygbp and prints or returns a string of the same length with e in the place of loops to eat and n in the place of loops to not eat.

For example, if your Froot Loop strand looked like

the input would be

gorboypbgbopyroybbbogppbporyoygbpr

and going from left to right we can find 3 complete roygbp rainbow sequences, but some of the loops need to be eaten away. Thus the output would be

eenenneennenennneeeeneennenennnnne

resulting in a perfect 3 cycle strand:

If there are no complete rainbow cycles in the input then the output would be all e's and the strand ends up loopless. e.g. the input proygb has output eeeeee. Conversely, proygbp has output ennnnnn.

You can assume all input strands have at least one loop.

The shortest code in bytes wins.

Hexagony, 920 722 271 bytes

Six different types of fruit loops, you say? That is what Hexagony was made for.

){r''o{{y\p''b{{g''<.{</"&~"&~"&<_.>/{.\.....~..&.>}<.._...=.>\<=..}.|>'%<}|\.._\..>....\.}.><.|\{{*<.>,<.>/.\}/.>...\'/../==.|....|./".<_>){{<\....._>\'=.|.....>{>)<._\....<..\..=.._/}\~><.|.....>e''\.<.}\{{\|./<../e;*\.@=_.~><.>{}<><;.(~.__..>\._..>'"n{{<>{<...="<.>../

Okay, it wasn't. Oh god, what did I do to myself...

This code is now a hexagon of side length 10 (it started out at 19). It could probably be golfed some more, maybe even to size 9, but I think my job is done here... For reference, there are 175 actual commands in the source, many of which are potentially unnecessary mirrors (or were added to cancel out a command from a crossing path).

Despite the apparent linearity, the code is actually two-dimensional: Hexagony will rearrange it into a regular hexagon (which is also valid code, but all whitespace is optional in Hexagony). Here is the unfolded code in all its... well I don't want to say "beauty":

          ) { r ' ' o { { y \
         p ' ' b { { g ' ' < .
        { < / " & ~ " & ~ " & <
       _ . > / { . \ . . . . . ~
      . . & . > } < . . _ . . . =
     . > \ < = . . } . | > ' % < }
    | \ . . _ \ . . > . . . . \ . }
   . > < . | \ { { * < . > , < . > /
  . \ } / . > . . . \ ' / . . / = = .
 | . . . . | . / " . < _ > ) { { < \ .
  . . . . _ > \ ' = . | . . . . . > {
   > ) < . _ \ . . . . < . . \ . . =
    . . _ / } \ ~ > < . | . . . . .
     > e ' ' \ . < . } \ { { \ | .
      / < . . / e ; * \ . @ = _ .
       ~ > < . > { } < > < ; . (
        ~ . _ _ . . > \ . _ . .
         > ' " n { { < > { < .
          . . = " < . > . . /

Explanation

I won't even try and begin explaining all the convoluted execution paths in this golfed version, but the algorithm and overall control flow are identical to this ungolfed version which might be easier to study for the really curious after I've explained the algorithm:

                 ) { r ' ' o { { \ / ' ' p { . . .
                . . . . . . . . y . b . . . . . . .
               . . . . . . . . ' . . { . . . . . . .
              . . . . . . . . \ ' g { / . . . . . . .
             . . . . . . . . . . . . . . . . . . . . .
            . . . . . . . . . . . . . . . . . . . . . .
           . . . . . . . . > . . . . < . . . . . . . . .
          . . . . . . . . . . . . . . > . . ) < . . . . .
         . . . . . . . . . . / = { { < . . . . ( . . . . .
        . . . . . . . . . . . ; . . . > . . . . . . . . . <
       . . . . . . . . . . . . > < . / e ; * \ . . . . . . .
      . . . . . . . . . . . . @ . } . > { } < . . | . . . . .
     . . . . . / } \ . . . . . . . > < . . . > { < . . . . . .
    . . . . . . > < . . . . . . . . . . . . . . . | . . . . . .
   . . . . . . . . _ . . > . . \ \ " ' / . . . . . . . . . . . .
  . . . . . . \ { { \ . . . > < . . > . . . . \ . . . . . . . . .
 . < . . . . . . . * . . . { . > { } n = { { < . . . / { . \ . . |
  . > { { ) < . . ' . . . { . \ ' < . . . . . _ . . . > } < . . .
   | . . . . > , < . . . e . . . . . . . . . . . . . = . . } . .
    . . . . . . . > ' % < . . . . . . . . . . . . . & . . . | .
     . . . . _ . . } . . > } } = ~ & " ~ & " ~ & " < . . . . .
      . . . \ . . < . . . . . . . . . . . . . . . . } . . . .
       . \ . . . . . . . . . . . . . . . . . . . . . . . < .
        . . . . | . . . . . . . . . . . . . . . . . . = . .
         . . . . . . \ . . . . . . . . . . . . . . . . / .
          . . . . . . > . . . . . . . . . . . . . . . . <
           . . . . . . . . . . . . . . . . . . . . . . .
            _ . . . . . . . . . . . . . . . . . . . . .
             . . . . . . . . . . . . . . . . . . . . .
              . . . . . . . . . . . . . . . . . . . .
               . . . . . . . . . . . . . . . . . . .
                . . . . . . . . . . . . . . . . . .
                 . . . . . . . . . . . . . . . . .

Honestly, in the first paragraph I was only half joking. The fact that we're dealing with a cycle of six elements was actually a great help. The memory model of Hexagony is an infinite hexagonal grid where each edge of the grid contains a signed arbitrary-precision integer, initialised to zero.

Here is a diagram of the layout of the memory I've used in this program:

The long straight bit on the left is used as a 0-terminated string a of arbitrary size which is associated with the letter r. The dashed lines on the other letters represent the same kind of structure, each one rotated by 60 degrees. Initially, the memory pointer points at the edge labelled 1, facing north.

The first, linear bit of the code sets the inner "star" of edges to the letters roygbp as well as setting the initial edge to 1, such that we know where the cycle ends/begins (between p and r):

){r''o{{y''g{{b''p{

After this, we're back on the edge labelled 1.

Now the general idea of the algorithm is this:

For each letter in the cycle, keep reading letters from STDIN and, if they are different from the current letter, append them to the string associated with that letter.
When we read the letter we're currently looking for, we store an e in the edge labelled ?, because as long as the cycle is not complete, we have to assume that we'll have to eat this character as well. Afterwards, we'll move around the ring to the next character in the cycle.
There are two ways this process can be interrupted:

Either we've completed cycle. In this case, we make another quick round through the cycle, replacing all those es in the ? edges with ns, because now we want that cycle to remain on the necklace. Then we move on to printing code.
Or we hit EOF (which we recognise as a negative character code). In this case, we write a negative value into the ? edge of the current character (so that we can easily distinguish it from both e and n). Then we search for the 1 edge (to skip the remainder of a potentially incomplete cycle) before moving to printing code as well.

The printing code goes through the cycle again: for each character in the cycle it clears the stored string while printing an e for each character. Then it moves to the ? edge associated with the character. If it's negative, we simply terminate the program. If it's positive, we simply print it and move on to the next character. Once we complete the cycle we go back to step 2.

Another thing that might be interesting is how I've implemented the arbitrary-size strings (because it's the first time I've used unbounded memory in Hexagony).

Imagine we're at some point where we're still reading characters for r (so we can use the diagram as is) and a[0] and a1 have already been filled with characters (everything north-west of them is still zero). E.g. maybe we've just read the first two characters og of the input into those edges and are now reading a y.

The new character is read into the in edge. We use the ? edge to check whether this character is equal to r. (There's a nifty trick here: Hexagony can only distinguish between positive and non-positive easily, so checking for equality via subtraction is annoying and requires at least two branches. But all the letters are less than a factor of 2 from each other, so we can compare the values by taking the modulo, which will only give zero if they are equal.)

Because y is different from r, we move the (unlabelled) edge left of in and copy the y there. We now move further around the hexagon, copying the character one edge further each time, until we have the y on the edge opposite of in. But now there is already a character in a[0] which we don't want to overwrite. Instead, we "drag" the y around the next hexagon and check a1. But there's a character there as well, so we go another hexagon further out. Now a[2] is still zero, so we copy the y into it. The memory pointer now moves back along the string towards the inner ring. We know when we've reached the beginning of the string, because the (unlabelled) edges between the a[i] are all zero whereas ? is positive.

This will probably be a useful technique for writing non-trivial code in Hexagony in general.


Python, 53 bytes

f=lambda n,i=1:n*[f]and[i]+f(n-1,2*i)+i%2*f(n-1,i-~i)

Try it online!

The recursive function generates the sorted list as a pre-order walk down this tree (example with n=4):

      1
     / \
    2   3
   /   / \
  4   6   7
 /   /   / \
8   12  14  15

1 2 4 8 3 6 12 7 14 15

Left branches double the value, and right branches do i->i*2+1 and exist only for odd i. So, the pre-order walk for non-leaves is T(i)=[i]+T(i*2)+i%2*T(i*2+1).

The tree terminates at depth n, where n is the input. This is achieved by decrementing n with each step down and stopping when it is 0.

An alternative strategy would be to terminate on values that i exceeds 2**n, rather than tracking depth. I found this to be one byte longer:

f=lambda n,i=1:2**n/i*[f]and[i]+f(n,2*i)+i%2*f(n,i-~i)
f=lambda n,i=1:[f][i>>n:]and[i]+f(n,2*i)+i%2*f(n,i-~i)