Can the Array be Unshuffled? Background

Very skilled card handlers are capable of a technique whereby they cut a deck perfectly in half, then perfectly interleave the cards. If they start with a sorted deck and perform this technique flawlessly 52 times in a row, the deck will be restored to sorted order. Your challenge is to take a deck of cards an integer array and determine whether it can be sorted using only Faro shuffles.

Definition

Mathematically, a Faro shuffle is a permutation on 2 n elements (for any positive integer n) which takes the element in position i (1-indexed) to position 2 i (mod 2 n+1). We would also like to be able to handle odd-length lists, so in that case, just add one element to the end of the list (a Joker, if you have one handy) and Faro shuffle the new list as above, but ignore the added dummy element when checking the list's order.

Goal

Write a program or function that takes a list of integers and returns or outputs  a truthy if some number of Faro shuffles would cause that list to be sorted in nondescending order (even if that number is zero--small lists should give a truthy). Otherwise,  return or output a falsy.

Examples

[1,1,2,3,5,8,13,21]  => True
[5,1,8,1,13,2,21,3] => True
[9,36,5,34,2,10,1] => True
[1,0] => True
[0] => True
[] => True
[3,2,1] => True
[3,1,2] => False
[9,8,7,6,5,4,3,2,1,0] => True
[9,8,7,6,5,4,3,2,0,1] => False
[3,1,4,1,5,9,2,6,9] => False
[-1,-1,-1,-2] => True

Scoring

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

MATL, 41 bytes

itn2\?YNh]tnt1+:"x[]2e!PY)ttZN~)tS=At.]wx

The output is 1 or 0.

Explanation

i              % get input array
tn2\           % is size odd?
?              % if that's the case
  YNh          % concat NaN at the end
]              % end if
tn             % get size of input array
t1+:           % vector 1:n+1, where n is input size, so loop will be entered even with []
"              % for loop
  x[]2e!PY)    % delete result from previous iteration and do the shuffling
  ttZN~)       % remove NaN, if there's any
  tS=A         % check if array is sorted
  t.           % copy the result. If true, break loop
]              % end for
wx             % remove unwanted intermediate result

Example

>> matl itn2\?YNh]tnt1+:"x[]2e!PY)ttZN~)tS=At.]wx
> [1,1,2,3,5,8,13,21]
1


Generate the Rummy Sequence Your task is to take an input n and output element n of the Rummy Sequence, a sequence which I made (looking on OEIS will not help you).

Definition

Each element of the Rummy Sequence is a set of truthy or falsey values. Ex.: [true, false].

The steps to producing a member of the Rummy Sequence are quite simple:

Start out with the first index, [] (this is element 0).
Set the leftmost falsey to truthy. If there are no falseys to change, then increase the length of the list by 1 and set all members of the new list to falsey.
Repeat step 2 until reaching element n.

Example

Let's define our function as rummy(int n) (stuff in {} is a step taken to get to the answer):

>>> rummy(5)
{[]}
{[false]}
{[true]}
{[false, false]}
{[true, false]}
[true, true]

Rules

Standard loopholes apply.
Must work for inputs 0 through your language's upper numerical bound.
You may output in any way you see fit, provided that it is clear that the output is a set of truthy/falseys.

Trivia

I call this the "Rummy Sequence" because, starting at index 2, it defines the sets you would need to lay down in each round of Progressive Rummy, where falsey is a book and truthy is a run.

Test Cases

>>> rummy(0)
[]

>>> rummy(1)
[false]

>>> rummy(6)
[false, false, false]

>>> rummy(20)
[true, true, true, true, true]

>>> rummy(1000)
[true, true, true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false]

JavaScript ES6, 94 92 72 70 66 64 bytes

Saved 6 bytes thanks to Neil!

n=>[...Array(a=Math.sqrt(8*n+1)-1>>1)].map((_,l)=>l<n-a*(a+1)/2)

I don't think this can be golfed more. At least with the equations.

Explanation

They are two main equations (n is input):

(Math.sqrt(8*n+1)-1)/2

This will give the total size the output array will need to be. In my program I used >>1 instead of (...)/2 these are the same as the first bit in binary has a value of 2. Shifting it will result in in floor(.../2)

n-a*(a+1)/2

This is the amount of trues there will be. a is the result of the previous expression.

This is what the syntax does:

[...Array(n)]

This code generates an array with range [0, n) in this answer n is the first equation.

.map((_,l)=>l<n) this will loop through the above range, l is the variable containing the current item in the range. If the item is less than the amount of trues they are (determined by second equation), then it will return true, else false.


How many characters are there on the icon of a Stack Exchange site? Given the name of a Stack Exchange site which doesn't have their own design yet, decide how many ASCII characters (non-ASCII ones are counted separately) are there on their icons. Your code should distinguish these 4 cases:

1 character:

Astronomy
Beer
Freelancing
Health
History
Law
Music: Practice & Theory
Parenting
The Great Outdoors
Writers

2 characters:

3D Printing
Amateur Radio
Biblical Hermeneutics
Bitcoin
Board & Card Games
Buddhism
Chinese Language
Coffee
Community Building
Computational Science
Computer Graphics
Data Science
Earth Science
Ebooks
Economics
Emacs
Engineering
Expatriates
French Language
Gardening & Landscaping
Genealogy & Family History
German Language
Hardware Recommendations
Hinduism
Homebrewing
Islam
Italian Language
Japanese Language
Joomla
Lifehacks
Martial Arts
Mathematics Educators
Motor Vehicle Maintenance & Repair
Music Fans
Mythology
Open Data
Personal Productivity
Pets
Philosophy
Physical Fitness
Politics
Portuguese Language
Project Management
Puzzling
Quantitative Finance
Reverse Engineering
Robotics
Russian Language
Software Quality Assurance & Testing
Software Recommendations
Sound Design
Space Exploration
Spanish Language
Sports
Startups
Sustainable Living
Tridion
Vi and Vim
Video Production
Windows Phone
Woodworking
Worldbuilding

3 characters:

Cognitive Sciences
elementary OS
Ethereum
History of Science and Mathematics
Linguistics
Open Source
Programming Puzzles & Code Golf
Signal Processing
Tor

Non-ASCII:

Anime & Manga
Arduino
Aviation
Chess
CiviCRM
Poker

Excluded in this challenge for having non-ASCII characters in their names:

LEGO® Answers
Русский язык

Your code should output a consistent distinct value for each of the 4 sets. Each output (or its string representation for non-string values returned from a function) should be no more than 10 bytes, not counting the optional trailing newline.

You can create multiple pieces of code in the same language. The output of your submission is considered to be the output of each piece of code concatenated in a fixed order (so you can use Regex).

Shortest code wins.

CJam, 50 48 45 bytes

l22b391"þÁ "+{i%}/"Yª>Þÿ9cîÂcVáòe~"322b4b=

There's unprintable characters in the strings above, which can be obtained by the snippets

[254 193 160]:c
[89 170 62 222 30 255 20 57 99 238 194 99 86 225 242 101 126 20]:c

This also shows that the code points are all below 256. Output is 0 for 1 letter, 1 for 2 letters, 2 for 3 letters and 3 for non-ASCII.

The program simply converts the input string to a base 22 number, performs a series of modulos to reduce the number down, before performing a lookup from a base-4 encoded table.

Try it online | Test suite


Penrose Triangle Codegolf The Penrose triangle, also known as the Penrose tribar, or the impossible tribar, is an impossible object.

The goal in this challenge is to display a Penrose triangle in the fewest bytes possible.

Source: Wikipedia

Rules:

You must display the Penrose Triangle digitally after generating it.
They must look the same as the above image of the wiki page (source above) without directly showing the image.
The same image with the same color scheme must be shown in at least 400x400 size.
Should be as accurate as possible.

Good luck and have fun!


Integers sorted by their digital roots The digital root (also repeated digital sum) of a positive integer is the (single digit) value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The process continues until a single-digit number is reached.

For example, the digital root of 65536 is 7, because 6 + 5 + 5 + 3 + 6 = 25 and 2 + 5 = 7.

Sorting all digital roots doesn't make much sense, since it would just start with infinitely many 1s.

Instead, we'll create lists of all the single digits integers along with their digital roots, then all double digit numbers along with their digital roots, then the triple, quadruple and so on.

Now, for each of those lists, we'll sort it so that all the integers with digital roots of 1 appear first, then all integers with digital roots of 2 and so on. The sorting will be stable, so that the list of integers with a certain digital roots should be in ascending order after the sorting.

Finally we'll concatenate these lists into one single sequence. This sequence will start with all single digit numbers, then all double digit numbers (sorted by their digital root), then all triple digit numbers and so on.

Challenge:

Take a positive integer n as input, and output the n'th number in the sequence described above. You may choose if the list is 0-indexed of 1-indexed.

The sequence goes like this:

1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 19, 28, 37, 46, 55, 64, 73, 82, 91, 11, 20, 29 ...
72, 81, 90, 99, 100, 109, 118, ...
981, 990, 999, 1000, 1009, 1018, 1027, ...

Test cases:

The test cases are 1-indexed.

   n   f(n)
   9      9
  10     10
  11     19
  40     13
  41     22
  42     31
  43     40
  44     49
  45     58
 600    105
 601    114
 602    123
 603    132
 604    141
 605    150
4050   1453
4051   1462
4052   1471
4053   1480
4054   1489
4055   1498

Easier to copy:

n =    9, 10, 11, 40, 41, 42, 43, 44, 45, 600, 601, 602, 603, 604, 605, 4050, 4051, 4052, 4053, 4054, 4055,
f(n) = 9, 10, 19, 13, 22, 31, 40, 49, 58, 105, 114, 123, 132, 141, 150, 1453, 1462, 1471, 1480, 1489, 1498

Clarifications:

You may not output all n first elements. You shall only output the n'th.
The code must theoretically work for all integers up to 10^9, but it's OK if it times out on TIO (or other interpreters with time restrictions) for inputs larger than 999.
Explanations are encouraged.

It's code-golf, so the shortest code in each language wins! Don't be discouraged by other solutions in the language you want to golf in, even if they are shorter than what you can manage!

Python 2, 78 60 52 46 45 bytes

-6 bytes thanks to G B.
-1 byte thanks to Jakob.

n=input()
b=10**~-len(`n`)
print~-b+n/b+n%b*9

Try it online!

Finally reached a closed form, 1-indexed.

Python 2, 78 bytes

0-indexed.

d=10;k=1
exec'\nk+=9\nif k>d+7:k=d;d*=10\nif k>=d:k-=d/10*9-1'*input()
print k

Try it online!


Happy Birthday to Me! Happy birthday to Me!

Write a program that prints Happy birthday to me! on its birthday.

The program's birthday is the creation, last modification or compilation time of the program (you choose), and must not be hard-coded.
The date you use as the birthday must not be affected by the program's invocation or execution in any way. You can't modify your birthday.
For extra credit (-15% byte count), print Happy birthday to you! on your birthday (hard coded), if it doesn't coincide with the program's. Or use some celebrity's birthday and get -14%.
It must print only this, and not print anything on any other day.
Count bytes, in UTF-8.
Use the Gregorian calendar.

Good luck and happy birthday (to the newborn programs).

P.S.
Following Izkata's comment, if you print Happy birthday to Mel on Mel Kaye's birthday, you get 20% off. But you have to provide a credible source that it's this date.

bash - 65

[ `date +%d%m -r $0` = `date +%d%m` ]&&echo Happy birthday to me!

Thanks to ugoren, ace and nyuszika7h for help.


Verify Tents and Trees solution Background
Tents and Trees (try here) is a puzzle played on a square (or rectangular) grid, where the objective is to place tents horizontally or vertically adjacent to each of the trees, so that no two tents touch each other in 8 directions (horizontally, vertically, and diagonally) and the number of tents on each row/column matches the given clues.
Example puzzle and solution
In these examples, trees are T and tents are A.
Puzzle
  2 0 2 0 2 1
2 . T . T . .
1 . . . . T .
1 T . T . . .
2 . . . . . T
1 T . . . . .
0 . . . . . .

Solution
  2 0 2 0 2 1
2 . T A T A .
1 A . . . T .
1 T . T . A .
2 A . A . . T
1 T . . . . A
0 . . . . . .

Challenge
Given a grid with some tents and trees, determine whether the tents are placed correctly. Ignore the number clues in this challenge. In particular, your program should check the following:

The number of tents equals the number of trees,
The tents do not touch each other in 8 directions, and
There is at least one way to associate every tent with an adjacent tree in 4 directions, so that every tree is used exactly once.

