Many programs, few characters Your task is to create many programs. The first outputs 1, the second outputs 2, etc. The higher you can go, the better!

However, all of these programs must be made the same list of characters. You can choose which characters to put in the list. Each program can only use a character as many times as it appears in the list.

For example, using the Python shell:

List of characters:  +122
-------
Program 1:      1
Program 2:      2
Program 3:      1+2
Program 4:      2+2   (2 appears twice in the list)

It is impossible to make a program which prints 5 without reusing the + character, so there are a total of 4 programs possible with this list. (Only consecutive numbers starting from 1 count. We therefore ignore other numbers we can make, like 12.)

Scoring

Let N be the number of programs.
Let S be the size of the shortest program, or 15, whichever is less.
Let L be the length of the list.

Your score is N / Γ((L-S)/5), where Γ is the gamma function.

In the example above, N is 4; S is 1; L is 4; the score is 4 / Γ((4-1)/5) = 2.686.

Highest score wins!

Below is a Stack Snippet to help calculate your score:

var g=7,C=[0.99999999999980993,676.5203681218851,-1259.1392167224028,771.32342877765313,-176.61502916214059,12.507343278686905,-0.13857109526572012,9.9843695780195716e-6,1.5056327351493116e-7];function gamma(z) {if(z<0.5){return Math.PI/(Math.sin(Math.PI*z)*gamma(1-z));}else{z--;var x=C[0];for(var i=1;i<g+2;i++)x+=C[i]/(z+i);var t=z+g+0.5;return Math.sqrt(2*Math.PI)*Math.pow(t,(z+0.5))*Math.exp(-t)*x;}}function go(){var N=parseInt(jQuery('#programs').val()),S=parseInt(jQuery('#shortest').val()),L=parseInt(jQuery('#length').val());if(S>15){S=15;}jQuery('#score').val(N/gamma((L-S)/5));}
<form>

Number of programs:	<input id='programs' oninput="go()" value='0'/>

Size of shortest program:	<input id='shortest' oninput="go()" value='0'/>

Size of list:	<input id='length' oninput="go()" value='0'/>

Score:	<output id='score'>0</output>

</form>
Code from http://stackoverflow.com/a/15454784/3148067

Rules

You can use programs or functions.
You may use different languages for different numbers.
Each program must work by itself. For example, you can not assume that the first program will run before the second program.

Pyth, Score of 1.664 * 10^26

Since you only have L different chars to choose from, you can maximal generate O(L!) different programs.

So lets build something really close: By indexing permutations of the alphabet:

I use a following list of characters is:

abcdefghijklmnoppqrstuvwxxyzG."

With these characters I can generate 26!-1 different programs like this:

Program 1: x.pG"abcdefghijklmnopqrstuvwxzy
Program 2: x.pG"abcdefghijklmnopqrstuvwyxz
Program 3: x.pG"abcdefghijklmnopqrstuvwyzx
  ...
Program 403291461126605635583999999: x.pG"zyxwvutsrqponmlkjihgfedcba

Notice I didn't use "abcdefghijklmnopqrstuvwxyz" (sorted alphabet), since I give an index of 0.

So we got N = 403291461126605635583999999, S = 15, L = 31, which gives a score of 1.663767345141228e+26.

Explanation:

x.pG"...
   G       G is pre-initialized with "abc...xyz"
 .p        gives all possible permutations
x   "...   the index of "..." in the permutation list

Notice, that none of the programs will actually run. Because of memory and time.

edit:

You can even get way higher. For instance by using also the uppercase letters. Gives me a score of about 10^76.

edit 2: a runnable version

Since none of the programs above is actually runnable, here's one that works.

x.pSK""Kabcde

The programs are:

Program 1: x.pSK"abced"K
Program 2: x.pSK"abdce"K
Program 3: x.pSK"abdec"K
  ...
Program 117: x.pSK"edbca"K
Program 118: x.pSK"edcab"K
Program 119: x.pSK"edcba"K

Here's an online Demonstration.

Explanation:

x.pSK"abced"K
    K"abced"   K = "abced"
   S           sort it
 .p            generate all permutations of sorted(K)
x           K  index of K in the permutations.

N = 119, S = 13, L = 13 gives a score of 0. But If we simply use a dummy char to the list we get N = 119, S = 13, L = 14 and a score of 25.92

Of course we can use more chars than abcde for the permutation. If we use n different chars, we get N = n!-1, S = 15, L = n+8, which gives a score of ~n!/(n-7)!. So we can get pretty much an unlimited score.


Bijective mapping from integers to a variable number of trits This challenge is a harder version of this one.

A variable number of trits is an array of 0 or more trits (a trit is a ternary digit). So [0, 2, 2, 1] is a variable number of trits, but so is [].

Write a function or program that, given an non-negative integer returns a variable number of trits such that every integer has a one-to-one (bijective) mapping with an array.

There are an infinite amount of such mappings, you are free to construct one as you please, but it must be one-to-one. Your mapping must conceptually be one-to-one for an arbitrarily sized integer, but it's OK if your implementation fails for large integers due to numerical limits of types in your preferred language (e.g. C's int).

As an example of what is not a one-to-one mapping, is simply listing the ternary digits of the integer. In such a system 5 becomes [1, 2] (because 1*3^1 + 2*3^0 = 5), but it's not one-to-one, because [0, 1, 2] also means 5 (because 0*3^2 + 1*3^1 + 2*3^0 = 5).

