答:
PHP - 136 characters

```<code>function t($c){foreach($a=str_split(strrev($c)) as $k=>&$v){$v=array_sum(str_split(($k % 2)!==0?2*$v:$v));}return !(array_sum($a)% 10);}
</code>```

Title: The Luhn algorithm for verifying credit card numbers, etc

Body:
Challenge

Write the shortest program or function to calculate the Luhn Algorithm for verifying (credit card) numbers.

Luhn algorithm explained

From RosettaCode, this algorithm for the purposes of this challenge is specified as such, with the example input of 49927398716:

```<code>Reverse the digits, make an array:
    6, 1, 7, 8, 9, 3, 7, 2, 9, 9, 4
Double the numbers in odd indexes:
    6, 2, 7, 16, 9, 6, 7, 4, 9, 18, 4
Sum the digits in each number:
    6, 2, 7, 7, 9, 6, 7, 4, 9, 9, 4
Sum all of the numbers:
    6 + 2 + 7 + 7 + 9 + 6 + 7 + 4 + 9 + 9 + 4 = 70
If the sum modulo 10 is 0, then the number is valid:
    70 % 10 = 0 => valid
</code>```

IO Rules

Input: A string or number (your choice), in your language's input/output format of choice

Output: A truthy or falsy value, respectively, indicating whether or not the input is valid according to the test above.

Notes / Tips

Try not to accidentally post your own credit card or account numbers, if you use them to test :)

If the input is invalid and impossible to process with the specified algorithm (i.e, too short to work with), you can do whatever you want, including blow up my computer.

However, the previous bullet does not mean that your language can do whatever it wants with Numbers that are too large for it to handle. If your language isn't capable of handling a test case, then consider taking a string as input.

Examples

The following examples were validated with this Python script; if you think one is wrong or have a question, just ping @cat.

```<code>49927398716      True
49927398717      False
1234567812345670 True
1234567812345678 False
79927398710      False
79927398711      False
79927398712      False
79927398713      True
79927398714      False
79927398715      False
79927398716      False
79927398717      False
79927398718      False
79927398719      False
374652346956782346957823694857692364857368475368 True
374652346956782346957823694857692364857387456834 False
8 False **
0 True  **
</code>```

** according to the Python implementation, but you may do anything because these are too short to be eligible by a strict adherence to the specification.

If any of the above invalidates existing answers (though I believe that should not be possible), then those answers are stil valid. However, new answers, in order to be valid, should follow the specification above.

Leaderboard

var QUESTION_ID=22,OVERRIDE_USER=73772;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

Body:
PHP - 136 characters

function t($c){foreach($a=str_split(strrev($c)) as $k=>&$v){$v=array_sum(str_split(($k % 2)!==0?2*$v:$v));}return !(array_sum($a)% 10);}


ContentLicense: CC BY-SA 3.0

Title: Sum the odd square numbers less than N