If all of the above are satisfied, output a truthy value; otherwise, output a falsy value. You can choose to follow your language's convention of truthy/falsy, or use two distinct values for true/false respectively.
You may take the input in any reasonable way to represent a matrix containing three distinct values to represent a tree, a tent, and an empty space respectively.
Standard code-golf rules apply. The shortest code in bytes wins.
Test cases
This uses the same notation as the above example; T for trees, A for tents, and . for empty spaces.
Truthy
. . .
. . .
. . . (empty board)

T A

A T A
. . T

A T A
T . T
A T A
(note that there are two ways to associate tents with trees)

A . .
T T A
A T T
. . A

. T A .
A . . T
T T . A
. A . .

Falsy
(The number of Ts and As don't match)
T

A

T A T

(Two A's touch each other)
T A T
A . .

A . . A
T T T T
. A A .

(Some T's are not associated with an A)
A T A
T T .
A T A

A . T
T T A
A . .

J, 88 86 bytes
Expects a matrix with 0 for ., 1 for A and 2 for T.
(2>1#.1=,);.3~&2 2*/@,&,1&=((1 e.[:*/"{2>[:+/"1|@-"2)i.@!@#A.]) ::0&($ #:i.@$#~&,])2&=

Try it online!
How it works
1&= (…) 2&=

Tents on the left side, trees on the right side.
(…)&($#:i.@$#~&,])

Convert both arguments to 2D coordinates.
(…) ::0

If the following function throws an error, return 0. This happens only in the single A case. :-(
i.@!@#A.]

List all permutations of the trees.
|@-"2

Get the difference between the tents from every permutation.
[:*/2>[:+/"1

Check that each difference's sum is 1.
1 e.

Does any permutation fulfill this?
(2>1#.1=,);.3~&2 2

Get all 2x2 matrices of the original, and check if there is at most one tent in there.
*/@,@,

Combine both results, flatten the lists, and check if there are only 1's.


Find the "Recursive Size" of a List Inspired by Find the “unwrapped size” of a list.

Define the Recursive Size, RS, of a list containing no lists as its length (number of items contained) and the Recursive Size of a list containing any lists as the sum of its length and the Recursive Size of those lists.

Challenge

Write a program or function that outputs the Recursive Size of any given list in as few bytes as possible.

The input is a list and may contain numbers, strings (if your language has them), and similar lists.

For example:

RS([]) = 0

RS([[]]) = 1

RS([4, 5, 6]) = 3
RS(["four", "five", "six"]) = 3
RS(["[[[[]]]]", "[][][][][]", "][][[[]]][]["]) = 3

RS([[4, 5, 6]]) = 4
RS([["four", "five", "six"]]) = 4
RS([["[[[[]]]]", "[][][][][]", "][][[[]]][]["]]) = 4

RS([[4], [5], [6]]) = 6
RS([["four"], ["five"], ["six"]]) = 6
RS([["[[[[]]]]"], ["[][][][][]"], ["][][[[]]][]["]]) = 6

RS([[[[[[[[[]]]]]]]]]) = 8

RS([[],[],[],[],[],[],[],[]]) = 8

RS([[],[],[[]],[[[[]]]]]) = 8

RS([0,[-1],[2.3,-4.3],[5,[6]],[7,[8,9,[10,11,[12,13,14]]]]]) = 22

Note that if your language has no strings but does have lists of characters, the examples containing "strings" above could actually be lists of characters and have larger results. As an example:

RS([['f','o','u','r'], ['f','i','v','e'], ['s','i','x']]) = 14

This is code-golf, so the shortest answer in bytes wins; no funny-business, as always.

A non-list input may produce any output.
I/O is as flexible as usual.

Python, 42 bytes

f=lambda x:x*0==[]and len(x)+sum(map(f,x))

For a non-list, output 0. For a list, output its length plus the sum of the recursive outputs for its elements.

Lists fall above numbers and below strings in the Python 2 ordering, requiring []<=x<''. Instead, we check x*0==[], whereas the result of 0 for a number or '' for a string.


In Honor of Adam West Adam West passed away, and I'd like to honor his memory here on PPCG, though I doubt he knew of our existence. While there are many, many different things that this man is known for, none are more prominent than his role as the original batman. I'll always remember my step-father still watching the old-school Batman and Robin to this day. This challenge is simplistic in nature, not at all in line with the complicated man that was Adam West. However, it's the best I could come up with, as this is the most iconic image of the man's career.

I wanted to post this earlier, but I was waiting for someone to come up with something better.

Output the following (with or without trailing spaces/newlines):

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

This is code-golf, the lowest byte-count will win.

Wordfuck, 5761 2686 bytes

I guess using his name as a source code gets Adam West some honor.

adam west adam west adam_wes t_a dam_we st_a dam_ west adam west adam west adam west_ad am_west_a dam_we st ad am we st ad am we st ad am west_a dam_we st_a dam_ west_ada m_w est ada m_w est ada m_west_ adam west_a dam_west_ adam_we st_ ad am_west ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am_wes t_ adam_w est_ adam west adam west adam west adam west adam we st_adam west_ad am we st ad am we st adam_w es t_ ad am west_ad am we st ad am we st ad am we st_ada m_ west_ad am we st ad am west_a da m_west_ ad am we st ad am we st ad am west_a da m_ we st adam_w es t_adam_ west_ad am we st ad am west_a da m_ we st adam_we st ad am we st ad am we st ad am we st_ada m_ we st ad am we st adam_we st ad am we st ad am we st ad am we st_ada m_ we st ad am_wes t_ adam_we st_adam we st ad am_wes t_ ad am we st ad am_west ad am we st ad am we st ad am we st adam_w es t_ ad am we st ad am_west ad am we st ad am we st ad am we st adam_w es t_ ad am we st adam_w es t_adam_ west_ad am we st_ada m_ we st ad am we st ad am west_ad am we st ad am we st ad am west_a da m_ we st ad am we st ad am_west ad am we st ad am we st ad am_wes t_ ad am we st ad am we st adam_w es t_adam_ west_ad am west_a da m_ we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st_ada m_ west_ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am west_a da m_west_ ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am_wes t_ adam_we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st adam_w es t_adam_ west_ad am west_a da m_ we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st_ada m_ west_ad am_west ad am west_a da m_ we st ad am_west ad am we st ad am we st_ada m_ we st ad am we st ad am we st ad am we st ad am we st ad am west_ad am we st ad am we st adam_w es t_ ad am we st_ada m_ west_ad am_west ad am we st adam_w es t_ ad am west_ad am we st ad am we st adam_w es t_ ad am_west ad am we st adam_w es t_ ad am we st_adam we st ad am west_a da m_ we st_adam we st ad am we st ad am_wes t_ ad am we st_ada m_ west_ad am_west ad am we st ad am we st_ada m_ we st_adam we st ad am we st ad am_wes t_ adam_we st ad am we st ad am_wes t_ ad am west_ad am we st ad am we st_ada m_ west_ad am we st ad am we st adam_w es t!

Try it online! (transpiled brainfuck)

Adam West singing (thanks @carusocomputing)


Draw the Sierpinski Arrowhead Curve Introduction
The Sierpinski Arrowhead Curve is a curve that's limit is Sierpinski's Triangle.
It first starts like this:
 _
/ \

Then, each line is replaced with a rotated version of the first one:
  _
 / \
 \ /
_/ \_

Next:
     _
    / \
    \ /
   _/ \_
  /     \
  \_   _/
 _  \ /  _
/ \_/ \_/ \

Your task
Given a number n, output the n-th iteration of the Sierpinski Arrowhead Curve.
You may choose 0 or 1-indexed input, but please specify that in your answer.
You may generate an image, or use Ascii Art in the format I have given above.
You may not use built-ins to generate this curve.
Remember, this is code-golf, so the code with the fewest bytes wins.

Octave, 240 236 221 bytes
This is made with the same idea used here but I had to change it to fit the sierpinsky arrowhead curve.
m=input(0);g=2*pi/6;u=cos(g);v=sin(g);A=[1,0];B=[u,v];C=[-u,v];D=-A;E=-B;F=-C;for k=1:m;f=[E;F;A];b=[A;B;C];A=[B;A;F];d=[C;D;E];C=[D;C;B];E=[F;E;D];B=b;D=d;F=f;end;A=[0,0;cumsum(A)];plot(A(:,1),A(:,2));axis off;axis equal


Maximal Substring Construction In this challenge, you are passed two things:

A string length, N
A list of strings, L, each with an assigned point value.  Any string that is not passed in has a point value of 0

You need to construct a string of length N such that the sum of all substring points is as large as possible.

For example:

5 [("ABC", 3), ("DEF", 4), ("CDG", 2)]

should output

ABCDG

Because the two substrings with points (ABC and CDG) have a total of 5 points, and no other possible construction can give 5 or more points.

Substrings can be used multiple times in a string, and can overlap.  You can assume that the points will always be positive, the substring lengths will be between 1 to N characters longs, and that N > 0.  If multiple constructions are maximal, print any one of them.

Your program must run in a reasonable amount of time (no more than a minute for each of the examples):

1 [("A", 7), ("B", 4), ("C", 100)]     => C
2 [("A", 2), ("B", 3), ("AB", 2)]      => AB
2 [("A", 1), ("B", 2), ("CD", 3)]      => BB
2 [("AD", 1), ("B", 2), ("ZB", 3)]     => ZB
3 [("AB", 2), ("BC", 1), ("CA", 3)]    => CAB
3 [("ABC", 4), ("DEF", 4), ("E", 1)]   => DEF
4 [("A", 1), ("BAB", 2), ("ABCD", 3)]  => AAAA or ABAB or BABA or ABCD
5 [("A", 1), ("BAB", 2), ("ABCD", 3)]  => BABCD or BABAB
5 [("ABC", 3), ("DEF", 4), ("CDG", 2)] => ABCDG
5 [("AB", 10), ("BC", 2), ("CA", 2)]   => ABCAB
6 [("AB", 10), ("BC", 2), ("CA", 2)]   => ABABAB
8 [("AA", 3), ("BA", 5)]               => BAAAAAAA
10 [("ABCDE", 19), ("ACEBD",  18), ("ABEDC", 17), ("BCEDA", 16), ("EBDAC", 15), ("BACD", 14), ("CADB", 13), ("ABDC", 12), ("CABD", 11), ("EBDC", 10), ("ACE", 9), ("CBA", 8), ("AEC", 7), ("BE", 6), ("AE", 5), ("DC", 4), ("BA", 3), ("A", 2), ("D", 1)]
=> ACEBDACEBD

This is a code-golf, so prepare your shortest answer in your favorite language!

Python 2.7, 503 Bytes
This isn't particularly golfed, nor is it particularly efficient; it's just a relatively condensed enumeration of feasible strings that are brute-forced.  I don't think it would be too hard to create an admissible heuristic to use with A*, which would probably be a bit quicker.  I didn't bother doing that, though, because this method solves all of the examples in about 47 seconds on my laptop.
import re
v=lambda l,s:sum([len([m.start() for m in re.finditer('(?=%s)'%u,s)])*v for u,v in l])
def m(n,l,e):
 if len(e)==n:
  yield e
 else:
  u=1
  for s,v in sorted(l,key=lambda j:j[1],reverse=True):
   for i in range(len(s)-1,0,-1):
    if len(e)+len(s)-i <= n and e.endswith(s[:i]):
     for r in m(n,l,e+s[i:]):
      u=0;yield r
   if len(e)+len(s)<=n:
    for r in m(n,l,e+s):
     u=0;yield r
  if u:
   yield e
def p(n,l):
 b,r=-1,0
 for s in m(n,l,''):
  a=v(l,s)
  if a>b:b,r=a,s
 return r

To test it:
if __name__ == "__main__":
    for n, l in [
            (1, [("A", 7), ("B", 4), ("C", 100)]),     # => C
            (2, [("A", 2), ("B", 3), ("AB", 2)]),      # => AB
            (2, [("A", 1), ("B", 2), ("CD", 3)]),      # => BB
            (2, [("AD", 1), ("B", 2), ("ZB", 3)]),     # => ZB
            (3, [("AB", 2), ("BC", 1), ("CA", 3)]),    # => CAB
            (3, [("ABC", 4), ("DEF", 4), ("E", 1)]),   # => DEF
            (4, [("A", 1), ("BAB", 2), ("ABCD", 3)]),  # => AAAA or ABAB or BABA or ABCD
            (5, [("A", 1), ("BAB", 2), ("ABCD", 3)]),  # => BABCD or BABAB
            (5, [("ABC", 3), ("DEF", 4), ("CDG", 2)]), # => ABCDG
            (5, [("AB", 10), ("BC", 2), ("CA", 2)]),   # => ABCAB
            (6, [("AB", 10), ("BC", 2), ("CA", 2)]),   # => ABABAB
            (8, [("AA", 3), ("BA", 5)]),               # => BAAAAAAA
            (10, [("ABCDE", 19), ("ACEBD",  18), ("ABEDC", 17), ("BCEDA", 16), ("EBDAC", 15), ("BACD", 14), ("CADB", 13), ("ABDC", 12), ("CABD", 11), ("EBDC", 10), ("ACE", 9), ("CBA", 8), ("AEC", 7), ("BE", 6), ("AE", 5), ("DC", 4), ("BA", 3), ("A", 2), ("D", 1)]) # => ACEBDACEBD
    ]:
        print p(n, l)

Explanation
The v function simply calculates the value of a given string by searching for all occurrences of the substrings in L.  The m function enumerates all strings of length n with prefix e that can be generated from the substrings in l.  m recursively calls itself; the first call should pass in '' for e.  For example:
>>> for s in m(4, [("A", 1), ("BAB", 2), ("ABCD", 3)], ''):print s
ABCD
BABA
ABCD
ABAB
AAAA

The p function simply loops through all possible strings (as enumerated by m) and returns the one with highest value (as determined by v).
Note that the m function actually prioritizes the enumeration by sorting based on substrings' values.  This turns out to be unnecessary to ensure optimality, and it actually hinders efficiency a bit; I could save ~20 or so bytes by removing it.


Special Character Coding Challenge - Check string for validity (Lots of rules) There are 5 different "special characters": % & # $ !

These special characters are in a string with numbers. Like so: "5 !    60%2$5.3" (valid). You must determine the validity of the string and there are certain rules in order to determine validity of the string.

Rules:

These special characters can exist in a string, however they cannot be next to each other (ignoring spaces). For example:

"!%" is invalid
"% %" is invalid
"#     %    $" is invalid

The only exception to the rule above is with the exclamation mark. Only one exclamation mark may be after another special character. These assume there are numbers before and after the special characters. For example:

"!!" is valid
"!!!" is invalid
"$!" is valid
"$!!" is invalid
"!$" is invalid

If a special character is at the end of the string, there MUST be a number after it (ignoring spaces). If a special character is at the start of the string, there MUST be a number before it. For example:

"5!" is invalid
"5!5" is valid
"5#!5" is valid
"%5" is invalid

The only exception to the rule above is with the exclamation mark. There does not need to be a number before the exclamation mark assuming there is a number after it. For example:

"!5" is valid
”!!5" is invalid
"5!!5” is valid

If there is a string with only numbers, that string is valid, if there is a space between the space is invalid. For example:

"2   5" is invalid
"25" is valid

If a string only contains operators it is automatically invalid. For example:

"!#%" is invalid
"#" is invalid

Extra Examples of Strings that are VALID

"5%!5"
"!5 !5 %!5"
"5.4 $ 2.9 !3.4 &! 89.8213"

Extra Examples of Strings that are INVALID

"5%%5"  (reason: two "%%")
"!5!!!!!!!!%%%5" (reason: way too many operators next to each other)
"!5 !5 !" (reason: no number after the last "!")
"2.0%"  (reason: no number after "%")
"!6.9#" (reason: no number after "#")
"$6.9&" (reason: no number after "#" AND no number before "$")

A number is a run of 0-9 digits with a possible . to indicate decimals.

You can assume you will only get a string with either numbers and/or these special characters inside. You can also assume the numbers will not have floating zeros like 9.000 or 0004 or 00.00. Treat a single zero as any other number, so for example 0$0 is valid. You can assume you won't receive an empty string.

Game winning criteria objective: code-golf

(If you want a more difficult challenge try using python3 without using eval or exec.) This was originally planned.

Raku, 41 bytes

{?/^[\s*\!?\s*\d+\.?\d*\s*]+%<[%&#$!]>$/}

Try it online!

Checks if the input matches against a regex.

Explanation:

{?/^                                 $/}  # Check if the input is
    [                     ]+  # A series of
        \!?                   # An optional ! followed by
              \d+\.?\d*       # A number
     \s*   \s*         \s*    # Interspersed with optional whitespace
                            %           # Joined by
                             <[    ]>   # Any of
                               %&#!     # The special characters


Layout my tiles for me I'm retiling my kitchen with different coloured tiles. In fact, it's going to have at least 2 colours - and 26 colours as a maximum.

But, I'm fussy. I want this wall to look random, but sometimes random isn't random enough.

So, when I lay out my tiles, I don't want to have any the same colour next to each other in the 4 Cartesian directions. Diagonally adjacent is (of course) fine.

Acceptable:

┌───┐
│ A │
└───┘

┌───┬───┬───┐
│ A │ B │ A │
├───┼───┼───┤
│ B │ A │ B │
└───┴───┴───┘

┌───┬───┬───┐
│ A │ B │ C │
├───┼───┼───┤
│ C │ A │ B │
└───┴───┴───┘

Unacceptable:

┌───┬───┬───┐
│ A │ B │ A │
├───┼───┼───┤
│ A │ A │ B │
└───┴───┴───┘

┌───┬───┬───┐
│ A │ C │ C │
├───┼───┼───┤
│ C │ A │ B │
└───┴───┴───┘

Given input in the form A B N where A is the width, B is the height and N is the number of colours - an integer from 2 to 26 - you need to output a grid like so:

Input:

5 6 4

Example output:

A B C D A
B A D A C
A D C D A
B C B A B
D A D C A
B C A D C

The input will be given as a) 3 arguments to a function or b) as 3 separate input statements or b) as A B N. Input will always be valid.

All colours have to be used and all valid tilings have to have a non-zero probability of being generated.

This is code-golf so the shortest code wins.

Python 2, 151 149 bytes

from random import*
W,H,N=input()
L='x'*W
exec"M='';exec'M+=sample(set(map(chr,range(65,65+N)))-{L[len(M)],M[-1:]},1)[0];'*W;L=M;print' '.join(L);"*H

Takes input comma-separated via STDIN, e.g. 10, 10, 2.


Does this line pass through that square? Divide the first quadrant (including the positive x-axis, the positive y-axis, and the origin) into 1x1 grids, with each grid labelled by the coordinates of its bottom-left corner, as demonstrated below:

Note that each grid contains its boundaries and its vertices. Using mathematical symbols, the grid labelled (m,n) would represent the square {(x,y) | m ≤ x ≤ m+1, n ≤ y ≤ n+1}.

Given a straight line in the form of ax+by+c=0 with integers a, b, and c, and a grid represented by (m,n), output whether the line passes through the grid, i.e. whether any point in the given grid is on the line.

a  b  c m n output
1  1  0 0 0 true
1  1  0 1 1 false
1  1  0 0 2 false
1  1 -3 0 1 true
1  1 -3 0 0 false
2 -1  0 1 1 true
2 -1  0 1 0 false
2 -1  0 0 2 true
2 -1  0 0 1 true
2 -1  0 1 2 true
2  0 -1 0 0 true
2  0 -1 0 1 true
2  0 -1 0 2 true
2  0 -1 1 0 false
2  0 -1 1 1 false
0  2 -1 0 0 true
0  2 -1 1 0 true
0  2 -1 2 0 true
0  2 -1 0 1 false
0  2 -1 1 1 false
1  0 -1 0 0 true
1  0 -1 0 1 true
1  0 -1 0 2 true
1  0 -1 1 0 true
1  0 -1 1 1 true

Please suggest more testcases in the comments.

This is code-golf. Shortest answer in bytes wins. Standard loopholes apply.

Python 3, 84 66 bytes

First golf, first fail (maybe).

Thanks to Rod for shaving off 18 bytes by using a function instead of direct input.

def f(a,b,c,m,n):f=-(a*m+c)/b;g=f-a/b;print(min(f,g)<=n<=max(f,g))

Try it online!

Explanation:

Basically we calculate the value of the line function for m and m+1, if n is inbetween the values, then the list must pass through it at some point.
Would be much better if the language had some simpler way to input multiple integers.


Python 2, 318 315 271 bytes

Mr.Xcoder, ovs and Jonathan Frech saved a lot of bytes

p=range
def f(x,i=0,j=-1):z=len(x[0]);j+=1;i+=j/z;j%=z;return i<len(x)and(x[i][j]and-~min([f([[v,v[:j]+[2]*(r-j)+v[r:]][i<=y<=e]for y,v in enumerate(x)],i,j)for e in p(i,len(x))for r in p(j+1,z+1)if all(all(k[j:r])for k in x[i:e+1])]+[f(x,i,j)-1]*(x[i][j]>1))or f(x,i,j))

Try it online!


Generate the python dictionary of phone keypresses for any letter In the fewest bytes, generate the dictionary of keypresses for any letter (as described in https://code.google.com/codejam/contest/351101/dashboard#s=p2)

In Python, the dictionary literal itself:

{'a':2,'c':222,'b':22,'e':33,'d':3,'g':4,'f':333,'i':444,'h':44,'k':55,'j':5,'m':6,'l':555,'o':666,'n':66,'q':77,'p':7,'s':7777,'r':777,'u':88,'t':8,'w':9,'v':888,'y':999,'x':99,'z':9999}

is 187 bytes so it needs to be less than that.  (The values can be strings or ints, ie you can have 'a':'2' or 'a':2 it's up to you)

NOTE: This is not asking you to solve the referenced GCJ problem, it's just asking you to generate a particular dictionary which is related to that problem.

EDIT: You may solve this in any language which has a dictionary-like type (ie hashmap, associative array etc.)

perl, 49 48 bytes

Using a different algorithm than my previous answer, we can lose another 12 bytes. The basic idea is that you usually just add the digit from the last letter's solution over again. We handle the other cases (detected by a short regex) by starting with a single instance of the last digit + 1.

{map{$d++,$t=""if/[dgjmptw]/;$_,$t.=$d||=2}a..z}

With output:

ski@anito:~/src$ perl -MData::Dumper  -e '$Data::Dumper::Sortkeys=1; $d=2;print Dumper {map{$d++,$t=""if/[dgjmptw]/;$_,$t.=$d}a..z}'
$VAR1 = {
      'a' => '2',
      'b' => '22',
      'c' => '222',
      'd' => '3',
      'e' => '33',
      'f' => '333',
      'g' => '4',
      'h' => '44',
      'i' => '444',
      'j' => '5',
      'k' => '55',
      'l' => '555',
      'm' => '6',
      'n' => '66',
      'o' => '666',
      'p' => '7',
      'q' => '77',
      'r' => '777',
      's' => '7777',
      't' => '8',
      'u' => '88',
      'v' => '888',
      'w' => '9',
      'x' => '99',
      'y' => '999',
      'z' => '9999'
};


Describe a 2D Bitmap Using Filled Rectangle Mapping Idea:

Consider a 2-bit bitmap of arbitrary side-lengths overlaid on a coordinate grid and imaged with random data (1's represent an element of the image, 0's represent the "blank" canvas background):

y x—0 2 4 6 8 10  14  18
|
0   0000000000111100000000
    0000000011111110000000
2   0000111111111111000000
    0000011111111111000000
4   0000000000000000000000
    1111111000000000011111
6   1111111111100000000011
    1111111111111111000000

Next, consider how the rasterized image may be described using a series of drawn, solid rectangles. Example:

    0 2 4 6 8 101214161820

0   0000000000111100000000
    0000000011111110000000
2   0000111111111111000000
    0000011111111111000000
4   0000000000000000000000
    xxxxxxx000000000011111
6   xxxxxxx111100000000011
    xxxxxxx111111111000000

The x's describe a region of the bitmap that may be described using a solid rectangle. Finally, consider how that rectangular section of the image can be described under the X-Y coordinate system by two of its vertices in the format:

{x0,y0,x1,y1}

In this case,

{0,5,6,7}

describes the example rectangular section.

Challenge:
Design a program which receives a 2D matrix containing bitmap data and outputs a concatenated list of rectangle coordinates.

Restrictions:

The output, when processed by remapping (plotting using 1's) the rectangles back onto a blank coordinate canvas (a canvas of all 0's) of the same side-length dimensions, should yield exactly the input matrix.

The output should be a concatenated list of all computed rectangles, no extraneous parsing characters or structures distinguishing one set of coordinates from another. The list will be read top-down, ordering will be inferred given that each rectangle requires only two coordinates to be described.

Example I/O:

(Do mind that this example in no way presents the ideal output, however, it is a valid output.)

Input 2D matrix:

0000000000111100000000
0000000011111110000000
0000111111111111000000
0000011111111111000000
0000000000000000000000
1111111000000000011111
1111111111100000000011
1111111111111111000000

Output concatenated list:

{10,0,13,3,8,1,9,3,5,2,7,3,4,2,4,2,14,1,14,3,15,2,15,3,0,5,6,7,7,6,10,7,11,7,15,7,17,5,21,5,20,6,21,6}

Efficiency score:

Programs will be ranked by their average-case efficiency using this resource (or one which functions identically) to generate pseudorandom, 2-bit, 20x20 matrices. Determine the average-case efficiency by calculating the arithmetic mean of the output lengths of at least 10 iterations (sum of the lengths divided by the number of iterations). The lesser the average length of the output, the greater the efficiency.

Rust

Try it online

Average case num rectangles: 57.9054 (10000 iterations of 20x20 matrices, with 1/7 probability of "0")

Solution to example input:
{10,0,13,3,8,1,14,3,4,2,15,2,5,3,15,3,0,5,6,7,17,5,21,5,0,6,10,7,20,6,21,6,0,7,15,7}

The algorithm is pretty simple: for each horizontal line of 1s, use that as the top side of a rectangle, extend this rectangle down while possible, and if it covers some previously uncovered area, add it to the list. This assumes rectangles can overlap. I have not verified whether the output is always correct, but the example input looks ok. The output was verified against the input for 10000 iterations, and it looks correct.

The code includes a benchmark function to calculate the score, and a function to draw the result. The input can be changed in the main function.

extern crate rand;
use rand::{Rng, thread_rng};

#[derive(Copy, Clone, Debug)]
struct Rect {
    x0: usize,
    y0: usize,
    x1: usize,
    y1: usize
}

impl Rect {
    fn contains_xslice(&self, xa: usize, xb: usize) -> bool {
        self.x0 <= xa && xb <= self.x1
    }
    fn contains(&self, r: &Rect) -> bool {
        // r is completely inside of self
        self.x0 <= r.x0 && r.x1 <= self.x1 && self.y0 <= r.y0 && r.y1 <= self.y1
    }
}

fn display_rects(r: &[Rect]) -> String {
    let s = r.iter()
        .map(|z| format!("{},{},{},{}", z.x0, z.y0, z.x1, z.y1))
        .collect::<Vec<_>>()
        .join(",");

    // transform 1,1 into {1,1}
    format!("{{{}}}", s)
}

fn draw_rects(r: &[Rect], w: usize, h: usize) -> String {
    let mut s = format!("");
    for y in 0..h {
        for x in 0..w {
            let p = Rect { x0: x, x1: x, y0: y, y1: y };
            if r.iter().any(|a| a.contains(&p)) {
                s.push_str("1");
            } else {
                s.push_str("0");
            }
        }
        s.push_str("\n");
    }
    s
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct Matrix {
    v: Vec<u8>,
    size: (usize, usize),
}

impl Matrix {
    fn new(w: usize, h: usize) -> Self {
        Self {
            v: vec![0; w*h],
            size: (w, h),
        }
    }
    fn from_str(s: &str) -> Self {
        let mut v = vec![];
        let mut w = None;
        let mut h = 0;
        for l in s.lines() {
            h += 1;
            let mut tw = 0;
            for c in l.chars() {
                tw += 1;
                let x = match c {
                    '0' => 0,
                    '1' => 1,
                    a => panic!("Invalid input! {:?} at {},{}", a, tw, h),
                };
                v.push(x);
            }
            if let Some(ww) = w {
                if tw != ww {
                    panic!("All lines must have the same width! {} != {}", tw, ww);
                }
            } else {
                w = Some(tw);
            }
        }

        let w = w.unwrap_or(0);

        Matrix {
            v,
            size: (w, h),
        }
    }
    fn random(w: usize, h: usize) -> Self {
        let mut rng = thread_rng();
        let mut v = vec![];

        for _ in 0..w*h {
            let n = rng.gen_range(0, 6+1);
            let x = if n == 0 { 0 } else { 1 };
            v.push(x);
        }

        Matrix {
            v,
            size: (w, h),
        }
    }
    fn get(&self, x: usize, y: usize) -> u8 {
        self.v[y * self.size.0 + x]
    }
    fn hline(&self, y: usize) -> &[u8] {
        &self.v[y * self.size.0 .. (y + 1) * self.size.0]
    }
    fn hline_1_pieces(&self, y: usize) -> Vec<Rect> {
        let mut r = vec![];
        let line = self.hline(y);
        let xmax = self.size.0 - 1;
        let y0 = y;
        let y1 = y;
        let mut lineit = line.iter();
        let mut xoff = 0;
        while lineit.len() > 0 {
            // Find first non-zero pixel
            if let Some(x0) = lineit.position(|&x| x != 0) {
                let x0 = xoff + x0;
                // x0..x1 is a line of 11111
                let x1 = x0 + lineit.position(|&x| x == 0).unwrap_or(xmax - x0);
                r.push(Rect { x0, x1, y0, y1 });
                // Remember offset because the iterator is being consumed
                xoff = x1 + 2;
            }
        }

        r
    }
    fn rectangles(&self) -> Vec<Rect> {
        let mut r: Vec<Rect> = vec![];
        let ymax = self.size.1 - 1;
        // For each hline, add rectangles covering the maximum width possible
        let hpieces: Vec<Vec<Rect>> = (0..self.size.1).map(|i| self.hline_1_pieces(i)).collect();
        // Extend each rectangle down while possible
        for (y0, layer) in hpieces.iter().enumerate() {
            for rect in layer {
                let mut y = y0 + 1;
                while y <= ymax {
                    if hpieces[y].iter().any(|&r| r.contains_xslice(rect.x0, rect.x1)) {
                        y += 1;
                    } else {
                        break;
                    }
                }
                let y1 = y - 1;
                let rn = Rect { y1, ..*rect };
                if r.iter().any(|&r1| r1.contains(&rn)) {
                    // An equivalent rectangle is already in the vec
                } else {
                    // This rectangle covers some new area, push it
                    r.push(rn);
                }
            }
        }

        r
    }
}

fn benchmark(iterations: usize) -> f64 {
    let mut sum = 0;
    for _ in 0..iterations {
        let m = Matrix::random(20, 20);
        let r = m.rectangles();
        let output = draw_rects(&m.rectangles(), 20, 20);
        assert_eq!(m, Matrix::from_str(&output));
        sum += r.len();
    }
    sum as f64 / iterations as f64
}

fn main() {
    let input = "\
0000000000111100000000
0000000011111110000000
0000111111111111000000
0000011111111111000000
0000000000000000000000
1111111000000000011111
1111111111100000000011
1111111111111111000000
";
    let m = Matrix::from_str(input);
    assert_eq!(input, draw_rects(&m.rectangles(), 22, 8));
    println!("{}", display_rects(&m.rectangles()));
    println!("{}", benchmark(10000));
}


Find the binary period We know that not all fractions have a terminating binary representation.  However every fraction can be written as a leading portion followed by a repeating portion.  For example \$1/3\$ starts with \$0.\$ and then just repeats \$01\$ endlessly.  This corresponds to the bar notation taught in primary school.  For example

$$
1/3 = 0.\overline{01}
$$

Where the portion with the bar is the repeating section.

For numbers with a terminating representation, (e.g. \$1/2 = 0.1\$) the repeating section is just \$0\$, since there are endless implicit zeros at the end of a terminating representation.

We will call the minimum1 length of the repeating section the binary period of the fraction.

Your task is to write a program or function which takes a positive integer \$n\$ as input and outputs the binary period of \$1/n\$.

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

OEIS A007733

1: We say minimum because if you duplicate a section again it keeps a valid representation. (e.g. \$0.\overline{01} = 0.\overline{0101}\$)

Jelly, 9 bytes

2*Ɱ%µẠȧQL

A monadic Link accepting a positive integer, n, which yields a positive integer, the period.

Try it online! Or see the test-suite.

How?

2*Ɱ%µẠȧQL - Link: integer, n
2         - literal two
  Ɱ       - map across [1..n]
 *        - exponentiate -> [1,2,4,8,...,2^n]
   %      - modulo n -> [1%n,2%n,4%n,8%n,...,2^n%n]
    µ     - start a new monadic chain - call that X
     Ạ    - all (X)? -> 0 if we reach zero, else 1 - i.e. 0 if n is a power of 2
       Q  - de-duplicate (X) -> the repeating 2^k%n values
      ȧ   - logical AND -> 0 if n is a power of 2 else Q(X)
        L - length (0 has a length of 1 (after an implicit make_digits))


Convert from binary to negabinary Given a binary integer inclusively between 0 and 1111111111111111 (i.e. a 16-bit unsigned integer) as input, output the same integer in negabinary.

The input can be in whatever format is most convenient for your language; for example, if it is easier for the program to handle input with 16 digits, like 0000000000000101, rather than simply 101, you can write the program to only accept input that way.

Sample I/O

> 1
1
> 10
110
> 1010
11110
> 110111001111000
11011001110001000
> 1001001
1011001

Here is a sample program I wrote that does base conversions, including negative and non-integer bases. You can use it to check your work.

APL, 21 characters
'01'[-(16/¯2)⊤-2⊥⍎¨⍞]

I used Dyalog APL for this, with ⎕IO set to 0, allowing us to index arrays starting at 0 rather than 1.
Explanation, from right to left:

⍞ gives us the user's input as a character vector.
⍎¨ applies the execute function (⍎) to each (¨) of the aforementioned characters, resulting in a vector of integer 1's and 0's.
2⊥ decodes the vector from base 2 into decimal.
- negates the resulting decimal integer.
(16/¯2)⊤ encodes the decimal integer into base ¯2 (negative 2). (16/¯2 replicates ¯2, 16 times, yielding 16 digits in our negabinary number.)
- negates each element of our newly encoded number (before this, it consists of -1's and 0's), so that we can use it to index our character vector.
'01'[ ... ] indexes the character array ('01') using the 0's and 1's of the negated negabinary vector. This is so we get a prettier output.

Example:
      '01'[-(16/¯2)⊤-2⊥⍎¨⍞]
10111010001
0001101011010001


Increment every number in a string Given a string containing decimal numbers:

teststring134this 123test string54 100

increment every number in this string by one to give the new string

teststring135this 124test string55 101.

The string can be provided as:

a command line argument
STDIN
a hard-coded variable or function argument

Cover all possible positions for a number:

as a prefix for a word; 123test ► 124test
as a suffix for a word; test123 ► test124
inside a word; te123st ► te124st
alone test 123 test ► test 124 test

Here's a non-golfed solution in Python:

NUMBERS = '0123456789'

def increment(s):
    out = ''

    number = ''
    for c in s:
        if c in NUMBERS:
            number += c
        else:
            if number != '':
                out += str(int(number) + 1)
                number = ''
            out += c

    if number != '':
        out += str(int(number) + 1)
        number = ''

    return out

print "\"%s\"" % (increment('teststring134this 123test string54 100'))

This is a code-golf question, shortest code wins.

Perl, 14 bytes

s/\d+/$&+1/ge

Requires the -p switch, which I have counted as one byte.

Example run

$ perl -p <(echo 's/\d+/$&+1/ge') <<< 'teststring134this 123test string54 100'
teststring135this 124test string55 101


The Final Stand - Defeat the Zombie Horde Introduction

You are alone on an island. The remainder of humanity is dead (probably due to the bug in user12345's code). The Zombie Pirate Horde has reached your island, and they are endless. It's time to kick ass or chew bubble gum, and you're all outta bubble gum.

Problem

Our doomsday scenario is described by 2 integers on a single line, m and n. On your island are outposts uniquely numbered from 1 to m. The following n lines each contain three integers, x, y, and z, separated by a space. x and y are the unique IDs of two outposts, and z is the number of zombies that will be encountered on the path between them.

When you travel a path, you lose z ammunition and you kill z zombies. If you travel the same path again, you will encounter the same number of zombies, unfortunately. All outposts generate +1 ammunition each time you travel a path. You begin with 100 ammunition at outpost 1. All outposts begin with 0 ammunition. You die immediately if no path exists for which your ammunition is greater than the number of zombies on that path, and the remainder of your ammunition is converted to kills. Such is your final stand.

Write a program that outputs the maximum number of zombies you can kill for a given scenario. If you can kill an infinite number of zombies, simply output x.

Example Input

5 6
1 2 4
2 3 4
3 1 4
2 4 10
2 5 10
1 1 50

Example Output

x

Assumptions

A path will be between two valid outposts. That is to say 1 <= x/y <= m
If a path between x and y is not listed, it cannot be traveled
A path is bidirectional
1 < m <= 100
1 < n <= 500
Input must be provided through stdin, read from a file, or accepted as a sole argument to the program, and it must exactly follow the format of the example
The runtime of your program may be arbitrarily large but must be determinably finite

The code with the fewest characters wins!

Java ( less grotesque: 8415 5291 3301)
Ok. Basically, I'm embarrassed no-one has submitted a solution. So a few days ago I began trying to solve this problem, b/c it's great.. Follow that link to watch my progress on it via GitHub.
Edit
New solver version, much more "golfed", with corrected cycle checker as identified by MT0. It also supports fast-forwarding routes, tuneable by changing how much memory is available to the VM. Latest BIG edit: realized that I had a few other small index errors and premature optimizations, that resulted in a failure to consider quite a large number of types of wins. So that's fixed, carefully. The new version is both smaller and below.
For our reference route, java -Xmx2GB ZombieHordeMin does the trick quite nicely (be warned, it will take a while).
Cool factoid
In a fascinating twist, there are MANY solutions at length 24, and my solver finds one different from MT0's, but identical in principle, except that it starts by visiting the the other outposts connected to 1. Fascinating! Totally counter human intuition, but perfectly valid.
Solution Highlights
So here's mine. It's (partially) golfed, b/c it's an exponential, almost-brute-force solver. I use an IDDFS (iterative deepening depth first search) algorithm, so it's a great general solver that doesn't skip, so it solves both parts of the OP's question, namely:

If a winning route is found (infinite zombies), output 'x'.
If all routes end in death (finite zombies), output the largest number of zombies killed.

Give it enough power, memory, and time, and it will do just that, even slow-death maps. I spent some more time improving this solver, and while more can be done, it's a bit better now. I also integrated MT0's advice on the best infinite-zombies solution, and removed several premature optimizations from my win-checker that prevented the previous version from finding it, and now I do in fact find a very similar solution to the one MT0 described.
A few other highlights:

As mentioned, uses an IDDFS to find the shortest possible winning route.
Since it is at core a DFS, it will also discover if every route ends in the death of our hero, and keeps track of the "best" route in terms of most zombies killed. Die a hero!
I've instrumented the algorithm to make it more interesting to watch Removed for golfing purposes. Follow one of the links to github to see the ungolfed version.
There are a number of comments throughout as well, so feel free to re-implement for your own solution building on my approach, or show me how it should be done!
Memory-adaptive route fast-forwarding

Up to available system memory, will keep track of "end routes" that did not result in death.
Using a fancy route compression and decompression routine, progress from a prior iteration of IDDFS is restored to prevent rediscovery all prior visited routes.
As an intentional side-bonus, acts as a dead-end route cull. Dead end routes aren't stored, and will never be visited again in future depths of IDDFS.

History of the solver

I tried a bunch of one-step look-ahead algorithms, and while for very simple scenarios they would work, ultimately they fall flat.
Then I tried a two-step look-ahead algorithm, which was.. unsatisfying.
I then began building an n-step lookahead, when I recognized that this approach is reducible to DFS, yet DFS is far ... more elegant.
While building the DFS, it occurred to me that IDDFS would ensure (a) find best HERO (death) route or (b) first winning cycle.
Turns out building a win-cycle checker is easy, but I had to go through several very very wrong iterations before I got to a provably successful checker.
Factored in MT0's win-path to remove three lines of premature optimization that made my algorithm blind to it.
Added an adaptive route-caching algorithm that will use all the memory you give it to prevent unnecessary redoing of work between IDDFS calls, and also culls dead-end routes up to the limits of memory.

The (golfed) code
On to the code (get the ungolfed version here or here):
import java.util.*;public class ZombieHordeMin{int a=100,b,m,n,i,j,z,y,D=0,R,Z,N;int p[][][];Scanner in;Runtime rt;int[][]r;int pp;int dd;int[][]bdr;int ww;int[][]bwr;int[][]faf;int ff;boolean ffOn;public static void main(String[]a){(new ZombieHordeMin()).pR();}ZombieHordeMin(){in=new Scanner(System.in);rt=Runtime.getRuntime();m=in.nextInt();N=in.nextInt();p=new int[m+1][m+1][N+1];int[]o=new int[m+1];for(b=0;b<N;b++){i=in.nextInt();j=in.nextInt();z=in.nextInt();o[i]++;o[j]++;D=(o[i]>D?o[i]:D);p[i][j][++p[i][j][0]]=z;if(i!=j)p[j][i][++p[j][i][0]]=z;D=(o[j]>D?o[j]:D);}m++;}void pR(){r=new int[5000][m+3];r[0][0]=a;Arrays.fill(r[0],1,m,1);r[0][m]=1;r[0][m+1]=0;r[0][m+2]=0;ww=-1;pp=dd=0;pR(5000);}void pR(int aMD){faf=new int[D][];ff=0;ffOn=true;for(int mD=1;mD<=aMD;mD++){System.out.printf("Checking len %d\n",mD);int k=ffR(0,mD);if(ww>-1){System.out.printf("%d x\n",ww+1);for(int win=0;win<=ww;win++)System.out.printf(" %d:%d,%d-%d",win,bwr[win][0],bwr[win][1],bwr[win][2]);System.out.println();break;}if(k>0){System.out.printf("dead max %d kills, %d steps\n",pp,dd+1);for(int die=0;die<=dd;die++)System.out.printf(" %d:%d,%d-%d",die,bdr[die][0],bdr[die][1],bdr[die][2]);System.out.println();break;}}}int ffR(int dP,int mD){if(ff==0)return pR(dP,mD);int kk=0;int fm=ff;if(ffOn&&D*fm>rt.maxMemory()/(faf[0][0]*8+12))ffOn=false;int[][]fmv=faf;if(ffOn){faf=new int[D*fm][];ff=0;}for(int df=0;df<fm;df++){dS(fmv[df]);kk+=pR(fmv[df][0],mD);}fmv=null;rt.gc();return kk==fm?1:0;}int pR(int dP,int mD){if(dP==mD)return 0;int rT=0;int dC=0;int src=r[dP][m];int sa=r[dP][0];for(int dt=1;dt<m;dt++){for(int rut=1;rut<=p[src][dt][0];rut++){rT++;r[dP+1][0]=sa-p[src][dt][rut]+r[dP][dt];for(int cp=1;cp<m;cp++)r[dP+1][cp]=(dt==cp?1:r[dP][cp]+1);r[dP+1][m]=dt;r[dP+1][m+1]=rut;r[dP+1][m+2]=r[dP][m+2]+p[src][dt][rut];if(sa-p[src][dt][rut]<1){dC++;if(pp<r[dP][m+2]+sa){pp=r[dP][m+2]+sa;dd=dP+1;bdr=new int[dP+2][3];for(int cp=0;cp<=dP+1;cp++){bdr[cp][0]=r[cp][m];bdr[cp][1]=r[cp][m+1];bdr[cp][2]=r[cp][0];}}}else{for(int chk=0;chk<=dP;chk++){if(r[chk][m]==dt){int fR=chk+1;for(int cM=0;cM<m+3;cM++)r[dP+2][cM]=r[dP+1][cM];for(;fR<=dP+1;fR++){r[dP+2][0]=r[dP+2][0]-p[r[dP+2][m]][r[fR][m]][r[fR][m+1]]+r[dP+2][r[fR][m]];for(int cp=1;cp<m;cp++)r[dP+2][cp]=(r[fR][m]==cp?1:r[dP+2][cp]+1);r[dP+2][m+2]=r[dP+2][m+2]+p[r[dP+2][m]][r[fR][m]][r[fR][m+1]];r[dP+2][m]=r[fR][m];r[dP+2][m+1]=r[fR][m+1];}if(fR==dP+2&&r[dP+2][0]>=r[dP+1][0]){ww=dP+1;bwr=new int[dP+2][3];for(int cp=0;cp<dP+2;cp++){bwr[cp][0]=r[cp][m];bwr[cp][1]=r[cp][m+1];bwr[cp][2]=r[cp][0];}return 0;}}}dC+=pR(dP+1,mD);if(ww>-1)return 0;}for(int cp=0;cp<m+3;cp++)r[dP+1][cp]=0;}}if(rT==dC)return 1;else{if(ffOn&&dP==mD-1)faf[ff++]=cP(dP);return 0;}}int[]cP(int dP){int[]cmp=new int[dP*2+3];cmp[0]=dP;cmp[dP*2+1]=r[dP][0];cmp[dP*2+2]=r[dP][m+2];for(int zip=1;zip<=dP;zip++){cmp[zip]=r[zip][m];cmp[dP+zip]=r[zip][m+1];}return cmp;}void dS(int[]cmp){int[]lv=new int[m];int dP=cmp[0];r[dP][0]=cmp[dP*2+1];r[dP][m+2]=cmp[dP*2+2];r[0][0]=100;r[0][m]=1;for(int dp=1;dp<=dP;dp++){r[dp][m]=cmp[dp];r[dp][m+1]=cmp[dP+dp];r[dp-1][cmp[dp]]=dp-lv[cmp[dp]];r[dp][m+2]=r[dp-1][m+2]+p[r[dp-1][m]][cmp[dp]][cmp[dP+dp]];r[dp][0]=r[dp-1][0]+r[dp-1][cmp[dp]]-p[r[dp-1][m]][cmp[dp]][cmp[dP+dp]];lv[cmp[dp]]=dp;}for(int am=1;am<m;am++)r[dP][am]=(am==cmp[dP]?1:dP-lv[am]+1);}}

Get the code from github here, to track any changes I make. Here are some other maps I used.
Output example
Example output for reference solution:
    $ java -d64 -Xmx3G ZombieHordeMin > reference_route_corrected_min.out
    5 6 1 2 4 2 3 4 3 1 4 2 4 10 2 5 10 1 1 50
    Checking len 1
    Checking len 2
    Checking len 3
    Checking len 4
    Checking len 5
    Checking len 6
    Checking len 7
    Checking len 8
    Checking len 9
    Checking len 10
    Checking len 11
    Checking len 12
    Checking len 13
    Checking len 14
    Checking len 15
    Checking len 16
    Checking len 17
    Checking len 18
    Checking len 19
    Checking len 20
    Checking len 21
    Checking len 22
    Checking len 23
    Checking len 24
    25 x
     0:1,0-100 1:3,1-97 2:1,1-95 3:2,1-94 4:5,1-88 5:2,1-80 6:4,1-76 7:2,1-68 8:1,1-70 9:2,1-68 10:1,1-66 11:2,1-64 12:1,1-62 13:2,1-60 14:1,1-58 15:2,1-56 16:1,1-54 17:2,1-52 18:1,1-50 19:2,1-48 20:1,1-46 21:2,1-44 22:1,1-42 23:2,1-40 24:1,1-38

Read the route output like this: step:source,route-to-get-here-ammo. So in the above solution, you would read it as:

At step 0, at outpost 1 with ammo 100.
At step 1, use route 1 to get to outpost 3 with ending ammo 97
At step 2, use route 1 to get to outpost 1 with ending ammo 95
...

Closing notes
So, I hope I've made my solution harder to beat, but PLEASE TRY! Use it against me, add in some parallel processing, better graph theory, etc. A couple of things I figure could improve this approach:

aggressively "reduce" loops to cut out needless retread as the algorithm progresses.

An example: in the example problem, consider the loops 1-2-3 and other permutations as "one step", so that we can make our way to end-cycle more quickly.
E.g. if you are at node 1, you can either (a) go to 2, (b) go to 1, (c) go through 1-2-3 as one step and so on. This would allow a solved to fold depth into breadth, increasing the number of routes at a particular depth but greatly speeding time-to-solution for long cycles.

cull dead routes. My current solution doesn't "remember" that a particular route is dead-ended, and has to rediscover it every time. It would be better to keep track of the earliest moment in a route that death is certain, and never progress beyond it. did this...
if careful, you could apply the dead route culling as a sub-route cull. By example, if 1-2-3-4 always results in death, and the solver is about to test the route 1-3-1-2-3-4, it should immediately stop descending that path as it is guaranteed to end in disappointment. It would still be possible to calculate # of kills, with some careful math.
Any other solution that trades memory for time, or allows aggressive avoidance of following dead-end routes. did this too!


Encode a program with the fewest distinct characters possible The goal is to write a program that encodes an other program (input) with the fewest character possible.
Scoring

The score is equal to the different number of characters needed for the output.
Lower score is better.

Rules

No target languages with a limited set of commands. (No Brainf**k, Whitespace etc)
Edit: I mean at least 26 significant characters, A doesn't change the way a brainf**k program operates, so you can't count this character. Same applies to whitespace.
The target language must exist at the time where this question is written.
You have to include a small explanation how you achieve your score.
The input program is valid.
The encoded program must be a valid program in the same language as the input.
The encoded program must do the same job as the original program.
Your encoder must work for every valid program in that language.
Include some sample input and output.

Notes

The encoder might be written in any language, not only in the language it targets.
This is not code-golf, readable programs are encouraged.
The great goal is to see how many different characters are needed to write anything in that language. I disallowed BF etc because there would be no challenge.
This was inspired by Print a string in as few distinct characters as possible, you could take it as metagolf for that question.

Example
In Java, you can use \uXXXX instead other characters. A valid entry encodes every character from the input this way. This would have a score of 18. (\ 0-9a-f)
Code in Tcl, encodes a Java program:
set res {}
foreach char [split [read stdin] {}] {
    append res [format \\u%04x [scan $char %c]]
}
puts $res


In what base this string equals the following decimal value? your task is...

Given a string x and a positive integer y, to determine whether there is a positive integer b and an injective mapping from the distinct characters in x to the digits of base b which permit us to interpret x as an integer equal to y.

details:

   If there is more than one base which works, you don't have to output all of them, just one.
   The answer should be a function for those languages that support it, otherwise, code snippet
   Your program should accept 0-9 and (a-z or A-Z) which are 36 characters. You don't have to care about kanji or snowman.
   (e.g. 6 doesn't have to mean 6, it's just a symbol. basically you get a number in unknown base with unknown symbols and you have to substitute them to get y)

for example:

   (foo,4) returns either 2 or 3 because

   f=1, o=0 -> 1002=410
   f=0, o=1 -> 0113=410

   (10,10) any integer greater than 4 but not 9 because

   1=2, 0=0 -> 205=1010
   1=1, 0=4 -> 146=1010
   1=1, 0=3 -> 137=1010
   1=1, 0=2 -> 128=1010
   1=1, 0=0 -> 1010=1010
   1=0, 0=10 -> 0111=1010
   above base 10, 1=0, 0=10 -> 01x=1010 for every x > 10

   (611,1) returns 0 which means there is no possible base for 611 meaning 110

bonus:

   You have to output every possible base, not just one. I know it can be infinite,
   indicate it somehow. 2,3,... for example.
   Answers with bonus gain a 0.7 multiplier.

Mathematica, 183 bytes * 0.7 = 128.1

f[s_,n_]:=(For[i=2,1>0,++i,d=(l=Length)@(g=IntegerDigits)[n,i];Which[Count[c=Characters@s,c[[-1]]]>1&&d==1,Return@0,l@c>=d&&And@@Unequal@@@(t=Thread)@Union@t@{g[n,i,l@c],c},Print@i]])

Less golf

f[s_, n_] := (
  For[i = 2, 1 > 0, ++i,
   d = (l = Length)@(g = IntegerDigits)[n, i];
   Which[
    Count[c = Characters@s, c[[-1]]] > 1 && d == 1,
    Return@0,
    l@c >= d && And @@
      Unequal @@@
       (t = Thread)@
        Union@
         t@
          {g[n, i, l@c], c},
    Print@i
    ]
   ]
  )

I don't actually recommend running this, because quick and infinite output is a bit tricky to abort in Mathematica sometimes. To get only the first result, change Print to Result (which is even a character longer). If you're using the version as is, a final 0 output will indicate that no further bases will be found (similar to the returning case).

The first part of the Which simply aborts the loop when no base can possibly be found (it might be possible to shorten this). The second loop is the interesting check. These are the steps taken:

Convert n to digits in the current base (Mathematica can handle arbitrarily large bases.)
Zip those digits up with the characters, basically creating the mapping at each position.
Union throws out duplicates - these are uninteresting because they just point to a consistent mapping.
Transpose the mapping, so I get a list of digits and a list of characters.
If there are no duplicates in either, we have an injective mapping and print the base.


Shortest code to sort walking points The challenge is to, given a list of points, sort in a way that, when they are connected in this order, they never intersect.

Input format (read from stdin):

X Y
1 2
3 4
5 6
...

Output should be the same as input, but sorted.

Rules:

You can start from any point.
The last point must be same as first one, making a close circuit.
It should be  done considering the Cartesian grid.
You may assume that the input points do not all lie on a single line.
The endpoints of each line do not count as intersecting.

For further help:

Mathematica - 20 30 chars

Just the sorting part

SortBy[%, ArcTan @@ # &]

Whole testing code, that consists of generating 100 random points and plotting the line

RandomReal[{-10, 10}, {100, 2}];
SortBy[%, ArcTan @@ # &];
ListPlot@% /.
 Point[p_] :> {EdgeForm[Dashed], FaceForm[White], Polygon[p],
   PointSize -> Large, Point[p]}

+26 chars

If you demand proper input/ouput, then

"0 0
 4 4
 0 4
 4 0";
Grid@SortBy[%~ImportString~"Table", ArcTan @@ # &]

+2 chars

Just adding N@

Grid@SortBy[%~ImportString~"Table", ArcTan @@ N @ # &]

because above code works only on real numbers and not on integers due to Mathematica's weird behavior when sorting symbolic expressions

N@Sort[{ArcTan[1], ArcTan[-2]}]
Sort[N@{ArcTan[1], ArcTan[-2]}]

{0.785398, -1.10715}
{-1.10715, 0.785398}

EDIT I just realized if the points are not around the origin it won't work, so it also requires shift to the center of points

SortBy[%, ArcTan @@ N[# - Mean@%] &]


Write a mathematical function whose result is "hello world" Write a mathematical function that results in an integer representation of "hello world"

For example "hello world" in hex is 68656c6c6f20776f726c64 so the goal will be to write a mathematical program that results in a number representing "hello world".

Here is a example of a possible solution using python:

print(2*2*3*59*61*97*416510539*72330832279)==int("68656c6c6f20776f726c64", 16)

Any type of mathematical equations could be used, such as: powers, series, factorials, and other mathematical operations.

The rules:

You may select your own way to encode/represent "hello world" as an integer. Hash functions are also allowed
Mathematical libraries (e.g. numpy, GMP) are allowed.
The intention is to focus on the mathematics part

I'll do better than just printing it, I'll print it infinitely many times!

The rational number

1767707668033969 / 3656158440062975

returns the following base-36 expansion:

0.helloworldhelloworldhelloworldhelloworldhelloworld...

Try it out! (Wolfram Alpha)

Or, if you want a more subliminal message, try:

2399843759207982499621172523113947162810942763812298565948669
/ 1357602166130257152481187563160405662935023615

Which returns (again in base 36):

helloworld.helpimtrappedinanumberfactoryhelpimtrappedinanumberfactoryhelpimtrappedinanumberfactory...

If your program worked with only integers, you'd never see the fractional part.


Is it dark outside? Draw a sun map! Our closest star, the sun, is quite fidgety. The times it rises and sets depend on where you are, and whether it is winter or not.

We would like to be able to deduce if the sun is shining outside without having to leave the comforts of our basements - which is why we need an up-to-date sun map (a.k.a. daylight map). You are the one to write a program that generates just that!

Rules: Your program should output an image (in a known format) or an ASCII art representation of our planet, showing (an approximation of) which parts are currently lit by the sun. Your program must be original and self-contained: you are not allowed to copy, use, include or call any code except your programming language's standard libraries.

If you still don't have a clue what I'm talking about, here's an example from Wikipedia:

This is a popularity contest. You should note in your answer which of the following you're trying to achieve (multiple choices possible):

Correctness. Note that the rules say 'an approximation of' - the better your approximation, the more points in this category. You can check your implementation against Wolfram Alpha's, Time and Date's or die.net's.
Functionality. For example, what about interactivity? Marking specific locations? Mapping other planets?
Aesthetics. Drawing continents? Bonus points. Textured continents? Bonus points. On a 3D earth? With clouds? Stars? Correct stars? Massive bonus points. And so on.
Using uncommon, old, or just plain wrong technology. Sure, you could whip this up in Mathematica, but have you considered using m4? SQL? Forth? x86 assembly?
Fun. Want to use a Dymaxion-projection map? Go ahead!
Short code. This is the Code Golf SE, after all.

Have fun!


Find the original string, without the repetition without the repetition in the middle Sometimes it happens that while typing a sentence, I am distracted and I end up typing the same couple of words twice couple of words twice in succession.

To make sure make sure other people are not bothered by this, your task is to write a program that resolves this problem!

Task

Given an input string (if it matters for your language, you may assume ASCII-only input that does not contain linefeeds.) str, that contains somewhere in its middle a substring that occurs twice in immediate succession, return the string with one instance of this substring removed.

In the case of multiple possibilities, return the shortest answer possible (that is, pick the longest consecutive repeating substring and remove that one).

In the case of multiple, equally-long consecutive repeating substrings, remove the first (that is, the first one encountered when reading through the string from front to back) one.

You may assume that the input is correct (i.e. always contains a consecutive repeating substring), which might help to golf it down.

Examples

Input: hello hello world -> Output: hello world.
Input: foofoo -> Output: foo. (So: Yes, the string might only consist of the repeating part twice).
Input: aaaaa -> Output: aaa, as the longest repeating consecutive substring is here aa.
Input: Slartibartfast -> This is not a valid input, as it does not contain a consecutive repeating substring, so you do not need to handle this case.
Input: the few the bar -> This is another invalid input, since the repeating part should immediately follow the original part. In this case, the and the are separated by something else in-between, so this input is invalid.
Input: ababcbc -> Output: abcbc. The two possible longest consecutive repeating substrings are ab and bc. As ab is encountered earlier in the string, this one is the correct answer.
Input: Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo. Output: Buffalo buffalo buffalo buffalo Buffalo buffalo. (The performed replacement should be case-sensitive).
Input: Sometimes it happens that while typing a sentence, I am distracted and I end up typing the same couple of words twice couple of words twice in succession. ->  Output: Sometimes it happens that while typing a sentence, I am distracted and I end up typing the same couple of words twice in succession.. Only the longest consecutive repeating substring is removed.

Your code should be as short as possible, since this is code-golf, so the shortest answer in bytes wins. Good luck!

Perl 6, 40 bytes

{.subst: m:ex/(.*))>$0/.max(*.chars),''}

Try it

{
  .subst:             # substitute

    m                 # match
    :exhaustive
    /
      ( .* )          # any number of chars

      )>              # don't include the following in what is returned

      $0              # the first match again
    /.max( *.chars ), # find the first longest submatch

    ''                # substitute it with nothing
}


Make a directory tree Imagine for a second that you can compose a tree out of dots.

       .
      ...
     .....
    .......
   .........
  ...........
 .............
...............
      ...
      ...

This tree is 13 dots tall.

Now imagine for a second that your filesystem looked like these dots. Your task in this challenge is to make a tree out of folders.

The Challenge

Given an input integer (let's call it n), make a tree out of subdirectories.

In each tree, you should start with a folder called 1.
In that folder, put the folders 1, 2, and 3.
In every level of folder thereon until n-3, in folder 1 of this level of the tree, there should be a folder labelled 1 and 2. In folder 2 of this level of the tree, there should be a folder called 3, in folder 3, a folder called called 4, and so on until the last folder (the integer this folder is called, we'll call k), in which there should be a folder called k and one called k+1.
At level n-3, however, all of the subdirectories but the middle three folders should be replaced with a file with the name that the subdirectories would have had. The middle three subdirectories should remain as subdirectories.
These three subdirectories should contain a folder called 1, 2, or 3 with respect to the order of these directories' name.
These are followed by a layer of files where 1 is in folder 1, 2 is in folder 2, and 3 is in folder three.

The example shown at the top of this question is represented below in folder form.

This would be n = 13.

Rules

You may use builtins for folder creation, but not for subdirectory creation.
All other standard loopholes apply.
You must support past n=5, but do not have to support greater than n=30.


Make me an upside-down Christmas tree! Challenge

We all know about normal Christmas trees - but how about an upside-down Christmas tree! This is a fairly easy, Christmas themed challenge. The objective of this challenge is to make me an ASCII upside-down Christmas tree. Here are the rules for this challenge:

Accept an odd, positive integer. You can assume it will always be between 7 and 51.
The base of the tree will be made of the characters:

___
\ /
 |

The top of the tree (the star), will be made up of a single *.
Each line of the tree will be constructed using the format <?> where ? is any number of -s. For example, if making a line of length 5, the line should be <--->. Or if making a line of length 8, the line should be <------>.
Here is how the body of the tree should be constructed:

Take the odd number n given as input, and create a line of the tree that length.
Subtract 4 from n and create a line of the tree that length.
Subtract 2 from n and create a line of the tree that length.
Decrement n by 2. After that, unless n equals 5, go back to step 2.

The base (see step 2.) the star (see step 3.) and each line of the tree (see steps 4. and 5.) should all be centered using the original odd number input (see step 1.) as the maximum width.

Examples/Test Cases

odd number inputed: 7
  ___
  \ /
   |
<----->      line length -> 7
  <->        line length -> 7 - 4 = 3
 <--->       line length -> 7 - 2 = 5
   *

odd number inputed: 13
     ___
     \ /
      |
<----------->      line length -> 13
  <------->        line length -> 13 - 4 = 9
 <--------->       line length -> 13 - 2 = 11
   <----->         line length -> 11 - 4 = 7
  <------->        line length -> 11 - 2 = 9
    <--->          line length -> 9 - 4 = 5
   <----->         line length -> 9 - 2 = 7
     <->           line length -> 7 - 4 = 3
    <--->          line length -> 7 - 2 = 5
      *

odd number inputed: 9
   ___
   \ /
    |
<------->      line length -> 9
  <--->        line length -> 9 - 4 = 5
 <----->       line length -> 9 - 2 = 7
   <->         line length -> 7 - 4 = 3
  <--->        line length -> 7 - 2 = 5
    *

odd number inputed: 17
       ___
       \ /
        |
<--------------->      line length -> 17
  <----------->        line length -> 17 - 4 = 13
 <------------->       line length -> 17 - 2 = 15
   <--------->         line length -> 15 - 4 = 11
  <----------->        line length -> 15 - 2 = 13
    <------->          line length -> 13 - 4 = 9
   <--------->         line length -> 13 - 2 = 11
     <----->           line length -> 11 - 4 = 7
    <------->          line length -> 11 - 2 = 9
      <--->            line length -> 9 - 4 = 5
     <----->           line length -> 9 - 2 = 7
       <->             line length -> 7 - 4 = 3
      <--->            line length -> 7 - 2 = 5
        *

Rules

Standard loopholes apply.
This is code-golf, so the shortest answer in bytes wins!

Python 3, 127 121 105 103 100 98 bytes

This is an unnamed lambda function which returns a list of lines:

lambda o:[s.center(o)for s in['___','\ /','|',*[f'<{"-"*(o-i+2-i%2*3)}>'for i in range(4,o)],'*']]

Try it online!

The main part of this answer is (o-i+2-i%2*3), which works out the number of dashes to have on a line. The rest of the answer is simply converting this into the desired ASCII-art.

Many thanks to Mr. Xcoder, for shaving 6 bytes, and discussing golfs with me in chat.

Thanks also to Lynn for noticing that 3*(i%2) can be i%2*3, 2 bytes shorter!


QR Codes... and all that Jazz! This is going to be relatively challenging code-golf challenge.

Input: Any URL, must have the protocol attached, e.g. http://codegolf.stackexchange.com (which will be our test case)

Output: A generated QR Code that represents this URL, which, when scanned by a smart device will take you to that URL on the smart device's browser.

Rules for this Code-Golf

As usual, smallest code wins.
No external web resources, libraries or plugins to generate the code for you. Your code must calculate the QR code image.
Output can be presented by an image, generated by HTML5/CSS3, or even using appropriate Unicode blocks, or if your platform's ASCII has it available, through ASCII characters that can form the QR code (this last one is directed at Commodore 64 Basic, Amiga QBasic, Amstrad Basic, etc users), but it must generate a QR code output such that I can scan the code.
Entries of the code must be followed with the generated output, either by a screen shot of the output after executing your code, or with a link showing the output (whichever suits the situation best)
You are to test your code with the URL "http://codegolf.stackexchange.com", and report the output in accordance to Rules 3 to 4.
You are to also test your code with a URL of your choice, and report the output in accordance to Rules 3 to 4.

References:

1) http://en.wikiversity.org/wiki/Reed%E2%80%93Solomon_codes_for_coders

2) http://www.pclviewer.com/rs2/calculator.html

3) http://en.wikipedia.org/wiki/Reed%E2%80%93Solomon_error_correction

4) http://en.wikipedia.org/wiki/QR_code

5) http://www.qrstuff.com/ for inspiration... ;)

Python 3: 974 chars [nb]
Further beat with the ugly stick, see notebook on GH-Gist. Python 3 has built-in ASCII-85 encoding, which helps with the zipped saus. 3's more advanced built-in compression algorithms (LZMA) don't seem to work well with such small things.
Zipping is very fickle about changing characters around, was almost tempted to write something that would randomly try different 1-letter names for variables to minimize the zipped size.
Python 2: 1420 1356 1085 1077 characters

I read the first argument passed when called, which can be a string up to 106-ish characters long. The output is always a version 5-L QR code and mask 4 which means it's 37x37 modules large and can only handle ~5% damage.
The program's only dependencies are numpy (array manipulations) and matplotlib (display only); all Reed-Solomon encoding, data packing, and module layout is handled within the provided code.  For RS, I basically robbed the Wikiversity functions...it's still kind of a black-box for me.  Learned a ton about QR in any event.
Here's the code before I beat it with the ugly stick:
import sys
import numpy as np
import matplotlib.pyplot as plt
# version 5-L ! = 108 data code words (bytes), 106 after metadata/packing

### RS code stolen from https://en.wikiversity.org/wiki/Reed%E2%80%93Solomon_codes_for_coders#RS_generator_polynomial
gf_exp = [1] + [0] * 511
gf_log = [0] * 256
x = 1
for i in range(1,255):
    x <<= 1
    if x & 0x100:
        x ^= 0x11d
    gf_exp[i] = x
    gf_log[x] = i
for i in range(255,512):
    gf_exp[i] = gf_exp[i-255]

def gf_mul(x,y):
    if x==0 or y==0:
        return 0
    return gf_exp[gf_log[x] + gf_log[y]]

def main():
    s = sys.argv[1]

    version = 5
    mode = 4 # byte mode
    dim = 17 + 4 * version
    datamatrix = 0.5 * np.ones((dim, dim))
    nsym = 26

    # PACK
    msg = [mode * 16, len(s) * 16] + [ord(c) << 4 for c in s]
    for i in range(1, len(msg)):
        msg[i-1] += msg[i] // 256
        msg[i] = msg[i] % 256

    pad = [236, 17]
    msg = (msg + pad * 54)[:108]

    # MAGIC (encoding)
    gen = [1]
    for i in range(0, nsym):
        q = [1, gf_exp[i]]
        r = [0] * (len(gen)+len(q)-1)
        for j in range(0, len(q)):
            for i in range(0, len(gen)):
                r[i+j] ^= gf_mul(gen[i], q[j])
        gen = r
    msg_enc = [0] * (len(msg) + nsym)
    for i in range(0, len(msg)):
        msg_enc[i] = msg[i]
    for i in range(0, len(msg)):
        coef = msg_enc[i]
        if coef != 0:
            for j in range(0, len(gen)):
                msg_enc[i+j] ^= gf_mul(gen[j], coef)
    for i in range(0, len(msg)):
        msg_enc[i] = msg[i]

    # PATTERN
    # position marks
    for _ in range(3):
        datamatrix = np.rot90(datamatrix)
        for i in range(4):
            datamatrix[max(0, i-1):8-i, max(0, i-1):8-i] = i%2
    datamatrix = np.rot90(datamatrix.T)

    # alignment
    for i in range(3):
        datamatrix[28+i:33-i, 28+i:33-i] = (i+1)%2

    # timing
    for i in range(7, dim-7):
        datamatrix[i, 6] = datamatrix[6, i] = (i+1)%2

    # the "dark module"
    datamatrix[dim-8, 8] = 1

    # FORMAT INFO
    L4 = '110011000101111' # Low/Mask4
    ptr_ul = np.array([8, -1])
    steps_ul = [0, 1] * 8 + [-1, 0] * 7
    steps_ul[13] = 2 # hop over vertical timing
    steps_ul[18] = -2 # then horizontal

    ptr_x = np.array([dim, 8])
    steps_x = [-1, 0] * 7 + [15-dim, dim-16] + [0, 1] * 7

    for bit, step_ul, step_x in zip(L4, np.array(steps_ul).reshape(-1,2), np.array(steps_x).reshape(-1,2)):
        ptr_ul += step_ul
        ptr_x += step_x
        datamatrix[tuple(ptr_ul)] = int(bit)
        datamatrix[tuple(ptr_x)] = int(bit)

    # FILL
    dmask = datamatrix == 0.5

    cols = (dim-1)/2
    cursor = np.array([dim-1, dim]) # starting off the matrix
    up_col = [-1, 1, 0, -1] * dim
    down_col = [1, 1, 0, -1] * dim
    steps = ([0, -1] + up_col[2:] + [0, -1] + down_col[2:]) * (cols/2)
    steps = np.array(steps).reshape(-1, 2)
    steps = iter(steps)

    # bit-ify everything
    msg_enc = ''.join('{:08b}'.format(x) for x in msg_enc) + '0' * 7 # 7 0's are for padding
    for bit in msg_enc:
        collision = 'maybe'
        while collision:
            cursor += steps.next()
            # skip vertical timing
            if cursor[1] == 6:
                cursor[1] = 5
            collision = not dmask[tuple(cursor)]
        datamatrix[tuple(cursor)] = int(bit)

    # COOK
    mask4 = lambda i, j: (i//2 + j//3)%2 == 0
    for i in range(dim):
        for j in range(dim):
            if dmask[i, j]:
                datamatrix[i, j] = int(datamatrix[i, j]) ^ (1 if mask4(i, j) else 0)

    # THE PRESTIGE
    plt.figure(facecolor='white')
    plt.imshow(datamatrix, cmap=plt.cm.gray_r, interpolation='nearest')
    plt.axis('off')
    plt.show()

if __name__ == '__main__':
    main()

After:
import sys
from pylab import*
n=range
l=len
E=[1]+[0]*511
L=[0]*256
x=1
for i in n(1,255):
 x<<=1
 if x&256:x^=285
 E[i]=x;L[x]=i
for i in n(255,512):E[i]=E[i-255]
def f(x,y):
 if x*y==0:return 0
 return E[L[x]+L[y]]
m=sys.argv[1]
m=[ord(c)*16 for c in'\4'+chr(l(m))+m]
for i in n(1,l(m)):m[i-1]+=m[i]/256;m[i]=m[i]%256
m=(m+[236,17]*54)[:108]
g=[1]
for i in n(26):
 q=[1,E[i]]
 r=[0]*(l(g)+l(q)-1)
 for j in n(l(q)):
    for i in n(l(g)):r[i+j]^=f(g[i],q[j])
 g=r
e=[0]*134
for i in n(108):
 e[i]=m[i]
for i in n(108):
 c=e[i]
 if c:
    for j in n(l(g)):e[i+j]^=f(g[j],c)
for i in n(108):e[i]=m[i]
m=.1*ones((37,)*2)
for _ in n(3):
 m=rot90(m)
 for i in n(4):m[max(0,i-1):8-i,max(0,i-1):8-i]=i%2
m=rot90(m.T)
for i in n(3):m[28+i:33-i,28+i:33-i]=(i+1)%2
for i in n(7,30):m[i,6]=m[6,i]=(i+1)%2
m[29,8]=1
a=array
t=tuple
g=int
r=lambda x:iter(a(x).reshape(-1,2))
p=a([8,-1])
s=[0,1]*8+[-1,0]*7
s[13]=2
s[18]=-2
P=a([37,8])
S=[-1,0]*7+[-22,21]+[0,1]*7
for b,q,Q in zip(bin(32170)[2:],r(s),r(S)):p+=q;P+=Q;m[t(p)]=g(b);m[t(P)]=g(b)
D=m==0.1
c=a([36,37])
s=r(([0,-1]+([-1,1,0,-1]*37)[2:]+[0,-1]+([1,1,0,-1]*37)[2:])*9)
for b in ''.join('{:08b}'.format(x) for x in e):
 k=3
 while k:
    c+=s.next()
    if c[1]==6:c[1]=5
    k=not D[t(c)]
 m[t(c)]=g(b)
a=n(37)
for i in a:
 for j in a:
    if D[i,j]:m[i,j]=g(m[i,j])^(j%3==0)
imshow(m,cmap=cm.gray_r);show()

(relying on a tab to count as 4/8/whatever number of spaces >= 2., not sure how well it will copy)
Because it's so long, we can zip it (saw someone do this somewhere else, forgot who though :( ) to save some more characters, bringing the total down to 1085 1077 because pylab is filthy:
import zlib,base64
exec zlib.decompress(base64.b64decode('eJxtU0tzmzAQvvSkX6FLaglkyiM2hHRvyS2HZNobo3QwwY6IBVjQFrfT/96V3KR4Wg5I+/6+3ZXSfWdGOhwHsjWdpv1xX26oclqPtGDKdleTPezrltxCEUm/CKW3iiJyB/YWr9ZkgohsO0MVVS1tWSTi1YrnhE4fP6KFqi2d3qNfPj1CnK0IvS2UhOn6rpgkqHkkxolVFPPceeBviRpJnuot3bJJHG1Sm807AoS5qcevpqUhoX9ut4VN6d8VRymJBuQUlGb3DUGjVHTmiVXci9bUVqyw4uLdwq+eDdszzbmv5TkJp801gkDSgKf8gCSu7cVJF5a6Bqb9Ik7WIkqxLZe8yKMwk2RnW3VGbW3BH1AtLDmJoF3/sPiO+3t24MuIEwetOUVYnY3Bb5bHuvPcFMpv5CNs2Q6TiUPRSAzegSG1yxoll2dkwsxmql+h/8dWgbW69lY5favazKvWs6qNFBX/J8/fChqCyOvaemAsSQX34pPzl5NzYktqMN14FWKbyZzhpW26LicWCmw9z7OlEucibs1FTN7Cg89nQBIbH2e+ypMEQ99uEpjyI46RM+dUJKEbslhb4Gsxc8MsVyKTuMIllMaURzLC+LXf1zhd1Y7EwL7Um6eSTrkaa8NKNvHA1MNz2ddsia+Ac9JDyYpM4ApxMuBoRCS9zC/QilNKyVBEiYTYnlhoGZN7648Ny9D/E7z6YUAci9g9PpshdRQ24iAeLI0fqmcbhczjKA15EedSGDZw/H3CqfU+HK7vfXjA1R1ZzyXs2IY74f6PQG5A44sKIlK5+muRpA6wYQwr2gfALBZEYwUvSV0V/832j4l7V6ehbCzAxSJoOgS4+JmH2ebXIkCLLkfslxv8ZH1quxIvkBD6/Vnta/pyWv3KhyFo62lk3Ml2P/FpAaxzd66c9gXabqQ3SKniuMT6dDlxKwE7k85WpMxn76zMX9Pe4BI00u1CY0NPF/7ImosEm8OJ0sNz951pUemyh0oHO9yJL4ZfOzX/DQ2mdSs='))

If you replace the last line with the following (it adds 62 chars), you get nearly-perfect output, but the other still scans, so whatever.
figure(facecolor='white');imshow(m,cmap=cm.gray_r,interpolation='nearest');axis('off');show()


Advent Challenge 6: Transport Dock Relabeling! << Prev Next >>

Thanks to the PPCG community, Santa managed to sort his presents into the correct order for moving into the transportation dock. Unfortunately, the transportation dock signs are broken so he doesn't know where to put all the presents! The presents are all grouped together and not by their ranges, which Santa admits would have been a better idea.

Now, given the presents in the sorted order, determine all possible minimal range configurations that would result in the present being in the correct order. That is, find all minimal range configurations such that sorting the presents according to the algorithm in Challenge #5 would not change the order.

Challenge

A minimal range configuration is a list of ranges such that the ranges are each as small as possible. That is, if a range is designated to cover a specific subset of presents, then the minimum and maximum of the range must be the same as that of the subset. In other words, shrinking any range in the cover would cause it to no longer be a cover.

The challenge is to find all possible minimal range configurations that would apply to the present sizes. Let's take an example: [3, 1, 2, 5, 4, 7, 6]

There is a trivial case, which is to take the range of the entire present configuration. In this case, [[1, 7]] would be a solution.

For examples with unique elements, another trivial case would be [[3], [1], [2], [5], [4], [7], [6]] (because the ranges don't need to be ordered).

For this example, we also see that [[1, 3], [4, 7]] and [[1, 3], [4, 5], [6, 7]] would work, as well as [[1, 3], [5], [4], [6, 7]] and [[1, 3], [4, 5], [7], [6]].

The final answer for [3, 1, 2, 5, 4, 7, 6] would be [[[3], [1], [2], [5], [4], [7], [6]], [[3], [1], [2], [5], [4], [6, 7]], [[3], [1], [2], [4, 5], [7], [6]], [[3], [1], [2], [4, 5], [6, 7]], [[3], [1], [2], [4, 7]], [[3], [1, 2], [5], [4], [7], [6]], [[3], [1, 2], [5], [4], [6, 7]], [[3], [1, 2], [4, 5], [7], [6]], [[3], [1, 2], [4, 5], [6, 7]], [[3], [1, 2], [4, 7]], [[1, 3], [5], [4], [7], [6]], [[1, 3], [5], [4], [6, 7]], [[1, 3], [4, 5], [7], [6]], [[1, 3], [4, 5], [6, 7]], [[1, 3], [4, 7]], [[1, 5], [7], [6]], [[1, 5], [6, 7]], [[1, 7]]].

Formatting Specifications

The input will be given as a flat list of positive integers within your language's reasonable supported number range in any reasonable format. The input may contain duplicate elements. The output should be given as a 3D list of positive integers in any reasonable format.

Each range in your output (which is at the second layer) can be represented either as [min, max], [num] if it's a single-value range, or as the entire range itself, but your output format must be consistent. Please specify if you wish to use a slightly different reasonable output format.

Duplicate values must be covered by a single range in the output; that is, no two ranges in the output may have any overlap.

Your solution may return the ranges in any order and this does not have to be deterministic.

Rules

Standard Loopholes Apply
This is code-golf so the shortest answer in bytes wins
No answer will be accepted

Test Case for a list with duplicate elements:

2 3 2 4 -> [[[2, 3], [4]], [[2, 4]]]

Reference Implementation

The header is the link.

Note: I drew inspiration for this challenge series from Advent Of Code. I have no affiliation with this site

You can see a list of all challenges in the series by looking at the 'Linked' section of the first challenge here.

Happy golfing!

Mathematica, 106 bytes

sSelect[MinMax/@s~TakeList~#&/@Join@@Permutations/@IntegerPartitions@Tr[1^s],Unequal@@Join@@Range@@@#&]

Try it online!

Martin saved 16 bytes


Abandon all squares, ye who divide me Definitions

A perfect square is an integer which can be expressed as the square of another integer. For example, 36 is a perfect square because 6^2 = 36.
A squarefree number is an integer which is not divisible by any perfect square, except by 1. For example, 10 is a squarefree number. However, 12 is not a squarefree number, because 12 is divisible by 4 and 4 is a perfect square.

Task

Given a positive integer n, output the largest squarefree number which divides n.

Testcases

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

Scoring

This is code-golf. Shortest answer in bytes wins.

Standard loopholes apply.

Reference

OEIS A007947

05AB1E, 2 bytes

fP

Try it online!

How it works

f   Implicitly take input and compute the integer's unique prime factors.
 P  Take the product.


Which side should I serve on? Introduction
In Tennis, the server alternates serving on the left side or the right side of the court every point, starting on the right. It is possible to figure out which side to serve on for that point just based on the score; if there have been an even number of points you serve on the right, and after an odd number of points, on the left. Scoring in tennis works as follows:
Points | Corresponding Call
       |
0      | Love
1      | 15
2      | 30
3      | 40

Once a player scores 4 points, they win the game. If the score is tied at 40-40, the call is "Deuce" rather than "40-40" or "40 all". At Deuce, the subsequent point is called as "Advantage [x]" or "Ad [x]" where x is the player who scored. If the opposite player scores next, the score returns to Deuce, but if the same player scores again, they win.
The Challenge
Your task is to write a function that takes the score and returns a truthy or falsey value. The input may be a string containing the call or a list containing the scores. Love, Deuce, and Ad must be strings but the rest of calls may be any numerical type as well. Deuce may be represented by singleton list containing "Deuce" or a list with "Deuce" and another value of your choice. You may choose which side corresponds to truthy and falsey, but you must specify which corresponds to which side in your answer. The scores will be separated by a hyphen, except in the case of Deuce wherein it will be simply "Deuce". For advantage, the score will be "Ad-40" or "40-Ad".
Winning
This is code golf, so the score is the number of bytes in your function and the answer with the lowest score wins. Standard loopholes are forbidden.
Test Cases
Love-Love | True
Love-15   | False
Love-30   | True
Love-40   | False
15-Love   | False
15-15     | True
15-30     | False
15-40     | True
30-Love   | True
30-15     | False
30-30     | True
30-40     | False
40-Love   | False
40-15     | True
40-30     | False
Deuce     | True
Ad-40     | False
40-Ad     | False

These test cases are exhaustive, i.e. that list represents every possible input and its corresponding output. I used True for right and False for left.

Retina 0.8.2, 7 bytes
M`4|5
1

Try it online! Link includes test cases. Outputs 0 for right and 1 for left. Explanation:
M`[45]

The number of 4s and 5s...
1

... must equal 1 if the serve is on the left.


Input number; Output line number Code Golf
Totally real backstory: I'm a contractor working on a website www.Sky.Net and one of our tasks it to create some self-aware program or something, I don't know I wasn't really listening to the boss. Anyways in an effort to make our code more self-aware we need IT to be able to know what code is on each line-number.

Challenge
Create a program or function that takes an input n and returns the code of said program or function on line n.

Rules
➊ Your program or function must be at least 4 lines long. Each line must be unique.
➋ You may assume the input will always be a positive integer greater than or equal to 1 and less than or equal to the number of lines in your program/function.
➌ The first line in your program/function is line 1, not line 0.
➍ You can not access the file that your program is on. (If someone has to ask "Isn't this technically breaking rule #4"; it probably is)
➎ Lines can-not be empty (this includes a space if spaces don't do anything in your language)
➏ Lines can-not be //comments (/* of any <!--style)

This is a quine-like challenge
This is code-golf, so the submission with the fewest bytes wins!

Vim, 7 bytes

1
2
3
4

Try it online!

As far as I can tell, this complies with all of the rules. In vim by default, the empty program prints out all of the input. Since

<N><CR>

Is a noop, nothing changes the input text, and since each input matches the desired output, this same approach works with any number of lines.


Build a rot32 encryptor Building a golfed rot13 encryptor is too easy because the letters are all the same order in the ASCII character space. Let's try a rot32 engine instead.

Your task is to build a function that takes a Base64 string as input and returns the same string but with each letter rotated 32 symbols from its original (in essence, with the first bit flipped).

The base64 encoding string to use for this problem is 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/ with a padding character of =. This is to prevent solutions that would otherwise use or import a built-in Base64 library where strings normally start with A instead of 0.

Example inputs and outputs:

> rot32("THE+QUICK+BROWN+FOX+JUMPS+OVER+THE+LAZY+DOG=")
nb8ukoc6eu5liqhu9irudogjmuip8lunb8uf4tsu7ia=

> rot32("NB8UKOC6EU5LIQHU9IRUDOGJMUIP8LUNB8UF4TSU7IA=")
h5Eoei6C8oBfckboFclo7iadgocjEfoh5Eo9AnmoDc4=

> rot32("Daisy++daisy++give+me+your+answer+true/I+/+m+half+crazy++all+for+the+love+of+you")
7GOY2uuJGOY2uuMO/KuSKu2U+XuGTY0KXuZX+KvcuvuSuNGRLuIXG32uuGRRuLUXuZNKuRU/KuULu2U+

The shortest program to do so in any language wins.

Bash / Unix shell, 29

tr 0-9a-zA-Z+/ w-zA-Z+/0-9a-v

Input from STDIN, output on STDOUT.


Regions of regular polygons Given a regular N-gon with all diagonals drawn, how many regions do the diagonals form?

For example, a regular triangle has exactly 1, a square has exactly 4, pentagon has exactly 11, and a hexagon has 24.

score is inversely proportional to number of bytes in solution
small fudge factors may be added to scores based on their runtime
the region surrounding the polygon does not count

Mathematica 118
Although  there are well-defined routines for computing the number of regions in a regular n-gon with all the diagonals drawn, they are quite cumbersome. I thought it might be fun to take an image processing approach: if we draw the n-gon with it's diagonals, would it be possible to count the regions from the drawn image (more precisely, from the rasterized and binarized representation of the image as an array)?
The following produces and processes an actual image of a polygon and determines the number of regions from the rasterized image.
Table[MorphologicalEulerNumber@Binarize@Rasterize@CompleteGraph[k, ImageSize->1200,EdgeStyle->Thickness[Large]],{k,3,14}]

{1, 3, 11, 24, 50, 80, 154, 220, 375, 444, 781, 952}

This is what might be referred to as an engineer's solution. It gets the job done, but only within some limited conditions. (And it's slow: the above code took 4.24 s to run.) The above routine works correctly up to and including a 14-Complete graph, shown below. I found this surprising, given that some of 952 regions are very difficult to see, even when the image is displayed at 1200 by 1200 pixels.
The picture below is the image before being rasterized and binarized.