It should be fairly obvious that a mapping is not one-to-one if it skips an integer (e.g. it doesn't work for 5), but I'd like to make it clear that skipping a variable trit array is also not one-to-one. You must map to every possible variable trit array, including [].

Bonus challenge

You will be awarded the official Super Smaht® Award™ if your answer includes an algorithm (not necessarily in your golfed program) that not only works for base 2 or 3, but for all bases.

Shortest code in bytes wins.

Pyth, 6 bytes

tjyhQ3

Explanation:

    Q    Input number.
   h     Add 1.
  y      Multiply by 2.
 j   3   Convert to base 3 as a list.
t        Remove the first element.

Test suite

Inverse function: Pyth, 14 bytes

t/i+-2%sQ2Q3 2

Explanation:

        Q        Input list.
       s         Sum.
      %  2       Modulo 2.
    -2           Subtract from 2.
   +      Q      Prepend to input list.
  i        3     Convert from base 3.
 /           2   Divide by 2.
t                Subtract 1.

Test suite

The bijection looks like this:

0: []
1: [1]
2: [0]
3: [2]
4: [0, 1]
5: [1, 0]
6: [1, 2]
7: [2, 1]
8: [0, 0]
9: [0, 2]
10: [1, 1]
11: [2, 0]
12: [2, 2]
13: [0, 0, 1]
14: [0, 1, 0]
15: [0, 1, 2]
16: [0, 2, 1]
17: [1, 0, 0]
18: [1, 0, 2]
19: [1, 1, 1]
⋮

General base

To make this work in any base b, simply replace 3 with b, 2 with (b − 1), and y with *(b − 1).


Format a list of words Your challenge is to format a list of words across multiple lines that are no longer than a given number of characters, so that each line contains as many words as possible and no words are unnecessarily cut off.
Input
The input will be a space-separated list of words and then a number that is at least 4.
Output
The output should be the input words grouped into lines so that none of the lines contains more characters than the input number. The words should be output in the order they were input. The words should be separated by a comma and then a space, except at the end of each line, where the space isn't needed. If a word is too long to fit on a line, it should be cut off as little as possible while following the other rules, and "..." should be added to the end.
Test cases
Input:
foo bar baz qux 12

Output:
foo, bar,
baz, qux

Input:
foo bar baz qux 5

Output:
foo,
bar,
baz,
qux

Input:
strength dexterity constitution intelligence wisdom charisma 10

Output:
strength,
dexterity,
consti...,
intell...,
wisdom,
charisma

Input:
quas wex exort 4

Output:
...,
wex,
e...


A sorcerer's spellbook Edit: I haven't played D&D before so when I initially made this question I didn't properly research it. I apologize for this, and I'm making a few edits that might invalidate answers to stay as true as possible to the dnd 5e rules. Sorry.

A D&D fan from a recent Hot Network Question seems to have some trouble working out whether a sorcerer's chosen spells line up with the possibilities - and I think we should help!

Introduction

(all of this is already described in the previously mentioned question)

A sorcerer knows two level 1 spells from start (level 1): [1, 1]

Every time a sorcerer gains a level (except for levels 12, 14, 16, 18, 19 and 20) they learn a new spell (mandatory).
Additionally, when leveling up one can choose (optional) to replace one of the spells with another.

The spells learned and replaced must be a valid spell slot level which is half your sorcerer's level rounded up. See this table:

Sorcerer level  Highest spell level possible
1               1
2               1
3               2
4               2
5               3
6               3
7               4
8               4
9               5
10              5
11              6
12              6
13              7
14              7
15              8
16              8
17              9
18              9
19              9
20              9

This means at level 3 one can have the spell levels [1, 1, 2, 2] like this:

Level 1: [1, 1] (initial)
Level 2: [1, 1, 1 (new)]
Level 3: [1, 1, 2 (replaced), 2 (new)]

It is not required to pick the highest level spells you have access to.

The spell levels [1, 1, 1, 1] are perfectly valid for a level 3.

Lastly, remember that replacing a spell is an optional option for every level. This means that some levels could skip the replace, while others make use of it.

The challenge

Make a program or function that takes an integer (level) between 1 and 20.

It should also take an array of integers (spell levels) with values ranging from 1 to 9 in any order (9 is the maximum spell level).

The output of the program should be a truthy/falsy value validating if the chosen spell levels are valid for a sorcerer of the given level.

Test cases

Level: 1
Spells: [1, 1]
Output: true

Level: 8
Spells: [1, 1, 2, 3, 3, 5]
Ouput: false

Reason: A level 8 can't ever have access to a level 5 spell.

Level: 5
Spells: [1, 1, 1, 2, 2, 2, 3]
Output: false

Reason: A level 5 can't have access to 7 spells

Level: 11
Spells: [3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6]
Output: false

Reason: Too many spell upgrades.
        The highest valid selection for level 11 is
        [3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6]

This is code-golf - fewest bytes wins!

Java (JDK 10), 191 bytes

L->S->{int m[]=new int[9],z=0,Z=0,l=0;for(m[0]++;l++<L;z+=--m[z]<1?1:0)m[Z=~-l/2-l/19]+=l<12?2:l>17?1:1+l%2;l=0;for(int s:S){if(--s>Z)l++;Z-=--m[Z>0?Z:0]<1?1:0;}for(int i:m)l|=i;return l==0;}

Try it online!

Input requirement: the spell list must be ordered from greatest spell levels to the lowest one.

Explanations

L->S->{                                        // Curried-lambda with 2 parameters: sorcerer-level and spell list
 int m[]=new int[9],                           // Declare variables: m is the max level  of each spell.
     z=0,                                      // z is the minimum spell level of the maximized spell list.
     Z=0,                                      // Z is the maximum spell level for the current level.
     l=0;                                      // l is first a level counter, then a reused variable
 for(m[0]++;l++<L;z+=--m[z]<1?1:0)             // for each level, compute the maximized known spells.
  m[Z=~-l/2-l/19]+=l<12?2:l>17?1:1+l%2;        //
                                               // Now m is the row for level L in the table below.
 l=0;                                          // l now becomes an error indicator
 for(int s:S){                                 // This loop checks if the spell-list matches the spells allowed for that level.
  if(--s>Z)l++;                                // Spell-levels are 1-based, my array is 0-based so decrease s.
  Z-=--m[Z>0?Z:0]<1?1:0;                       // Remove a max level if we've expleted all the spells, avoiding exception.
 }                                             //
 for(int i:m)l|=i;                             // Make sure there are no more values in m.
 return l==0;                                  // Return true if no miscount were encountered.
}

Table 1: Maximized spell distribution for each sorcerer-level, used from Axoren's answer on the linked question.

Credits

Saved 14 bytes thanks to Kevin Cruijssen.


Check if there is an isomorph substring This question is an extension of Check if words are isomorphs  and copies the first part of it to give the definition of an isomorph.

Two words are isomorphs if they have the same pattern of letter repetitions. For example, both ESTATE and DUELED have pattern abcdca

ESTATE
DUELED

abcdca

because letters 1 and 6 are the same, letters 3 and 5 are the same, and nothing further. This also means the words are related by a substitution cipher, here with the matching E <-> D, S <-> U, T <-> E, A <-> L.

Given two strings X and Y, with X no longer than Y, the task is to determine if there is a substring of Y which is an isomorph with X.

Input: Two non-empty strings of letters from a..zA..Z which one string per line.  This will come from standard input.

Output A substring of the second string which is an isomorph with the first string, if such a thing exists. Otherwise output "No!".

Rules Your code must run in linear time in the total length of the input.

Score Your score is the number of bytes in your code.  Fewest bytes wins.

Example input and output

adca
ddaddabdaabbcc

dabd

Tip

There is at least one not that complicated, practically fast and linear time solution to this problem.

Python 2, 338 326 323 321 310 306 297 293 290 289 280 279 266 264 259 237 230 229 226 223 222 220 219 217 (260 238 231 228 225 223 221 220 218 with 0 exit status)

exec'''s=raw_input()
S=[M-s.rfind(c,0,M)for M,c in enumerate(s)]
k=0
j=x=%s
while k<=M+x:
 if S[k]>j<W[j]or S[k]==W[j]:
    k+=1;j+=1;T+=[j]
    if j-L>x:print s[k-j:k];z
 else:j=T[j]
'''*2%('-1;T=[0];W=S;L=M',0)
print'No!'

The algorithm is a variation of KMP, using an index-based test for character matching. The basic idea is that if we get a mismatch at position X[i] then we can fall back to the next possible place for a match according to the longest suffix of X[:i] that is isomorphic to a prefix of X.

Working from left to right, we assign each character an index equal to the distance to the most recent previous occurrence of that character, or if there is no previous occurrence then we take the length of the current string prefix. For example:

MISSISSIPPI
12313213913

To test whether two characters match, we compare indices, adjusting appropriately for indices that are greater than the length of the current (sub)string.

The KMP algorithm becomes a little simplified since we cannot get a mismatch on the first character.

This program outputs the first match if one exists. I use a runtime error to exit in the event of a match, but the code can be easily modified to exit cleanly at the cost of some bytes.

Note: For computing indices, we can use str.rfind (as opposed to my earlier approach using a dictionary) and still have linear complexity, assuming that str.rfind starts searching from the end (which seems the only sane implementation choice) -- for each character in the alphabet, we never have to traverse the same part of the string twice, so there is an upper bound of (size of alphabet) * (size of string) comparisons.

Since the code got fairly obfuscated in the course of golfing, here is an earlier (293 byte) solution that's a bit easier to read:

e=lambda a:a>i<W[i]or a==W[i]
exec('s=raw_input();S=[];p={};M=i=0\nfor c in s:S+=[M-p.get(c,-1)];p[c]=M;M+=1\nW=S;L=M;'*2)[:-9]
T=[0]*L
k=1
while~k+L:
 if e(W[k]):i+=1;k+=1;T[k]=i
 else:i=T[i]
m=i=0
while m+i<M:
 if e(S[m+i]):
    if~-L==i:print s[m:m+L];z
    i+=1
 else:m+=i-T[i];i=T[i]
print'No!'

The e function tests equivalence of characters. The exec statement assigns indices and does some variable initialisations. The first loop processes X for fall back values, and the second loop does the string search.

Update: Here is a version that exits cleanly, at the cost of one byte:

r='No!'
exec'''s=raw_input()
S=[M-s.rfind(c,0,M)for M,c in enumerate(s)]
k=0
j=x=%s
while k<=M+x:
 if S[k]>j<W[j]or S[k]==W[j]:
    k+=1;j+=1;T+=[j]
    if j-L>x:r=k=s[k-j:k]
 else:j=T[j]
'''*2%('-1;T=[0];W=S;L=M',0)
print r


Write a Program for winning sevens game Build a function in python that can win a Sevens game provided that there are only 2 players

Here are the instructions from Wikipedia:

  All cards are dealt to the players, even if as a result some players
  have one card more than others. The owner of the seven of hearts
  begins by playing it. Similarly, the other three sevens may later be
  played as the first cards of their respective suits. After that, cards
  may be added in sequence down to the ace and up to the king. A player
  who cannot place a card passes.

  You cannot pass if you have a card to play.

  The one who gets the seven of hearts is the first to play.

The cards will be randomly distributed to the user and the computer.

The function will have two parameter:

List of cards remaining to play for computer
List cards that have been played

The syntax of a card is like this:

  [value, suit]

For example [king, "clubs"]

  The list of suits are:

  clubs
  spades
  diamonds
  hearts

  The list of values are:

  1
  2
  3 ....
  11(jack)
  12(queen)
  13(king)

The remaining cards for player 1 will be stored in list named card_1_rem and the remaining cards for player 2 will be stored in list named card_2_rem

The cards that have been played will be stored in a list called played_cards

The function will have to append the played card to the list called played_cards and subtract the item for the list called card_1_rem or card_2_rem

The return of one function will be the input of the competitor

The one who finishes his cards first, wins.

Winning Condition

Step 1: Users will submit their programs.

Step 2: I will test the programs against each other.

Step 3: The first program to remain in first place (as measured by lowest total running score) for 50 consecutive games will be the winner.  This will help smooth out the effects of luck.  However, a maximum of 10000 games will be played, and if no player meets the first criterion, then the player with the lowest total score after 10000 games wins.

Step 4: All the results will be uploaded to a github repo(which I will soon make).

  The loser has to count his points as follows

Ace : 1
2 : 2
3 : 3
4 : 4
5 : 5
6 : 6
7 : 7
8 : 8
9 : 9
10 : 10
jack : 10
queen : 10
king : 10

  For example if a king and an ace remain in the loser's hand, he gets
  11 point.

  The objective is to minimize the points you have got.

  Winner gets 0 points

IMP : Submissions are allowed only in the Python 3 language.

The controller code of this challenge is here(major update has been done): https://gist.github.com/Salil03/19a093554205b52d05dc7dc55992375a

Synergistic

I'm not really a Python guy, but wanted to give this a go. This builds the set of playable cards at each turn, and assigns each of them a simple static score. The card with the highest score is played (assuming any playable card exists).

def synergistic(cards_in_hand, played_cards):
    def list2dict(lst):
        d = {}
        for val, suit in lst:
            if suit in d:
                d[suit].append(val)
            else:
                d[suit] = [val]
        return d
    def play_card(card):
        cards_in_hand.remove(card)
        played_cards.append(card)

    hand = list2dict(cards_in_hand)
    if not played_cards:
        if 7 in hand['hearts']:
            play_card([7, 'hearts'])
        return (cards_in_hand, played_cards)
    table = list2dict(played_cards)

    playable_cards = {}
    for suit in hand:
        if 7 in hand[suit]:
            playable_cards[(7, suit)] = -1

        if suit not in table:
            continue
        visible = set(table[suit] + hand[suit])
        opp_hand = set(range(1,14)) - visible
        highcard = max(table[suit]) + 1

        if highcard in hand[suit]:
            if highcard+1 in opp_hand:
                playable_cards[(highcard, suit)] = 1
            else:
                playable_cards[(highcard, suit)] = 2

        lowcard = min(table[suit]) - 1
        if lowcard in hand[suit]:
            if lowcard - 1 in opp_hand:
                playable_cards[(lowcard, suit)] = 0
            else:
                playable_cards[(lowcard, suit)] = 1

    if not playable_cards:
        return (cards_in_hand, played_cards)

    best_card = list(max(playable_cards, key=playable_cards.get))
    #print(hand, "\n", table, "\n", best_card)
    play_card(best_card)

    return (cards_in_hand, played_cards)

By the way, the controller seemed to have several issues, including in score calculation and comparison. I made some changes to the controller here, please take a look  and update your version if this seems right.

Two things I haven't fixed in the controller:

why is the loop condition (win2 <= 50) and (win1 <= 100) ? This should probably be symmetrical, it should exit the loop whenever either of the players has 100 consecutive wins.
trying some runs of the controller locally, with the same function for both players, Player 2 seems to win most of the time - it can't be inherent to the game since the initial 7H requirement would smooth that out (as @Veskah mentioned in the comments), so, yet undetected controller bugs? Or my player code somehow maintaining state and having a bias this way? Per-game, it's not like Player 2 dominates heavily (from the results output txt), but somehow the overall score per controller run ends up favouring player 2 much more than random (Player 1's total scores are often more than 2x that of Player 2).


Guess my Number - Code Golf The puzzle is as follows:

Create the traditional 'Guess my Number' game in as little keystrokes as possible. The player should input a guess between and including 1 and 100, and the computer should reply with either + (meaning the player needs to guess higher), - (meaning the player needs to guess lower) or = (meaning the player has guessed the number. The game continues until the player has guessed the number. The number that the computer generates MUST be a random number between and including 1 and 100.

Sample gameplay

50
+
75
-
60
-
55
+
57
=

Happy Golfing!


Shortest Konami Code The Problem
You must write a program that, when the Konami Code is typed in during runtime, prints the string "+30 lives" and sounds a noise of your choice from the computer's speaker.
Definition
The "Konami Code" is defined as UUDDLRLRBA followed by pressing the enter key.
The Rules

You may choose to use the up arrow for U, down for D, left for L, and right for R, as long as your code is consistent with either arrows or letters.

Your input may be accepted from a controller or a keyboard, but does not need to support both.

Existing answers may continue to use BABA instead of BA, but may also shorten it if they wish to do so. Future answers should all use BA for consistency.

Empty input doesn't need to be supported.

05AB1E, 33 bytes (Fine on Empty Input)

Dg0Qiq}•ï“ë™µyê!•36BQi7ç“+30™‹“J,

Try it online!

05AB1E, 30 26 bytes (Fails on Empty Input)

-4 thanks to Adnan

•ï“ë™µyê!•36BQi7ç,“+30™‹“,

Try it online!

•ï“ë™µyê!•36B                  # UUDDLRLRBABA in base-214, converted back to base-36.
             Qi                # If implicit input is equal to...
               7ç,             # Print 7 converted to a character to the console (bell sound)...
                  “+30™‹“, # Print +30 lives.

Disclaimer: Bell sound does not play on TryItOnline, maybe ask Dennis if one of his servers somewhere is pinging when you run it.


Verify the queens puzzle If you don't know what a queen is in chess, it doesn't matter much; it's just a name :)

Your input will be a square of arbitrary width and height containing some amount of queens. The input board will look like this (this board has a width and height of 8):

...Q....
......Q.
..Q.....
.......Q
.Q......
....Q...
Q.......
.....Q..

There are 8 queens on this board. If there were, say, 7, or 1, or 10 on here, the board wouldn't be valid.

Here we  use a . for an empty space, and a Q for a queen. You may, alternatively, use any non-whitespace character you wish instead.

This input can be verified as valid, and you should print (or return) a truthy value (if it is was not valid, you should print (or return) a falsy value). It is valid because no queen is in the same row, column, diagonal or anti-diagonal as another.

Examples (don't output things in brackets):

...Q....
......Q.
..Q.....
.......Q
.Q......
....Q...
Q.......
.....Q..

1

...Q.
Q....
.Q...
....Q
..Q..

0

Q.
Q.

0

..Q
...
.Q.

0 (this is 0 because there are only 2 queens on a 3x3 board)

..Q.
Q...
...Q
.Q..

1

Q

1 (this is valid, because the board is only 1x1, so there's no queen that can take another)

Let me stress that an input is only valid, if no queen is in the same row, column, diagonal or anti-diagonal as another.

Rules

You will never receive an empty input
If the input contains fewer queens than the sqaure root of the area of the board, it is not valid.
Note there are no valid solutions for a 2x2 or 3x3 board, but there is a solution for every other size square board, where the width and height is a natural number.
The input may be in any reasonable format, as per PPCG rules
The input will always be a sqaure
I used 1 and 0 in the examples, but you may use any truthy or falsy values (such as Why yes, sir, that is indeed the case and Why no, sir, that is not the case)

As this is code-golf, the shortest code wins!

Snails, 14 bytes

&
o.,\Q!(z.,\Q

Try it online!

Nothing like a 2D pattern matching language for a 2D decision problem. :)

Explanation

The & on the first line is a match mode option which requires the pattern on the second line to match from every possible position in the input. If that's the case, the program prints 1, otherwise it prints 0.

As for the pattern itself, note that there's an implicit ) at the end.

o       ,, Move in any orthogonal direction (up, down, left or right).
.,\Q    ,, Make sure that there's a Q somewhere in that direction from the
        ,, starting position of the match.
!(      ,, After finding the Q, make sure that the following part _doesn't_ match:
  z     ,,   Move in any orthogonal or diagonal direction.
  .,\Q  ,,   Try to find another Q in a straight line.
)

Why this works is easiest to see by starting from the negative lookahead: by ensuring that there is no Q in a straight line from the other Q we've already found, we make sure that there are no more than N queens (otherwise, there would have to be two in one row, and it wouldn't be possible to find these queens without finding another). Then the first part, making sure that there's a queen reachable in an orthogonal direction from any position, makes sure that there are exactly N queens. If one was missing, there would be a row and a column without a queen. Starting from the intersection of these, it wouldn't be possible to find a queen by going only in an orthogonal direction.


Hello World in 1024 characters In exactly 1024 characters, no more, no less:

Must print Hello World.
Must not use unnecessary whitespace.
Must not use comments.

Judging should favor creativity and/or humor over simple obfuscation when voting up answers.

The earliest I will select an answer is the 11th (Sunday) of November (2012). I'm seeing some awesome entries so far, can't wait to see what else people come up with.

C# (and without “Hello World” anywhere)

Code-golfed, so that obviously no unnecessary whitespace is used:

using System;using System.IO.Compression;using System.Runtime.Serialization;using System.Runtime.Serialization.Json;using System.Linq;using System.Net;using System.Text.RegularExpressions;class C{static void Main(){var g=WebRequest.Create("https://api.stackexchange.com/2.1/questions/8859?site=codegolf&filter=withbody");var r=(HttpWebResponse)g.GetResponse();if(r.StatusCode==HttpStatusCode.OK){var s=r.GetResponseStream();foreach(var a in r.ContentEncoding.ToLowerInvariant().Split(',').Reverse())switch(a){case"gzip":s=new GZipStream(s,CompressionMode.Decompress);break;case"deflate":s=new DeflateStream(s,CompressionMode.Decompress);break;default:throw new InvalidOperationException();}var d=new DataContractJsonSerializer(typeof(R));var q=(R)d.ReadObject(s);var e=new Regex("([^<]*)");var m=e.Match(q.I[0].B);Console.WriteLine(m.Groups[1].Value);}}}[DataContract]public class R{[DataMember(Name="items")]public I[]I{get;set;}}[DataContract]public class I{[DataMember(Name="body")]public string B{get;set;}}

Formatted for readability:

using System;
using System.IO.Compression;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;

class C
{
    static void Main()
    {
        var g = WebRequest.Create("https://api.stackexchange.com/2.1/questions/8859?site=codegolf&filter=withbody");
        var r = (HttpWebResponse)g.GetResponse();
        if (r.StatusCode == HttpStatusCode.OK)
        {
            var s=r.GetResponseStream();
            foreach (var a in r.ContentEncoding.ToLowerInvariant().Split(',').Reverse())
            switch(a)
            {
                case "gzip":
                    s = new GZipStream(s,CompressionMode.Decompress);
                    break;
                case "deflate":
                    s = new DeflateStream(s,CompressionMode.Decompress);
                    break;
                default:
                    throw new InvalidOperationException();
            }
            var d = new DataContractJsonSerializer(typeof(R));
            var q = (R)d.ReadObject(s);
            var e = new Regex("([^<]*)");
            var m = e.Match(q.I[0].B);
            Console.WriteLine(m.Groups[1].Value);
        }
    }
}

[DataContract]
public class R
{
    [DataMember(Name="items")]
    public I[] I { get; set; }
}

[DataContract]
public class I
{
    [DataMember(Name="body")]
    public string B { get; set; }
}

The program retrieves this question from Code Golf using Stack Exchange API, finds the first piece of text formatted as code (which, in case of this question, is the “Hello World” text), and prints it out.


You have a n day streak! Write a program that keeps track of the number of consecutive days it has been run.

The day resets at midnight (the local time of the computer on which the program is run).

If there is a day that the program is not run, the counter is reset to zero.

Every time the program is run, the counter should go up by one day if it is the first time the program is run that day. This means that the first time the program is run, it should say, "You have a 1 day streak!"

The output of the program is in the form: You have a [streak_length] day streak!

You are allowed to store data externally or modify the source code––your choice.

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

Bash, 102 bytes

find ! -newerat 0-1day -delete
touch -a a
echo You have a $((1+(`stat -c %X-%Y a`)/86400)) day streak!

Warning, do not run in any folder you care about. It deletes any file not accessed in the last day in the working directory.

Uses a file a to store data, using the accessed/modified timestamps.


Eating fish, growing in size You are fish in a pond that needs to survive by eating other fish. You can only eat fish that are the same size or smaller than yourself. You must create a program that takes a shoal of fish as sorted input. From this you must work out how many fish you can eat and ultimately the size you will grow to.

Size chart

+--------------+--------------+--------------+--------------+
|              | Amount extra | Total size 1 | Increase to  |
| Current size |  needed for  |     fish     |    size      |
|              |  next size   |              |              |
+--------------+--------------+--------------+--------------+
|      1       |      4       |      4       |      2       |
+--------------+--------------+--------------+--------------+
|      2       |      8       |      12      |      3       |
+--------------+--------------+--------------+--------------+
|      3       |      12      |      24      |      4       |
+--------------+--------------+--------------+--------------+
|      4       |      16      |      40      |      5       |
+--------------+--------------+--------------+--------------+
|      5       |      20      |      60      |      6       |
+--------------+--------------+--------------+--------------+
|      6       |      24      |      84      |      7       |
+--------------+--------------+--------------+--------------+

Rules

Your size starts at 1
The shoal input will contain fish integers between 0-9
0 = algae and wont help you feed.
The fish integer represents the size of the fish (1-9).
You can only eat fish the same size or less than yourself.
You can eat the fish in any order you choose to maximize your size.
You can only eat each fish once.
The bigger fish you eat, the faster you grow. A size 2 fish equals two size 1 fish, size 3 fish equals three size 1 fish, and so on.
Your size increments by one each time you reach the amounts below.

Returns an integer of the maximum size you could be

Examples

"11112222" => 3
4 fish size 1 increases to 2, 4 size 2 makes you 3

"111111111111" => 3
4 fish size 1 increases to 2, 8 size 1 makes you 3

The shortest code (counting in bytes) to do so in any language in which numbers wins.

JavaScript (ES6), 44 bytes
Takes input as an array of integers.

a=>a.map(x=>s+=(t+=s>=x&&x)>s*-~s*2,t=s=1)|s

Try it online!
How?
The threshold \$T_s\$ to reach the size \$s+1\$ is given by:
$$T_s=2s(s+1)$$
We keep track of our current size in \$s\$ and of what we've eaten so far in \$t\$ (we start with \$t=1\$, so this is actually off by \$1\$).
For each fish \$x\$ in the shoal, assuming it's sorted from smallest to biggest:

we add \$x\$ to \$t\$ (i.e. we eat the fish) whenever we have \$s\ge x\$
we increment \$s\$ (i.e. we grow in size) if \$t > T_s\$


It's Hip to be Square Challenge
So, um, it seems that, while we have plenty of challenges that work with square numbers or numbers of other shapes, we don't have one that simply asks:
Given an integer n (where n>=0) as input return a truthy value if n is a perfect square or a falsey value if not.

Rules

You may take input by any reasonable, convenient means as long as it's permitted by standard I/O rules.
You need not handle inputs greater than what your chosen language can natively handle nor which would lead to floating point inaccuracies.
Output should be one of two consistent truthy/falsey values (e.g., true or false, 1 or 0) - truthy if the input is a perfect square, falsey if it's not.
This is code-golf so lowest byte count wins.

Test Cases
Input:  0
Output: true

Input:  1
Output: true

Input:  64
Output: true

Input:  88
Output: false

Input:  2147483647
Output: false

Neim, 2 bytes

q

Explanation:

q      Push an infinite list of squares
      Is the input in that list?

When I say 'infinite' I mean up until we hit the maximum value of longs (2^63-1). However, Neim is (slowly) transitioning to theoretically infinitely large BigIntegers.

Try it!


Shorten an already short mathematical expression For once, I was doing some real work, updating old code, and bumped into an expression that is equivalent to what would be written as πx + ex in good old-fashioned math. I thought it would be possible to write it shorter than it was written in the language I work with (APL), and therefore present this very simple challenge:

Write a function or program that (by any means) accepts zero or more numbers, and returns (by any means) the result of the above expression for x = each of the given numbers with at least 3 significant digits for each result.

If your language does not have π and/or e, use the values 3.142 and 2.718.

Scoring is number of bytes, so preface your answer with # LanguageName, 00 bytes.

Standard loop-holes are not allowed.

Edit: Now the solution I came up with, ○+*, has been found. The original code was (○x)+*x.

Emotinomicon, 48 bytes / 13 characters

I do it, not because it is short, but because it is fun. Try it here. You'll have to copy+paste it into the textbox.

⏪✖➕⏩

Explanation:

  ⏪       ✖       ➕         ⏩   explanation
                                              take numeric input
    ⏪                                           open loop
                                              duplicate top of stack
                                              push pi
                ✖                               multiply top two elements on stack
                                              reverse stack
                                              pop N, push e^N
                            ➕                   add top two elements on stack
                                              take numeric input
                                              duplicate top of stack
                                              pop N, push N+1
                                            ⏩   close loop

Here is the program in its native environment, the mobile phone:


Weighted average - the pressup trend problem Let's say that this array is how many press-ups I've achieved each day in the last 28 days:

[
  20,20,20,30,30,30,30,
  35,35,40,40,40,45,45,
  50,50,50,50,50,50,50,
  60,70,80,90,100,110,120
]

As you can see, it's taken a steep upward trend in the last week, and that's the part of this data I'm most interested in. The further in the past it is, the less I want that data to feature in my 'average' number of press-ups.

To that end, I want to work out an 'average' where each week is worth more than the previous week.

Background information, not part of this problem.

Normal average:

The sum of all values / the number of values

For above:

1440 / 28 = 51.42857142857143

Weighted average:

Split the array into 4 groups of 7, and start up a new array.

Add the first group to the array.
Add the second group to the array twice.
Add the third group to the array thrice.
Add the fourth group to the array four times.

Sum all of the new array, and divide by the length of the new array.

For above:

Convert the array to this:

[
  20,20,20,30,30,30,30, # first week once
  35,35,40,40,40,45,45,
  35,35,40,40,40,45,45, # second week twice
  50,50,50,50,50,50,50,
  50,50,50,50,50,50,50,
  50,50,50,50,50,50,50, # third week thrice
  60,70,80,90,100,110,120,
  60,70,80,90,100,110,120,
  60,70,80,90,100,110,120,
  60,70,80,90,100,110,120 # Fourth week four times
]

Then run a normal average on that array.

4310 / 70 = 61.57142857142857

Note that it's higher than the normal average value because of the upward trend in the last week.

The rules:

The input is a flat array of 28 nonnegative integers.
Any language you'd like to write in.
Output a number.
I always like to see TIO links.
Try to solve the problem in the smallest number of bytes.
The result should be a decimal accurate to at least 4 decimal places (either truncated or rounded up from the test case values is fine) or an exact fraction.

Test cases:

Case 1: Upward trend

[
  20,20,20,30,30,30,30,
  35,35,40,40,40,45,45,
  50,50,50,50,50,50,50,
  60,70,80,90,100,110,120
]

Normal average: 51.42857142857143
Weighted average: 61.57142857142857

Case 2: Leaving the lull behind

(I had a bad week, but it was a while ago)

[
  50,50,50,50,50,50,50,
  10,10,10,10,10,10,10,
  50,50,50,50,50,50,50,
  50,50,50,50,50,50,50
]

Normal average: 40
Weighted average: 42

Case 3: Giving up

I had a bad week, it's pulling my average down fast.

[
  50,50,50,50,50,50,50,
  50,50,50,50,50,50,50,
  50,50,50,50,50,50,50,
  10,10,10,10,10,10,10
]

Normal average: 40
Weighted average: 34

Case 4: Averaging out

Okay, so I'm just playing around here, I thought it might be the same value for the normal and weighted averages, but, of course, it was not.

[
  60,60,60,60,60,60,60,
  30,30,30,30,30,30,30,
  20,20,20,20,20,20,20,
  15,15,15,15,15,15,15
]

Normal average: 31.25
Weighted average: 24.0

Bonus problem:

What combination of 28 values would have the same normal average and weighted average?

Happy golfing!

Python 3, 38 bytes

lambda x:sum(x+x[7:]+x[14:]+x[21:])/70

Try it online!


split and capitalize Challenge :

Given a string split at specific positions and capitalize the first character of the given word. Capitalize the first word's first char if and only if it was already capitalized

Input :

A string s and a character c.

Ouput :

The string with each occurrence of c replaced with the first char capitalized

Examples :

STRING(s)             CHARACTER(c)  RESULT
Hello_world           _             HelloWorld
me,no,like            ,             meNoLike
you-got-it            -             youGotIt
Am^I^clear            ^             AmIClear
go!full!caps          !             goFullCaps
weird&but&tRue        &             weirdButTRue
ProbleM1fixed1no      1             ProbleMFixedNo
!prob!!lem!s!Olved!!  !             ProbLemSOlved

Note :

Given input will always be valid. i.e : The first will always be a string with at least one instance of the character to replace at. The second will always will be a single character.
The length of the input string will be greater 4.
There will be at least one occurrence of the character to split at.
The input is guaranteed to contain only letters and the separator (Thanks @Arnauld)
Separator is anything that is not an alphabet (a-z / A-Z) (suggested by @Dennis)

Winning criteria :

This is code-golf so shortest code in bytes for each language wins.

Thanks to @JonathanAllan for pointing out two mistakes.

Python 3, 63 bytes

lambda s,c:''.join(map(min,s,s[0]+s.title()[1:])).replace(c,'')

Try it online!


Look-and-say sequence: roman numerals edition Challenge description

We've had a few challenges involving the Look-and-say sequence. Quick reminder:

The sequence starts with 1,
Subsequent terms of this sequence are generated by enumerating each group of repeating digits in the previous term,

So the first few terms are:

1        "one"
11       "one one" (we look at the previous term)
21       "two ones"
1211     "one two, one one"
111221   "one one, one two, two ones"
312211   "three ones, two twos, one one"

Now let's do the same thing, but use Roman Numerals instead. We start with I and follow the same rules (we apply the digit-counting rule to characters instead, so we read IVX as one one, one five, one ten instead of one four, one ten or some other way):

I           "one"
II          "one one"
III         "two ones" = "II" + "I"
IIII        "three ones" = "III" + "I"
IVI         "four ones" = "IV" + "I"
IIIVII      "one one, one five, one one"
IIIIIVIII   "three ones, one five, two ones" = ("III" + "I") + ("I" + "V") + ("II" + "I")

Given a positive integer N, either:

Output first N numerals of this sequence (any reasonable separator is fine, as well as ["I", "II", "III", ...]
Output Nth term of this sequence (it may be 0-indexed).

Remember to make your code as short as possible, since this is a code-golf challenge!

EDIT: I believe that there is always one standard/preferred way of expressing integers as roman numerals, (like 95 -> XCV instead of VC). Couple of Roman numeral converters I found online corroborate my opinion. If in doubt, use an online converter, as listing all the possible edge-cases and specific rules of writing Roman numerals is not the point of this challenge.

EDIT2: @PeterTaylor and @GregMartin pointed out that only numbers less or equal to 5 appear in the sequence, so you don't have to worry about the ambiguity of Roman numerals (numbers 1 - 8 are I, II, III, IV, V, VI, VII, and VIII)

Perl, 49 bytes

Includes +1 for -p

Run with the 0-based index on STDIN, e.g.

ecce.pl <<< 14

ecce.pl:

#!/usr/bin/perl -p
s,(.)\1*,$&/$1%182 .$1,eg for($_=/$/)x$`;y;19;IV

Magic formulas are so magic.

Normally I would use ($_=//)x$' to make the loop control one byte shorter, but scoring on this site gives that a handicap of 2 so it ends up 1 byte longer. On older perls you can drop the space before for. Some versions of perl force you to add a final ; to close the transliteration. But what is given above is the code that works on my system.

Explanation

Working backwards from solution to code:

The string transformations we need:

I     -> II
II    -> III
III   -> IIII
IIII  -> IVI
IIIII -> VI

V     -> IV
VV    -> IIV

Each replacement ends with the repeated character. I will get a sequence of the same characters using regex /(.)\1*/, so this can be done by appending $1. The part before the -> is in $&. With that I still need:

I     -> I
II    -> II
III   -> III
IIII  -> IV
IIIII -> V

V     -> I
VV    -> II

Write I as 1 and V as 9:

1     -> 1
11    -> 11
111   -> 111
1111  -> 19
11111 -> 9

9     -> 1
99    -> 11

By dividing the part before -> by the repeated digit this becomes:

1     -> 1
11    -> 11
111   -> 111
1111  -> 19
11111 -> 9

1     -> 1
11    -> 11

So now the original repeated V is not an exception anymore. So I want an expression that makes this happen:

1     -> 1
11    -> 11
111   -> 111
1111  -> 19
11111 -> 9

And this can be done by a simple modulo 182:

1     % 182 = 1
11    % 182 = 11
111   % 182 = 111
1111  % 182 = 19
11111 % 182 = 9

(this even gets IIIIII to VI right though it isn't needed here)

All that is left is initializing the working variable to 1 for index 0, repeat this transformation in a loop and at the end replace 1 by I and 9 by V

1, 9 and 182 is the only parameter combination for which this simple formula works.


Fancy String Replace let S, a and b each represent a string

Goal: Write a standard string replace function where the you replace all occurrences of a in a string S with b so long as a is not already part of an instance of b

for example, if we have the string S = My oh my that there is a big ol' that

and we wanted to do a fancy replace with a = that and b = that there we would replace every instance of that with that there as long as the instance of that isn't already an instance of that there

So in this case the output would be: My oh my that there is a big ol' that there

The first that is not replaced because it is already part of an instance of that there

Notes

All 3 inputs must be strings containing only printable ascii characters
Input may be given as 3 separate strings or a list of 3 strings
Input will be in the order S, a, b unless otherwise specified in the answer
In order for a to be considered a part of b, all of the instance of a must be part of an instance b

Some Corner Cases Explained

Input:  ["1222", "22", "122"]
Output: "12122"

In the case above example the latter 22 is replaced. Even though part of it is part of an instance of b, the entirety of it is NOT a part of the instance of b. Since the entire instance of a is not part of an instance of b it is replaced.

Input:  ["123 ", "23", "12"]
Output: "112 "

This test case illustrates the same case as above but perhaps in a slightly more clear way. Again the 2 in the middle is both part of an instance of a as well as part of an instance of b, however since all of a is not part of the instance of b it is still replaced.

Input: ["Empty", "", "p"]
Output: "pEpmptpyp"

In the above test case both the empty string before and after the p are not replaced as the can wholly be considered part of the instance of p.

Other Test Cases

Input:  ["aabbaa", "aa", "aabb"]
Output: "aabbaabb"

Input:  ["Hello World!", "o", " no"]
Output: "Hell no W norld!"

Input: ["Wow, oh wow, seriously WOW that's... wow", "wow", "WOW,"]
Output: "Wow, oh WOW,, seriously WOW that's... WOW,"

Input: ["Empty", "", "b"]
Output: "bEbmbpbtbyb"

Input: ["Empty", "b", "br"]
Output: "Empty"

Input: ["Empty", "pty", "Empty"]
Output: "Empty"

Input:  ["aabbaaa", "aa", "PP"]
Output: "PPbbPPa"

Input:  ["121212","1","121"]
Output: "121212"

This is a question for code-golf so the shortest answer in bytes wins.

Perl 6, 76 bytes

{$^b;$^a;&{S:g/$a<?{$!=$/;all m:ex/$b/>>.&{$!.to>.to||.from>$!.from}}>/$b/}}

Try it online!

Anonymous code block that takes input curried, like f(a,b)(s).

I'm pretty sure this matches up with the intent of the question. Basically, it only makes the substitution if the position of a is not within any of the overlapping matches of b.


Output integers in negative order, increase the maximum integer everytime Main task

Your task is to print out integers in descending order, starting from 1, and increasing as you keep hitting 1 again, up until the given input is reached, then, print out the rest until you hit 1 again. Example with input 6:
1
21
321
4321
54321
654321
Without newlines (valid output):
121321432154321654321

Side note: this is A004736 in the OEIS. Also, the first example (with newlines) is an invalid output, as specified in the rules.

Input

Your code may take any kind of input (graphical, STDIN) in the form of an integer or number.

Output

Your code should output the above described sequence, up until the input number is reached, then finish to output until it reaches 1 again. The output may be anything, therefore numbers, strings, integers, or graphical output. It is required to print out a single number (no newlines if it's a string). Your output can be in- and outroduced with as many characters as you need (e.g. []).

Since there was some misunderstanding, here's a regex pattern you can try your outputs on.

^(\D*(\d)+\D*)$

Rules

The output must be a full number, not split up by anything, not even newlines.
The algorithm shouldn't check for the first instance of N appearing in any way (e.g. the 21 in 121321), but rather for the first instance of N as the actual number.
A single trailing newline is allowed.
The handling for negative input is fully your choice, negative numbers aren't cases you should test.

Test cases

Input: 6
Output: 121321432154321654321

Input: 1
Output: 1

Input: 26
Output: 121321432154321654321765432187654321987654321109876543211110987654321121110987654321131211109876543211413121110987654321151413121110987654321161514131211109876543211716151413121110987654321181716151413121110987654321191817161514131211109876543212019181716151413121110987654321212019181716151413121110987654321222120191817161514131211109876543212322212019181716151413121110987654321242322212019181716151413121110987654321252423222120191817161514131211109876543212625242322212019181716151413121110987654321

Input: 0
Output: 0, Empty, or Error

Input: 21
Output: 121321432154321654321765432187654321987654321109876543211110987654321121110987654321131211109876543211413121110987654321151413121110987654321161514131211109876543211716151413121110987654321181716151413121110987654321191817161514131211109876543212019181716151413121110987654321212019181716151413121110987654321
Thanks @Emigna, I used his algorithm to calculate these test cases.

Winner

The winner has been chosen! It was ErikGolfer's answer with an impressive 5 bytes! Congratulations!

05AB1E, 6 bytes

L€LíJJ

Try it online!

Explanation

Example input 4

L       # range [1 ... input]
        # STACK: [1,2,3,4]
 €L     # map: range
        # STACK: [[1],[1,2],[1,2,3],[1,2,3,4]]
   í    # reverse each
        # STACK: [[1],[2,1],[3,2,1],[4,3,2,1]]
    J   # join inner lists
        # STACK: ['1','21','321','4321']
     J  # join list
        # OUTPUT: 1213214321


Counting in pyramids You should write a program or function which receives a list of distinct integers as input and outputs or returns the number of occurrences of the input numbers in the following upside-down number pyramid.

Starting from the original list in every step we create a new one with the maximal values of every pair of adjacent numbers (e.g. 5 1 2 6 becomes 5 2 6). We stop when there is only one number in the list.

The full pyramid for 5 1 2 6 is

5 1 2 6
 5 2 6
  5 6
   6

The resulting number of occurrences are 3 1 2 4 (for 5 1 2 6 respectively).

Input

A list of one or more integers with no repetition. (e.g. 1 5 1 6 is invalid.)

Output

A list of positive integers. The ith element of the list is the number of occurrences of the ith input number in the pyramid.

Examples

Input => Output

-5 => 1

8 4 => 2 1

5 9 7 => 1 4 1

1 2 3 9 8 6 7 => 1 2 3 16 3 1 2

6 4 2 1 3 5 => 6 4 2 1 3 5

5 2 9 1 6 0 => 2 1 12 1 4 1

120 5 -60 9 12 1 3 0 1200 => 8 2 1 3 16 1 4 1 9

68 61 92 58 19 84 75 71 46 69 25 56 78 10 89 => 2 1 39 2 1 27 6 5 1 6 1 2 14 1 12

This is code-golf so the shortest entry wins.

Bonus puzzle: can you solve the problem in O(n*log n) time?

Python, 81

def f(L):
 if L:i=L.index(max(L));L=f(L[:i])+[~i*(i-len(L))]+f(L[i+1:])
 return L

A divide-and-conquer solution. The maximum element M seeps all the way down the pyramid, splitting it into a rectangle of M's and two subpyramids.

* * * M * *
 * * M M *
  * M M M
   M M M
    M M
     M

So, the overall result is the output for the left sublist, followed by the area of the rectangle, followed by the output for the right sublist.

The input variable L is reused to stored the result so that the empty list is mapped to the empty list.

The constructs in solution are wordy in Python. Maybe some language with pattern-matching can implement the following pseudocode?

def f(L):
 [] -> []
 A+[max(L)]+B -> f(A)+[(len(A)+1)*(len(B)+1)]+f(B)


Difference of the square of the sum Find the difference between the square of the sums and sum of the squares.

This is the mathematical representation:

\$\left(\sum n\right)^2-\sum n^2\$

Your program/method should take two inputs, these are your lower and upper limits of the range, and are inclusive.
Limits will be whole integers above 0.

Your program/method should return the answer.

You may use whichever base you would like to, but please state in your answer which base you have used.

Test case (Base 10)

5,9      970
91,123   12087152
1,10     2640

This is usual code-golf, so the shorter the answer the better.

Python 2, 43 bytes

f=lambda a,b,s=0:b/a and 2*a*s+f(a+1,b,s+a)

Test it on Ideone.
How it works
Call the function defined in the specification \$g(a, b)\$. We have that
$$
\newcommand{\sumab}[2]{\sum_{a \le #1 \le b} #2 \:}
\begin{align}
g(a,b) & = \left( \sumab n n \right)^2 - \sumab n {n^2} \\
& = \sumab {i,j} {ij} - \sumab n {n^2} \\
& = \sumab {i<j} {ij} + \sumab {i=j} {ij} + \sumab {j<i} {ij} - \sumab n {n^2} \\
& = 2 \sumab {j<i} {ij} \\
& = 2 \sumab {i} {\sum_{a \le i < j} ij} \\
& = \sumab {i} {\left( 2i \sum_{a \le j < i} j \right)}
\end{align}
$$
Define the function \$f(x, y, s)\$ recursively as follows.
$$ f(x, y, s) =
\begin{cases}
2xs + f(x+1, y, s+x) & \text{ if } x \le y \\
0 & \text{ if} x > y
\end{cases}
$$
By applying the recurrence relation of \$f(a, b, 0)\$ a total of \$b - a\$ times, we can show that:
$$
\begin{align}
f(a, b, 0) & = 2\cdot0 + f(a+1, b, a) \\
& = 2\cdot0 + 2\cdot(a+1)\cdot a + f(a+2, b, a+(a+1)) \\
& = 2\cdot0 + 2\cdot(a+1)\cdot a + 2\cdot(a+2)\cdot(a+(a+1)) + f(a+3, b, a+(a+1)+(a+2)) \\
& \vdots \\
& = \sumab {i} {\left( 2i \sum_{a \le j < i} j \right)} + f\left(b+1, b, \sumab j j\right) \\
& = \sumab {i} {\left( 2i \sum_{a \le j < i} j \right)} \\
& = g(a, b)
\end{align}
$$
This is the function f of the implementation. While b/a returns a non-zero integer, the code following and is executed, thus implementing the recursive definition of f.
Once b/a reaches 0, we have that b > a and the lambda returns False = 0, thus implementing the base case of the definition of f.


Most optimized algorithm for incrementing squares Write the "fastest" program to print an incrementing series of squares from a given input to a given input.

Example input:

-2
7

Example output:

4, 1, 0, 1, 4, 9, 16, 25, 36, 49

When using a "cryptic" language, please post the pseudocode, in addition to your program.

The entries will be judged on the most efficient algorithm.

The tag says "code-challenge", but I don't see any challenge. Just some mathematics we studied when I was about 12.

import java.util.*;

public class IncSquares
{
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        int min = in.nextInt();
        int max = in.nextInt();

        int sq = min * min;
        System.out.print(sq);
        while (min < max) {
            sq += (min << 1) + 1;
            min++;
            System.out.print(", " + sq);
        }
        System.out.println();
    }
}


Solve the Alien Probe puzzle Introduction
In this TED-Ed video (which I'd recommend watching first), a puzzle is presented. 27 unit cubes must be painted with one of red, green, or purple on each face, so that they can be reassembled into a large 3x3x3 cube that shows only red on the outside, then a different arrangement that shows only green, and then only purple. One solution is presented at the end of the video, but it is not obviously generalisable (and there are lots more solutions).
Then, in this lazykh video, a simple algorithm for solving the puzzle is presented. It is as follows:

Paint the faces that currently make up the exterior of the large cube green
For each dimension of the cube (X, Y, Z), shift the arrangement of the cubes over in that direction by 1 unit
Repeat these steps for each colour

The lazykh video has graphics which explain the algorithm more clearly than can be done in this textual medium, so I suggest you watch that as well.
This algorithm generalises easily for higher sizes and numbers of colours than 3 (e.g. a 5x5x5 cube which must be painted with 5 different colours). Interestingly, it also generalises to higher dimensions than 3, but I'll save that for a different challenge.
Challenge
Given the size \$ n \$ (where \$ n \$ is a positive integer) of the large cube, output a solution to the \$ n \times n \times n \$ version of this generalised puzzle.
Using the algorithm described above is certainly  not the only way to find a solution, but I've included it as a starting-point. You are free to work out the solution however you choose.
Output should be given as a list of 6-tuples (or similar structure), representing the face colours of each small cube. The elements of the tuples should be from a predictable sequence of distinct values, (e.g. integers from \$ 0 \$ to \$ n - 1 \$), each representing a colour. The faces within a tuple can be in whatever order you choose but it must be consistent. The list should be flat and \$ n ^ 3 \$ in length, but its elements can be in any order (since they will need to be rearranged anyway for assembly into the \$ n \$ alien probes).
Test cases
Input Output
1     [(0, 0, 0, 0, 0, 0)]
2     [(0, 0, 0, 1, 1, 1), (1, 0, 0, 0, 1, 1), (0, 1, 0, 1, 0, 1), (1, 1, 0, 0, 0, 1), (0, 0, 1, 1, 1, 0), (1, 0, 1, 0, 1, 0), (0, 1, 1, 1, 0, 0), (1, 1, 1, 0, 0, 0)]
3     [(0, 0, 0, 2, 2, 2), (2, 0, 0, 1, 2, 2), (1, 0, 0, 0, 2, 2), (0, 2, 0, 2, 1, 2), (2, 2, 0, 1, 1, 2), (1, 2, 0, 0, 1, 2), (0, 1, 0, 2, 0, 2), (2, 1, 0, 1, 0, 2), (1, 1, 0, 0, 0, 2), (0, 0, 2, 2, 2, 1), (2, 0, 2, 1, 2, 1), (1, 0, 2, 0, 2, 1), (0, 2, 2, 2, 1, 1), (2, 2, 2, 1, 1, 1), (1, 2, 2, 0, 1, 1), (0, 1, 2, 2, 0, 1), (2, 1, 2, 1, 0, 1), (1, 1, 2, 0, 0, 1), (0, 0, 1, 2, 2, 0), (2, 0, 1, 1, 2, 0), (1, 0, 1, 0, 2, 0), (0, 2, 1, 2, 1, 0), (2, 2, 1, 1, 1, 0), (1, 2, 1, 0, 1, 0), (0, 1, 1, 2, 0, 0), (2, 1, 1, 1, 0, 0), (1, 1, 1, 0, 0, 0)]
6     https://gist.github.com/pxeger/a82bdce4427f487490ce0df19840807a#file-6-txt
20    https://gist.github.com/pxeger/a82bdce4427f487490ce0df19840807a#file-20-txt

Rules

Your solution does not need to complete in reasonable time for large \$ n \$, but it must work in theory
Standard loopholes are forbidden
You may use any sensible I/O method
This is code-golf, so the shortest code in bytes wins

Wolfram Language (Mathematica), 36 34 33 30 bytes
#-1|#&~Array~#~Tuples~3/.#->0&

Try it online!
Returns a length-\$n^3\$ list of \$\{x|x',y|y',z|z'\}\$ colorings.
Verify with a \$n\times n\times n\$ matrix output.

Explanation:
Consider a cube \$x\$th from the front in some initial configuration. If the frontmost layer of cubes is painted \$1\$, the second \$2\$, etc., so that the color number increments with each shift, the front face of the cube will be painted \$x\$. After one more shift, the cube will be in the backmost layer, so the back face is painted \$x+1\$.
The same logic applies in other dimensions, so we can paint the cube at position \$(x,y,z)\$ with colors \$(x,y,z,x+1,y+1,z+1)\$ (modulo \$n\$).
#-1|#&~Array~#~Tuples~3         (* 3-tuples of {0|1, 1|2, ..., n-1|n} *)
                       /.#->0&  (* and replace n with 0. *)


Count the ASCII hamantaschen! Today is Purim on which one custom is to give out triangle-shaped cookies with filling called hamantaschen (singular: hamantasch).  Another custom is to drink heavily.

I'm not the most perfect baker.... I have so many irregularly-sized hamantaschen to give out and so many friends to give them to! If I sent you a picture of my cookies, can you tell me how many I have of which size and filling?  But because it's Purim and I'm too drunk to read much code, it needs to be as small code as you can make.

Definitions

Size

A hamantasch can be any size.  The smallest hamantasch is size 1 and looks like these:

/\  --
--  \/

Sometimes, multiple hamantaschen can overlap.  The shape below counts as two hamantaschen (one size 1, one size 2):

 /\
/\ \
----

Some hamantaschen have filling.  This will be indicated by filling all whitespace inside with a character.  Note that size 1 hamantaschen cannot have filling.

We will name hamantaschen based on filling and size.  Let's use the format <filling> <size> and if unfilled, - <size> (you can use a space instead of a -, but markdown doesn't like that).

Here are a . 2, a . 4, and a - 3:

          /\
         /./\
 ----   /./  \
 \../  /./    \
  \/   --------

These are a @ 3, a . 2 and a - 4:

          /\
         / /\
  /\    / /@@\
 /..\  / /@@@@\
 ----  --------

Here's something more difficult.  See how the & 2 has less filling than you've come to expect due to the slant from the overlapping - 3?  It has a - 1, a & 2 a - 3 and a & 4:

--------
\   \/&/
 \  /\/
  \/&/
   \/

Input

You will be given a text file or single string of hamantaschen (optional trailing newline and optionally padded trailing whitespace to be even).

Limits

You can expect the string to be valid - that is, every non-whitespace character contributes to a deliciously sweet hamantasch (why waste dough?).
You can also expect it to be properly filled or not - that is, each hamantasch it will be entirely filled with a consistent ASCII character - ASCII 32 for unfilled, or anything 32..127 for filled (excluding /, \ and -).
These hamantaschen are not stacked in 3-space. All / and \ will be visible.  All - that are not blocked by / and \ will be visible.  Filling comes very last.
All hamantaschen will have at least half of their horizontal line (rounding up) visible.
Any contiguous block of filling only fills the smallest
hamantasch that surrounds it.

Output

Return a list of "names" of all the hamantaschen that can be found meeting the above criteria.  The output can be in whatever form you'd like (a string, a hash, stdout, etc).

Test cases

Test case #1

Input #1:

          /\
         / /\
  /\    / /@@\
 /..\  / /@@@@\
 ----  --------
    /\
   /**\
  /*/\*\
 /*/..\*\
 --------

Output #1:

. 2
. 2
- 4
@ 3
* 4

Test Case #2

Input #2:

  /\----
 /\/\*\/
/ /\d\/
------

Output #2:

- 3
- 2
d 2
- 1
* 2
- 1

Test #3

Input #3:

----
\/\/
/\/\  /\
---- /::\
     ----

Output #3:

- 1
- 1
- 2
- 1
- 1
- 2
: 2

Test #4

Input #4:

 /\/\
/ /\$\
-/--/\\
 --/--\
  /xxx/\
 /xxx/##\
 ---/----\
   /      \
   --------

Output #4:

$ 2
x 4
- 3
- 2
- 4
- 1
- 1
# 2

Invalid Test Case #5

Input:

/\
\/

Output:

You do not need to handle this.

C#, 496 452 bytes

Edit: found a bug with bounds checking... but also striped a load of bytes having been forced to understand my own code. Unrolling the local function helped a bit, and removed the C# 7 specific code. This question has been a lot of fun.

using C=System.Console;class P{static void Main(){string D="",L;int W=0,H=0,z=0,d,q,c,j,b;for(;(L=C.ReadLine())!=null;H+=W=L.Length)D+=L;var B=new int[H];for(d=W;(d=-d)>0||++z<H*H;)for(c=1,q=z%H;c<=z/H&q%W+c<W&q>=d&q<H+d&&D[q]==(d>0?92:47)&D[j=q+c]==(d<0?92:47);q-=d+1,c+=2){for(b=0;j>q;)b+=D[--j-d]==45?2:0;for(char h='-',e;c==z/H&b>c;C.WriteLine(h+" "+c/2))for(b=c++;b>1;j=q+=d+1,b-=2)for(;j<q+b;)B[j]=h=B[j]<1&h==45&(e=D[j++])!=47&e!=92&e>32?e:h;}}}

Try it Online

Complete program, expects space-padded input to standard in, outputs to standard out. The output is one entry per line, with trailing line feed. Cookies are outputted in increasing size order, upper-left most first. It took me a good while to understand the rules, but I think it passes all the examples provided.

It works by repeatedly searching the entire grid for valid Hamantaschen, incrementing the 'allowed' size. For each cell, it checks up and down, following the \ and / on either side as far as it can. If it notices that the next row has lots of -, and the current size is the 'allowed' size, then it determines the filling and prints out the entry.

The filling is found by exploring the entire space of the cookie, looking for an 'unused' cell. When an unused cell is found, it is marked as used (since we increase the allowed size, we know we are the smallest cookie that contains it), and we record the filling.

Formatted and commented code:

using C=System.Console;

class P
{
    static void Main()
    {
        //   32
        // - 45
        // / 47
        // \ 92
        // range 32..127 (no mod for you)

        string D="", // the whole map
            L; // initally each line of the map, later each line of output

        int W=0, // width
            H=0, // length (width * height)
            z=0, // search tracker
            d, // check direction (this is backwards (1 byte saving!))
            q, // check tracker
            c, // counter (truely, this is the distance from the right to the left)
            //M, // c max (now inlined as z/H)
            j, // horiontal tracker
            b; // - count, and reverse counter

        // read map and width
        for(;(L=C.ReadLine())!=null; // read a line, while we can
                H+=W=L.Length) // record the width, and increment height
            D+=L; // add the line to the map

        var B=new int[H]; // whether this filling has been used already (0 -> false, >0 -> true)

        for(d=W; // init direction
            (d=-d)>0|| // swap direction, else increment z (this allows us to run the check for the same z twice with opposite direction)
            ++z<H*H; // for all M, for all q (z<H -> M=z/H=0 -> no valid cookies, so we can safetly skip them)
            )
            for(//M=z/H, // c allow (now inlined)
                c=1, // reset counter
                q=z%H; // note position
                c<=z/H& // counter check
                // no need for a left check: if we run off the left end, then the right check will necessarily fail
                q%W+c<W& // right check
                q>=d& // high check
                q<H+d&& // low check (short-circuit lookups)
                D[q]==(d>0?92:47)&D[j=q+c]==(d<0?92:47); // /\ or \/ check, and set j=q+c
                    q-=d+1, // move left tracker
                    c+=2) // increase counter (move right tracker)
            {
                // count the number of '-' into b
                for(b=0; // zero b
                    j>q; // for each element in the row below
                        ) // empty
                    b+=D[--j-d]==45?2:0; // add 2 to b if we tap a '-'

                // j = q

                // check valid before looking up cHaracter (so we don't mark unused stuff as taken)
                // if we are at the current max count, and we have enough -, then we are valid and should be commited
                for( // this runs either one or zero times, we only have a for here (rather than an if) so we can ditch a pair of braces
                    char h='-', // default filling
                         e; // filling we are considering
                    c==z/H&b>c;
                        C.WriteLine(h+" "+c/2)) // print filling and count
                    // continuously compute character
                    for(b=c++; // count b backwards, starting from c (add 1 to c so we can /2 in print)
                        b>1;j=q+=d+1,b-=2) // count q backwards toward z%H (where q came from), and b backwards toward 1 (for each row)
                        for(;j<q+b;) // for each cell in row
                            B[j]= // mark cell as taken (h,e > 0)
                            h= // record filling
                                B[j]<1& // check cell not already used
                                h==45& // '-'
                                (e=D[j++])!=47& // '/'
                                e!=92& // '\'
                                e>32 // ' '
                                ?e:h; // take first filling we can
                    // c runs out after this (exists both loops), so no need to action
            }
    }
}

Outputs for the 4 test cases:

testcase #1
. 2
. 2
@ 3
- 4
* 4

testcase #2
- 1
- 1
- 2
d 2
* 2
- 3

testcase #3
- 1
- 1
- 1
- 1
- 2
- 2
: 2

testcase #4
- 1
- 1
- 2
$ 2
# 2
- 3
x 4
- 4


Write a Boolfuck Compiler or Interpreter From now on considering the word "fuck" to be non-profane would be a good idea

Make the smallest compiler or an interpreter for the Brainfuck variant, Boolfuck. It has to be executable in Windows, DOS, or a Unix operating system (so Linux, Mac, OpenBSD etc). Boolfuck is very similar to Brainfuck, and a complete definition can be found here.

Differences from Brainfuck

Works with bits not bytes (each cell is a single bit)
The output character is ; not .
The input is read in little endian mode and reads a single bit at a time.
Output is stored to a stream, then outputted in little endian mode

Rules

Use bits for the cells, not bytes
Support the complete list of operations from the official definition:

+  Flips the value of the bit under the pointer.

,  Reads a bit from the input stream, storing it under the pointer.
   The end-user types information using characters, though. Bytes
   are read in little-endian order; the first bit read from the
   character a, for instance, is 1, followed by 0, 0, 0, 0, 1, 1,
   and finally 0.

;  Outputs the bit under the pointer to the output stream. The bits
   get output in little-endian order, the same order in which they
   would be input. If the total number of bits output is not a
   multiple of eight at the end of the program, the last character
   of output gets padded with zeros on the more significant end. If
   the end-of-file character has been input, outputs a zero to the
   bit under the pointer.

<  This moves the pointer left by one bit.

>  This moves the pointer right by one bit.

[  If the value under the pointer is zero, jumps forward, just past
   the matching ] character.
]  Jumps back to the matching [ character.

Any character not in the official definition is ignored.
The program must start in the middle of the tape, not on an end.
The tape must be unbounded in size (infinite in both directions).

Here is a sample Boolfuck program; it outputs Hello, world!:

;;;+;+;;+;+;
+;+;+;+;;+;;+;
;;+;;+;+;;+;
;;+;;+;+;;+;
+;;;;+;+;;+;
;;+;;+;+;+;;
;;;;;+;+;;
+;;;+;+;;;+;
+;;;;+;+;;+;
;+;+;;+;;;+;
;;+;;+;+;;+;
;;+;+;;+;;+;
+;+;;;;+;+;;
;+;+;+;

Perl - 171 bytes

#!perl -0
%h=qw(< --$p > ++$p + $$p^=1 [ while($$p){ ] } ; $o|=$$p<<$g++;$g&=7or$o=!print+chr$o , $f&=7or$_=getc;$$p=1&ord>>$f++);$p=-1e9;eval<ARGV>=~s/./$h{$&};/gr;$g&&print+chr$o

Counting the shebang as 1 byte.

This translates the source into perl, and then evaluates the translation. The target program is taken as a command line argument, input sent to the program should be piped via stdin.

Sample usage:

$ perl boolf.pl hello.blf
Hello, world!

Details

Each of the commands is translated as follows:

< ⇒ --$p;
> ⇒ ++$p;
+ ⇒ $$p^=1;
[ ⇒ while($$p){
] ⇒ }
; ⇒ $o|=$$p<<$g++;$g&=7or$o=!print+chr$o;
, ⇒ $f&=7or$_=getc;$$p=1&ord>>$f++;

Negative integers are valid variable names, which is exploited here. $p, the cell pointer, is initialized as -1000000000, which is approximately at the center of the valid range, -2147483648 .. -1.

I've violated the specification in one regard: output is not printed all at once at the end, but rather as soon as a full byte has been collected. It's slightly longer this way, but I think it's more useful, as it allows for interactive scripts. For example, the Rot13 program below can be run in 'interactive mode', terminating the program with an eof char (^D on linux, ^Z on windows).

  Edit - Demonstration of Endianness

  There seems to be some doubt as to whether this interpreter reads bits in the proper (little-endian) order. I offer the following Boolfuck program, which reads a total of 8 bits, one at a time, and outputs each value read as its numeric ascii representation (0 outputs character 48, 1 outputs character 49). Each value is output entirely before the next bit is even read.

,;[+];;;+;;+;;
,;[+];;;+;;+;;
,;[+];;;+;;+;;
,;[+];;;+;;+;;
,;[+];;;+;;+;;
,;[+];;;+;;+;;
,;[+];;;+;;+;;
,;[+];;;+;;+;;

  Sample usage:

$ echo a | perl boolf.pl test.blf
10000110

  From the problem description:
  "Bytes are read in little-endian order; the first bit read from the character a, for instance, is 1, followed by 0, 0, 0, 0, 1, 1, and finally 0."

  According to this description, the bits are read in the proper order.

Stress Testing

First, a script to translate Brainfuck programs into Boolfuck:

#!perl -n0

%h = (
  '+' => '>[>]+<[+<]>>>>>>>>>[+]<<<<<<<<<',
  '-' => '>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+]<<<<<<<<<',
  '<' => '<<<<<<<<<',
  '>' => '>>>>>>>>>',
  ',' => '>,>,>,>,>,>,>,>,<<<<<<<<',
  '.' => '>;>;>;>;>;>;>;>;<<<<<<<<',
  '[' => '>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]',
  ']' => '>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]'
);

$o .= $h{$_} for /./g;
$o =~ s/<(?R)?>//g;
print $o

The Rot13 program from the Brainfuck Wiki Page translates thusly (with slight modification for null byte eof, rather than 255):

,>,>,>,>,>,>,>,>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]>>>>>>>>>+<<<<<<<<+[>+]
<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]>>>>>>>>>>>>>>>>>>>[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<
[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]+<<<<<<<<+[
>+]<[<]>>>>>>>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>>>>>>>>>]<[+<]+<
<<<<<<<+[>+]<[<]>>>>>>>>>[+]<<<<<<<<,>,>,>,>,>,>,>,>+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]

On a 26 character string, this runs in approximately 0.17 seconds:

$ echo abcdefghijklmnopqrstuvwxyz | timeit perl boolf.pl rot13.blf
nopqrstuvwxyzabcdefghijklm

Elapsed Time:     0:00:00.171

The squares.b from Daniel Cristofani's site:

>[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<
<<<[>]+<[+<]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]>>>>>>>>>>[>]+<
[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]
+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<<+<<<<<<<<+[>+]<[<]>>>>>>>>>[+
]+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]>>>>>>>>>>>>>>>>>>+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<
<<<<[>]+<[+<]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[
+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]<<<<<<<<[>]+<[+<]>>>>>>>>>[+]>>>>>>>>>+<<
<<<<<<+[>+]<[<]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>>>]<[+<]>[>]+<[+<]>>>>>>>>>[+]<<<
<<<<<<<<<<<<<<[>]+<[+<]>>>>>>>>>[+]+<<<<<<<<+[>+]<[<]>>>>>>>>>[+<<<<<<<<[>]+<[+<]>>>>
>>>>>>>>>>>>>>+<<<<<<<<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1444
1521
1600
1681
1764
1849
1936
2025
2116
2209
2304
2401
2500
2601
2704
2809
2916
3025
3136
3249
3364
3481
3600
3721
3844
3969
4096
4225
4356
4489
4624
4761
4900
5041
5184
5329
5476
5625
5776
5929
6084
6241
6400
6561
6724
6889
7056
7225
7396
7569
7744
7921
8100
8281
8464
8649
8836
9025
9216
9409
9604
9801
10000

Elapsed Time:     0:00:02.421


Find the nearest clock hands Challenge

Given a number of seconds past midnight, output the smallest angle between any two hands on a clock face, using as few bytes as possible.

You may assume that the number of seconds is always less than 86400.
Angles may be represented in degrees or radians.

A reference solution is at: http://ideone.com/eVdgC0

Test Cases (results in degrees)

0 -> 0
60 -> 0.5
600 -> 5
3600 -> 0
5400 -> 45
6930 -> 84.75
50000 -> 63.333

Clarificarions

The clock has 3 hands: hours, minutes and seconds.
All hands move continuously, thus hour and minute hands can be found between graduations on the clock face.

CJam, 36 35 34 32 30 bytes

riP*30/_60/_C/]2m*::-:mc:mC$3=

The output is in radians. I've verified the solutions for all 86400 possible inputs.

Try it online in the CJam interpreter.

Idea

Since 2π radians is a full lap, each minute/second interval on the clock is 2π/60 = π/30 radians wide.

Thus, dividing the number of seconds by π/30 yields the position of the second hand.

The minute hand moves at one sixtieth of the pace of the second hand, so dividing the result from above by 60 yields the position of the minute hand.

Likewise, dividing the last result by 12 yields the position of the hour hand.

Note that our three quotient from above are not necessarily in the range [0,2π).

By calculating all nine possible differences of the hands' angles, we obtain three 0's (angular distance between a hand and itself) and the six distances between the different hands.

If the closest hands are on a half that does not include 12, one of the differences from above will be the desired output (mod 2π).

However, at 01:55:30 (for example), the hour hand is at an angle of 1.008 rad (57.75 deg) and the minute hand at an angle of 5.812 rad (333.00 deg) from 12, giving a difference of 4.804 rad (275.25 deg). By subtracting this result from a full lap, we obtain the angle measured "in the other direction", which equals 1.479 rad (84.75 rad).

Now, rather than mapping each angle θ in [0,2π) and conditionally subtracting the result from π, we can simply calculate arccos(cos(θ)), since cos is both periodic and even, and arccos always yields a value in [0,π).

Skipping over the three smallest results (all zero), the fourth smallest will be the desired output.

Code

ri                             e# Read an integer from STDIN.
  P*30/                        e# Multiply by π and divide by 30.
       _60/                    e# Divide a copy by 60.
           _C/                 e# Divide a copy by 12.
              ]2m*             e# Push the array of all pairs of quotients.
                  ::-          e# Replace each pair by its difference.
                     :mc       e# Apply cosine to each difference.
                        :mC    e# Apply arccosine to each cosine.
                           $3= e# Sort and select the fourth smallest element.

Alternate version (34 bytes)

rd6*_60/_C/]360f%2m*::m360X$f-+$6=

The output is in degrees and no trigonometric functions are used.

Try it online in the CJam interpreter.


Determine the lexicographical permutation your code is in Write a program that outputs the number 0.

That's a bit trivial, isn't it?

Let's sort all distinct permutations of your code in lexicographical order. When any of these codes are run, it should output the its location in the array (0-indexed or 1-indexed).

This means that your code must be the lexicographically smallest permutation of your code possible.

For example, if your code is ABB, then ABB -> 0; BAB -> 1; BBA -> 2.

Rules

Out of all distinct permutations of your code, it must be the lexicographically smallest.
Your program must be at least 3 bytes long.
"Output" represents any acceptable output: on the stack, to STDOUT, as a return value, as an exit code, etc.
Your program is to not take any form of input.
This is code-bowling, so longest code wins.

brainfuck, bytes = score

...

Try it online!

How it works: this program only has one distinct permutation and it outputs 0. It trivially satisfies all the other restrictions. The score can be made arbitrarily large by adding more ..


Encode the column cipher Given a string to encode, and a number of columns (the key), encode the string as follows:

I will be using the example Hello, world! and the key 3

First, write out the number of columns:

1 2 3

Next, write the text starting from the upper left, one character per column, and when you run out of columns, go to the next line.

1 2 3
H e l
l o ,
  w o
r l d
!

Now, to get your encoded text, read the text starting from the top left corner, but this time, first read one column, and then the next, and so on. If there is not a character in the slot, put a space.

Hl r!eowl l,od

Note that here, there is a trailing space.

This is your encoded text.

Another test case is Programming Puzzles and Code Golf SE with key 5:

1 2 3 4 5
P r o g r
a m m i n
g   P u z
z l e s
a n d   C
o d e   G
o l f   S
E

The encoded text is PagzaooErm lndl omPedef gius    rnz CGS.

More test cases

"abcdefghijklmnopqrstuvwxyz", 2 -> "acegikmoqsuwybdfhjlnprtvxz"
"codegolf.stackexchange.com", 4 -> "cg.ccgoooskhemdltea. efaxnc "
"Pen Pineapple Apple Pen!!!", 7 -> "PeAeeapnnpp! pl!Ple!ie  n P "
"1,1,2,3,5,8,13,21,34,55,89", 10 -> "18,,,5115,3,2,8,2931 ,, 53 ,4 "

Remember, this is code-golf, so the code with the fewest bytes wins.

MATL, 4 bytes

e!1e

Try it online!

This is about as straightforward as possible. e is a builtin that reshapes a matrix into n rows. So we read in input1 as a string, and shape into a matrix with input2 rows:

Hl r!
eowl
l,od

Then, we transpose it to get this:

Hel
lo,
 wo
rld
!

After that, we just call 1e to reshape it into a single row, and display it as a string.

As you can see in this sample program, the "reshape" function conveniently adds as many zeroes as necessary for the matrix to be a perfect rectangle. When displaying as a string, MATL treats '0's as spaces, so this automatically fills in the necessary number of spaces for no extra work.


Typing with scrambled keys Your friend isn't too good with computers so as a practical joke someone scrambled the letters (a-z) on his keyboard. When he sit down and tried to type his name looking at the keyboard he realized that the letters are scrambled and asked your help.

You are smart so you know that if he types his name and then repeatedly retypes what comes up on the screen instead of his name he will succeed inputting in his name eventually. You are also kind and rearrange the keys but want to know how many turns would it take to succeed.

Your task is to write a program or function that given the shuffling of the letters and the friend's name computes the number of turns.

Input details:

Two string are given as input in a structure convenient for your language.
The first string is the list of the new lowercase letters in alphabetical order of the old ones. (The first character is the one that is at the position of a, last one is  at the position of z.) Some change will always occur in the string.
The second string is the name. It could contain any printable ascii character but only the upper and lowercase alphabetical characters will be shuffled if any. The name itself might not get shuffled at al.

Output details:

Output is a single integer the number of turns minimally required. Newline is optional.

Examples:

Input:
'abcfdeghijklmnopqrstuvwxyz' 'Mr. John Doe' (d, e, f positions changed)

Output:
3 (The shown names are: Mr. John Fod => Mr. John Eof => Mr. John Doe )

Input:
'nopqrstuvwxyzabcdefghijklm' 'Mr. John Doe' (the ROT13 cipher)

Output:
2 (Any input name that contains letters will take 2 rounds to produce the original name.)

Input:
'aebcdjfghiqklmnopzrstuvwxy' 'John Doe'

Output:
140

This is code-golf so the shortest entry wins.

CJam, 31 27 25 24 bytes
l:A;lel:N{_A_$er_N#}g;],

Takes input in the form of:
aebcdjfghiqklmnopzrstuvwxy
Mr. John Doe

i.e. first line - alphabets, second line - name.
How it works:
l:A;lel:N{_A_$er_N#}g;],
l:A;                         "Read the alphabets from the 1st line in A and pop from stack";
    lel:N                    "Read the name in small caps from 2nd line and store in N";
         {         }g        "Run a while loop until we have the original name back again";
          _                  "Put a dummy string on stack just to keep count of times";
           A                 "Put the alphabets on stack";
            _$               "Copy them and sort the copy to get the correct order";
              er             "Transliterate the right keys with the wrong ones";
                _N#          "Copy the result and see if its equal to the original name";
                     ;]      "Pop the last name and wrap everything in an array";
                       ,     "Get the length now. Since we were putting a dummy string";
                             "on stack in each iteration of the while loop, this length";
                             "represents the number of times we tried typing the name";

Try it online here


Can't see the forest for the keys Write a program or function that takes in a nonempty list of integers in any reasonable convenient format such as 4, 0, -1, -6, 2 or [4 0 -1 -6 2].

Print or return a string that depicts the list as an ASCII art forest where each number becomes a tree of proportional height. Each tree takes up four  columns of text in the output as follows:

A positive integer N becomes a tree whose base is __|_ and top is   ^ , with N layers of  / \ in between.

For example, when N = 1 the tree is

  ^
 / \
__|_

when N = 2 the tree is

  ^
 / \
 / \
__|_

when N = 3 the tree is

  ^
 / \
 / \
 / \
__|_

and so on.
A negative integer N becomes just like the corresponding positive tree except a vertical bar is between the branch slashes instead of a space.

For example, when N = -1 the tree is

  ^
 /|\
__|_

when N = -2 the tree is

  ^
 /|\
 /|\
__|_

when N = -3 the tree is

  ^
 /|\
 /|\
 /|\
__|_

and so on.
When the integer is 0 there is technically no tree, just an empty space of four underscores:

____

The underscores at the base of each tree must line up in the output, i.e. all the trees must have their bases at the same level. Also, a single underscore is added to the end of the line of underscores after the last tree. This makes it so every tree has an empty column of "air" on either side of it.

As an example, the output for 4 0 -1 -6 2 would be

              ^
             /|\
  ^          /|\
 / \         /|\
 / \         /|\  ^
 / \      ^  /|\ / \
 / \     /|\ /|\ / \
__|_______|___|___|__

Note how the tree patterns always have a leading column of empty space but an underscore had to be added to pad the right side of the last tree.

Also:

Trailing spaces on any lines are fine, but there should be no unnecessary leading spaces.
Leading newlines are not allowed (the tallest tree should touch the top of the output text grid) and only up to one trailing newline is allowed.
The list may contain any integers from -250 to 250 inclusive. Handling taller trees is not required.

The shortest code in bytes wins.

More Examples

3:

  ^
 / \
 / \
 / \
__|__

-2:

  ^
 /|\
 /|\
__|__

0:

_____

0, 0:

_________

0, 1, 0:

      ^
     / \
______|______

0, -1, 2, -3, 4:

                  ^
              ^  / \
          ^  /|\ / \
      ^  / \ /|\ / \
     /|\ / \ /|\ / \
______|___|___|___|__

Python 2, 165 bytes

a=input()
l=max(map(abs,a))
while l+2:s=' _'[l<0];print(s+s.join((([' ^ ','//| \\\\'[x>0::2],'   '][cmp(abs(x),l)],'_|_')[l<0],s*3)[x==0]for x in a)+s).rstrip();l-=1

This is a full program that accepts a list as input. I'm still golfing this horrid mess.


The Written Digits Sequence Here's a reasonably trivial sequence which is not in the Online Encyclopedia of Integer Sequences.

Start with an empty sequence then define each term as the number of characters required to write out, in English, all of the digits of the sequence so far without spaces.*

For reference the number of characters of all of the (base ten) digits in English are:

zero   one    two    three  four   five   six    seven  eight  nine
4      3      3      5      4      4      3      5      5      4

(Which is the start of both A52360 and A5589.)

This makes the first entry \$a(0) = 0\$ since there are zero digits present in the empty sequence.

This makes the second entry \$a(1) = 4\$ as it takes four characters to write "zero", the only digit present so far.

This makes the third entry \$a(2) = 8\$ as it takes four more characters to write the "four" for a total of eight to write "zerofour".

This makes the fourth entry \$a(3) = 13\$ as it takes five more characters to write "eight" for a total of thirteen to write "zerofoureight".

This makes the fifth entry \$a(4) = 21\$ as it takes eight more characters to write "onethree" for a total of twenty-one to write "zerofoureightonethree".

...and so on. Here are the first 100 entries:

0, 4, 8, 13, 21, 27, 35, 44, 52, 59, 67, 75, 84, 93, 102, 112, 121, 130, 142, 152, 162, 171, 182, 193, 205, 216, 225, 235, 247, 259, 270, 282, 293, 305, 318, 331, 344, 357, 371, 384, 398, 412, 422, 432, 444, 456, 467, 479, 492, 503, 516, 526, 536, 548, 561, 571, 583, 597, 610, 620, 630, 642, 652, 662, 671, 682, 693, 705, 718, 731, 744, 757, 771, 784, 798, 812, 823, 836, 849, 862, 873, 888, 903, 916, 926, 936, 948, 961, 971, 983, 997, 1010, 1024, 1038, 1055, 1070, 1086, 1101, 1114, 1127

* We could define it for other languages and/or other bases or with spaces of course

The challenge

Given \$n\$ output, in as few bytes of code as possible, any of:

The first \$n\$ terms of the sequence (should work for non-negative integers)
The value of \$a(n)\$  (should work for non-negative integers)
The \$n\$th term of the sequence (should work for positive integers - i.e. value of \$a(n-1)\$)

This is code-golf so the shortest answer in bytes wins for each language, and the shortest answer in bytes wins. Don't let golfing languages stop you from entering in your favourite language be it a practical one or an esoteric one!

Perl 6, 45 bytes

{({[+] @_.join.uninames>>.comb X-6}...*)[$_]}

Try it online!
No need for fancy moduloing when you can get the name of the digit directly! Anonymous code block that returns the nth value of the sequence, or you can pass in a range to get a list of values
Explanation:
{(                                     )[$_]}  # Index input into:
  {                               }...*        # An infinite sequence
                                               # Where each element is
   [+]   # The sum of
       @_.join  # All previous elements joined together
              .uninames  # The unicode names for each character
                         # These are names in the form "DIGIT ONE"
                       >>.comb  # Split each to lists of characters
                               X-6  # Subtract 6 from each