Body:
Write a program or function to output the sum of the odd square numbers (OEIS #A016754) less than an input n.

The first 44 numbers in the sequence are:

```<code>1, 9, 25, 49, 81, 121, 169, 225, 289, 361, 441, 529, 625, 729, 841, 961, 1089,
1225, 1369, 1521, 1681, 1849, 2025, 2209, 2401, 2601, 2809, 3025, 3249, 3481,
3721, 3969, 4225, 4489, 4761, 5041, 5329, 5625, 5929, 6241, 6561, 6889, 7225, 7569
</code>```

The formula for the sequence is a(n) = ( 2n + 1 ) ^ 2.

Notes

Your program's behaviour may be undefined for n < 1 (that is, all valid inputs are >= 1.)

Test cases

```<code>1 => 0
2 => 1
9 => 1
10 => 10
9801 => 156849
9802 => 166650
10000 => 166650
</code>```

Body:
Ruby, 32 bytes

f=->n,i=1{i*i<n ?i*i+f[n,i+2]:0}


答:
Haskell, 30 bytes

f n=sum[x^2|x<-[1,3..n],x^2<n]
```

Surprisingly normal-looking.

Title: Sum the odd square numbers less than N

Body:
Haskell, 30 bytes

f n=sum[x^2|x<-[1,3..n],x^2<n]

Surprisingly normal-looking.


问:
Driftsort an array
Driftsort is a simple way to "sort" an array. It works by "sliding" or "rotating" the elements over in the array until the array is sorted, or until the array fails to be sorted.

Let's walk through two examples. First, consider the array [10, 2, 3, 4, 7]. Since the array is not sorted, we rotate it once. (This can happen in either direction, so long as it remains the same direction.) Then, the array becomes:

```<code>[7, 10, 2, 3, 4]
</code>```

This is not sorted, so we rotate again.

```<code>[4, 7, 10, 2, 3]
</code>```

And again:

```<code>[3, 4, 7, 10, 2]
</code>```

And a final time:

```<code>[2, 3, 4, 7, 10]
</code>```

And it's sorted! So the array [10, 2, 3, 4, 7] is driftsortable. Here are all the rotations of the array, for clarity:

```<code>[10, 2, 3, 4, 7]
[7, 10, 2, 3, 4]
[4, 7, 10, 2, 3]
[3, 4, 7, 10, 2]
[2, 3, 4, 7, 10]
</code>```

Consider now the array [5, 3, 9, 2, 6, 7]. Look at its rotations:

```<code>[5, 3, 9, 2, 6, 7]
[7, 5, 3, 9, 2, 6]
[6, 7, 5, 3, 9, 2]
[2, 6, 7, 5, 3, 9]
[9, 2, 6, 7, 5, 3]
[3, 9, 2, 6, 7, 5]
</code>```

None of these arrays are sorted, so the array [5, 3, 9, 2, 6, 7] is not driftsortable.

Objective Given a nonempty array/list of integers as input to a program/function, implement driftsort on the input and output it, or output a falsey value (or an empty array/list) if it cannot be driftsorted. The integers are bound to your languages max/min, but this must be at least 255 for the max, and 0 for the min.

You may use built-in sorting methods, but not a built-in which solves the challenge.

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

Test cases

```<code>input => output
[1] => [1]
[5, 0, 5] => [0, 5, 5]
[3, 2, 1] => false
[0, 9, 3] => false
[1, 2, 3, 4] => [1, 2, 3, 4]
[4, 1, 2, 3] => [1, 2, 3, 4]
[0, 2, 0, 2] => false
[5, 3, 9, 2, 6, 7] => false
[0, 0, 0, 0, 0, 0, 0] => [0, 0, 0, 0, 0, 0, 0]
[75, 230, 30, 42, 50] => [30, 42, 50, 75, 230]
[255, 255, 200, 200, 203] => [200, 200, 203, 255, 255]
</code>```

答:
Brachylog, 39 bytes

```<code>l:0re:?{[0:L],!L.|rh$(L,?h-1=:L:1&.}.o.
</code>```

I really need to add an optional argument to $( - circular permute left to permute more than once... this would have been 13 bytes. This will wait after implementing a stable new transpiler in Prolog.

Explanation

```<code>l:0re                                     I = a number between 0 and the length of Input
     :?{[0:L],!L.|rh$(L,?h-1=:L:1&.}      All this mess is simply circular permutating the
                                          input I times
                                    .o.   Unify the Output with that circular permutation
                                          if it is sorted, else try another value of I
</code>```

Title: Driftsort an array

Body:
Brachylog, 39 bytes

l:0re:?{[0:L],!L.|rh$(L,?h-1=:L:1&.}.o.

I really need to add an optional argument to $( - circular permute left to permute more than once... this would have been 13 bytes. This will wait after implementing a stable new transpiler in Prolog.

Explanation

l:0re                                     I = a number between 0 and the length of Input
     :?{[0:L],!L.|rh$(L,?h-1=:L:1&.}      All this mess is simply circular permutating the
                                          input I times
                                    .o.   Unify the Output with that circular permutation
                                          if it is sorted, else try another value of I


答:
Julia, <s>71</s> <s>66</s> 52 bytes

x->(y=sort(x))∈[circshift(x,i)for i=1:endof(x)]&&y
```

This is an anonymous function that accepts an array and returns an array or a boolean. To call it, assign it to a variable.

For an input array x, we construct the set of all rotations of x and check whether the sorted version x is an element of that list. If it is, we return x sorted, otherwise we return false.

Saved 19 bytes thanks to Dennis!

Title: Driftsort an array

Body:
Driftsort is a simple way to "sort" an array. It works by "sliding" or "rotating" the elements over in the array until the array is sorted, or until the array fails to be sorted.

Let's walk through two examples. First, consider the array [10, 2, 3, 4, 7]. Since the array is not sorted, we rotate it once. (This can happen in either direction, so long as it remains the same direction.) Then, the array becomes:

```<code>[7, 10, 2, 3, 4]
</code>```

This is not sorted, so we rotate again.

```<code>[4, 7, 10, 2, 3]
</code>```

And again:

```<code>[3, 4, 7, 10, 2]
</code>```

And a final time:

```<code>[2, 3, 4, 7, 10]
</code>```

And it's sorted! So the array [10, 2, 3, 4, 7] is driftsortable. Here are all the rotations of the array, for clarity:

```<code>[10, 2, 3, 4, 7]
[7, 10, 2, 3, 4]
[4, 7, 10, 2, 3]
[3, 4, 7, 10, 2]
[2, 3, 4, 7, 10]
</code>```

Consider now the array [5, 3, 9, 2, 6, 7]. Look at its rotations:

```<code>[5, 3, 9, 2, 6, 7]
[7, 5, 3, 9, 2, 6]
[6, 7, 5, 3, 9, 2]
[2, 6, 7, 5, 3, 9]
[9, 2, 6, 7, 5, 3]
[3, 9, 2, 6, 7, 5]
</code>```

None of these arrays are sorted, so the array [5, 3, 9, 2, 6, 7] is not driftsortable.

Objective Given a nonempty array/list of integers as input to a program/function, implement driftsort on the input and output it, or output a falsey value (or an empty array/list) if it cannot be driftsorted. The integers are bound to your languages max/min, but this must be at least 255 for the max, and 0 for the min.

You may use built-in sorting methods, but not a built-in which solves the challenge.

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

Test cases

```<code>input => output
[1] => [1]
[5, 0, 5] => [0, 5, 5]
[3, 2, 1] => false
[0, 9, 3] => false
[1, 2, 3, 4] => [1, 2, 3, 4]
[4, 1, 2, 3] => [1, 2, 3, 4]
[0, 2, 0, 2] => false
[5, 3, 9, 2, 6, 7] => false
[0, 0, 0, 0, 0, 0, 0] => [0, 0, 0, 0, 0, 0, 0]
[75, 230, 30, 42, 50] => [30, 42, 50, 75, 230]
[255, 255, 200, 200, 203] => [200, 200, 203, 255, 255]
</code>```

Body:
Julia, <s>71</s> <s>66</s> 52 bytes

x->(y=sort(x))∈[circshift(x,i)for i=1:endof(x)]&&y

This is an anonymous function that accepts an array and returns an array or a boolean. To call it, assign it to a variable.

For an input array x, we construct the set of all rotations of x and check whether the sorted version x is an element of that list. If it is, we return x sorted, otherwise we return false.

Saved 19 bytes thanks to Dennis!


答:
Ruby, 47 bytes

Recursive function. Returns nil if the input array cannot be driftsorted.

```<code>f=->a,i=0{a.sort==a ?a:a[i+=1]?f[a.rotate,i]:p}
</code>```

Title: Driftsort an array

Body:
Ruby, 47 bytes

Recursive function. Returns nil if the input array cannot be driftsorted.

f=->a,i=0{a.sort==a ?a:a[i+=1]?f[a.rotate,i]:p}


答:
Python 2, 51 bytes

lambda l:sorted(l)*(map(cmp,l[-1:]+l,l).count(1)<3)
```

Doesn't bother rotating. Instead, sorts the list, then sees if the original is drift-sortable by checking if there's at most one decrease among consecutive elements of the cyclified list. The count is <3 because map pads the shorter list with None at the end, adding a fake decrease.

Title: Driftsort an array

Body:
Python 2, 51 bytes

lambda l:sorted(l)*(map(cmp,l[-1:]+l,l).count(1)<3)

Doesn't bother rotating. Instead, sorts the list, then sees if the original is drift-sortable by checking if there's at most one decrease among consecutive elements of the cyclified list. The count is <3 because map pads the shorter list with None at the end, adding a fake decrease.


答:
Racket, 57 bytes

```<code>(λ(n)(for/sum([m(map sqr(range 1 n 2))]#:when(< m n))m))
</code>```

Title: Sum the odd square numbers less than N

Body:
Racket, 57 bytes

(λ(n)(for/sum([m(map sqr(range 1 n 2))]#:when(< m n))m))


答:
Python, 83 bytes

```<code>def f(l):g=sorted(l);return g if any(l[x:]+l[:x]==g for x in range(len(l)))else 1>2
</code>```

This got put to shame by the other python answers, but I might as well post it anyway. I really dislike the

```<code>range(len(l)))
</code>```

part. Is there a faster way to iterate through the list?

Title: Driftsort an array

Body:
Python, 83 bytes

def f(l):g=sorted(l);return g if any(l[x:]+l[:x]==g for x in range(len(l)))else 1>2

This got put to shame by the other python answers, but I might as well post it anyway. I really dislike the

range(len(l)))

part. Is there a faster way to iterate through the list?


答:
Ruby, 33

```<code>->a{a.any?{a.sort==a.rotate!}&&a}
</code>```

a.any? fires up to once for each element in the array, except it stops (and returns true) as soon as the array has been mutated into a sorted state. If this happens, we return the mutated array. Otherwise we return the false value that any? returns.

Title: Driftsort an array

Body:
Ruby, 33

->a{a.any?{a.sort==a.rotate!}&&a}

a.any? fires up to once for each element in the array, except it stops (and returns true) as soon as the array has been mutated into a sorted state. If this happens, we return the mutated array. Otherwise we return the false value that any? returns.


答:
JavaScript (ES6), <s>72</s> <s>70</s> 65 bytes

```<code>a=>a.map(y=>{c+=x>y;x=y},x=a.slice(c=-1))|c<1&&a.sort((a,b)=>a-b)
</code>```

Returns 0 on failure. Previous <s>85</s> <s>83</s> 80-byte version avoided calling sort:

```<code>a=>a.map((y,i)=>{x>y&&(c++,j=i);x=y},x=a.slice(c=-1))|c<1&&a.splice(j).concat(a)
</code>```

Edit: Saved 2 bytes by initialising c to -1 instead of 0. Saved 5 bytes by switching from reduce to map, sigh...

Title: Driftsort an array

Body:
JavaScript (ES6), <s>72</s> <s>70</s> 65 bytes

a=>a.map(y=>{c+=x>y;x=y},x=a.slice(c=-1))|c<1&&a.sort((a,b)=>a-b)

Returns 0 on failure. Previous <s>85</s> <s>83</s> 80-byte version avoided calling sort:

a=>a.map((y,i)=>{x>y&&(c++,j=i);x=y},x=a.slice(c=-1))|c<1&&a.splice(j).concat(a)

Edit: Saved 2 bytes by initialising c to -1 instead of 0. Saved 5 bytes by switching from reduce to map, sigh...


答:
MATLAB/Octave,  118 bytes

```<code>function r(a)
i=0
while (~issorted(a) && i<length(a))
    a=a([2:end 1]),i=i+1
end
if issorted(a)
    a
else
    0
end
</code>```

Title: Driftsort an array

Body:
MATLAB/Octave,  118 bytes

function r(a)
i=0
while (~issorted(a) && i<length(a))
    a=a([2:end 1]),i=i+1
end
if issorted(a)
    a
else
    0
end


答:
PowerShell v2+, <s>87</s> 80 bytes

```<code>param($a)0..($a.length-1)|%{if($a[$_-1]-gt$a[$_]){$c--}};(0,($a|sort))[++$c-ge0]
</code>```

Steps through the input list $a, checking each pairwise element (including the last and first) to see if there is more than one decreasing pair. If the particular pair is decreasing, we decrement $c. Outputs either the sorted list, or single element 0, based on the value of $c at the end. If more than one "bad" pair is present, then ++$c will still be negative, otherwise it will be at least 0, so the second element of the pseudo-ternary is chosen ($a|sort).

I see xnor did something similar, but I came up with this independently.

Title: Driftsort an array

Body:
PowerShell v2+, <s>87</s> 80 bytes

param($a)0..($a.length-1)|%{if($a[$_-1]-gt$a[$_]){$c--}};(0,($a|sort))[++$c-ge0]

Steps through the input list $a, checking each pairwise element (including the last and first) to see if there is more than one decreasing pair. If the particular pair is decreasing, we decrement $c. Outputs either the sorted list, or single element 0, based on the value of $c at the end. If more than one "bad" pair is present, then ++$c will still be negative, otherwise it will be at least 0, so the second element of the pseudo-ternary is chosen ($a|sort).

I see xnor did something similar, but I came up with this independently.


答:
05AB1E, 12 bytes

Code:

```<code>DgFÀÐ{Qi,}}0
</code>```

Uses CP-1252 encoding. Try it online!.

Title: Driftsort an array

Body:
05AB1E, 12 bytes

Code:

DgFÀÐ{Qi,}}0

Uses CP-1252 encoding. Try it online!.


答:
Matlab, <s>61</s> <s>47</s> 41 bytes

Thanks @Suever for -6 bytes!

```<code>@(a)sort(a)+0*min(strfind([a,a],sort(a)))
</code>```

If strfind([a,a],sort(a)) tries to find the sorted input vector as a 'substring' of the unsorted, that was appended to itself. If true, the input is driftsortable and we get a vector of length 2, if not we get a empty vector. min just transforms this to an number / empty vector. Adding the sorted vector to 0 just displays it, adding it to an empty vector throws an error.

Title: Driftsort an array

Body:
Matlab, <s>61</s> <s>47</s> 41 bytes

Thanks @Suever for -6 bytes!

@(a)sort(a)+0*min(strfind([a,a],sort(a)))

If strfind([a,a],sort(a)) tries to find the sorted input vector as a 'substring' of the unsorted, that was appended to itself. If true, the input is driftsortable and we get a vector of length 2, if not we get a empty vector. min just transforms this to an number / empty vector. Adding the sorted vector to 0 just displays it, adding it to an empty vector throws an error.


答:
Pyke, 7 bytes (noncompetitive)

Add up_to function which repeats until the rtn is above inp.

```<code>#}hX)Os
</code>```

Explanation:

```<code>#   )   -  While rtn < input:
        -   i = 0
 }hX    -    rtn = ((i*2)+1)**2
        -   i+=1
     O  -  rtn[:-1]
      s - sum(^)
</code>```

Try it here!

Title: Sum the odd square numbers less than N

Body:
Pyke, 7 bytes (noncompetitive)

Add up_to function which repeats until the rtn is above inp.

#}hX)Os

Explanation:

#   )   -  While rtn < input:
        -   i = 0
 }hX    -    rtn = ((i*2)+1)**2
        -   i+=1
     O  -  rtn[:-1]
      s - sum(^)

Try it here!


答:
Jelly, 6 bytes

```<code>ṙỤċṢȧṢ
</code>```

Try it online! or verify all test cases.

How it works

```<code>ṙỤċṢȧṢ  Main link. Argument: A (list)

 Ụ      Grade up; return the indices of A, sorted by their corresponding values.
ṛ       Rotate A by each index, yielding the list of all rotations.
   Ṣ    Yield A, sorted.
  ċ     Count the number of times sorted(A) appears in the rotations.
        This gives 0 if the list isn't driftsortable.
    ȧṢ  Logical AND with sorted(A); replaces a positive count with the sorted list.
</code>```

Title: Driftsort an array

Body:
Jelly, 6 bytes

ṙỤċṢȧṢ

Try it online! or verify all test cases.

How it works

ṙỤċṢȧṢ  Main link. Argument: A (list)

 Ụ      Grade up; return the indices of A, sorted by their corresponding values.
ṛ       Rotate A by each index, yielding the list of all rotations.
   Ṣ    Yield A, sorted.
  ċ     Count the number of times sorted(A) appears in the rotations.
        This gives 0 if the list isn't driftsortable.
    ȧṢ  Logical AND with sorted(A); replaces a positive count with the sorted list.


答:
Pyth, 9 bytes

```<code>*SQ}SQ.:+
</code>```

Explanation:

```<code>           - Q = eval(input())
         + -    Q+Q
       .:  -   sublists(^)
   }       -  V in ^
    SQ     -   sorted(Q)
*SQ        - ^ * sorted(Q) (return sorted(Q) if ^ True)
</code>```

Try it here!

Or use a test suite!

Title: Driftsort an array

Body:
Pyth, 9 bytes

*SQ}SQ.:+

Explanation:

           - Q = eval(input())
         + -    Q+Q
       .:  -   sublists(^)
   }       -  V in ^
    SQ     -   sorted(Q)
*SQ        - ^ * sorted(Q) (return sorted(Q) if ^ True)

Try it here!

Or use a test suite!


问:
Tips for golfing in MATL
MATL is a golfing language created by Luis Mendo. MATL has proven to be highly competitive, often beating submissions in other golfing languages such as Pyth, CJam and Jelly.

What are some useful tips for golfing in MATL? (As always, one tip per answer, please!)

For the record, MATL can be tested online here.

Documentation can be found on Github

答:
Know the predefined literals

Although some of them keep information when copied to the clipboard, they all have a predefined value.

F, pushes 0 (actually False)

T, pushes 1 (actually True)

H, pushes 2 (predefined clipboard value)

I, pushes 3 (predefined clipboard value)

K, pushes 4 (predefined clipboard value)

J, pushes 0 + 1j (predefined clipboard value)

Not sure if I have covered all predefined values though.

Title: Tips for golfing in MATL


问:
Tips for golfing in PARI/GP
PARI/GP is a free computer algebra system. It is designed for (algebraic) number theory, not golfing, but that's part of the attraction. Unsurprisingly, it fares best at mathematical tasks; its support for string manipulation is primitive. (Having said that, advice for golfing non-mathematical tasks is also welcome.)

As usual, please post one tip per answer.

These tips should be at least somewhat specific to PARI/GP; advice which applies to 'most' languages belongs at Tips for golfing in <all languages>. Some general tips which don't need to be included:

Compress whitespace. (In GP all whitespace outside of strings is optional.)

Use single-character variables. (There are 50 choices, a-z and A-Z except I and O.)

Use < and > rather than <= and >= when possible.

Chain assignments. (a=b=c or a+=b*=c)

答:
Use operators to replace commands (or longer operators!) when possible.

length(v) → #v (saves 5-7 bytes)

matsize(M)[2] → #M (saves 9-11 bytes)

matsize(M)[1] → #M~ (saves 8-10 bytes)

floor(x) → x\1 (saves 3-5 bytes)

round(x) → x\/1 (saves 2-4 bytes)*

shift(x,n) → x>>n or x<<n (saves 2-6 bytes)

sqr(x) → x^2 (saves 1-3 bytes)

deriv(x) → x' (saves 4-6 bytes)

mattranspose(M) → M~ (saves 11-13 bytes)

factorial(n) → n! (saves 8-10 bytes)

&& → & (saves 1 byte; note that this syntax is deprecated)

|| → | (saves 1 byte; only works in older versions)

* Prior to 2.8.1 (2016) the \/ operator did not work correctly on t_REAL numbers—update if you haven't!

Title: Tips for golfing in PARI/GP


答:
Snowman 1.0.2, 27 bytes

```<code>((}#AsO|##aC,as|aLNdE`aR*))
</code>```

This is a subroutine that takes input from and outputs to the current permavar.

Try it online!

```<code>((                       ))  subroutine
  }                          set our active variables b, e, and g:
                              .[a] *[b] .[c]
                              .[d]      *[e]    (* represents an active variable)
                              .[f] *[g] .[h]
   #                         store the input in variable b
    AsO                      sort in-place
       |                     swap b with g; now sorted input is in g
        ##                   store the input again in b and e
          aC                 concat; now the input doubled is in b and e is empty
            ,                swap e/g; now b has 2*input and e has sorted input
             as              split 2*input on sort(input) and store result in g
               |             bring the result up to b (we no longer care about g)
                aLNdE        take length and decrement; now we have 0 in b if the
                               array is not driftsortable and 1 if it is
                     `aR     repeat e (the sorted array) b times:
                               if b is 0 (nondriftsortable), returns [] (falsy)
                               otherwise (b=1), returns sorted array unchanged
                        *    put this back into the permavar
</code>```

Title: Driftsort an array

Body:
Snowman 1.0.2, 27 bytes

((}#AsO|##aC,as|aLNdE`aR*))

This is a subroutine that takes input from and outputs to the current permavar.

<a href="http://snowman.tryitonline.net/#code=Ly8gdGhlIGJlbG93IHN0cmluZyAoY2RlZmFiKSBpcyB0aGUgaW5wdXQuIEluIFNub3dtYW4sIHN0cmluZ3MgYXJlIHJlYWxseSBqdXN0Ci8vIGFycmF5cyBvZiBBU0NJSSBjb2Rlcy4gSSdtIHVzaW5nIGEgc3RyaW5nIGhlcmUgYmVjYXVzZSBpdCdzIHZlcnkgYW5ub3lpbmcKLy8gdG8gcHJvZHVjZSBhcnJheXMgb2YgY29uc3RhbnQgbnVtYmVycyBpbiBTbm93bWFu4oCUYnV0ICJjZGVmYWIiIGV4cGFuZHMgdG8KLy8gWzk5IDEwMCAxMDEgMTAyIDk3IDk4XS4gRm9yIGFuIGV4YW1wbGUgb2YgYSBmYWxzeSB0ZXN0IGNhc2UsIHRyeSBjaGFuZ2luZwovLyAiY2RlZmFiIiB0byBzb21ldGhpbmcgbGlrZSAiY2VkYWZiIi4KfiJjZGVmYWIiKgoKLy8gaGVyZSdzIHRoZSBzdWJyb3V0aW5lIGNhbGw6CigofSNBc098IyNhQyxhc3xhTE5kRWBhUiopKQoKLy8gbm93IHdlIG91dHB1dCB0aGUgcmVzdWx04oCUZW1wdHkgYXJyYXkgaXMgcmV0dXJuZWQgZm9yIHRoZSBmYWxzeSB2YWx1ZSAoYWthCi8vIGVtcHR5IHN0cmluZywgc28gbm90aGluZyB3aWxsIGJlIHNlbnQgdG8gU1RET1VUKQojc1A&input=" rel="nofollow">Try it online!

((                       ))  subroutine
  }                          set our active variables b, e, and g:
                              .[a] *[b] .[c]
                              .[d]      *[e]    (* represents an active variable)
                              .[f] *[g] .[h]
   #                         store the input in variable b
    AsO                      sort in-place
       |                     swap b with g; now sorted input is in g
        ##                   store the input again in b and e
          aC                 concat; now the input doubled is in b and e is empty
            ,                swap e/g; now b has 2*input and e has sorted input
             as              split 2*input on sort(input) and store result in g
               |             bring the result up to b (we no longer care about g)
                aLNdE        take length and decrement; now we have 0 in b if the
                               array is not driftsortable and 1 if it is
                     `aR     repeat e (the sorted array) b times:
                               if b is 0 (nondriftsortable), returns [] (falsy)
                               otherwise (b=1), returns sorted array unchanged
                        *    put this back into the permavar


答:
CJam, <s>17</s> 13 bytes

Thanks to Dennis for saving 4 bytes.

```<code>{_$\_+1$#)g*}
</code>```

An unnamed block (function) which takes and returns a list.

Test suite.

Explanation

This essentially uses xnor's observation that the sorted list appears in twice the original list if its drift sortable:

```<code>_$   e# Duplicate input and sort.
\_+  e# Get other copy and append to itself.
1$   e# Copy sorted list.
#    e# Find first position of sorted list in twice the original,
     e# of -1 if it's not found.
)g   e# Increment and take signum to map to 0 or 1.
*    e# Repeat sorted array that many times to turn it into an empty
     e# array if the input was not drift sortable.
</code>```

Title: Driftsort an array

Body:
CJam, <s>17</s> 13 bytes

Thanks to Dennis for saving 4 bytes.

{_$\_+1$#)g*}

An unnamed block (function) which takes and returns a list.

<a href="http://cjam.aditsu.net/#code=qN%2F%7B'%2C-%22%20%3D%3E%20%22%2F0%3D~%0A%0A%7B_%24%5C2*1%24%23)g*%7D%0A%0A~pNo%7D%2F&input=%5B1%5D%20%3D%3E%20%5B1%5D%0A%5B5%2C%200%2C%205%5D%20%3D%3E%20%5B0%2C%205%2C%205%5D%0A%5B3%2C%202%2C%201%5D%20%3D%3E%20false%0A%5B0%2C%209%2C%203%5D%20%3D%3E%20false%0A%5B1%2C%202%2C%203%2C%204%5D%20%3D%3E%20%5B1%2C%202%2C%203%2C%204%5D%0A%5B4%2C%201%2C%202%2C%203%5D%20%3D%3E%20%5B1%2C%202%2C%203%2C%204%5D%0A%5B0%2C%202%2C%200%2C%202%5D%20%3D%3E%20false%0A%5B5%2C%203%2C%209%2C%202%2C%206%2C%207%5D%20%3D%3E%20false%0A%5B0%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%5D%20%3D%3E%20%5B0%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%5D%0A%5B75%2C%20230%2C%2030%2C%2042%2C%2050%5D%20%3D%3E%20%5B30%2C%2042%2C%2050%2C%2075%2C%20230%5D%0A%5B255%2C%20255%2C%20200%2C%20200%2C%20203%5D%20%3D%3E%20%5B200%2C%20200%2C%20203%2C%20255%2C%20255%5D" rel="nofollow">Test suite.

Explanation

This essentially uses xnor's observation that the sorted list appears in twice the original list if its drift sortable:

_$   e# Duplicate input and sort.
\_+  e# Get other copy and append to itself.
1$   e# Copy sorted list.
#    e# Find first position of sorted list in twice the original,
     e# of -1 if it's not found.
)g   e# Increment and take signum to map to 0 or 1.
*    e# Repeat sorted array that many times to turn it into an empty
     e# array if the input was not drift sortable.


问:
Finish a symmetrical map
You are given one-quarter of a map that is symmetrical over the x- and y-axes as input. The program should print the complete map.

The map can contain the following characters: -+/\|., and they should be turned as expected. The in data is always rectangular and small.

Example

```<code>$ cat in
+---
|./.
|/..

$ ./solution < in
+------+
|./..\.|
|/....\|
|\..../|
|.\../.|
+------+
</code>```

Shortest code wins.

ContentLicense: CC BY-SA 2.5

Title: Finish a symmetrical map

Body:
Perl, 80 chars

print reverse map{s@.*@($b=$&)=~y:/\\:\\/:,$&.reverse$b@e;print;y@/\\@\\/@;$_}<>


答:
Pip, 15 + 1 = <s>17</s> 16 bytes

Ugh, the other golfing languages are blowing this out of the water. However, since I've already written it...

```<code>L#gI$<gPBPOgYgy
</code>```

Takes input as space-separated command-line arguments. Requires -p or another array-formatting flag to display the result legibly rather than concatenated. The false case outputs an empty string, which is visible by virtue of the trailing newline.

```<code>                 Implicit: g is array of cmdline args; y is empty string
L#g              Loop len(g) times:
         POg       Pop the first item from g
      gPB          Push it onto the back of g
    $<             Fold on < (true if g is now sorted)
   I        Yg     If true, yank g into y
              y  Autoprint y
</code>```

Title: Driftsort an array

Body:
Driftsort is a simple way to "sort" an array. It works by "sliding" or "rotating" the elements over in the array until the array is sorted, or until the array fails to be sorted.

Let's walk through two examples. First, consider the array [10, 2, 3, 4, 7]. Since the array is not sorted, we rotate it once. (This can happen in either direction, so long as it remains the same direction.) Then, the array becomes:

```<code>[7, 10, 2, 3, 4]
</code>```

This is not sorted, so we rotate again.

```<code>[4, 7, 10, 2, 3]
</code>```

And again:

```<code>[3, 4, 7, 10, 2]
</code>```

And a final time:

```<code>[2, 3, 4, 7, 10]
</code>```

And it's sorted! So the array [10, 2, 3, 4, 7] is driftsortable. Here are all the rotations of the array, for clarity:

```<code>[10, 2, 3, 4, 7]
[7, 10, 2, 3, 4]
[4, 7, 10, 2, 3]
[3, 4, 7, 10, 2]
[2, 3, 4, 7, 10]
</code>```

Consider now the array [5, 3, 9, 2, 6, 7]. Look at its rotations:

```<code>[5, 3, 9, 2, 6, 7]
[7, 5, 3, 9, 2, 6]
[6, 7, 5, 3, 9, 2]
[2, 6, 7, 5, 3, 9]
[9, 2, 6, 7, 5, 3]
[3, 9, 2, 6, 7, 5]
</code>```

None of these arrays are sorted, so the array [5, 3, 9, 2, 6, 7] is not driftsortable.

Objective Given a nonempty array/list of integers as input to a program/function, implement driftsort on the input and output it, or output a falsey value (or an empty array/list) if it cannot be driftsorted. The integers are bound to your languages max/min, but this must be at least 255 for the max, and 0 for the min.

You may use built-in sorting methods, but not a built-in which solves the challenge.

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

Test cases

```<code>input => output
[1] => [1]
[5, 0, 5] => [0, 5, 5]
[3, 2, 1] => false
[0, 9, 3] => false
[1, 2, 3, 4] => [1, 2, 3, 4]
[4, 1, 2, 3] => [1, 2, 3, 4]
[0, 2, 0, 2] => false
[5, 3, 9, 2, 6, 7] => false
[0, 0, 0, 0, 0, 0, 0] => [0, 0, 0, 0, 0, 0, 0]
[75, 230, 30, 42, 50] => [30, 42, 50, 75, 230]
[255, 255, 200, 200, 203] => [200, 200, 203, 255, 255]
</code>```

Body:
Pip, 15 + 1 = <s>17</s> 16 bytes

Ugh, the other golfing languages are blowing this out of the water. However, since I've already written it...

L#gI$<gPBPOgYgy

Takes input as space-separated command-line arguments. Requires -p or another array-formatting flag to display the result legibly rather than concatenated. The false case outputs an empty string, which is visible by virtue of the trailing newline.

                 Implicit: g is array of cmdline args; y is empty string
L#g              Loop len(g) times:
         POg       Pop the first item from g
      gPB          Push it onto the back of g
    $<             Fold on < (true if g is now sorted)
   I        Yg     If true, yank g into y
              y  Autoprint y


Title: Driftsort an array

Body:
Javascript ES6, <s>48</s> <s>45</s> 43 chars

x=>~(x+[,x]).indexOf(x.sort((a,b)=>a-b))&&x

Test:

f=x=>~(x+[,x]).indexOf(x.sort((a,b)=>a-b))&&x
;`[1] => [1]
[5, 0, 5] => [0, 5, 5]
[3, 2, 1] => false
[0, 9, 3] => false
[1, 2, 3, 4] => [1, 2, 3, 4]
[4, 1, 2, 3] => [1, 2, 3, 4]
[0, 2, 0, 2] => false
[5, 3, 9, 2, 6, 7] => false
[0, 0, 0, 0, 0, 0, 0] => [0, 0, 0, 0, 0, 0, 0]
[75, 230, 30, 42, 50] => [30, 42, 50, 75, 230]
[255, 255, 200, 200, 203] => [200, 200, 203, 255, 255]`
.split`
`.map(t => t.replace(/^(.*) => (.*)$/, "f($1)+'' == $2")).every(eval)


问:
The Luhn algorithm for verifying credit card numbers, etc

Challenge

Write the shortest program or function to calculate the Luhn Algorithm for verifying (credit card) numbers.

Luhn algorithm explained

From RosettaCode, this algorithm for the purposes of this challenge is specified as such, with the example input of 49927398716:

```<code>Reverse the digits, make an array:
    6, 1, 7, 8, 9, 3, 7, 2, 9, 9, 4
Double the numbers in odd indexes:
    6, 2, 7, 16, 9, 6, 7, 4, 9, 18, 4
Sum the digits in each number:
    6, 2, 7, 7, 9, 6, 7, 4, 9, 9, 4
Sum all of the numbers:
    6 + 2 + 7 + 7 + 9 + 6 + 7 + 4 + 9 + 9 + 4 = 70
If the sum modulo 10 is 0, then the number is valid:
    70 % 10 = 0 => valid
</code>```

IO Rules

Input: A string or number (your choice), in your language's input/output format of choice

Output: A truthy or falsy value, respectively, indicating whether or not the input is valid according to the test above.

Notes / Tips

Try not to accidentally post your own credit card or account numbers, if you use them to test :)

If the input is invalid and impossible to process with the specified algorithm (i.e, too short to work with), you can do whatever you want, including blow up my computer.

However, the previous bullet does not mean that your language can do whatever it wants with Numbers that are too large for it to handle. If your language isn't capable of handling a test case, then consider taking a string as input.

Examples

The following examples were validated with this Python script; if you think one is wrong or have a question, just ping @cat.

```<code>49927398716      True
49927398717      False
1234567812345670 True
1234567812345678 False
79927398710      False
79927398711      False
79927398712      False
79927398713      True
79927398714      False
79927398715      False
79927398716      False
79927398717      False
79927398718      False
79927398719      False
374652346956782346957823694857692364857368475368 True
374652346956782346957823694857692364857387456834 False
8 False **
0 True  **
</code>```

** according to the Python implementation, but you may do anything because these are too short to be eligible by a strict adherence to the specification.

If any of the above invalidates existing answers (though I believe that should not be possible), then those answers are stil valid. However, new answers, in order to be valid, should follow the specification above.

Leaderboard

var QUESTION_ID=22,OVERRIDE_USER=73772;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

Body:
Perl, <s>46</s> <s>42</s> 41 bytes

Includes +1 for -p

Give input on STDIN:

luhn.pl <<< 79927398713

luhn.pl:

#!/usr/bin/perl -p
s%.%$=-=-$&-$&*1.2*/\G(..)+$/%eg;$_=/0$/


答:
Julia, 29 bytes

f(n,i=1)=i^2<n?i^2+f(n,i+2):0
```

This is a recursive function that accepts an integer and returns an integer.

We start an index at 1 and if its square is less than the input, we take the square and add the result of recusing on the index + 2, which ensures that even numbers are skipped, otherwise we return 0.

Title: Sum the odd square numbers less than N

Body:
Write a program or function to output the sum of the odd square numbers (OEIS #A016754) less than an input n.

The first 44 numbers in the sequence are:

```<code>1, 9, 25, 49, 81, 121, 169, 225, 289, 361, 441, 529, 625, 729, 841, 961, 1089,
1225, 1369, 1521, 1681, 1849, 2025, 2209, 2401, 2601, 2809, 3025, 3249, 3481,
3721, 3969, 4225, 4489, 4761, 5041, 5329, 5625, 5929, 6241, 6561, 6889, 7225, 7569
</code>```

The formula for the sequence is a(n) = ( 2n + 1 ) ^ 2.

Notes

Your program's behaviour may be undefined for n < 1 (that is, all valid inputs are >= 1.)

Test cases

```<code>1 => 0
2 => 1
9 => 1
10 => 10
9801 => 156849
9802 => 166650
10000 => 166650
</code>```

Body:
Julia, 29 bytes

f(n,i=1)=i^2<n?i^2+f(n,i+2):0

This is a recursive function that accepts an integer and returns an integer.

We start an index at 1 and if its square is less than the input, we take the square and add the result of recusing on the index + 2, which ensures that even numbers are skipped, otherwise we return 0.


答:
C++, 313 <s>359</s> <s>370</s> bytes

Huge shoutout to @Qwertiy for getting this working and teaching me some great golfing methods!

Golfed:

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main(){vector<int> v;int x,c=0,s=0,y;while(cin>>x)v.push_back(x);do if(rotate(v.begin(),v.begin()+1,v.end()),c++,is_sorted(v.begin(),v.end()))s=1;while(!s&c<=v.size());if(s)for(y=0;y<v.size();y++)cout<<v[y]<<" ";else cout<<"False";}
```

<h3>Ungolfed:</h3>

<pre class="lang-cpp prettyprint-override"><code>#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

int main(){
  vector <int> v;
  int x, c=0, s=0, y;

  while(cin>>x)
    v.push_back(x);

  do
    if (
      rotate(v.begin(),v.begin()+1,v.end()),
      c++,
      is_sorted(v.begin(),v.end())
    ) s = 1;
  while(!s & c <= v.size());

  if (s)
    for(y=0; y<v.size(); y++)
      cout<<v[y]<<" ";
  else
    cout<<"False";
}
</code>```

Title: Driftsort an array

Body:
C++, 313 <s>359</s> <s>370</s> bytes

Huge shoutout to @Qwertiy for getting this working and teaching me some great golfing methods!

Golfed:

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main(){vector<int> v;int x,c=0,s=0,y;while(cin>>x)v.push_back(x);do if(rotate(v.begin(),v.begin()+1,v.end()),c++,is_sorted(v.begin(),v.end()))s=1;while(!s&c<=v.size());if(s)for(y=0;y<v.size();y++)cout<<v[y]<<" ";else cout<<"False";}

Ungolfed:

#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

int main(){
  vector <int> v;
  int x, c=0, s=0, y;

  while(cin>>x)
    v.push_back(x);

  do
    if (
      rotate(v.begin(),v.begin()+1,v.end()),
      c++,
      is_sorted(v.begin(),v.end())
    ) s = 1;
  while(!s & c <= v.size());

  if (s)
    for(y=0; y<v.size(); y++)
      cout<<v[y]<<" ";
  else
    cout<<"False";
}


答:
MATL, <s>13</s> <s>12</s> <s>10</s> 9 bytes

```<code>SGthyXfa*
</code>```

The same idea as @flawr's answer where we hijack strfind (Xf) to find the sorted version of the input within the concatenation of two copies of the input.

Try it Online!

Explanation

```<code>        % Implicitly get input
S       % Sort the input
Gth     % Explicitly grab the input again and concatenate with itself
y       % Copy the sorted version from the bottom of the stack
Xf      % Look for the sorted version as a subset
a       % Gives a 1 if there were matches and 0 otherwise
*       % Multiply by the sorted array. Yields all zeros for no match and the
        % sorted array when a match was found
        % Implicitly display the stack contents
</code>```

Title: Driftsort an array

Body:
MATL, <s>13</s> <s>12</s> <s>10</s> 9 bytes

SGthyXfa*

The same idea as @flawr's answer where we hijack strfind (Xf) to find the sorted version of the input within the concatenation of two copies of the input.

Try it Online!

Explanation

        % Implicitly get input
S       % Sort the input
Gth     % Explicitly grab the input again and concatenate with itself
y       % Copy the sorted version from the bottom of the stack
Xf      % Look for the sorted version as a subset
a       % Gives a 1 if there were matches and 0 otherwise
*       % Multiply by the sorted array. Yields all zeros for no match and the
        % sorted array when a match was found
        % Implicitly display the stack contents


答:
Factor, 47 bytes

```<code>[ dup dup append [ natural-sort ] dip subseq? ]
</code>```

join the sequence onto itself, then check if the sorted rendition of the original is a subsequence.

Title: Driftsort an array

Body:
Factor, 47 bytes

[ dup dup append [ natural-sort ] dip subseq? ]

join the sequence onto itself, then check if the sorted rendition of the original is a subsequence.


答:
Mathematica <s>55 50 61</s> 58 bytes

With 3 bytes saved thanks to Martin Büttner.

My earlier attempts did not pass all of the test case. I needed to add Union to avoid repetitions in list that were input in order.

```<code>Join@Union@Cases[NestList[RotateRight,#,Length@#],Sort@#]&
</code>```

Tests

```<code>Join@Union@Cases[NestList[RotateRight,#,Length@#],Sort@#]&/@
{{1},{5,0,5},{3,2,1},{0,9,3},{1,2,3,4},{4,1,2,3},{0,2,0,2},{5,3,9,2,6,7},
{0,0,0,0,0,0,0},{75,230,30,42,50},{255,255,200,200,203}}
</code>```

{{1}, {0, 5, 5}, {}, {}, {1, 2, 3, 4}, {1, 2, 3, 4}, {}, {}, {0, 0, 0,
     0, 0, 0, 0}, {30, 42, 50, 75, 230}, {200, 200, 203, 255, 255}}

Explanation

Right rotate the input list from 1 to n times, where n is the length of the input list.  If the sorted input list is among the output rotated lists, return it; otherwise return an empty list.

Title: Driftsort an array

Body:
Mathematica <s>55 50 61</s> 58 bytes

With 3 bytes saved thanks to Martin Büttner.

My earlier attempts did not pass all of the test case. I needed to add Union to avoid repetitions in list that were input in order.

Join@Union@Cases[NestList[RotateRight,#,Length@#],Sort@#]&

Tests

Join@Union@Cases[NestList[RotateRight,#,Length@#],Sort@#]&/@
{{1},{5,0,5},{3,2,1},{0,9,3},{1,2,3,4},{4,1,2,3},{0,2,0,2},{5,3,9,2,6,7},
{0,0,0,0,0,0,0},{75,230,30,42,50},{255,255,200,200,203}}

{{1}, {0, 5, 5}, {}, {}, {1, 2, 3, 4}, {1, 2, 3, 4}, {}, {}, {0, 0, 0,
     0, 0, 0, 0}, {30, 42, 50, 75, 230}, {200, 200, 203, 255, 255}}

Explanation

Right rotate the input list from 1 to n times, where n is the length of the input list.  If the sorted input list is among the output rotated lists, return it; otherwise return an empty list.


问:
Calculator that adds char values

Task

Build a calculator, that takes any string, from a file, stdin or whatever, and adds up all the values of the chars.

Example

```<code>Input
Hello World!

Output
1085
</code>```

Rules

The calculator needs to accept just ASCII encoding.

The shortest code wins.

Notes

Regarding to the comment of m.buettner, I need to say, I didn't thought of the multibyte part.

So I leave it as a bonus thing aswell.

The calculator should be run as written, so no need to modify before compiling or interpreting.

Bonus

Thanks to Synthetica, here is one more bonus,

The program that has the lowest output when you use its code as its input wins gets a star.

I don't want to modify it completly.

If you write it additional to output the (right) value in UTF-8 you get a star.

The code that executes fastest on my Laptop (Lenovo Yoga 13 Intel Core i5 3317U 1.7Ghz, 8GB RAM, 128GB SSD, Intel HD 4000, Windows 8) gets a star.

Web codes will run first under IE11 with chakra and then in FireFox 29.0.1 with SpiderMonkey

Linux code will run on a Raspberry Pi with Raspbian.

The teststring is this:

```<code>q/%8hnp>T%y?'wNb\},9krW &D9']K$n;l.3O+tE*$*._B^s!@k\&Cl:EO1zo8sVxEvBxCock_I+2o6 yeX*0Xq:tS^f)!!7=!tk9K<6#/E`ks(D'$z$\6Ac+MT&[s[]_Y(`<g%"w%cW'`c&q)D$0#C$QGf>?A$iawvc,}`9!('`c&q)D$0#C$QGf>?A$iawvc,}`9!(
</code>```

Have fun coding :)

Bonusscoring

I plan to do the scoring at this Saturday so the 07.06.14, all answers after that date won't get bonus points ;)

You can download the code I gonna use for testing here feel free to fork and improve it :)

Little update because of the bonus, my laptop is partially broken so I will do it probably next weekend, I am really sorry for that :(

答:
C++, 131 <s>140</s> bytes

Golfed:

#include<iostream>
int main(){int a=0;std::string x;getline(std::cin,x);for(int c=0;c<x.length();c++){a=a+(int)x[c];}std::cout<<a;}
```

<h3>Ungolfed:</h3>

<pre class="lang-cpp prettyprint-override"><code>#include<iostream>

int main(){
    int a = 0;
    std::string x;
    getline(std::cin, x);
    for(int c = 0; c < x.length(); c++){
        a = a + (int) x[c];
    }
    std::cout<<a;
}
</code>```

Title: Calculator that adds char values

Body:
C++, 131 <s>140</s> bytes

Golfed:

#include<iostream>
int main(){int a=0;std::string x;getline(std::cin,x);for(int c=0;c<x.length();c++){a=a+(int)x[c];}std::cout<<a;}

Ungolfed:

#include<iostream>

int main(){
    int a = 0;
    std::string x;
    getline(std::cin, x);
    for(int c = 0; c < x.length(); c++){
        a = a + (int) x[c];
    }
    std::cout<<a;
}


答:
Logical arrays can often be used as numeric arrays

You can often use "TF" notation instead of array literals of zeros and ones. For example, FTF is the same as [0,1,0], only that FTF produces logical values, not double values. This is usually not a problem, as any arithmetical operation will treat logical values as numbers. For example, FTFQ gives [1,2,1] (Q is "increase by 1").

In some cases, conversion of a number to binary may be shorter. For example, [1,0,1], TFT and 5B are the same; again with the caution that the latter two are logical values.

A case where the difference between TF (logical) and [1 0] (numeric) matters is when used as indices. An array of type logical used as an index means: pick elements corresponding to T, discard those corresponding to F. So [10 20]TF) produces 10 (select the first element), whereas [10 20][1 0]) produces [10 20] (the index [1 0] has the interpretation of 1:end, that is, pick all elements of the array).

Title: Tips for golfing in MATL

Body:
MATL is a golfing language created by Luis Mendo. MATL has proven to be highly competitive, often beating submissions in other golfing languages such as Pyth, CJam and Jelly.

What are some useful tips for golfing in MATL? (As always, one tip per answer, please!)

For the record, MATL can be tested online here.

Documentation can be found on Github


问:
Regex Golf: Verify a Sudoku Solution
Write a regex which matches any valid sudoku solution and doesn't match any invalid sudoku solution. The input is an unrolled version of the sudoku, i.e. there are no line delimiters. E.g. the following board:

```<code>7 2 5 8 9 3 4 6 1
8 4 1 6 5 7 3 9 2
3 9 6 1 4 2 7 5 8
4 7 3 5 1 6 8 2 9
1 6 8 4 2 9 5 3 7
9 5 2 3 7 8 1 4 6
2 3 4 7 6 1 9 8 5
6 8 7 9 3 5 2 1 4
5 1 9 2 8 4 6 7 3
</code>```

would be given as:

```<code>725893461841657392396142758473516829168429537952378146234761985687935214519284673
</code>```

The rules are probably common knowledge by now, but just in case... a sudoku board is valid if and only if:

Each row contains the digits from 1 to 9 exactly once.

Each column contains the digits from 1 to 9 exactly once.

Each of the nine 3x3 subgrids contains the digits from 1 to 9 exactly once.

Rules

Your answer should consist of a single regex, without any additional code (except, optionally, a list of regex modifiers required to make your solution work). You must not use features of your language's regex flavour that allow you to invoke code in the hosting language (e.g. Perl's e modifier).

You can use any regex flavour which existed before this challenge, but please specify the flavour.

Do not assume that the regex is anchored implicitly. E.g. if you're using Python, assume that your regex is used with re.search and not with re.match. Your regex does not need to match the entire string. It just needs to match at least one substring (which may be empty) for valid solutions and yield no matches for invalid solutions.

You may assume that the input will always be a string of 81 positive digits.

This is regex golf, so the shortest regex in bytes wins. If your language requires delimiters (usually /.../) to denote regular expressions, don't count the delimiters themselves. If your solution requires modifiers, add one byte per modifier.

Test Cases

Valid boards:

```<code>123456789456789123789123456231564897564897231897231564312645978645978312978312645
725893461841657392396142758473516829168429537952378146234761985687935214519284673
395412678824376591671589243156928437249735186738641925983164752412857369567293814
679543182158926473432817659567381294914265738283479561345792816896154327721638945
867539142324167859159482736275398614936241587481756923592873461743615298618924375
954217683861453729372968145516832497249675318783149256437581962695324871128796534
271459386435168927986273541518734269769821435342596178194387652657942813823615794
237541896186927345495386721743269158569178432812435679378652914924813567651794283
168279435459863271273415986821354769734692518596781342615947823387526194942138657
863459712415273869279168354526387941947615238138942576781596423354821697692734185
768593142423176859951428736184765923572389614639214587816942375295837461347651298
243561789819327456657489132374192865926845317581673294162758943735914628498236571
243156789519847326687392145361475892724918653895263471152684937436729518978531264
498236571735914628162758943581673294926845317374192865657489132819327456243561789
978531264436729518152684937895263471724918653361475892687392145519847326243156789
341572689257698143986413275862341957495726831173985426519234768734869512628157394
</code>```

Invalid boards:

```<code>519284673725893461841657392396142758473516829168429537952378146234761985687935214
839541267182437659367158924715692843624973518573864192298316475941285736456729381
679543182158926473432817659567381294914256738283479561345792816896154327721638945
867539142324167859159482736275398684936241517481756923592873461743615298618924375
754219683861453729372968145516832497249675318983147256437581962695324871128796534
271459386435168927986273541518734269769828435342596178194387652657942813823615794
237541896186927345378652914743269158569178432812435679495386721924813567651794283
168759432459613278273165984821594763734982516596821347615437829387246195942378651
869887283619214453457338664548525781275424668379969727517385163319223917621449519
894158578962859187461322315913849812241742157275462973384219294849882291119423759
123456789456789123564897231231564897789123456897231564312645978645978312978312645
145278369256389147364197258478512693589623471697431582712845936823956714931764825
243561789829317456657489132374192865916845327581673294162758943735924618498236571
243156789529847316687392145361475892714928653895263471152684937436719528978531264
498236571735924618162758943581673294916845327374192865657489132829317456243561789
978531264436719528152684937895263471714928653361475892687392145529847316243156789
342571689257698143986413275861342957495726831173985426519234768734869512628157394
345678192627319458892451673468793521713524986951862347179246835534187269286935714
341572689257698143986413275862341957495726831173985426519234768734869512628517394
</code>```

For further test cases, you can use this CJam script which takes a valid board as input and randomly shuffles it to give a new valid board (input format irrelevant as long as it contains only digits and optionally whitespace).

If your regex is compatible with the .NET flavour, you can test it online using Retina. A valid solution should print 0 for invalid boards and some positive integer for valid boards. To run all test cases at once, use this template and insert the regex on the second line. If you need regex modifiers, prepend a ` to the regex and put the standard modifier letters in front of it.

答:
.NET regex, 8339 bytes

Yes, I know my solution is very naive, since Martin told me he did it in like 130 bytes. In fact, the URL to try it online is so long that I couldn't find a URL shortener that would accept it.

```<code>(code removed, since it's so long nobody will read it here,
and it made the post take forever to load. Just use the "Try it online" link.)
</code>```

The below link does not work in IE, but does work in Chrome and Firefox.

Try it online - All test cases at once, with the help of !`  at the beginning, not included in byte count.

Here's the Python script I used to generate it (code below):

R=range(0,9)
S=range(1,10)

o = ""

# validate rows
T = "(?=.{%s,%s}%s)"
for j in R:
    for i in S:
        o += T % (9*j,9*(j+1)-1, i)

# validate columns
# "(?=(.{%s}|.{%s}|.{%s}|.{%s}|.{%s}|.{%s}|.{%s}|.{%s}|.{%s})%s)"
T = "(?=("+"|".join([".{%s}"]*9)+")%s)"
for j in R:
    for i in S:
        o += T % (j,j+9,j+18,j+27,j+36,j+45,j+54,j+63,j+72, i)

# validate boxes
# (?=.{0,2}1|.{9,11}1|.{18,20}1)(?=.{3,5}1|.{12,14}1|.{21,23}1)
# (?=.{27,29}1|.{36,38}1|.{45,47}1)
T = ".{%s,%s}%s"
for i in S:
    for x in (0,27,54):
        for y in (0,3,6):
            o += "(?="+"|".join(T % (x+y+z,x+y+z+2, i) for z in (0,9,18))+")"

o += ".{81}"

o = o.replace(".{0}","").replace(",80}",",}")
print(o)
```

Title: Regex Golf: Verify a Sudoku Solution

Body:
.NET regex, 8339 bytes

Yes, I know my solution is very naive, since Martin told me he did it in like 130 bytes. In fact, the URL to try it online is so long that I couldn't find a URL shortener that would accept it.

(code removed, since it's so long nobody will read it here,
and it made the post take forever to load. Just use the "Try it online" link.)

The below link does not work in IE, but does work in Chrome and Firefox.

<a href="http://retina.tryitonline.net/#[encoded data, 11127 characters]&input=MTIzNDU2Nzg5NDU2Nzg5MTIzNzg5MTIzNDU2MjMxNTY0ODk3NTY0ODk3MjMxODk3MjMxNTY0MzEyNjQ1OTc4NjQ1OTc4MzEyOTc4MzEyNjQ1CjcyNTg5MzQ2MTg0MTY1NzM5MjM5NjE0Mjc1ODQ3MzUxNjgyOTE2ODQyOTUzNzk1MjM3ODE0NjIzNDc2MTk4NTY4NzkzNTIxNDUxOTI4NDY3MwozOTU0MTI2Nzg4MjQzNzY1OTE2NzE1ODkyNDMxNTY5Mjg0MzcyNDk3MzUxODY3Mzg2NDE5MjU5ODMxNjQ3NTI0MTI4NTczNjk1NjcyOTM4MTQKNjc5NTQzMTgyMTU4OTI2NDczNDMyODE3NjU5NTY3MzgxMjk0OTE0MjY1NzM4MjgzNDc5NTYxMzQ1NzkyODE2ODk2MTU0MzI3NzIxNjM4OTQ1Cjg2NzUzOTE0MjMyNDE2Nzg1OTE1OTQ4MjczNjI3NTM5ODYxNDkzNjI0MTU4NzQ4MTc1NjkyMzU5Mjg3MzQ2MTc0MzYxNTI5ODYxODkyNDM3NQo5NTQyMTc2ODM4NjE0NTM3MjkzNzI5NjgxNDU1MTY4MzI0OTcyNDk2NzUzMTg3ODMxNDkyNTY0Mzc1ODE5NjI2OTUzMjQ4NzExMjg3OTY1MzQKMjcxNDU5Mzg2NDM1MTY4OTI3OTg2MjczNTQxNTE4NzM0MjY5NzY5ODIxNDM1MzQyNTk2MTc4MTk0Mzg3NjUyNjU3OTQyODEzODIzNjE1Nzk0CjIzNzU0MTg5NjE4NjkyNzM0NTQ5NTM4NjcyMTc0MzI2OTE1ODU2OTE3ODQzMjgxMjQzNTY3OTM3ODY1MjkxNDkyNDgxMzU2NzY1MTc5NDI4MwoxNjgyNzk0MzU0NTk4NjMyNzEyNzM0MTU5ODY4MjEzNTQ3Njk3MzQ2OTI1MTg1OTY3ODEzNDI2MTU5NDc4MjMzODc1MjYxOTQ5NDIxMzg2NTcKODYzNDU5NzEyNDE1MjczODY5Mjc5MTY4MzU0NTI2Mzg3OTQxOTQ3NjE1MjM4MTM4OTQyNTc2NzgxNTk2NDIzMzU0ODIxNjk3NjkyNzM0MTg1Cjc2ODU5MzE0MjQyMzE3Njg1OTk1MTQyODczNjE4NDc2NTkyMzU3MjM4OTYxNDYzOTIxNDU4NzgxNjk0MjM3NTI5NTgzNzQ2MTM0NzY1MTI5OAoKNTE5Mjg0NjczNzI1ODkzNDYxODQxNjU3MzkyMzk2MTQyNzU4NDczNTE2ODI5MTY4NDI5NTM3OTUyMzc4MTQ2MjM0NzYxOTg1Njg3OTM1MjE0CjgzOTU0MTI2NzE4MjQzNzY1OTM2NzE1ODkyNDcxNTY5Mjg0MzYyNDk3MzUxODU3Mzg2NDE5MjI5ODMxNjQ3NTk0MTI4NTczNjQ1NjcyOTM4MQo2Nzk1NDMxODIxNTg5MjY0NzM0MzI4MTc2NTk1NjczODEyOTQ5MTQyNTY3MzgyODM0Nzk1NjEzNDU3OTI4MTY4OTYxNTQzMjc3MjE2Mzg5NDUKODY3NTM5MTQyMzI0MTY3ODU5MTU5NDgyNzM2Mjc1Mzk4Njg0OTM2MjQxNTE3NDgxNzU2OTIzNTkyODczNDYxNzQzNjE1Mjk4NjE4OTI0Mzc1Cjc1NDIxOTY4Mzg2MTQ1MzcyOTM3Mjk2ODE0NTUxNjgzMjQ5NzI0OTY3NTMxODk4MzE0NzI1NjQzNzU4MTk2MjY5NTMyNDg3MTEyODc5NjUzNAoyNzE0NTkzODY0MzUxNjg5Mjc5ODYyNzM1NDE1MTg3MzQyNjk3Njk4Mjg0MzUzNDI1OTYxNzgxOTQzODc2NTI2NTc5NDI4MTM4MjM2MTU3OTQKMjM3NTQxODk2MTg2OTI3MzQ1Mzc4NjUyOTE0NzQzMjY5MTU4NTY5MTc4NDMyODEyNDM1Njc5NDk1Mzg2NzIxOTI0ODEzNTY3NjUxNzk0MjgzCjE2ODc1OTQzMjQ1OTYxMzI3ODI3MzE2NTk4NDgyMTU5NDc2MzczNDk4MjUxNjU5NjgyMTM0NzYxNTQzNzgyOTM4NzI0NjE5NTk0MjM3ODY1MQo4Njk4ODcyODM2MTkyMTQ0NTM0NTczMzg2NjQ1NDg1MjU3ODEyNzU0MjQ2NjgzNzk5Njk3Mjc1MTczODUxNjMzMTkyMjM5MTc2MjE0NDk1MTkKODk0MTU4NTc4OTYyODU5MTg3NDYxMzIyMzE1OTEzODQ5ODEyMjQxNzQyMTU3Mjc1NDYyOTczMzg0MjE5Mjk0ODQ5ODgyMjkxMTE5NDIzNzU5CjEyMzQ1Njc4OTQ1Njc4OTEyMzU2NDg5NzIzMTIzMTU2NDg5Nzc4OTEyMzQ1Njg5NzIzMTU2NDMxMjY0NTk3ODY0NTk3ODMxMjk3ODMxMjY0NQoxNDUyNzgzNjkyNTYzODkxNDczNjQxOTcyNTg0Nzg1MTI2OTM1ODk2MjM0NzE2OTc0MzE1ODI3MTI4NDU5MzY4MjM5NTY3MTQ5MzE3NjQ4MjU" rel="noreferrer">Try it online - All test cases at once, with the help of !`  at the beginning, not included in byte count.

Here's the Python script I used to generate it (code below):

R=range(0,9)
S=range(1,10)

o = ""

# validate rows
T = "(?=.{%s,%s}%s)"
for j in R:
    for i in S:
        o += T % (9*j,9*(j+1)-1, i)

# validate columns
# "(?=(.{%s}|.{%s}|.{%s}|.{%s}|.{%s}|.{%s}|.{%s}|.{%s}|.{%s})%s)"
T = "(?=("+"|".join([".{%s}"]*9)+")%s)"
for j in R:
    for i in S:
        o += T % (j,j+9,j+18,j+27,j+36,j+45,j+54,j+63,j+72, i)

# validate boxes
# (?=.{0,2}1|.{9,11}1|.{18,20}1)(?=.{3,5}1|.{12,14}1|.{21,23}1)
# (?=.{27,29}1|.{36,38}1|.{45,47}1)
T = ".{%s,%s}%s"
for i in S:
    for x in (0,27,54):
        for y in (0,3,6):
            o += "(?="+"|".join(T % (x+y+z,x+y+z+2, i) for z in (0,9,18))+")"

o += ".{81}"

o = o.replace(".{0}","").replace(",80}",",}")
print(o)


答:
C++ 14, 242 chars

#include<iostream>
#include<vector>
#include<algorithm>
#define b v.begin()
using namespace std;int main(){vector<int>v;int x,n=0;for(;cin>>x;++n)v.push_back(x);for(x=n;x--;rotate(b,b+1,b+n))if(is_sorted(b,b+n)){for(x:v)cout<<x<<' ';return 0;}}
```

<p>If I can't leave output empty, 252 chars http://ideone.com/HAzJ5V</p>

<pre class="lang-cpp prettyprint-override"><code>#include<iostream>
#include<vector>
#include<algorithm>
#define b v.begin()
using namespace std;int main(){vector<int>v;int x,n=0;for(;cin>>x;++n)v.push_back(x);for(x=n;x--;rotate(b,b+1,b+n))if(is_sorted(b,b+n)){for(x:v)cout<<x<<' ';return 0;}cout<<'-';}
</code>```

Ungolfed version http://ideone.com/Dsbs8W

#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

#define b v.begin()

int main()
{
  vector <int> v;
  int x, n=0;

  for(;cin>>x;++n)
    v.push_back(x);

  for(x=n;x--;rotate(b,b+1,b+n))
    if(is_sorted(b,b+n))
    {
      for(x:v) cout<<x<<' ';
      return 0;
    }

  cout << '-';
}
```

PS: Based on @MichelfrancisBustillos's idea.

Title: Driftsort an array

Body:
C++ 14, 242 chars

#include<iostream>
#include<vector>
#include<algorithm>
#define b v.begin()
using namespace std;int main(){vector<int>v;int x,n=0;for(;cin>>x;++n)v.push_back(x);for(x=n;x--;rotate(b,b+1,b+n))if(is_sorted(b,b+n)){for(x:v)cout<<x<<' ';return 0;}}

If I can't leave output empty, 252 chars http://ideone.com/HAzJ5V

#include<iostream>
#include<vector>
#include<algorithm>
#define b v.begin()
using namespace std;int main(){vector<int>v;int x,n=0;for(;cin>>x;++n)v.push_back(x);for(x=n;x--;rotate(b,b+1,b+n))if(is_sorted(b,b+n)){for(x:v)cout<<x<<' ';return 0;}cout<<'-';}

Ungolfed version http://ideone.com/Dsbs8W

#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

#define b v.begin()

int main()
{
  vector <int> v;
  int x, n=0;

  for(;cin>>x;++n)
    v.push_back(x);

  for(x=n;x--;rotate(b,b+1,b+n))
    if(is_sorted(b,b+n))
    {
      for(x:v) cout<<x<<' ';
      return 0;
    }

  cout << '-';
}

PS: Based on @MichelfrancisBustillos's idea.


答:
Java 7, 207 bytes

int[]D(int[]i){int x,z;z=x=-1;int[]d=new int[i.length];while(++xi[(x+1)%i.length])if(z<0)z=(x+1)%i.length;else return null;if(z<0)z=0;x=-1;while(++x<d.length)d[x]=i[z++%i.length];return d;}
```

<p><strong>Detailed</strong> <em>try here</em></p>

<pre class="lang-java prettyprint-override"><code>// driftsort in ascending-order
int[] D(int[]i)
{
    int x = -1,z = -1;
    int[] d = new int[i.length];

    while ((++x) < i.length)
    {
        if (i[x] > i[(x+1)%i.length])
        {
            if(z < 0) z = (x+1)%i.length;
            else return null; // not driftsortable
        }
    }

    if(z < 0) z = 0;
    x = -1;
    while ((++x) < d.length)
    {
        d[x] = i[(z++)%i.length];
    }

    return d;
}
</code>```

Title: Driftsort an array

Body:
Java 7, 207 bytes

int[]D(int[]i){int x,z;z=x=-1;int[]d=new int[i.length];while(++x<i.length)if(i[x]>i[(x+1)%i.length])if(z<0)z=(x+1)%i.length;else return null;if(z<0)z=0;x=-1;while(++x<d.length)d[x]=i[z++%i.length];return d;}

Detailed try here

// driftsort in ascending-order
int[] D(int[]i)
{
    int x = -1,z = -1;
    int[] d = new int[i.length];

    while ((++x) < i.length)
    {
        if (i[x] > i[(x+1)%i.length])
        {
            if(z < 0) z = (x+1)%i.length;
            else return null; // not driftsortable
        }
    }

    if(z < 0) z = 0;
    x = -1;
    while ((++x) < d.length)
    {
        d[x] = i[(z++)%i.length];
    }

    return d;
}


Title: Regex Golf: Verify a Sudoku Solution

Body:
Write a regex which matches any valid sudoku solution and doesn't match any invalid sudoku solution. The input is an unrolled version of the sudoku, i.e. there are no line delimiters. E.g. the following board:

```<code>7 2 5 8 9 3 4 6 1
8 4 1 6 5 7 3 9 2
3 9 6 1 4 2 7 5 8
4 7 3 5 1 6 8 2 9
1 6 8 4 2 9 5 3 7
9 5 2 3 7 8 1 4 6
2 3 4 7 6 1 9 8 5
6 8 7 9 3 5 2 1 4
5 1 9 2 8 4 6 7 3
</code>```

would be given as:

```<code>725893461841657392396142758473516829168429537952378146234761985687935214519284673
</code>```

The rules are probably common knowledge by now, but just in case... a sudoku board is valid if and only if:

Each row contains the digits from 1 to 9 exactly once.

Each column contains the digits from 1 to 9 exactly once.

Each of the nine 3x3 subgrids contains the digits from 1 to 9 exactly once.

Rules

Your answer should consist of a single regex, without any additional code (except, optionally, a list of regex modifiers required to make your solution work). You must not use features of your language's regex flavour that allow you to invoke code in the hosting language (e.g. Perl's e modifier).

You can use any regex flavour which existed before this challenge, but please specify the flavour.

Do not assume that the regex is anchored implicitly. E.g. if you're using Python, assume that your regex is used with re.search and not with re.match. Your regex does not need to match the entire string. It just needs to match at least one substring (which may be empty) for valid solutions and yield no matches for invalid solutions.

You may assume that the input will always be a string of 81 positive digits.

This is regex golf, so the shortest regex in bytes wins. If your language requires delimiters (usually /.../) to denote regular expressions, don't count the delimiters themselves. If your solution requires modifiers, add one byte per modifier.

Test Cases

Valid boards:

```<code>123456789456789123789123456231564897564897231897231564312645978645978312978312645
725893461841657392396142758473516829168429537952378146234761985687935214519284673
395412678824376591671589243156928437249735186738641925983164752412857369567293814
679543182158926473432817659567381294914265738283479561345792816896154327721638945
867539142324167859159482736275398614936241587481756923592873461743615298618924375
954217683861453729372968145516832497249675318783149256437581962695324871128796534
271459386435168927986273541518734269769821435342596178194387652657942813823615794
237541896186927345495386721743269158569178432812435679378652914924813567651794283
168279435459863271273415986821354769734692518596781342615947823387526194942138657
863459712415273869279168354526387941947615238138942576781596423354821697692734185
768593142423176859951428736184765923572389614639214587816942375295837461347651298
243561789819327456657489132374192865926845317581673294162758943735914628498236571
243156789519847326687392145361475892724918653895263471152684937436729518978531264
498236571735914628162758943581673294926845317374192865657489132819327456243561789
978531264436729518152684937895263471724918653361475892687392145519847326243156789
341572689257698143986413275862341957495726831173985426519234768734869512628157394
</code>```

Invalid boards:

```<code>519284673725893461841657392396142758473516829168429537952378146234761985687935214
839541267182437659367158924715692843624973518573864192298316475941285736456729381
679543182158926473432817659567381294914256738283479561345792816896154327721638945
867539142324167859159482736275398684936241517481756923592873461743615298618924375
754219683861453729372968145516832497249675318983147256437581962695324871128796534
271459386435168927986273541518734269769828435342596178194387652657942813823615794
237541896186927345378652914743269158569178432812435679495386721924813567651794283
168759432459613278273165984821594763734982516596821347615437829387246195942378651
869887283619214453457338664548525781275424668379969727517385163319223917621449519
894158578962859187461322315913849812241742157275462973384219294849882291119423759
123456789456789123564897231231564897789123456897231564312645978645978312978312645
145278369256389147364197258478512693589623471697431582712845936823956714931764825
243561789829317456657489132374192865916845327581673294162758943735924618498236571
243156789529847316687392145361475892714928653895263471152684937436719528978531264
498236571735924618162758943581673294916845327374192865657489132829317456243561789
978531264436719528152684937895263471714928653361475892687392145529847316243156789
342571689257698143986413275861342957495726831173985426519234768734869512628157394
345678192627319458892451673468793521713524986951862347179246835534187269286935714
341572689257698143986413275862341957495726831173985426519234768734869512628517394
</code>```

For further test cases, you can use this CJam script which takes a valid board as input and randomly shuffles it to give a new valid board (input format irrelevant as long as it contains only digits and optionally whitespace).

If your regex is compatible with the .NET flavour, you can test it online using Retina. A valid solution should print 0 for invalid boards and some positive integer for valid boards. To run all test cases at once, use this template and insert the regex on the second line. If you need regex modifiers, prepend a ` to the regex and put the standard modifier letters in front of it.

Body:
Javascript regex, <s>532</s> <s>530</s> <s>481</s> 463 chars

Validate rows:

/^((?=.{0,8}1)(?=.{0,8}2)(?=.{0,8}3)(?=.{0,8}4)(?=.{0,8}5)(?=.{0,8}6)(?=.{0,8}7)(?=.{0,8}8)(?=.{0,8}9).{9})+$/

Validate columns:

/^((?=(.{9}){0,8}1)(?=(.{9}){0,8}2)(?=(.{9}){0,8}3)(?=(.{9}){0,8}4)(?=(.{9}){0,8}5)(?=(.{9}){0,8}6)(?=(.{9}){0,8}7)(?=(.{9}){0,8}8)(?=(.{9}){0,8}9).){9}/

Validate square from its first char:

/(?=.?.?(.{9}){0,2}1)(?=.?.?(.{9}){0,2}2)(?=.?.?(.{9}){0,2}3)(?=.?.?(.{9}){0,2}4)(?=.?.?(.{9}){0,2}5)(?=.?.?(.{9}){0,2}6)(?=.?.?(.{9}){0,2}7)(?=.?.?(.{9}){0,2}8)(?=.?.?(.{9}){0,2}9)/

Set preview to start of the square:

/^(((?=)...){3}.{18})+$/

And the whole expression:

/^(?=((?=.{0,8}1)(?=.{0,8}2)(?=.{0,8}3)(?=.{0,8}4)(?=.{0,8}5)(?=.{0,8}6)(?=.{0,8}7)(?=.{0,8}8)(?=.{0,8}9).{9})+$)(?=((?=(.{9}){0,8}1)(?=(.{9}){0,8}2)(?=(.{9}){0,8}3)(?=(.{9}){0,8}4)(?=(.{9}){0,8}5)(?=(.{9}){0,8}6)(?=(.{9}){0,8}7)(?=(.{9}){0,8}8)(?=(.{9}){0,8}9).){9})(((?=.?.?(.{9}){0,2}1)(?=.?.?(.{9}){0,2}2)(?=.?.?(.{9}){0,2}3)(?=.?.?(.{9}){0,2}4)(?=.?.?(.{9}){0,2}5)(?=.?.?(.{9}){0,2}6)(?=.?.?(.{9}){0,2}7)(?=.?.?(.{9}){0,2}8)(?=.?.?(.{9}){0,2}9)...){3}.{18})+$/

Matches the whole string.

Test in Javascript ES6:

r = /^(?=((?=.{0,8}1)(?=.{0,8}2)(?=.{0,8}3)(?=.{0,8}4)(?=.{0,8}5)(?=.{0,8}6)(?=.{0,8}7)(?=.{0,8}8)(?=.{0,8}9).{9})+$)(?=((?=(.{9}){0,8}1)(?=(.{9}){0,8}2)(?=(.{9}){0,8}3)(?=(.{9}){0,8}4)(?=(.{9}){0,8}5)(?=(.{9}){0,8}6)(?=(.{9}){0,8}7)(?=(.{9}){0,8}8)(?=(.{9}){0,8}9).){9})(((?=.?.?(.{9}){0,2}1)(?=.?.?(.{9}){0,2}2)(?=.?.?(.{9}){0,2}3)(?=.?.?(.{9}){0,2}4)(?=.?.?(.{9}){0,2}5)(?=.?.?(.{9}){0,2}6)(?=.?.?(.{9}){0,2}7)(?=.?.?(.{9}){0,2}8)(?=.?.?(.{9}){0,2}9)...){3}.{18})+$/
;`123456789456789123789123456231564897564897231897231564312645978645978312978312645
725893461841657392396142758473516829168429537952378146234761985687935214519284673
395412678824376591671589243156928437249735186738641925983164752412857369567293814
679543182158926473432817659567381294914265738283479561345792816896154327721638945
867539142324167859159482736275398614936241587481756923592873461743615298618924375
954217683861453729372968145516832497249675318783149256437581962695324871128796534
271459386435168927986273541518734269769821435342596178194387652657942813823615794
237541896186927345495386721743269158569178432812435679378652914924813567651794283
168279435459863271273415986821354769734692518596781342615947823387526194942138657
863459712415273869279168354526387941947615238138942576781596423354821697692734185
768593142423176859951428736184765923572389614639214587816942375295837461347651298`
.split`
`.every(r.test.bind(r))
&&
`519284673725893461841657392396142758473516829168429537952378146234761985687935214
839541267182437659367158924715692843624973518573864192298316475941285736456729381
679543182158926473432817659567381294914256738283479561345792816896154327721638945
867539142324167859159482736275398684936241517481756923592873461743615298618924375
754219683861453729372968145516832497249675318983147256437581962695324871128796534
271459386435168927986273541518734269769828435342596178194387652657942813823615794
237541896186927345378652914743269158569178432812435679495386721924813567651794283
168759432459613278273165984821594763734982516596821347615437829387246195942378651
869887283619214453457338664548525781275424668379969727517385163319223917621449519
894158578962859187461322315913849812241742157275462973384219294849882291119423759
123456789456789123564897231231564897789123456897231564312645978645978312978312645
145278369256389147364197258478512693589623471697431582712845936823956714931764825`
.split`
`.every(s => !r.test(s))


答:
Java 8, 113 chars

```<code>BigInteger C(String s){BigInteger i=BigInteger.ZERO;s.chars().forEach(x->i=i.add(BigInteger.valueOf());return i;}
</code>```

Note each character in Java is Unicode 1-4 bytes unsigned integer, using sum function would easily overflow.

Detailed

```<code>BigInteger C (String s)
{
    BigInteger i = BigInteger.ZERO;

    s.chars().forEach(x -> i = i.add(BigInteger.valueOf(x));

    return i;
}
</code>```

Java 8, 57 chars

ASCII only solution

```<code>int C(String s){return s.chars().filter(x->x<128).sum();}
</code>```

Detailed try here

```<code>public static int C (String s)
{
    return s
        .chars() // stream the characters
        .filter(x -> x < 128) // filter ASCII (optional)
        .sum(); // return the sum
}
</code>```

Title: Calculator that adds char values

Body:
Task

Build a calculator, that takes any string, from a file, stdin or whatever, and adds up all the values of the chars.

Example

```<code>Input
Hello World!

Output
1085
</code>```

Rules

The calculator needs to accept just ASCII encoding.

The shortest code wins.

Notes

Regarding to the comment of m.buettner, I need to say, I didn't thought of the multibyte part.

So I leave it as a bonus thing aswell.

The calculator should be run as written, so no need to modify before compiling or interpreting.

Bonus

Thanks to Synthetica, here is one more bonus,

The program that has the lowest output when you use its code as its input wins gets a star.

I don't want to modify it completly.

If you write it additional to output the (right) value in UTF-8 you get a star.

The code that executes fastest on my Laptop (Lenovo Yoga 13 Intel Core i5 3317U 1.7Ghz, 8GB RAM, 128GB SSD, Intel HD 4000, Windows 8) gets a star.

Web codes will run first under IE11 with chakra and then in FireFox 29.0.1 with SpiderMonkey

Linux code will run on a Raspberry Pi with Raspbian.

The teststring is this:

```<code>q/%8hnp>T%y?'wNb\},9krW &D9']K$n;l.3O+tE*$*._B^s!@k\&Cl:EO1zo8sVxEvBxCock_I+2o6 yeX*0Xq:tS^f)!!7=!tk9K<6#/E`ks(D'$z$\6Ac+MT&[s[]_Y(`<g%"w%cW'`c&q)D$0#C$QGf>?A$iawvc,}`9!('`c&q)D$0#C$QGf>?A$iawvc,}`9!(
</code>```

Have fun coding :)

Bonusscoring

I plan to do the scoring at this Saturday so the 07.06.14, all answers after that date won't get bonus points ;)

You can download the code I gonna use for testing here feel free to fork and improve it :)

Little update because of the bonus, my laptop is partially broken so I will do it probably next weekend, I am really sorry for that :(

Body:
Java 8, 113 chars

BigInteger C(String s){BigInteger i=BigInteger.ZERO;s.chars().forEach(x->i=i.add(BigInteger.valueOf());return i;}

Note each character in Java is Unicode 1-4 bytes unsigned integer, using sum function would easily overflow.

Detailed

BigInteger C (String s)
{
    BigInteger i = BigInteger.ZERO;

    s.chars().forEach(x -> i = i.add(BigInteger.valueOf(x));

    return i;
}

Java 8, 57 chars

ASCII only solution

int C(String s){return s.chars().filter(x->x<128).sum();}

Detailed try here

public static int C (String s)
{
    return s
        .chars() // stream the characters
        .filter(x -> x < 128) // filter ASCII (optional)
        .sum(); // return the sum
}


答:
Java, 139 Bytes

//takes input from cmd line args

```<code>class P {public static void main(String a[]){String s=a[0];int v=0;for(int i=0;i<s.length();i++){v+=(int)s.charAt(i);}System.out.print(v);}}
</code>```

It's big, but yeah.

Title: Calculator that adds char values

Body:
Java, 139 Bytes

//takes input from cmd line args

class P {public static void main(String a[]){String s=a[0];int v=0;for(int i=0;i<s.length();i++){v+=(int)s.charAt(i);}System.out.print(v);}}

It's big, but yeah.


问:
Death By Shock Probe: That's a lot of dice
In the webcomic Darths & Droids, Pete, who plays R2-D2 in the fictional roleplaying campaign around which the comic is based, once claims (warning: potential spoilers in the linked comic) that, with the Lost Orb of Phanastacoria rigged up to his shock probe, he can now dish out a whopping 1048576d4 of damage. (The GM has neither confirmed nor denied this.) Since it should be reasonably obvious that almost no one will actually have the patience to roll that many dice, write a computer program to do it for him, outputting the total value rolled in some reasonable format. Entries will be ranked by program size (shortest program, by byte count, wins), both overall and per-language, with run time breaking ties. Answer may be either a full program or a function definition.

Scores Per-Language

Pyth

Maltysen - 8 bytes*

Jakube - 10 bytes

APL

Alex A - 10 bytes

CJam

Optimizer - 11 bytes

J

ɐɔıʇǝɥʇuʎs - 12 bytes **

Clip10

Ypnypn - 12 bytes **

K

JohnE - 13 bytes

Ti-84 BASIC

SuperJedi224 - 17 bytes*

R

MickyT - 23 bytes

OCTAVE/MATLAB

Oebele - 24 bytes

PARI/GP

Charles - 25 bytes **

Wolfram/Mathematica

LegionMammal978 - 27 bytes

Perl

Nutki - 29 bytes

AsciiThenAnsii - 34 bytes

Ruby

Haegin - 32 bytes **

ConfusedMr_C - 51 bytes **

Commodore Basic

Mark - 37 bytes **

PHP

Ismael Miguel - 38 bytes

VBA

Sean Cheshire - 40 bytes **

PowerShell

Nacht - 41 bytes **

Javascript

Ralph Marshall - 41 bytes

edc65 - 54 bytes (Requires ES6 functionality not available in all browsers.)

Lua

cryptych - 51 bytes

Java

RobAu - 52 bytes **

Geobits - 65 bytes

C

Functino - 57 bytes

Python

CarpetPython - 58 bytes

Postgre/SQL

Andrew - 59 bytes **

Swift

Skrundz - 69 bytes

GoatInTheMachine - 81 bytes

Haskell

Zeta - 73 bytes **

ActionScript

Brian - 75 bytes **

><>

ConfusedMr_C - 76 bytes

GO

Kristoffer Sall-Storgaard - 78 bytes

C#

Brandon - 91 bytes **

Andrew - 105 bytes

Ewan - 148 bytes

Scratch

SuperJedi224 - 102 bytes

C++

Michelfrancis Bustillos - 154 bytes

Polyglots

Ismael Miguel (Javascript/ActionScript2) - 67 bytes

Top 10 Overall

```
Maltysen
Alex A
Jakube
Optimizer
ɐɔıʇǝɥʇuʎs/Ypnypn (order uncertain)
JohnE
SuperJedi224
MickyT
Oebele
```

Warning- entries marked with a * are VERY SLOW.

Programmed marked ** I have not yet been able to properly test

答:
C++, 154 bytes

Golfed:

#include<iostream>
#include <stdlib.h>
#include <time.h>
int main(){int c=0;srand(time(NULL));for(int x=0;x<=1048576;x++){c=c+(rand()%4+1);}std::cout<<c;}
```

<h3>Ungolfed:</h3>

<pre class="lang-cpp prettyprint-override"><code>#include<iostream>
#include <stdlib.h>
#include <time.h>

int main(){
    int c = 0;
    srand (time(NULL));
    for(int x = 0; x <= 1048576; x++){
        c = c + (rand() % 4 + 1);
    }

    std::cout<<c;
}
</code>```

Body:
C++, 154 bytes

Golfed:

#include<iostream>
#include <stdlib.h>
#include <time.h>
int main(){int c=0;srand(time(NULL));for(int x=0;x<=1048576;x++){c=c+(rand()%4+1);}std::cout<<c;}

Ungolfed:

#include<iostream>
#include <stdlib.h>
#include <time.h>

int main(){
    int c = 0;
    srand (time(NULL));
    for(int x = 0; x <= 1048576; x++){
        c = c + (rand() % 4 + 1);
    }

    std::cout<<c;
}


问:
Implement a Truth-Machine
A truth-machine (credits goes to this guy for coming up with it) is a very simple program designed to demonstrate the I/O and control flow of a language. Here's what a truth-machine does:

Gets a number (either 0 or 1) from STDIN.

If that number is 0, print out 0 and terminate.

If that number is 1, print out 1 forever.

Challenge

Write a truth-machine as described above in your language of choice. The truth-machine must be a full program that follows these rules:

take input from STDIN or an acceptable alternative

If your language cannot take input from STDIN, it may take input from a hardcoded variable or suitable equivalent in the program

must output to STDOUT or an acceptable alternative

If your language is incapable of outputting the characters 0 or 1, byte or unary I/O is acceptable.

when the input is 1, it must continually print 1s and only stop if the program is killed or runs out of memory

the output must only be either a 0 followed by either one or no newline or space, or infinite 1s with each 1 followed by either one or no newline or space. No other output can be generated, except constant output of your language's interpreter that cannot be suppressed (such as a greeting, ANSI color codes or indentation). Your usage of newlines or spaces must be consistent: for example, if you choose to output 1 with a newline after it all 1s must have a newline after them.

if and only if your language cannot possibly terminate on an input of 0 it is acceptable for the code to enter an infinite loop in which nothing is outputted.

Since this is a catalog, languages created after this challenge are allowed to compete. Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. Other than that, all the standard rules of code-golf must be obeyed. Submissions in most languages will be scored in bytes in an appropriate preexisting encoding (usually UTF-8).

Catalog

The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```<code>## Language Name, N bytes
</code>```

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

```<code>## Ruby, <s>104</s> <s>101</s> 96 bytes
</code>```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

```<code>## Perl, 43 + 2 (-p flag) = 45 bytes
</code>```

You can also make the language name a link which will then show up in the snippet:

```<code>## [><>](http://esolangs.org/wiki/Fish), 121 bytes
</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

答:
UGL, 6 bytes

```<code>il$o:o
</code>```

Try it online!

How it works:

```<code>i       #stack.push(input)
 l  :   #while stack.peek():
  $     #    stack.dup()
   o    #    print(stack.pop())
      o #print(stack.pop())
</code>```

Title: Implement a Truth-Machine

Body:
UGL, 6 bytes

il$o:o

Try it online!

How it works:

i       #stack.push(input)
 l  :   #while stack.peek():
  $     #    stack.dup()
   o    #    print(stack.pop())
      o #print(stack.pop())


答:
PCRE, 117 <s>119 130 133 147</s> bytes

```<code>^(?!(.{27})*(...){0,2}(.{9})?.?.?(.).?.?(?=(?2)*$).{6,8}(?3)?\4.{0,17}(?1)*$|.*(.)(.{8}(?3)*|((?!(?3)*$)(|.(?7))))\5)
</code>```

<s>Should also work in Python, Java, etc. flavors.</s> Now with recursion! And the "recursion" feature used non-recursively for "subroutines", which I totally forgot about until I had to use actual recursion.

Title: Regex Golf: Verify a Sudoku Solution

Body:
PCRE, 117 <s>119 130 133 147</s> bytes

^(?!(.{27})*(...){0,2}(.{9})?.?.?(.).?.?(?=(?2)*$).{6,8}(?3)?\4.{0,17}(?1)*$|.*(.)(.{8}(?3)*|((?!(?3)*$)(|.(?7))))\5)

<s>Should also work in Python, Java, etc. flavors.</s> Now with recursion! And the "recursion" feature used non-recursively for "subroutines", which I totally forgot about until I had to use actual recursion.


答:
PCRE, 3579 bytes

An absolutely terrible brute force solution. Negative lookbehinds ahoy!

I spent way too much time on this to abandon it, so here it is, for posterity's sake.

On the bright side, if Sudoku suddenly starts using a different set of 9 characters, this'll still work, I guess...

http://pastebin.com/raw/CwtviGkC

I don't know how to operate Retina, but you can also paste it into https://regex101.com or similar and it'll match.

Ruby code used to generate the regex:

```<code># Calculate the block you're in
def block(x)
    x /= 3
    x + x%3 - x%9
end

81.times do |i|
    row, col = i.divmod(9)
    neg = []
    neg += (0...col).map {|e| 9*row + e + 1}
    neg += (0...row).map {|e| 9*e + col + 1}
    neg += (0...i).map {|e| e + 1 if block(e) == block(i)}.compact
    neg = neg.uniq.sort.map {|e| "\\#{e}"}
    if neg.size > 0
        print "(?!#{neg.join '|'})"
    end
    print "(.)"
end
</code>```

Title: Regex Golf: Verify a Sudoku Solution

Body:
PCRE, 3579 bytes

An absolutely terrible brute force solution. Negative lookbehinds ahoy!

I spent way too much time on this to abandon it, so here it is, for posterity's sake.

On the bright side, if Sudoku suddenly starts using a different set of 9 characters, this'll still work, I guess...

http://pastebin.com/raw/CwtviGkC

I don't know how to operate Retina, but you can also paste it into https://regex101.com or similar and it'll match.

Ruby code used to generate the regex:

# Calculate the block you're in
def block(x)
    x /= 3
    x + x%3 - x%9
end

81.times do |i|
    row, col = i.divmod(9)
    neg = []
    neg += (0...col).map {|e| 9*row + e + 1}
    neg += (0...row).map {|e| 9*e + col + 1}
    neg += (0...i).map {|e| e + 1 if block(e) == block(i)}.compact
    neg = neg.uniq.sort.map {|e| "\\#{e}"}
    if neg.size > 0
        print "(?!#{neg.join '|'})"
    end
    print "(.)"
end


答:
Julia, 26 bytes

```<code>x->sum((r=1:2:x-1)∩r.^2)
</code>```

This constructs the range of all odd, positive integers below n and the array of the squares of the integers in that range, then computes the sum of the integers in both iterables.

Try it online!

Title: Sum the odd square numbers less than N

Body:
Write a program or function to output the sum of the odd square numbers (OEIS #A016754) less than an input n.

The first 44 numbers in the sequence are:

```<code>1, 9, 25, 49, 81, 121, 169, 225, 289, 361, 441, 529, 625, 729, 841, 961, 1089,
1225, 1369, 1521, 1681, 1849, 2025, 2209, 2401, 2601, 2809, 3025, 3249, 3481,
3721, 3969, 4225, 4489, 4761, 5041, 5329, 5625, 5929, 6241, 6561, 6889, 7225, 7569
</code>```

The formula for the sequence is a(n) = ( 2n + 1 ) ^ 2.

Notes

Your program's behaviour may be undefined for n < 1 (that is, all valid inputs are >= 1.)

Test cases

```<code>1 => 0
2 => 1
9 => 1
10 => 10
9801 => 156849
9802 => 166650
10000 => 166650
</code>```

Body:
Julia, 26 bytes

x->sum((r=1:2:x-1)∩r.^2)

This constructs the range of all odd, positive integers below n and the array of the squares of the integers in that range, then computes the sum of the integers in both iterables.

Try it online!


答:
Julia, 33 bytes

```<code>x->sum(diff([x;x]).<0)<3&&sort(x)
</code>```

Try it online!

How it works

This concatenates the array x with itself and counts the number of pairs that are out of order, i.e. the number of contiguous subarrays [a, b] for which b - a < 0. If c is the number of unordered pairs of x itself and t is 1 if x's last element is larger than its first, sum will return 2c + t.

The array x is driftsortable iff (c, t) = (1, 0) (x has to be rotated to the smaller value of the only unordered pair), (c, t) = (0, 1) (x is sorted) or (c, t) = (0, 0) (x is sorted and all of its elements are equal), which is true iff 2c + t < 3.

Title: Driftsort an array

Body:
Driftsort is a simple way to "sort" an array. It works by "sliding" or "rotating" the elements over in the array until the array is sorted, or until the array fails to be sorted.

Let's walk through two examples. First, consider the array [10, 2, 3, 4, 7]. Since the array is not sorted, we rotate it once. (This can happen in either direction, so long as it remains the same direction.) Then, the array becomes:

```<code>[7, 10, 2, 3, 4]
</code>```

This is not sorted, so we rotate again.

```<code>[4, 7, 10, 2, 3]
</code>```

And again:

```<code>[3, 4, 7, 10, 2]
</code>```

And a final time:

```<code>[2, 3, 4, 7, 10]
</code>```

And it's sorted! So the array [10, 2, 3, 4, 7] is driftsortable. Here are all the rotations of the array, for clarity:

```<code>[10, 2, 3, 4, 7]
[7, 10, 2, 3, 4]
[4, 7, 10, 2, 3]
[3, 4, 7, 10, 2]
[2, 3, 4, 7, 10]
</code>```

Consider now the array [5, 3, 9, 2, 6, 7]. Look at its rotations:

```<code>[5, 3, 9, 2, 6, 7]
[7, 5, 3, 9, 2, 6]
[6, 7, 5, 3, 9, 2]
[2, 6, 7, 5, 3, 9]
[9, 2, 6, 7, 5, 3]
[3, 9, 2, 6, 7, 5]
</code>```

None of these arrays are sorted, so the array [5, 3, 9, 2, 6, 7] is not driftsortable.

Objective Given a nonempty array/list of integers as input to a program/function, implement driftsort on the input and output it, or output a falsey value (or an empty array/list) if it cannot be driftsorted. The integers are bound to your languages max/min, but this must be at least 255 for the max, and 0 for the min.

You may use built-in sorting methods, but not a built-in which solves the challenge.

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

Test cases

```<code>input => output
[1] => [1]
[5, 0, 5] => [0, 5, 5]
[3, 2, 1] => false
[0, 9, 3] => false
[1, 2, 3, 4] => [1, 2, 3, 4]
[4, 1, 2, 3] => [1, 2, 3, 4]
[0, 2, 0, 2] => false
[5, 3, 9, 2, 6, 7] => false
[0, 0, 0, 0, 0, 0, 0] => [0, 0, 0, 0, 0, 0, 0]
[75, 230, 30, 42, 50] => [30, 42, 50, 75, 230]
[255, 255, 200, 200, 203] => [200, 200, 203, 255, 255]
</code>```

Body:
Julia, 33 bytes

x->sum(diff([x;x]).<0)<3&&sort(x)

Try it online!

How it works

This concatenates the array x with itself and counts the number of pairs that are out of order, i.e. the number of contiguous subarrays [a, b] for which b - a < 0. If c is the number of unordered pairs of x itself and t is 1 if x's last element is larger than its first, sum will return 2c + t.

The array x is driftsortable iff (c, t) = (1, 0) (x has to be rotated to the smaller value of the only unordered pair), (c, t) = (0, 1) (x is sorted) or (c, t) = (0, 0) (x is sorted and all of its elements are equal), which is true iff 2c + t < 3.


答:
Factor, <s>58</s> 57 bytes

```<code>[| n | n 2 * iota [ 2 * 1 + 2^ ] map [ n < ] filter sum ]
</code>```

Well, this was simpler than I thought!

```<code>[| n |       ! new local var n
    n 2 *    ! double n
    iota     ! fixnum>range
    [
        2 *  ! double
        1 +  ! + 1
        2^  ! square
    ] map    ! each item in range(0, n*2)
    [
        n <  ! entries over n
    ] filter ! keep-only
    sum ]    ! sum the resulting array
</code>```

Unit tests, if you like:

```<code>{ 0 }  [ 1  sum-odds-lt ] unit-test
{ 1 }  [ 2  sum-odds-lt ] unit-test
{ 1 }  [ 9  sum-odds-lt ] unit-test
{ 10 } [ 10 sum-odds-lt ] unit-test
{ 156849 } [ 9801 sum-odds-lt ] unit-test
{ 166650 } [ 9802 sum-odds-lt ] unit-test
{ 166650 } [ 10000 sum-odds-lt ] unit-test
</code>```

Title: Sum the odd square numbers less than N

Body:
Factor, <s>58</s> 57 bytes

[| n | n 2 * iota [ 2 * 1 + 2^ ] map [ n < ] filter sum ]

Well, this was simpler than I thought!

[| n |       ! new local var n
    n 2 *    ! double n
    iota     ! fixnum>range
    [
        2 *  ! double
        1 +  ! + 1
        2^  ! square
    ] map    ! each item in range(0, n*2)
    [
        n <  ! entries over n
    ] filter ! keep-only
    sum ]    ! sum the resulting array

Unit tests, if you like:

{ 0 }  [ 1  sum-odds-lt ] unit-test
{ 1 }  [ 2  sum-odds-lt ] unit-test
{ 1 }  [ 9  sum-odds-lt ] unit-test
{ 10 } [ 10 sum-odds-lt ] unit-test
{ 156849 } [ 9801 sum-odds-lt ] unit-test
{ 166650 } [ 9802 sum-odds-lt ] unit-test
{ 166650 } [ 10000 sum-odds-lt ] unit-test