问:
Weapons of Math Instruction
Last time when I tried to come up with something easy that wasn't a duplicate, it ended up being way too hard.. So hopefully this time it's indeed something newcomers can try as well.

Input:

An array/list with integers/decimals. (Or a string representing an array with integers/decimals.)

Output:

Loop through the numbers and apply the following five mathematical operands in this order:

Addition (+);

Subtraction (−);

Multiplication (* or × or ·);

Real / Calculator Division (/ or ÷);

Exponentiation (^ or **).

(NOTE: The symbols between parenthesis are just added as clarification. If your programming language uses a completely different symbol for the mathematical operation than the examples, then that is of course completely acceptable.)

Keep continuing until you've reached the end of the list, and then give the result of the sum.

Challenge rules:

Exponentiation by 0 (n ^ 0) should result in 1 (this also applies to 0 ^ 0 = 1).

There are no test cases for division by 0 (n / 0), so you don't have to worry about that edge-case.

If the array contains just a single number, we return that as the result.

General rules:

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

Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.

Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call.

Default Loopholes are forbidden.

If possible, please add a link with a test for your code.

Test cases:

```<code>[1,2,3,4,5] -> 0
-> 1 + 2 = 3
  -> 3 - 3 = 0
    -> 0 * 4 = 0
      -> 0 / 5 = 0

[5,12,23,2,4,4,2,6,7] -> 539
-> 5 + 12 = 17
  -> 17 - 23 = -6
    -> -6 * 2 = -12
      -> -12 / 4 = -3
        -> -3 ^ 4 = 81
          -> 81 + 2 = 83
            -> 83 - 6 = 77
              -> 77 * 7 -> 539

[-8,50,3,3,-123,4,17,99,13] -> -1055.356...
-> -8 + 50 = 42
  -> 42 - 3 = 39
    -> 39 * 3 = 117
      -> 117 / -123 = -0.9512...
        -> -0.9512... ^ 4 = 0.818...
          -> 0.818... + 17 = 17.818...
            -> 17.818... - 99 -> -81.181...
              -> -81.181... * 13 = -1055.356...

[2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2] -> 256
-> 2 + 2 = 4
  -> 4 - 2 = 2
    -> 2 * 2 = 4
      -> 4 / 2 = 2
        -> 2 ^ 2 = 4
          -> 4 + 2 = 6
            -> 6 - 2 = 4
              -> 4 * 2 = 8
                -> 8 / 2 = 4
                  -> 4 ^ 2 = 16
                    -> 16 + 2 = 18
                      -> 18 - 2 = 16
                        -> 16 * 2 = 32
                          -> 32 / 2 = 16
                            -> 16 ^ 2 = 256

[1,0,1,0,1,0] -> 1
-> 1 + 0 = 1
  -> 1 - 1 = 0
    -> 0 * 0 = 0
      -> 0 / 1 = 0
        -> 0 ^ 0 = 1

[-9,-8,-1] -> -16
  -> -9 + -8 = -17
    -> -17 - -1 = -16

[0,-3] -> -3
  -> 0 + -3 = -3

[-99] -> -99
</code>```

Title: Weapons of Math Instruction

Body:
PHP, <s>206</s>,<s>198</s>,197 bytes

function f($a){while(count($a)>1){$l=array_shift($a);$r=array_shift($a);array_unshift($a,($j=$i++%5)==0?($l+$r):($j==1?($l-$r):($j==2?($l*$r):($j==3?($l/$r):(pow($l,$r))))));}return array_pop($a);}

Ungolfed

<?php

function f($a)
{
    while(count($a)>1)
    {
        $l = array_shift($a); $r = array_shift($a);
        array_unshift($a,($j=$i++%5)==0?($l+$r):($j==1?($l-$r):($j==2?($l*$r):($j==3?($l/$r):(pow($l,$r))))));
    }
    return array_pop($a);
}

echo f([1,2,3,4,5])."\n";
echo f([5,12,23,2,4,4,2,6,7])."\n";
echo f([-8,50,3,3,-123,4,17,99,13])."\n";
echo f([2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2])."\n";
echo f([1,0,1,0,1,0])."\n";
echo f([-9,-8,-1])."\n";
echo f([0,-3])."\n";
echo f([-99])."\n";

In PHP, logic similar to my c# answer (202 bytes) :) .


问:
Golf the repeated totient function
You will take two positive integers n and x as input, and output Euler's totient function (number of positive integers less than x co-prime to x) applied n times.

Testcases

```<code>n x   result
1 10  4
2 10  2
3 10  1
1 100 40
2 100 16
3 100 8
4 100 4
5 100 2
6 100 1
</code>```

答:
CJam, 20 bytes

```<code>q~{_mf1|1-{1$\/-}/}*
</code>```

Try it online!

How it works

```<code>q~                    Read and evaluate all input. Pushes x and n.
  {               }*  Repeat n times:
   _mf                  Compute the prime factorization of a copy of x.
      1|1-              Add and remove 1 from the prime factorization.
                        | deduplicates and - handles the edge case 1mf -> [1].
          {     }/      For each remaining prime p:
           1$             Push a copy of x.
             \/           Swap with p and divide, pushing x/p.
               -          Subtract from x, pushing x-x/p.
</code>```

ContentLicense: CC BY-SA 3.0

Title: Golf the repeated totient function

Body:
CJam, 20 bytes

q~{_mf1|1-{1$\/-}/}*

Try it online!

How it works

q~                    Read and evaluate all input. Pushes x and n.
  {               }*  Repeat n times:
   _mf                  Compute the prime factorization of a copy of x.
      1|1-              Add and remove 1 from the prime factorization.
                        | deduplicates and - handles the edge case 1mf -> [1].
          {     }/      For each remaining prime p:
           1$             Push a copy of x.
             \/           Swap with p and divide, pushing x/p.
               -          Subtract from x, pushing x-x/p.


问:
"Bit-borrow" two numbers
Did you know that a small number can borrow bits from a larger number? Here's an example. Let's say our two numbers 5 and 14. First, write them out in binary:

```<code>5       14
000101  001110
</code>```

First we take the smallest on bit away from the larger number, and we give it to the smallest off bit on the other number. So

```<code>This bit turns off
            |
            v
000101  001110
    ^
    |
This bit turns on
</code>```

Now we have

```<code>000111  001100
</code>```

and our numbers are 7 and 12. The first number is still smaller, so we continue.

```<code>000111  001100
001111  001000
</code>```

Now we have 15 and 8, so we can stop. We'll call this set of operations "bit-borrowing" two numbers. Let's do another example. 20 and 61.

```<code>20        61
010100    111101
010101    111100
010111    111000
111111    100000
63        32
</code>```

So our end result is 32, 63. Let's do one more. 31, and 12. 31 is already bigger than 12, so there's nothing to do! Bit-borrowing 31 and 12 gives 31 and 12, no change.

The challenge

Your challenge is to write a program or function that takes two numbers and bit-borrows them. The two numbers will always positive integers. Your input and output can be in any reasonable format.

Test IO:

```<code>Input: 2, 3
Output: 3, 2

Input: 3, 2
Output: 3, 2

Input: 8, 23
Output: 31, 0

Input: 42, 81
Output: 63, 0

Input: 38, 41
Output: 47, 32

Input: 16, 73
Output: 23, 0

Input: 17, 17
Output: 17, 17
</code>```

Standard loopholes apply, and shortest answer in bytes wins!

答:
Mathematica, 46 bytes

```<code>If[#<#2,BitOr[#,#+1]~#0~BitAnd[#2,#2-1],{##}]&
</code>```

Same method as used in my solution in J.

Thanks to @Martin for saving 1 byte and reminding me of infix application ~.

Usage

The input consists of two integer arguments and the output is a list with the bit-borrowed values.

Title: "Bit-borrow" two numbers

Body:
Mathematica, 46 bytes

If[#<#2,BitOr[#,#+1]~#0~BitAnd[#2,#2-1],{##}]&

Same method as used in my solution in J.

Thanks to @Martin for saving 1 byte and reminding me of infix application ~.

Usage

The input consists of two integer arguments and the output is a list with the bit-borrowed values.


答:
Java 7, 73 bytes

```<code>void d(int x,int y){while(x<y){x|=x+1;y&=y-1;}System.out.print(x+","+y);}
</code>```

Ungolfed & test cases:

Try it here.

```<code>public class Main{
  static void d(int x, int y){
    while(x < y){
      x |= x + 1;
      y &= y - 1;
    }
    System.out.print(x + "," + y);
  }

  public static void main(String[] a){
    print(2, 3);
    print(3, 2);
    print(8, 23);
    print(42, 81);
    print(38, 41);
    print(16, 73);
    print(17, 17);
  }

  public static void print(int a, int b){
    d(a, b);
    System.out.println();
  }
}
</code>```

Output:

```<code>3,2
3,2
31,0
63,0
47,32
23,0
17,17
</code>```

Old challenge rules [<s>126</s> <s>125</s> 123 bytes]:

NOTE: The old challenge rules used two integer-arrays as input, instead of two loose integers.

```<code>void d(int[]a,int[]b){int i=-1,x,y;while(++i<a.length){x=a[i];y=b[i];for(;x<y;x|=x+1,y&=y-1);System.out.println(x+","+y);}}
</code>```

Title: "Bit-borrow" two numbers

Body:
Did you know that a small number can borrow bits from a larger number? Here's an example. Let's say our two numbers 5 and 14. First, write them out in binary:

```<code>5       14
000101  001110
</code>```

First we take the smallest on bit away from the larger number, and we give it to the smallest off bit on the other number. So

```<code>This bit turns off
            |
            v
000101  001110
    ^
    |
This bit turns on
</code>```

Now we have

```<code>000111  001100
</code>```

and our numbers are 7 and 12. The first number is still smaller, so we continue.

```<code>000111  001100
001111  001000
</code>```

Now we have 15 and 8, so we can stop. We'll call this set of operations "bit-borrowing" two numbers. Let's do another example. 20 and 61.

```<code>20        61
010100    111101
010101    111100
010111    111000
111111    100000
63        32
</code>```

So our end result is 32, 63. Let's do one more. 31, and 12. 31 is already bigger than 12, so there's nothing to do! Bit-borrowing 31 and 12 gives 31 and 12, no change.

The challenge

Your challenge is to write a program or function that takes two numbers and bit-borrows them. The two numbers will always positive integers. Your input and output can be in any reasonable format.

Test IO:

```<code>Input: 2, 3
Output: 3, 2

Input: 3, 2
Output: 3, 2

Input: 8, 23
Output: 31, 0

Input: 42, 81
Output: 63, 0

Input: 38, 41
Output: 47, 32

Input: 16, 73
Output: 23, 0

Input: 17, 17
Output: 17, 17
</code>```

Standard loopholes apply, and shortest answer in bytes wins!

Body:
Java 7, 73 bytes

void d(int x,int y){while(x<y){x|=x+1;y&=y-1;}System.out.print(x+","+y);}

Ungolfed & test cases:

Try it here.

public class Main{
  static void d(int x, int y){
    while(x < y){
      x |= x + 1;
      y &= y - 1;
    }
    System.out.print(x + "," + y);
  }

  public static void main(String[] a){
    print(2, 3);
    print(3, 2);
    print(8, 23);
    print(42, 81);
    print(38, 41);
    print(16, 73);
    print(17, 17);
  }

  public static void print(int a, int b){
    d(a, b);
    System.out.println();
  }
}

Output:

3,2
3,2
31,0
63,0
47,32
23,0
17,17

Old challenge rules [<s>126</s> <s>125</s> 123 bytes]:

NOTE: The old challenge rules used two integer-arrays as input, instead of two loose integers.

void d(int[]a,int[]b){int i=-1,x,y;while(++i<a.length){x=a[i];y=b[i];for(;x<y;x|=x+1,y&=y-1);System.out.println(x+","+y);}}


答:
Julia, 27 bytes

x<|y=x<y?x|-~x<|y&~-y:[x,y]
```

Try it online!

How it works

We define the binary operator <| for our purposes. It is undefined in recent versions of Julia, but still recognized as an operator by the parser. While \ (not explicitly defined for integers) is one byte shorter, its high precedence would require replacing x|-~x<|y&~-y with (x|-~x)\(y&~-y), thus increasing the byte count.

<| checks if its first argument is strictly less than the second one. If so, it recursively calls itself with arguments x | -~x = x | (x + 1) and y & ~-y = y & (y - 1).

Since adding 1 to x toggles all trailing set bits and the lowest unset bit, x | (x + 1) toggles the lowest unset bit (and no other bits). Likewise, since subtracting 1 from y toggles all trailing unset bits and the lowest set bit, y & (y + 1) toggles the lowest set bit.

Finally, when the inequality x < y no longer holds, <| returns the pair [x, y].

Title: "Bit-borrow" two numbers

Body:
Julia, 27 bytes

x<|y=x<y?x|-~x<|y&~-y:[x,y]

Try it online!

How it works

We define the binary operator <| for our purposes. It is undefined in recent versions of Julia, but still recognized as an operator by the parser. While \ (not explicitly defined for integers) is one byte shorter, its high precedence would require replacing x|-~x<|y&~-y with (x|-~x)\(y&~-y), thus increasing the byte count.

<| checks if its first argument is strictly less than the second one. If so, it recursively calls itself with arguments x | -~x = x | (x + 1) and y & ~-y = y & (y - 1).

Since adding 1 to x toggles all trailing set bits and the lowest unset bit, x | (x + 1) toggles the lowest unset bit (and no other bits). Likewise, since subtracting 1 from y toggles all trailing unset bits and the lowest set bit, y & (y + 1) toggles the lowest set bit.

Finally, when the inequality x < y no longer holds, <| returns the pair [x, y].


答:
05AB1E, <s>16</s> 15 bytes

```<code>[D`›#`D<&sD>~s‚
</code>```

Try it online

Title: "Bit-borrow" two numbers

Body:
05AB1E, <s>16</s> 15 bytes

[D`›#`D<&sD>~s‚

Try it online


问:
Wait a minute – in less than ten seconds

Task

Using any type of parallelisation, wait multiple periods, for a total sleep time of at least a minute (but less than a minute and a half).

The program/function must terminate within 10 seconds and return (by any means and in any format) two values: the total elapsed time, and the total executed sleep time. Both time values have to have a precision of at least 0.1 seconds.

This is similar to the concept of man-hours: a job that takes 60 hours can be completed in only 6 hours if 10 workers are splitting the job. Here we can have 60 seconds of sleep time e.g. in 10 parallel threads, thus requiring only 6 seconds for the whole job to be completed.

Example

The program MyProgram creates 14 threads, each thread sleeps for 5 seconds:

MyProgram → [5.016,70.105]

The execution time is greater than 5 seconds, and the total sleep time is greater than 70 seconds because of overhead.

答:
C, 127 bytes (spins CPU)

This solution spins the CPU instead of sleeping, and counts time using the times POSIX function (which measures CPU time consumed by the parent process and in all waited-for children).

It forks off 7 processes which spin for 9 seconds apiece, and prints out the final times in C clocks (on most systems, 100 clock ticks = 1 second).

```<code>t;v[4];main(){fork(fork(fork(t=time(0))));while(time(0)<=t+9);wait(0);wait(0);wait(0)>0&&(times(v),printf("%d,%d",v[0],v[2]));}
</code>```

Sample output:

```<code>906,6347
</code>```

meaning 9.06 seconds real time and 63.47 seconds total CPU time.

For best results, compile with -std=c90 -m32 (force 32-bit code on a 64-bit machine).

Body:
C, 127 bytes (spins CPU)

This solution spins the CPU instead of sleeping, and counts time using the times POSIX function (which measures CPU time consumed by the parent process and in all waited-for children).

It forks off 7 processes which spin for 9 seconds apiece, and prints out the final times in C clocks (on most systems, 100 clock ticks = 1 second).

t;v[4];main(){fork(fork(fork(t=time(0))));while(time(0)<=t+9);wait(0);wait(0);wait(0)>0&&(times(v),printf("%d,%d",v[0],v[2]));}

Sample output:

906,6347

meaning 9.06 seconds real time and 63.47 seconds total CPU time.

For best results, compile with -std=c90 -m32 (force 32-bit code on a 64-bit machine).


答:
JavaScript (ES6), 33 bytes

```<code>f=(n,m)=>n<m?f(n|n+1,m&m-1):[n,m]
</code>```

Simple port of the answers by @miles.

Title: "Bit-borrow" two numbers

Body:
JavaScript (ES6), 33 bytes

f=(n,m)=>n<m?f(n|n+1,m&m-1):[n,m]

Simple port of the answers by @miles.


答:
MATLAB, <s>67</s> 66 bytes

loop:

```<code>function[]=f(x,y)
while x<y
x=bitor(x,x+1);y=bitand(y,y-1);end
x,y
</code>```

recursive (67 bytes):

```<code>function[]=f(x,y)
if x<y
f(bitor(x,x+1),bitand(y,y-1))
else
x,y
end
</code>```

Same approach to changing bits as many other anwers.

Title: "Bit-borrow" two numbers

Body:
MATLAB, <s>67</s> 66 bytes

loop:

function[]=f(x,y)
while x<y
x=bitor(x,x+1);y=bitand(y,y-1);end
x,y

recursive (67 bytes):

function[]=f(x,y)
if x<y
f(bitor(x,x+1),bitand(y,y-1))
else
x,y
end

Same approach to changing bits as many other anwers.


问:
Find the smallest number bigger than the input whose digital sum is the input
"Digital sum" refers to the sum of all the digits in a number.

For example, the digital sum of 1324 is 10, because 1+3+2+4 = 10.

The challenge is to write a program/function to calculate the smallest number bigger than the input whose digital sum is the input.

Example with walkthrough

As an example, take the number 9 as the input:

```<code>9 = 1+8 -> 18
9 = 2+7 -> 27
9 = 3+6 -> 36
...
9 = 8+1 -> 81
9 = 9+0 -> 90
</code>```

The valid output would be the smallest number above, which is 18.

Specs

Note that 9 is not the valid output for this example, because the reversed number must be greater than the original number.

Note that the input will be positive.

Test-Cases:

```<code> 2 => 11      (2 = 1 + 1)
 8 => 17      (8 = 1 + 7)
12 => 39     (12 = 3 + 9)
16 => 79     (16 = 7 + 9)
18 => 99     (18 = 9 + 9)
24 => 699    (24 = 6 + 9 + 9)
32 => 5999   (32 = 5 + 9 + 9 + 9)
</code>```

References:

This is OEIS A161561.

Edit: Added an additional Testcase (18)

Thanks to Martin Ender for the Leaderboard Snippet

var QUESTION_ID=81047,OVERRIDE_USER=31373;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

```

答:
Python 3 55 Bytes

Takes two arguments that are the same

```<code>f=lambda a,b:a if sum(map(int,str(a)))==b else f(-~a,b)
</code>```

i.e. to call it you would use f(x,x)

Body:
Python 3 55 Bytes

Takes two arguments that are the same

f=lambda a,b:a if sum(map(int,str(a)))==b else f(-~a,b)

i.e. to call it you would use f(x,x)


问:
Compute the Discrete Fourier Transform
Implement the Discrete Fourier Transform (DFT) for a sequence of any length. This may implemented as either a function or a program and the sequence can be given as either an argument or using standard input.

The algorithm will compute a result based on standard DFT in the forward direction. The input sequence has length N and consists of [x(0), x(1), ..., x(N-1)]. The output sequence will have the same length and consists of [X(0), X(1), ..., X(N-1)] where each X(k) is defined by the relation below.

$$X_k\overset{\text{def}}{=}\sum_{n=0}^{N-1}x_n\cdot e^{-2\pi ikn/N}$$

Rules

This is code-golf so the shortest solution wins.

Builtins that compute the DFT in forward or backward (also known as inverse) directions are not allowed.

Floating-point inaccuracies will not be counted against you.

Test Cases

```<code>DFT([1, 1, 1, 1]) = [4, 0, 0, 0]
DFT([1, 0, 2, 0, 3, 0, 4, 0]) = [10, -2+2j, -2, -2-2j, 10, -2+2j, -2, -2-2j]
DFT([1, 2, 3, 4, 5]) = [15, -2.5+3.44j, -2.5+0.81j, -2.5-0.81j, -2.5-3.44j]
DFT([5-3.28571j, -0.816474-0.837162j, 0.523306-0.303902j, 0.806172-3.69346j, -4.41953+2.59494j, -0.360252+2.59411j, 1.26678+2.93119j] = [2, -3j, 5, -7j, 11, -13j, 17]
</code>```

Help

There was a previous challenge for finding the DFT using a FFT algorithm for sequences with lengths equal to a power of 2. You may find some tricks there that might help you here. Keep in mind that this challenge does not limit you to any complexity and also requires your solution to work for sequences of any length.

答:
Mathematica, <s>49</s> <s>48</s> 47 bytes

```<code>Total[I^Array[4(+##-##-1)/n&,{n=Length@#,n}]#]&
</code>```

Based on the formula from @Dennis' solution.

ContentLicense: CC BY-SA 4.0

Title: Compute the Discrete Fourier Transform

Body:
Mathematica, <s>49</s> <s>48</s> 47 bytes

Total[I^Array[4(+##-##-1)/n&,{n=Length@#,n}]#]&

Based on the formula from @Dennis' solution.


问:
Lithp Tranthlator
My friend made a lisp translator the other day, that is to say it took a string and converted s=>th and S=>Th. It was quite long and I thought that it could be golfed.

So the task is to make a program/function that takes an input string, translates it in to lisp and outputs the string

Test case

```<code>Sam and Sally like Sheep        Tham and Thally like Thheep
Sally likes sausages            Thally liketh thauthageth
Sally sells seashells           Thally thellth theathhellth
</code>```

Note that it doesn't matter that h gets repeated all the time

This is code golf so shortest answer wins

答:
GNU Sed - 17

```<code>s/S/Th/g;s/s/th/g
</code>```

The obvious answer.

```<code>$ sed -e "s/S/Th/g;s/s/th/g"

Sam and Sally like Sheep
Tham and Thally like Thheep

Sally likes sausages
Thally liketh thauthageth

Sally sells seashells
Thally thellth theathhellth
</code>```

Title: Lithp Tranthlator

Body:
GNU Sed - 17

s/S/Th/g;s/s/th/g

The obvious answer.

$ sed -e "s/S/Th/g;s/s/th/g"

Sam and Sally like Sheep
Tham and Thally like Thheep

Sally likes sausages
Thally liketh thauthageth

Sally sells seashells
Thally thellth theathhellth


答:
Retina, 9 bytes

```<code>S
Th
s
th
</code>```

Try it online!

The obvious answer.

Title: Lithp Tranthlator

Body:
My friend made a lisp translator the other day, that is to say it took a string and converted s=>th and S=>Th. It was quite long and I thought that it could be golfed.

So the task is to make a program/function that takes an input string, translates it in to lisp and outputs the string

Test case

```<code>Sam and Sally like Sheep        Tham and Thally like Thheep
Sally likes sausages            Thally liketh thauthageth
Sally sells seashells           Thally thellth theathhellth
</code>```

Note that it doesn't matter that h gets repeated all the time

This is code golf so shortest answer wins

Body:
Retina, 9 bytes

S
Th
s
th

Try it online!

The obvious answer.


答:
Python3 - 46 bytes

```<code>lambda s:s.replace("s","th").replace("S","Th")
</code>```

Dropped 4 bytes with the help of @DenkerAffe!

Title: Lithp Tranthlator

Body:
Python3 - 46 bytes

lambda s:s.replace("s","th").replace("S","Th")

Dropped 4 bytes with the help of @DenkerAffe!


答:
C# 6.0 - 58 bytes

```<code>string f(string s)=>s.Replace("s","th").Replace("S","Th");
</code>```

Takes the input string as an argument to the function.

Title: Lithp Tranthlator

Body:
C# 6.0 - 58 bytes

string f(string s)=>s.Replace("s","th").Replace("S","Th");

Takes the input string as an argument to the function.


答:
Pyth, 14 bytes

```<code>::z\s"th"\S"Th
</code>```

Test suite

Thanks to @LeakyNun for spotting a typo!

Title: Lithp Tranthlator

Body:
Pyth, 14 bytes

::z\s"th"\S"Th

Test suite

Thanks to @LeakyNun for spotting a typo!


问:
Golf all the 16 logic gates with 2 inputs and 1 output!
For example, the gate A and B is a logic gate with 2 inputs and 1 output.

There are exactly 16 of them, because:

each logic gate takes two inputs, which can be truthy or falsey, giving us 4 possible inputs

of the 4 possible inputs, each can have an output of truthy and falsey

therefore, there are 2^4 possible logic gates, which is 16.

Your task is to write 16 programs/functions which implement all of them separately.

Your functions/programs must be independent.

They are valid as long as they output truthy/falsey values, meaning that you can implement A or B in Python as lambda a,b:a+b, even if 2 is produced for A=True and B=True.

Score is total bytes used for each function/program.

List of logic gates

0,0,0,0 (false)

0,0,0,1 (and)

0,0,1,0 (A and not B)

0,0,1,1 (A)

0,1,0,0 (not A and B)

0,1,0,1 (B)

0,1,1,0 (xor)

0,1,1,1 (or)

1,0,0,0 (nor)

1,0,0,1 (xnor)

1,0,1,0 (not B)

1,0,1,1 (B implies A)

1,1,0,0 (not A)

1,1,0,1 (A implies B)

1,1,1,0 (nand)

1,1,1,1 (true)

Where the first number is the output for A=false, B=false,
the second number is the output for A=false, B=true,
the third number is the output for A=true, B=false,
the fourth number is the output for A=true, B=true.

Leaderboard

var QUESTION_ID=82938,OVERRIDE_USER=48934;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+(?:\.\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

```

答:
Java, 695 bytes

```<code>class L{boolean f(){return false;}boolean d(boolean... x){return a(x)==t()?b(x):f();}boolean q(boolean...x){return d(a(x),n(b(x)));}boolean n(boolean x){return x==t()?f():t();}boolean a(boolean... x){return x[0];}boolean w(boolean...x){return d(n(a(x)),b(x));}boolean b(boolean...x){return x[1];}boolean x(boolean...x){return d(o(x),n(d(x)));}boolean o(boolean...x){return n(d(n(a(x)),n(b(x))));}boolean s(boolean...x){return n(o(x));}boolean r(boolean...x){return n(x(x));}boolean l(boolean...x){return n(b(x));}boolean j(boolean...x){return n(w(x));}boolean c(boolean...x){return n(a(x));}boolean v(boolean...x){return n(q(x));}boolean m(boolean...x){return n(d(x));}boolean t(){return !f();}}
</code>```

Ungolfed

```<code>public class LogicGate
{
    public static boolean f(boolean... x)
    {
        return false;
    }

    public static boolean and(boolean... x)
    {
        return a(x)==t() ? b(x) : f();
    }

    public static boolean aandnotb(boolean... x)
    {
        return and( a(x), not(b(x)) );
    }

    private static boolean not(boolean x)
    {
        return x==t()?f():t();
    }

    public static boolean a(boolean... x)
    {
        return x[0];
    }

    public static boolean notaandb(boolean... x)
    {
        return and( not(a(x)), b(x));
    }

    public static boolean b(boolean... x)
    {
        return x[1];
    }

    public static boolean xor(boolean... x)
    {
        return and( or(x), not(and(x)) );
    }

    public static boolean or(boolean... x)
    {
        return not( and( not(a(x)), not(b(x))) );//see de morgan's law
    }

    public static boolean nor(boolean... x)
    {
        return not(or(x));
    }

    public static boolean xnor(boolean... x)//it is understandable when written nxor. See https://en.wikipedia.org/wiki/XNOR_gate
    {
        return not(xor(x));
    }

    public static boolean notb(boolean... x)
    {
        return not(b(x));
    }

    public static boolean bimpliesa(boolean... x) //A ⇒ B is true only in the case that either A is false o B is true.
    {
        return not(notaandb(x)) ;// == o( n(b(x)), a(x));
    }

    public static boolean nota(boolean... x)
    {
        return not(a(x));
    }

    public static boolean aimpliesb(boolean... x)
    {
        return not(aandnotb(x));
    }

    public static boolean nand(boolean... x)
    {
        return not( and(x) );
    }

    public static boolean t(boolean... x)
    {
        return !f();
    }
}
</code>```

Test case to try above code.

Body:
Java, 695 bytes

class L{boolean f(){return false;}boolean d(boolean... x){return a(x)==t()?b(x):f();}boolean q(boolean...x){return d(a(x),n(b(x)));}boolean n(boolean x){return x==t()?f():t();}boolean a(boolean... x){return x[0];}boolean w(boolean...x){return d(n(a(x)),b(x));}boolean b(boolean...x){return x[1];}boolean x(boolean...x){return d(o(x),n(d(x)));}boolean o(boolean...x){return n(d(n(a(x)),n(b(x))));}boolean s(boolean...x){return n(o(x));}boolean r(boolean...x){return n(x(x));}boolean l(boolean...x){return n(b(x));}boolean j(boolean...x){return n(w(x));}boolean c(boolean...x){return n(a(x));}boolean v(boolean...x){return n(q(x));}boolean m(boolean...x){return n(d(x));}boolean t(){return !f();}}

Ungolfed

public class LogicGate
{
    public static boolean f(boolean... x)
    {
        return false;
    }

    public static boolean and(boolean... x)
    {
        return a(x)==t() ? b(x) : f();
    }

    public static boolean aandnotb(boolean... x)
    {
        return and( a(x), not(b(x)) );
    }

    private static boolean not(boolean x)
    {
        return x==t()?f():t();
    }

    public static boolean a(boolean... x)
    {
        return x[0];
    }

    public static boolean notaandb(boolean... x)
    {
        return and( not(a(x)), b(x));
    }

    public static boolean b(boolean... x)
    {
        return x[1];
    }

    public static boolean xor(boolean... x)
    {
        return and( or(x), not(and(x)) );
    }

    public static boolean or(boolean... x)
    {
        return not( and( not(a(x)), not(b(x))) );//see de morgan's law
    }

    public static boolean nor(boolean... x)
    {
        return not(or(x));
    }

    public static boolean xnor(boolean... x)//it is understandable when written nxor. See https://en.wikipedia.org/wiki/XNOR_gate
    {
        return not(xor(x));
    }

    public static boolean notb(boolean... x)
    {
        return not(b(x));
    }

    public static boolean bimpliesa(boolean... x) //A ⇒ B is true only in the case that either A is false o B is true.
    {
        return not(notaandb(x)) ;// == o( n(b(x)), a(x));
    }

    public static boolean nota(boolean... x)
    {
        return not(a(x));
    }

    public static boolean aimpliesb(boolean... x)
    {
        return not(aandnotb(x));
    }

    public static boolean nand(boolean... x)
    {
        return not( and(x) );
    }

    public static boolean t(boolean... x)
    {
        return !f();
    }
}

Test case to try above code.


答:
CJam, 15 bytes

```<code>q"sS""thTh"2/er
</code>```

Test it here.

Explanation

```<code>q      e# Read input.
"sS"   e# Push string.
"thTh" e# Push string.
2/     e# Split into pairs, i.e. ["th" "Th"].
er     e# Transliteration, replaces 's' with 'th' and 'S' with 'Th'.
</code>```

Title: Lithp Tranthlator

Body:
CJam, 15 bytes

q"sS""thTh"2/er

Test it here.

Explanation

q      e# Read input.
"sS"   e# Push string.
"thTh" e# Push string.
2/     e# Split into pairs, i.e. ["th" "Th"].
er     e# Transliteration, replaces 's' with 'th' and 'S' with 'Th'.


答:
Common Lithp, 62

```<code>(map()(lambda(u)(princ(case u(#\s"th")(#\S"Th")(t u))))(read))
</code>```

First, (read) the input (it should be a string).
Strings in CL are sequences so we use map to iterate on each character. The first argument to map represents the type of the result (e.g. I could build a list from a vector). When it is nil, a.k.a. (), results are discarded. The function that is mapped to the input simply princ (print non-readably) each character, except the ones that should be replaced.

Title: Lithp Tranthlator

Body:
Common Lithp, 62

(map()(lambda(u)(princ(case u(#\s"th")(#\S"Th")(t u))))(read))

First, (read) the input (it should be a string).
Strings in CL are sequences so we use map to iterate on each character. The first argument to map represents the type of the result (e.g. I could build a list from a vector). When it is nil, a.k.a. (), results are discarded. The function that is mapped to the input simply princ (print non-readably) each character, except the ones that should be replaced.


答:
05AB1E, <s>14</s> 12 bytes

```<code>'s„th:'S„Th:
</code>```

The straight forward answer.

Try it online

Saved 2 bytes thanks to @Adnan

Title: Lithp Tranthlator

Body:
05AB1E, <s>14</s> 12 bytes

's„th:'S„Th:

The straight forward answer.

Try it online

Saved 2 bytes thanks to @Adnan


答:
Labyrinth, <s>37</s> 34 bytes

```<code>?"
}
|=:{:
)   }
: :;-{
=&( {!;\!@
</code>```

Try it online!

Explanation

Quick Labyrinth primer:

Labyrinth operates on two stacks of arbitrary-precision integers, main and auxiliary, which are initially filled with an (implicit) infinite amount of zeros.

The source code resembles a maze, where the instruction pointer (IP) follows corridors. All interesting control flow happens at junctions: when the IP has more than one cell to go to, the top of the main stack is inspected. If the value is negative, the IP turns left, if it's positive, the IP turns right, and otherwise it moves straight ahead. If the chosen direction is blocked by a wall (i.e. a space), the IP moves in the opposite direction instead.

The program uses the same algorithm as the other answers: we replace (a, b) with (a | a+1, b & b-1) as long as a < b. I'll add a full explanation after I've tried golfing it some more.

The IP starts in the top left corner, going right. ? reads an integer a. Then " is a no-op, but it's necessary to prevent the IP from moving down immediately. This is also a dead end, so the IP turns around and executes ? again to read b. } then moves b from main to aux, so now we've got:

```<code>Main [ ... 0 a | b 0 ...] Aux
</code>```

The | then does nothing, because it takes the bitwise OR of a and 0. Since we know a is always positive, the IP turns east (because it can't turn west). This begins the main loop of the program. We start with a short linear section in order to compare a and b:

```<code>=   Swap tops of stacks, i.e. swap a and b.
:   Duplicate b.
{   Pull a over to main.
:   Duplicate a.
}   Push one copy back to aux.
-   Compute b-a.
</code>```

The IP is now at another junction. First, let's consider the case where the result is positive. That means b > a and we need to perform one more iteration. That iteration is also completely linear. Note that the stacks are currently:

```<code>Main [ ... 0 b (b-a) | a 0 ...] Aux

;   Discard b-a.
:   Duplicate b.
(   Decrement.
&   Bitwise AND with b, clearing the least-significant 1.
=   Swap new b with old a.
:   Duplicate a.
)   Increment.
|   Bitwise OR with a, setting the least-significant 0.
</code>```

And then we're back to the start of the loop (since a is again positive, the IP turns east again).

If at some point b-a is no longer positive, the IP will take one of the other two paths. Note that in both cases we fetch a with {, then hit a corner where the IP follows the bend and then print a with !. Now the top of the stack is again b-a which means that in both cases the IP will end up moving east. All that's left is a short linear bit now:

```<code>;   Discard b-a.
\   Print a linefeed.
!   Print b.
@   Terminate the program.
</code>```

Title: "Bit-borrow" two numbers

Body:
Did you know that a small number can borrow bits from a larger number? Here's an example. Let's say our two numbers 5 and 14. First, write them out in binary:

```<code>5       14
000101  001110
</code>```

First we take the smallest on bit away from the larger number, and we give it to the smallest off bit on the other number. So

```<code>This bit turns off
            |
            v
000101  001110
    ^
    |
This bit turns on
</code>```

Now we have

```<code>000111  001100
</code>```

and our numbers are 7 and 12. The first number is still smaller, so we continue.

```<code>000111  001100
001111  001000
</code>```

Now we have 15 and 8, so we can stop. We'll call this set of operations "bit-borrowing" two numbers. Let's do another example. 20 and 61.

```<code>20        61
010100    111101
010101    111100
010111    111000
111111    100000
63        32
</code>```

So our end result is 32, 63. Let's do one more. 31, and 12. 31 is already bigger than 12, so there's nothing to do! Bit-borrowing 31 and 12 gives 31 and 12, no change.

The challenge

Your challenge is to write a program or function that takes two numbers and bit-borrows them. The two numbers will always positive integers. Your input and output can be in any reasonable format.

Test IO:

```<code>Input: 2, 3
Output: 3, 2

Input: 3, 2
Output: 3, 2

Input: 8, 23
Output: 31, 0

Input: 42, 81
Output: 63, 0

Input: 38, 41
Output: 47, 32

Input: 16, 73
Output: 23, 0

Input: 17, 17
Output: 17, 17
</code>```

Standard loopholes apply, and shortest answer in bytes wins!

Body:
Labyrinth, <s>37</s> 34 bytes

?"
}
|=:{:
)   }
: :;-{
=&( {!;\!@

Try it online!

Explanation

Quick Labyrinth primer:

Labyrinth operates on two stacks of arbitrary-precision integers, main and auxiliary, which are initially filled with an (implicit) infinite amount of zeros.

The source code resembles a maze, where the instruction pointer (IP) follows corridors. All interesting control flow happens at junctions: when the IP has more than one cell to go to, the top of the main stack is inspected. If the value is negative, the IP turns left, if it's positive, the IP turns right, and otherwise it moves straight ahead. If the chosen direction is blocked by a wall (i.e. a space), the IP moves in the opposite direction instead.

The program uses the same algorithm as the other answers: we replace (a, b) with (a | a+1, b & b-1) as long as a < b. I'll add a full explanation after I've tried golfing it some more.

The IP starts in the top left corner, going right. ? reads an integer a. Then " is a no-op, but it's necessary to prevent the IP from moving down immediately. This is also a dead end, so the IP turns around and executes ? again to read b. } then moves b from main to aux, so now we've got:

Main [ ... 0 a | b 0 ...] Aux

The | then does nothing, because it takes the bitwise OR of a and 0. Since we know a is always positive, the IP turns east (because it can't turn west). This begins the main loop of the program. We start with a short linear section in order to compare a and b:

=   Swap tops of stacks, i.e. swap a and b.
:   Duplicate b.
{   Pull a over to main.
:   Duplicate a.
}   Push one copy back to aux.
-   Compute b-a.

The IP is now at another junction. First, let's consider the case where the result is positive. That means b > a and we need to perform one more iteration. That iteration is also completely linear. Note that the stacks are currently:

Main [ ... 0 b (b-a) | a 0 ...] Aux

;   Discard b-a.
:   Duplicate b.
(   Decrement.
&   Bitwise AND with b, clearing the least-significant 1.
=   Swap new b with old a.
:   Duplicate a.
)   Increment.
|   Bitwise OR with a, setting the least-significant 0.

And then we're back to the start of the loop (since a is again positive, the IP turns east again).

If at some point b-a is no longer positive, the IP will take one of the other two paths. Note that in both cases we fetch a with {, then hit a corner where the IP follows the bend and then print a with !. Now the top of the stack is again b-a which means that in both cases the IP will end up moving east. All that's left is a short linear bit now:

;   Discard b-a.
\   Print a linefeed.
!   Print b.
@   Terminate the program.


答:
C, 50 bytes

```<code>s(c){c=getchar();c+=c-83&95?0:'h\1';s(printf(&c));}
</code>```

Replace \1 with an actual \x01 byte.

jimmy23013 saved a byte, and then I saved two more using his approach! Thanks.

Title: Lithp Tranthlator

Body:
C, 50 bytes

s(c){c=getchar();c+=c-83&95?0:'h\1';s(printf(&c));}

Replace \1 with an actual \x01 byte.

jimmy23013 saved a byte, and then I saved two more using his approach! Thanks.


Title: Lithp Tranthlator

Body:
Haskell, 36 bytes

f 's'="th";f 'S'="Th";f x=[x]
(>>=f)


答:
JavaThcript ETh6, 38 bytes

At first I went with the obvious solution

```<code>a=>a.replace(/s/g,'th').replace(/S/g,'Th')
</code>```

But I golfed it down 4 bytes

```<code>a=>a.replace(/s/gi,b=>b>'r'?'th':'Th')
</code>```

This makes use of the regex i flag, which searches for case-insensitive patterns. The good thing about Javascript is that you can specify an anonymous function to handle (regex) replacing.

Try it here

f=
a=>a.replace(/s/gi,b=>b>'r'?'th':'Th')

s.innerHTML = [
    'abScdsefSghsij',
    'Sam and Sally like Sheep',
    'Sally likes sausages',
    'Sally sells seashells'
].map(c=>c + ' => ' + f(c)).join`<br>````
<pre class="snippet-code-html lang-html prettyprint-override"><code><pre id=s></code>```

Title: Lithp Tranthlator

Body:
JavaThcript ETh6, 38 bytes

At first I went with the obvious solution

a=>a.replace(/s/g,'th').replace(/S/g,'Th')

But I golfed it down 4 bytes

a=>a.replace(/s/gi,b=>b>'r'?'th':'Th')

This makes use of the regex i flag, which searches for case-insensitive patterns. The good thing about Javascript is that you can specify an anonymous function to handle (regex) replacing.

Try it here

f=
a=>a.replace(/s/gi,b=>b>'r'?'th':'Th')

s.innerHTML = [
    'abScdsefSghsij',
    'Sam and Sally like Sheep',
    'Sally likes sausages',
    'Sally sells seashells'
].map(c=>c + ' => ' + f(c)).join`<br>`

<pre id=s>


答:
JavaThcript ETh6, 43 byteth

```<code>s=>s.replace(/s/gi,m=>({s:'th',S:'Th'})[m])
</code>```

Tetht Thuite:

th=s=>s.replace(/s/gi,m=>({s:'th',S:'Th'})[m])

console.log(th('Sam and Sally like Sheep'));
console.log(th('Sally likes sausages'));
console.log(th('Sally sells seashells'));```

Title: Lithp Tranthlator

Body:
JavaThcript ETh6, 43 byteth

s=>s.replace(/s/gi,m=>({s:'th',S:'Th'})[m])

Tetht Thuite:

th=s=>s.replace(/s/gi,m=>({s:'th',S:'Th'})[m])

console.log(th('Sam and Sally like Sheep'));
console.log(th('Sally likes sausages'));
console.log(th('Sally sells seashells'));


问:
Leyland Numbers
Given a natural number \$n\$, return the \$n\$-th Leyland number.

Leyland Number

Leyland numbers are positive integers \$k\$ of the form

$$k = x^y + y^x$$

Where \$x\$ and \$y\$ are integers strictly greater than 1.

They are enumerated in ascending order.

EDIT: @DigitalTrauma suggested I include following "definition":

Imagine we throw \$x^y+y^x\$ in a bag for all possible values of \$x\$ and \$y\$, and avoid throwing in duplicates. Then we sort that bag. The sorted bag is our sequence.

Details

You may use 0 or 1 based indexing, whatever suits you best.

Your program must be able to output at least all Leyland numbers less than the maximum of signed 32-bit integers. (The last Leyland number below this limit is 1996813914, at index 82.)

Test cases

The first few terms are following:

```<code>8, 17, 32, 54, 57, 100, 145, 177, 320, 368, 512, 593, 945, 1124
</code>```

A076980 in OEIS, except for the first entry. Note that because of that additional first entry, the indices on OEIS are shifted by one.

More can be found in the OEIS b-file

答:
J, 29 bytes

```<code><:{[:/:~@~.@,[:(^+^~)"0/~2+i.
</code>```

Uses one-based indexing. Conversion from my Mathematica solution.

The true secret here is that I have :(^+^~) on my side.

Usage

```<code>   f =: <:{[:/:~@~.@,[:(^+^~)"0/~2+i.
   f 7
145
   (,.f"0) >: i. 10  NB. Extra commands for formatting
 1   8
 2  17
 3  32
 4  54
 5  57
 6 100
 7 145
 8 177
 9 320
10 368
</code>```

Explanation

```<code><:{[:/:~@~.@,[:(^+^~)"0/~2+i.  Input: n
                         2+i.  Step one
                     "0/~      Step two
              :(^+^~)          ???
<:{[:/:~@~.@,[                 Profit
</code>```

More seriously,

```<code><:{[:/:~@~.@,[:(^+^~)"0/~2+i.  Input: n
                           i.  Create the range [0, 1, ..., n-1]
                         2+    Add 2 to each
               (^+^~)"0        Create a dyad (2 argument function) with inputs x, y
                               and returns x^y + y^x
             [:        /~      Use that function to create a table using the previous range
   [:       ,                  Flatten the table into a list
         ~.@                   Take its distinct values only
     /:~@                      Sort it in ascending order
<:                             Decrement n (since J is zero-indexed)
  {                            Select the value at index n-1 from the list and return
</code>```

Title: Leyland Numbers

Body:
J, 29 bytes

<:{[:/:~@~.@,[:(^+^~)"0/~2+i.

Uses one-based indexing. Conversion from my Mathematica solution.

The true secret here is that I have :(^+^~) on my side.

Usage

   f =: <:{[:/:~@~.@,[:(^+^~)"0/~2+i.
   f 7
145
   (,.f"0) >: i. 10  NB. Extra commands for formatting
 1   8
 2  17
 3  32
 4  54
 5  57
 6 100
 7 145
 8 177
 9 320
10 368

Explanation

<:{[:/:~@~.@,[:(^+^~)"0/~2+i.  Input: n
                         2+i.  Step one
                     "0/~      Step two
              :(^+^~)          ???
<:{[:/:~@~.@,[                 Profit

More seriously,

<:{[:/:~@~.@,[:(^+^~)"0/~2+i.  Input: n
                           i.  Create the range [0, 1, ..., n-1]
                         2+    Add 2 to each
               (^+^~)"0        Create a dyad (2 argument function) with inputs x, y
                               and returns x^y + y^x
             [:        /~      Use that function to create a table using the previous range
   [:       ,                  Flatten the table into a list
         ~.@                   Take its distinct values only
     /:~@                      Sort it in ascending order
<:                             Decrement n (since J is zero-indexed)
  {                            Select the value at index n-1 from the list and return


答:
Java, 71 65 bytes

String t(String s){return s.replace("S","Th").replace("s","th");}
```

First attempt at golfing, so why not with Java.

Title: Lithp Tranthlator

Body:
Java, 71 65 bytes

String t(String s){return s.replace("S","Th").replace("s","th");}

First attempt at golfing, so why not with Java.


问:
Computer Generated Cracked Soil
Write a program that takes in an integer from 0 to 65535 (216-1) and generates a unique 500×500 pixel image that looks as similar as possible to these 6 real life images of cracked soil:

These are thumbnails, click them to see the full-size 500×500 images.

The goal here is to make your computer generated images as photorealistic as possible. So ideally, if any of the images output by your program were mixed in with the 6 images above, someone seeing the images for the first time would not be able to tell the computer generated ones apart from the real ones.

Perfect photorealism is tricky however, so just do the best you can. This is a popularity-contest so the answers that have more realistic outputs will be upvoted more and be more likely to win.

Rules

You may use image processing functions or libraries.

You may base your algorithm on information gathered from the 6 sample images, but your 65536 (216) possible output images should be visually distinct from each other and the sample images, especially with regard to the arrangement of the cracks. You must truly generate your images, don't just rotate and translate a selection from a preexisting photo.

You should not otherwise hardcode your outputs. A generic algorithm should be used and numbers larger than 65535 should theoretically produce valid outputs. (I've restricted it merely to accommodate small-maximum integer types.)

The input integer can be thought of as a seed that results in a random cracked soil output image. It should be deterministic though, so the same input should always result in the same output.

The output images must be exactly 500×500 pixels.

The output images may be saved in any common image file format, or simply displayed.

Be sure to include a few example output images in your answer, and their corresponding input numbers.

The answer with the most votes wins. Voters should of course upvote answers that attempt to produce images similar to the 6 samples, and downvote answers that break rules or give inconsistent results.

The 6 sample images were taken from texturelib.com. 1000×1000 pixel area selections were taken from two larger images of cracked soil and then resized to 500×500. You may use analysis from these larger images in your program but the output should specifically imitate the 6 chosen sample images.

答:
Mathematica

A Voronoi diagram looks like this drawing, from Wikipedia, showing 19 cells, each containing a single seed point.   A cell consists of the subregion of points which the respective generating point is closer to than any of the other seed points.

The code below generates a diagram from 80 random points (in the square region bound by (-1,-1) and (1,1)).

It uses the polygon primitives (in 2D) in the diagram to build polyhedra (in 3D).  Imagine that each polygon has, just under it, a translation (-.08 in z) of itself. Think of the two polygons as the upper and lower face of a polyhedron.  "Side faces" are then added to complete the polyhedron.

Each polyhedron is then translated outwards, from the center of the image, on the xy plane; it moves away from the middle. The magnitude of the translation varies directly with the distance between the polyhedron's original generating random point and the center of the screen. This "spreading out" of the polyhedra in the xy plane results in crevices.

```<code>crackedMud[1]
</code>```

```<code>crackedMud[65535]
</code>```

Code

```<code>ClearAll[polyhedronFromPolygon, voronoiPolygons, generatingPointFromPolygon, crackedMud]

(* polyhedronFromPolygon returns a single polyhedron from a polygon *)

polyhedronFromPolygon[polygon_] :=
 Module[{twoPolygons, verticesOfUpperPolygonCell, nVertices, n = 1},
 verticesOfUpperPolygonCell = Join @@ (polygon[[1]] /. {x_, y_} :> {{x, y, 0}, {x, y, -.08}});
 (* number of vertices in a single *Voronoi* cell *)
 nVertices = Length[verticesOfUpperPolygonCell]/2;

(*vertex indices of the upper and lower polygon faces *)
twoPolygons = Select[Range@(2*nVertices), #] & /@ {OddQ, EvenQ};

(*vertex indices of a rectangular face of the polyhedron *)
While[n < nVertices + 1, AppendTo[twoPolygons,
    {twoPolygons[[1, n]], twoPolygons[[2, n]],
     twoPolygons[[2, If[n + 1 < nVertices + 1, n + 1, 1]]],
     twoPolygons[[1, If[n + 1 < nVertices + 1, n + 1, 1]]]}]; n++];
(*the graphics complex returned is a polyhedron, even though it says Polygon *)
 GraphicsComplex[verticesOfUpperPolygonCell, Polygon[twoPolygons]] ]

(* takes two dimensional coordinates and returns all of the cells of a Voronoi diagram *)

voronoiPolygons[pts_] :=
Module[{voronoiRegion, data},
  voronoiRegion = VoronoiMesh[pts, ImageSize -> Medium,
  PlotTheme -> "Lines", Axes -> True, AxesOrigin -> {0, 0}];
  data = Join @@ (MeshPrimitives[voronoiRegion, 2][[All, 1]] /. {x_, y_} :> {{x, y, 0}, {x, y, .04}});
 (* the mesh primitives are the polygons *)
  MeshPrimitives[voronoiRegion, 2]]

(* Returns, in 3D, the point which was used to generate the nth Voronoi cell. *)
generatingPointFromPolygon[n_, points_, pgons_] :=
 FirstCase[points, {x_, y_} /; RegionMember[pgons[[n]], {x, y}] :> {x,y,0}]

crackedMud[seedNumber_] :-
 Module[{pts, pts3D, geometricImage, nPts, polygons, polyhedra, centerPtinImage},
  SeedRandom[seedNumber];
  nPts = 80;
  pts = RandomReal[{-1, 1}, {nPts, 2}];
  pts3D = pts /. {x_, y_} :> {x, y, .0};
  polygons = voronoiPolygons[pts];
  polyhedra = polyhedronFromPolygon /@ polygons;
  centerPtinImage =   (Mean /@ (PlotRange /.
        AbsoluteOptions[
         Graphics3D[{polyhedra, Blue, Point@pts3D}, Axes -> False,
         Boxed -> False]])) /. {x_Real, y_, _} :> {x, y, 0};
  geometricImage =
  Graphics3D[{RGBColor[0.75, 0.75, 0.8], EdgeForm[Darker@Gray],
        (* # is the nth polygon which yields the nth polyhedron *)
        (* generatingPointFromPolygon returns the point the generated the #th polygon *)

     GeometricTransformation[{polyhedronFromPolygon[polygons[[#]]]},
        TranslationTransform[(generatingPointFromPolygon[#, pts, polygons] - centerPtinImage)/5]] & /@ Range@nPts},
         Axes -> False,  Boxed -> False, ViewPoint -> {0., -1, 1.5},
         Background -> Black, ImageSize -> 1200];

     (*ImageTrim returns a 500 by 500 pixel clip from the center of the image *)
     ImageTrim[
        (*ImageEffect speckles the image *)
        ImageEffect[Rasterize[geometricImage], {"Noise", 1/5}],
     {{250, 250}, {750, 750}}]
  ]
</code>```

Title: Computer Generated Cracked Soil

Body:
Mathematica

A Voronoi diagram looks like this drawing, from Wikipedia, showing 19 cells, each containing a single seed point.   A cell consists of the subregion of points which the respective generating point is closer to than any of the other seed points.

The code below generates a diagram from 80 random points (in the square region bound by (-1,-1) and (1,1)).

It uses the polygon primitives (in 2D) in the diagram to build polyhedra (in 3D).  Imagine that each polygon has, just under it, a translation (-.08 in z) of itself. Think of the two polygons as the upper and lower face of a polyhedron.  "Side faces" are then added to complete the polyhedron.

Each polyhedron is then translated outwards, from the center of the image, on the xy plane; it moves away from the middle. The magnitude of the translation varies directly with the distance between the polyhedron's original generating random point and the center of the screen. This "spreading out" of the polyhedra in the xy plane results in crevices.

crackedMud[1]

crackedMud[65535]

Code

ClearAll[polyhedronFromPolygon, voronoiPolygons, generatingPointFromPolygon, crackedMud]

(* polyhedronFromPolygon returns a single polyhedron from a polygon *)

polyhedronFromPolygon[polygon_] :=
 Module[{twoPolygons, verticesOfUpperPolygonCell, nVertices, n = 1},
 verticesOfUpperPolygonCell = Join @@ (polygon[[1]] /. {x_, y_} :> {{x, y, 0}, {x, y, -.08}});
 (* number of vertices in a single *Voronoi* cell *)
 nVertices = Length[verticesOfUpperPolygonCell]/2;

(*vertex indices of the upper and lower polygon faces *)
twoPolygons = Select[Range@(2*nVertices), #] & /@ {OddQ, EvenQ};

(*vertex indices of a rectangular face of the polyhedron *)
While[n < nVertices + 1, AppendTo[twoPolygons,
    {twoPolygons[[1, n]], twoPolygons[[2, n]],
     twoPolygons[[2, If[n + 1 < nVertices + 1, n + 1, 1]]],
     twoPolygons[[1, If[n + 1 < nVertices + 1, n + 1, 1]]]}]; n++];
(*the graphics complex returned is a polyhedron, even though it says Polygon *)
 GraphicsComplex[verticesOfUpperPolygonCell, Polygon[twoPolygons]] ]

(* takes two dimensional coordinates and returns all of the cells of a Voronoi diagram *)

voronoiPolygons[pts_] :=
Module[{voronoiRegion, data},
  voronoiRegion = VoronoiMesh[pts, ImageSize -> Medium,
  PlotTheme -> "Lines", Axes -> True, AxesOrigin -> {0, 0}];
  data = Join @@ (MeshPrimitives[voronoiRegion, 2][[All, 1]] /. {x_, y_} :> {{x, y, 0}, {x, y, .04}});
 (* the mesh primitives are the polygons *)
  MeshPrimitives[voronoiRegion, 2]]

(* Returns, in 3D, the point which was used to generate the nth Voronoi cell. *)
generatingPointFromPolygon[n_, points_, pgons_] :=
 FirstCase[points, {x_, y_} /; RegionMember[pgons[[n]], {x, y}] :> {x,y,0}]

crackedMud[seedNumber_] :-
 Module[{pts, pts3D, geometricImage, nPts, polygons, polyhedra, centerPtinImage},
  SeedRandom[seedNumber];
  nPts = 80;
  pts = RandomReal[{-1, 1}, {nPts, 2}];
  pts3D = pts /. {x_, y_} :> {x, y, .0};
  polygons = voronoiPolygons[pts];
  polyhedra = polyhedronFromPolygon /@ polygons;
  centerPtinImage =   (Mean /@ (PlotRange /.
        AbsoluteOptions[
         Graphics3D[{polyhedra, Blue, Point@pts3D}, Axes -> False,
         Boxed -> False]])) /. {x_Real, y_, _} :> {x, y, 0};
  geometricImage =
  Graphics3D[{RGBColor[0.75, 0.75, 0.8], EdgeForm[Darker@Gray],
        (* # is the nth polygon which yields the nth polyhedron *)
        (* generatingPointFromPolygon returns the point the generated the #th polygon *)

     GeometricTransformation[{polyhedronFromPolygon[polygons[[#]]]},
        TranslationTransform[(generatingPointFromPolygon[#, pts, polygons] - centerPtinImage)/5]] & /@ Range@nPts},
         Axes -> False,  Boxed -> False, ViewPoint -> {0., -1, 1.5},
         Background -> Black, ImageSize -> 1200];

     (*ImageTrim returns a 500 by 500 pixel clip from the center of the image *)
     ImageTrim[
        (*ImageEffect speckles the image *)
        ImageEffect[Rasterize[geometricImage], {"Noise", 1/5}],
     {{250, 250}, {750, 750}}]
  ]


答:
Java

I used an approach based on recursive Voronoi diagrams. The outputs doesn't look very realistic, but I guess they're okay.

Here are some example images (resized to 250x250 so that it doesn't fill the entire screen):

0:

1:

More details about the algorithm:

All images in this section are using the same seed.

The algorithm starts by generating a Voronoi diagram with 5 points:

If we look at the original images in the challenge, we can see that the lines aren't all straight like that, so we weigh the distance by a random value, based on the angle to the point, also, closer angles gives closer values:

Now, we recursively draw these kinds of Voronoi diagrams inside of each region, with thinner and more transparent line, and remove the background, with a maximum recursion depth of 3, and we get:

Now, we just add the pale brown background, and we're done!

Code:

The code consists of three classes, Main.java, VoronoiPoint.java and Vector.java:

Main.java:

```<code>import java.awt.Desktop;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Random;

import javax.imageio.ImageIO;

public class Main {
    public static int WIDTH = 500;
    public static int HEIGHT = 500;
    public static int RECURSION_LEVELS = 3;
    public static int AMOUNT_OF_POINTS = 5;
    public static int ROTATION_RESOLUTION = 600;
    public static int ROTATION_SMOOTHNESS = 10;
    public static int BACKGROUND = 0xFFE0CBAD;

    public static Random RAND;

    public static void main(String[] args) {

        int seed = new Random().nextInt(65536);
        if (args.length == 1) {
            System.out.println(Arrays.toString(args));
            seed = Integer.parseInt(args[0]);
        } else {
            System.out.println("Generated seed: " + seed);
        }
        RAND = new Random(seed);

        ArrayList<Vector> points = new ArrayList<Vector>();
        for (int x = 0; x < WIDTH; x++) {
            for (int y = 0; y < HEIGHT; y++) {
                points.add(new Vector(x, y));
            }
        }
        BufferedImage soil = generateSoil(WIDTH, HEIGHT, seed, points, AMOUNT_OF_POINTS, RECURSION_LEVELS);

        BufferedImage background = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_ARGB);
        for (int x = 0; x < background.getWidth(); x++) {
            for (int y = 0; y < background.getHeight(); y++) {
                background.setRGB(x, y, BACKGROUND ^ (RAND.nextInt(10) * 0x010101));
            }
        }

        Graphics g = background.getGraphics();
        g.drawImage(soil, 0, 0, null);
        g.dispose();

        String fileName = "soil";
        File output = new File(fileName + ".png");
        for (int i = 0; output.exists(); i++) {
            output = new File(fileName + i + ".png");
        }
        try {
            ImageIO.write(background, "png", output);
            Desktop.getDesktop().open(output);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("Done. Saved as " + output);
    }

    private static BufferedImage generateSoil(int width, int height, int seed, ArrayList<Vector> drawPoints,
            int amountOfPoints, int recursionLevel) {

        BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

        ArrayList<VoronoiPoint> points = new ArrayList<VoronoiPoint>();
        for (int i = 0; i < amountOfPoints; i++) {
            points.add(new VoronoiPoint(drawPoints.get(RAND.nextInt(drawPoints.size()))));
        }

        HashMap<Integer, ArrayList<Vector>> pointMaps = new HashMap<Integer, ArrayList<Vector>>();
        for (VoronoiPoint point : points) {
            pointMaps.put(point.hashCode(), new ArrayList<Vector>());
        }
        System.out.println(pointMaps);

        System.out.println(points);

        for (Vector v : drawPoints) {
            VoronoiPoint closest = null;
            VoronoiPoint secondClosest = null;

            for (VoronoiPoint point : points) {
                double distance = point.getMultiplicativeDistanceTo(v);
                if (closest == null || distance < closest.getMultiplicativeDistanceTo(v)) {
                    secondClosest = closest;
                    closest = point;
                } else if (secondClosest == null || distance < secondClosest.getMultiplicativeDistanceTo(v)) {
                    secondClosest = point;
                }
            }

            int col = 0;
            if (Math.abs(closest.getMultiplicativeDistanceTo(v)
                    - secondClosest.getMultiplicativeDistanceTo(v)) < (recursionLevel * 5 / RECURSION_LEVELS)) {
                col = 0x01000000 * (recursionLevel * 255 / RECURSION_LEVELS);
            } else {
                pointMaps.get(closest.hashCode()).add(v);
            }
            result.setRGB((int) v.getX(), (int) v.getY(), col);
        }
        Graphics g = result.getGraphics();
        if (recursionLevel > 0) {
            for (ArrayList<Vector> pixels : pointMaps.values()) {
                if (pixels.size() > 10) {
                    BufferedImage img = generateSoil(width, height, seed, pixels, amountOfPoints,
                            recursionLevel - 1);
                    g.drawImage(img, 0, 0, null);
                }
            }
        }
        g.dispose();

        return result;
    }

    public static int modInts(int a, int b) {
        return (int) mod(a, b);
    }

    public static double mod(double a, double b) {
        a = a % b;
        while (a < 0)
            a += b;
        return a;
    }
}
</code>```

VoronoiPoint.java:

```<code>public class VoronoiPoint {

    private Vector pos;
    private double[] distances;

    public VoronoiPoint(Vector pos) {
        this.pos = pos;
        distances = new double[Main.ROTATION_RESOLUTION];
        for (int i = 0; i < distances.length; i++)
            distances[i] = Main.RAND.nextFloat() / 2 + 0.51;

        for (int iter = 0; iter < Main.ROTATION_SMOOTHNESS; iter++) {
            for (int i = 0; i < distances.length; i++) {
                distances[i] = (distances[Main.modInts(i - Main.RAND.nextInt(4) - 2, distances.length)] + distances[i]
                        + distances[Main.modInts(i + Main.RAND.nextInt(4) - 2, distances.length)]) / 3;
            }
        }
    }

    public Vector getPos() {
        return pos;
    }

    public double getRotationFromAngle(double radians) {
        return distances[(int) (Main.mod(Math.toDegrees(radians) / 360, 1) * distances.length)];
    }

    public double getRotationFromVector(Vector vec) {
        return getRotationFromAngle(Math.atan2(pos.getY() - vec.getY(), -(pos.getX() - vec.getX())));
    }

    public double getMultiplicativeDistanceTo(Vector other) {
        return pos.getLengthTo(other) * getRotationFromVector(other);
    }

    public String toString() {
        return "VoronoiPoint(pos=[" + pos.getX() + ", " + pos.getY() + "])";
    }

    public int hashCode() {
        return distances.hashCode() ^ pos.hashCode();
    }
}
</code>```

Vector.java: (This class is copied from one of my other projects, so it contains some unnecessary code)

```<code>package com.loovjo.soil;

import java.util.ArrayList;
import java.util.Random;

public class Vector {
    private static final float SMALL = 1f / Float.MAX_EXPONENT * 100;
    private float x, y;

    public Vector(float x, float y) {
        this.setX(x);
        this.setY(y);
    }

    public Vector(int x, int y) {
        this.setX(x);
        this.setY(y);
    }

    public Vector(double x, double y) {
        this.setX((float) x);
        this.setY((float) y);
    }

    public float getY() {
        return y;
    }

    public void setY(float y) {
        this.y = y;
    }

    public float getX() {
        return x;
    }

    public void setX(float x) {
        this.x = x;
    }

    /*
     * Gets the length ^ 2 This is faster than getting the length.
     */
    public float getLengthToSqrd(float x, float y) {
        return (float) ((this.x - x) * (this.x - x) + (this.y - y) * (this.y - y));
    }

    public float getLengthToSqrd(Vector v) {
        return getLengthToSqrd(v.x, v.y);
    }

    public float getLengthSqrd() {
        return getLengthToSqrd(0, 0);
    }

    public float getLengthTo(float x, float y) {
        return (float) Math.sqrt(getLengthToSqrd(x, y));
    }

    public float getLengthTo(Vector v) {
        return getLengthTo(v.x, v.y);
    }

    public float getLength() {
        return getLengthTo(0, 0);
    }

    public Vector setLength(float setLength) {
        float length = getLength();
        x *= setLength / length;
        y *= setLength / length;
        return this;
    }

    public float getFastLengthTo(float x, float y) {
        return getFastLengthTo(new Vector(x, y));
    }

    public float getFastLengthTo(Vector v) {
        float taxiLength = getTaxiCabLengthTo(v);
        float chebyDist = getChebyshevDistanceTo(v);
        return Float.min(taxiLength * 0.7f, chebyDist);
    }

    public float getFastLength() {
        return getLengthTo(0, 0);
    }

    public Vector setFastLength(float setLength) {
        float length = getFastLength();
        x *= setLength / length;
        y *= setLength / length;
        return this;
    }

    public float getTaxiCabLengthTo(float x, float y) {
        return Math.abs(this.x - x) + Math.abs(this.y - y);
    }

    public float getTaxiCabLengthTo(Vector v) {
        return getTaxiCabLengthTo(v.x, v.y);
    }

    public float getTaxiCabLength() {
        return getTaxiCabLengthTo(0, 0);
    }

    public Vector setTaxiCabLength(float setLength) {
        float length = getTaxiCabLength();
        x *= setLength / length;
        y *= setLength / length;
        return this;
    }

    public Vector absIfBoth() {
        if (x < 0 && y < 0)
            return new Vector(-x, -y);
        return this;
    }

    public Vector abs() {
        return new Vector(x < 0 ? -x : x, y < 0 ? -y : y);
    }

    public float getChebyshevDistanceTo(float x, float y) {
        return Math.max(Math.abs(this.x - x), Math.abs(this.y - y));
    }

    public float getChebyshevDistanceTo(Vector v) {
        return getChebyshevDistanceTo(v.x, v.y);
    }

    public float getChebyshevDistance() {
        return getChebyshevDistanceTo(0, 0);
    }

    public Vector setChebyshevLength(float setLength) {
        float length = getChebyshevDistance();
        x *= setLength / length;
        y *= setLength / length;
        return this;
    }

    public Vector sub(Vector v) {
        return new Vector(this.x - v.getX(), this.y - v.getY());
    }

    public Vector add(Vector v) {
        return new Vector(this.x + v.getX(), this.y + v.getY());
    }

    public Vector mul(Vector v) {
        return new Vector(this.x * v.getX(), this.y * v.getY());
    }

    public Vector mul(float f) {
        return mul(new Vector(f, f));
    }

    public Vector div(Vector v) {
        return new Vector(this.x / v.getX(), this.y / v.getY());
    }

    public Vector div(float f) {
        return div(new Vector(f, f));
    }

    public Vector mod(Vector v) {
        return new Vector(this.x % v.getX(), this.y % v.getY());
    }

    public Vector mod(int a, int b) {
        return mod(new Vector(a, b));
    }

    public Vector mod(int a) {
        return mod(a, a);
    }

    public String toString() {
        return "Vector(" + getX() + ", " + getY() + ")";
    }

    /*
     * Returns a list with vectors, starting with this, ending with to, and each
     * one having length between them
     */
    public ArrayList<Vector> loop(Vector to, float length) {
        Vector delta = this.sub(to);
        float l = delta.getLength();
        ArrayList<Vector> loops = new ArrayList<Vector>();
        for (float i = length; i < l; i += length) {
            delta.setLength(i);
            loops.add(delta.add(to));
        }
        loops.add(this);

        return loops;
    }

    public boolean intersects(Vector pos, Vector size) {
        pos.sub(this);
        if (pos.getX() < getX())
            return false;
        if (pos.getY() < getY())
            return false;
        return true;
    }

    public Vector copy() {
        return new Vector(x, y);
    }

    public void distort(float d) {
        x += Math.random() * d - d / 2;
        y += Math.random() * d - d / 2;
    }

    @Override
    public boolean equals(Object o) {
        if (o instanceof Vector) {
            Vector v = (Vector) o;
            return getLengthToSquared(v) < SMALL * SMALL;
        }
        return false;
    }

    private float getLengthToSquared(Vector v) {
        return sub(v).getLengthSquared();
    }

    private float getLengthSquared() {
        return x * x + y * y;
    }

    public boolean kindaEquals(Vector o, int i) {
        if (o.x + i < x)
            return false;
        if (o.x - i > x)
            return false;
        if (o.y + i < y)
            return false;
        if (o.y - i > y)
            return false;
        return true;
    }
    /*
     * Gets the direction, from 0 to 8.
     */
    public int getDirection() {
        return (getDirectionInDegrees()) / (360 / 8);
    }
    /*
     * Gets the direction in degrees.
     */
    public int getDirectionInDegrees() {
        return (int) positize((float) Math.toDegrees(Math.atan2(x, -y)), 360f);
    }

    private float positize(float f, float base) {
        while (f < 0)
            f += base;
        return f;
    }
    // 0 = north,
            // 1 = northeast,
            // 2 = east,
            // 3 = southeast,
            // 4 = south,
            // 5 = southwest,
            // 6 = west,
            // 7 = northwest
    public Vector moveInDir(int d) {
        d = d % 8;
        d = (int) positize(d, 8);

        if (d == 0)
            return this.add(new Vector(0, -1));
        if (d == 1)
            return this.add(new Vector(1, -1));
        if (d == 2)
            return this.add(new Vector(1, 0));
        if (d == 3)
            return this.add(new Vector(1, 1));
        if (d == 4)
            return this.add(new Vector(0, 1));
        if (d == 5)
            return this.add(new Vector(-1, 1));
        if (d == 6)
            return this.add(new Vector(-1, 0));
        if (d == 7)
            return this.add(new Vector(-1, -1));
        return this;
    }
    /*
     * Gets the angle in degrees to o.
     */
    public float getRotationTo(Vector o) {
        float d = (float) Math.toDegrees((Math.atan2(y - o.y, -(x - o.x))));
        while (d < 0)
            d += 360;
        while (d > 360)
            d -= 360;
        return d;
    }
    public float getRotation() {
        return getRotationTo(new Vector(0, 0));
    }
    /*
     * In degrees
     */
    public Vector rotate(double n) {
        n = Math.toRadians(n);
        float rx = (float) ((this.x * Math.cos(n)) - (this.y * Math.sin(n)));
        float ry = (float) ((this.x * Math.sin(n)) + (this.y * Math.cos(n)));
        return new Vector(rx, ry);
    }

    public int hashCode() {
        int xx = (int) x ^ (int)(x * Integer.MAX_VALUE);
        int yy = (int) y ^ (int)(y * Integer.MAX_VALUE);
        return new Random(12665 * xx).nextInt() ^ new Random(5349 * yy).nextInt() + new Random((30513 * xx) ^ (19972 * yy)).nextInt();
    }

    public boolean isPositive() {
        return x >= 0 && y >= 0;
    }

    public Vector clone() {
        return new Vector(x, y);
    }
}
</code>```

But I don't want to compile a bunch of Java classes!

Here is a JAR file which you can run to generate these images yourself. Run as java -jar Soil.jar number, where number is the seed (can be anything up to 231-1), or run as java -jar Soil.jar, and it chooses a seed by itself. There will be some debug output.

Title: Computer Generated Cracked Soil

Body:
Write a program that takes in an integer from 0 to 65535 (216-1) and generates a unique 500×500 pixel image that looks as similar as possible to these 6 real life images of cracked soil:

These are thumbnails, click them to see the full-size 500×500 images.

The goal here is to make your computer generated images as photorealistic as possible. So ideally, if any of the images output by your program were mixed in with the 6 images above, someone seeing the images for the first time would not be able to tell the computer generated ones apart from the real ones.

Perfect photorealism is tricky however, so just do the best you can. This is a popularity-contest so the answers that have more realistic outputs will be upvoted more and be more likely to win.

Rules

You may use image processing functions or libraries.

You may base your algorithm on information gathered from the 6 sample images, but your 65536 (216) possible output images should be visually distinct from each other and the sample images, especially with regard to the arrangement of the cracks. You must truly generate your images, don't just rotate and translate a selection from a preexisting photo.

You should not otherwise hardcode your outputs. A generic algorithm should be used and numbers larger than 65535 should theoretically produce valid outputs. (I've restricted it merely to accommodate small-maximum integer types.)

The input integer can be thought of as a seed that results in a random cracked soil output image. It should be deterministic though, so the same input should always result in the same output.

The output images must be exactly 500×500 pixels.

The output images may be saved in any common image file format, or simply displayed.

Be sure to include a few example output images in your answer, and their corresponding input numbers.

The answer with the most votes wins. Voters should of course upvote answers that attempt to produce images similar to the 6 samples, and downvote answers that break rules or give inconsistent results.

The 6 sample images were taken from texturelib.com. 1000×1000 pixel area selections were taken from two larger images of cracked soil and then resized to 500×500. You may use analysis from these larger images in your program but the output should specifically imitate the 6 chosen sample images.

Body:
Java

I used an approach based on recursive Voronoi diagrams. The outputs doesn't look very realistic, but I guess they're okay.

Here are some example images (resized to 250x250 so that it doesn't fill the entire screen):

0:

1:

More details about the algorithm:

All images in this section are using the same seed.

The algorithm starts by generating a Voronoi diagram with 5 points:

If we look at the original images in the challenge, we can see that the lines aren't all straight like that, so we weigh the distance by a random value, based on the angle to the point, also, closer angles gives closer values:

Now, we recursively draw these kinds of Voronoi diagrams inside of each region, with thinner and more transparent line, and remove the background, with a maximum recursion depth of 3, and we get:

Now, we just add the pale brown background, and we're done!

Code:

The code consists of three classes, Main.java, VoronoiPoint.java and Vector.java:

Main.java:

import java.awt.Desktop;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Random;

import javax.imageio.ImageIO;

public class Main {
    public static int WIDTH = 500;
    public static int HEIGHT = 500;
    public static int RECURSION_LEVELS = 3;
    public static int AMOUNT_OF_POINTS = 5;
    public static int ROTATION_RESOLUTION = 600;
    public static int ROTATION_SMOOTHNESS = 10;
    public static int BACKGROUND = 0xFFE0CBAD;

    public static Random RAND;

    public static void main(String[] args) {

        int seed = new Random().nextInt(65536);
        if (args.length == 1) {
            System.out.println(Arrays.toString(args));
            seed = Integer.parseInt(args[0]);
        } else {
            System.out.println("Generated seed: " + seed);
        }
        RAND = new Random(seed);

        ArrayList<Vector> points = new ArrayList<Vector>();
        for (int x = 0; x < WIDTH; x++) {
            for (int y = 0; y < HEIGHT; y++) {
                points.add(new Vector(x, y));
            }
        }
        BufferedImage soil = generateSoil(WIDTH, HEIGHT, seed, points, AMOUNT_OF_POINTS, RECURSION_LEVELS);

        BufferedImage background = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_ARGB);
        for (int x = 0; x < background.getWidth(); x++) {
            for (int y = 0; y < background.getHeight(); y++) {
                background.setRGB(x, y, BACKGROUND ^ (RAND.nextInt(10) * 0x010101));
            }
        }

        Graphics g = background.getGraphics();
        g.drawImage(soil, 0, 0, null);
        g.dispose();

        String fileName = "soil";
        File output = new File(fileName + ".png");
        for (int i = 0; output.exists(); i++) {
            output = new File(fileName + i + ".png");
        }
        try {
            ImageIO.write(background, "png", output);
            Desktop.getDesktop().open(output);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("Done. Saved as " + output);
    }

    private static BufferedImage generateSoil(int width, int height, int seed, ArrayList<Vector> drawPoints,
            int amountOfPoints, int recursionLevel) {

        BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

        ArrayList<VoronoiPoint> points = new ArrayList<VoronoiPoint>();
        for (int i = 0; i < amountOfPoints; i++) {
            points.add(new VoronoiPoint(drawPoints.get(RAND.nextInt(drawPoints.size()))));
        }

        HashMap<Integer, ArrayList<Vector>> pointMaps = new HashMap<Integer, ArrayList<Vector>>();
        for (VoronoiPoint point : points) {
            pointMaps.put(point.hashCode(), new ArrayList<Vector>());
        }
        System.out.println(pointMaps);

        System.out.println(points);

        for (Vector v : drawPoints) {
            VoronoiPoint closest = null;
            VoronoiPoint secondClosest = null;

            for (VoronoiPoint point : points) {
                double distance = point.getMultiplicativeDistanceTo(v);
                if (closest == null || distance < closest.getMultiplicativeDistanceTo(v)) {
                    secondClosest = closest;
                    closest = point;
                } else if (secondClosest == null || distance < secondClosest.getMultiplicativeDistanceTo(v)) {
                    secondClosest = point;
                }
            }

            int col = 0;
            if (Math.abs(closest.getMultiplicativeDistanceTo(v)
                    - secondClosest.getMultiplicativeDistanceTo(v)) < (recursionLevel * 5 / RECURSION_LEVELS)) {
                col = 0x01000000 * (recursionLevel * 255 / RECURSION_LEVELS);
            } else {
                pointMaps.get(closest.hashCode()).add(v);
            }
            result.setRGB((int) v.getX(), (int) v.getY(), col);
        }
        Graphics g = result.getGraphics();
        if (recursionLevel > 0) {
            for (ArrayList<Vector> pixels : pointMaps.values()) {
                if (pixels.size() > 10) {
                    BufferedImage img = generateSoil(width, height, seed, pixels, amountOfPoints,
                            recursionLevel - 1);
                    g.drawImage(img, 0, 0, null);
                }
            }
        }
        g.dispose();

        return result;
    }

    public static int modInts(int a, int b) {
        return (int) mod(a, b);
    }

    public static double mod(double a, double b) {
        a = a % b;
        while (a < 0)
            a += b;
        return a;
    }
}

VoronoiPoint.java:

public class VoronoiPoint {

    private Vector pos;
    private double[] distances;

    public VoronoiPoint(Vector pos) {
        this.pos = pos;
        distances = new double[Main.ROTATION_RESOLUTION];
        for (int i = 0; i < distances.length; i++)
            distances[i] = Main.RAND.nextFloat() / 2 + 0.51;

        for (int iter = 0; iter < Main.ROTATION_SMOOTHNESS; iter++) {
            for (int i = 0; i < distances.length; i++) {
                distances[i] = (distances[Main.modInts(i - Main.RAND.nextInt(4) - 2, distances.length)] + distances[i]
                        + distances[Main.modInts(i + Main.RAND.nextInt(4) - 2, distances.length)]) / 3;
            }
        }
    }

    public Vector getPos() {
        return pos;
    }

    public double getRotationFromAngle(double radians) {
        return distances[(int) (Main.mod(Math.toDegrees(radians) / 360, 1) * distances.length)];
    }

    public double getRotationFromVector(Vector vec) {
        return getRotationFromAngle(Math.atan2(pos.getY() - vec.getY(), -(pos.getX() - vec.getX())));
    }

    public double getMultiplicativeDistanceTo(Vector other) {
        return pos.getLengthTo(other) * getRotationFromVector(other);
    }

    public String toString() {
        return "VoronoiPoint(pos=[" + pos.getX() + ", " + pos.getY() + "])";
    }

    public int hashCode() {
        return distances.hashCode() ^ pos.hashCode();
    }
}

Vector.java: (This class is copied from one of my other projects, so it contains some unnecessary code)

package com.loovjo.soil;

import java.util.ArrayList;
import java.util.Random;

public class Vector {
    private static final float SMALL = 1f / Float.MAX_EXPONENT * 100;
    private float x, y;

    public Vector(float x, float y) {
        this.setX(x);
        this.setY(y);
    }

    public Vector(int x, int y) {
        this.setX(x);
        this.setY(y);
    }

    public Vector(double x, double y) {
        this.setX((float) x);
        this.setY((float) y);
    }

    public float getY() {
        return y;
    }

    public void setY(float y) {
        this.y = y;
    }

    public float getX() {
        return x;
    }

    public void setX(float x) {
        this.x = x;
    }

    /*
     * Gets the length ^ 2 This is faster than getting the length.
     */
    public float getLengthToSqrd(float x, float y) {
        return (float) ((this.x - x) * (this.x - x) + (this.y - y) * (this.y - y));
    }

    public float getLengthToSqrd(Vector v) {
        return getLengthToSqrd(v.x, v.y);
    }

    public float getLengthSqrd() {
        return getLengthToSqrd(0, 0);
    }

    public float getLengthTo(float x, float y) {
        return (float) Math.sqrt(getLengthToSqrd(x, y));
    }

    public float getLengthTo(Vector v) {
        return getLengthTo(v.x, v.y);
    }

    public float getLength() {
        return getLengthTo(0, 0);
    }

    public Vector setLength(float setLength) {
        float length = getLength();
        x *= setLength / length;
        y *= setLength / length;
        return this;
    }

    public float getFastLengthTo(float x, float y) {
        return getFastLengthTo(new Vector(x, y));
    }

    public float getFastLengthTo(Vector v) {
        float taxiLength = getTaxiCabLengthTo(v);
        float chebyDist = getChebyshevDistanceTo(v);
        return Float.min(taxiLength * 0.7f, chebyDist);
    }

    public float getFastLength() {
        return getLengthTo(0, 0);
    }

    public Vector setFastLength(float setLength) {
        float length = getFastLength();
        x *= setLength / length;
        y *= setLength / length;
        return this;
    }

    public float getTaxiCabLengthTo(float x, float y) {
        return Math.abs(this.x - x) + Math.abs(this.y - y);
    }

    public float getTaxiCabLengthTo(Vector v) {
        return getTaxiCabLengthTo(v.x, v.y);
    }

    public float getTaxiCabLength() {
        return getTaxiCabLengthTo(0, 0);
    }

    public Vector setTaxiCabLength(float setLength) {
        float length = getTaxiCabLength();
        x *= setLength / length;
        y *= setLength / length;
        return this;
    }

    public Vector absIfBoth() {
        if (x < 0 && y < 0)
            return new Vector(-x, -y);
        return this;
    }

    public Vector abs() {
        return new Vector(x < 0 ? -x : x, y < 0 ? -y : y);
    }

    public float getChebyshevDistanceTo(float x, float y) {
        return Math.max(Math.abs(this.x - x), Math.abs(this.y - y));
    }

    public float getChebyshevDistanceTo(Vector v) {
        return getChebyshevDistanceTo(v.x, v.y);
    }

    public float getChebyshevDistance() {
        return getChebyshevDistanceTo(0, 0);
    }

    public Vector setChebyshevLength(float setLength) {
        float length = getChebyshevDistance();
        x *= setLength / length;
        y *= setLength / length;
        return this;
    }

    public Vector sub(Vector v) {
        return new Vector(this.x - v.getX(), this.y - v.getY());
    }

    public Vector add(Vector v) {
        return new Vector(this.x + v.getX(), this.y + v.getY());
    }

    public Vector mul(Vector v) {
        return new Vector(this.x * v.getX(), this.y * v.getY());
    }

    public Vector mul(float f) {
        return mul(new Vector(f, f));
    }

    public Vector div(Vector v) {
        return new Vector(this.x / v.getX(), this.y / v.getY());
    }

    public Vector div(float f) {
        return div(new Vector(f, f));
    }

    public Vector mod(Vector v) {
        return new Vector(this.x % v.getX(), this.y % v.getY());
    }

    public Vector mod(int a, int b) {
        return mod(new Vector(a, b));
    }

    public Vector mod(int a) {
        return mod(a, a);
    }

    public String toString() {
        return "Vector(" + getX() + ", " + getY() + ")";
    }

    /*
     * Returns a list with vectors, starting with this, ending with to, and each
     * one having length between them
     */
    public ArrayList<Vector> loop(Vector to, float length) {
        Vector delta = this.sub(to);
        float l = delta.getLength();
        ArrayList<Vector> loops = new ArrayList<Vector>();
        for (float i = length; i < l; i += length) {
            delta.setLength(i);
            loops.add(delta.add(to));
        }
        loops.add(this);

        return loops;
    }

    public boolean intersects(Vector pos, Vector size) {
        pos.sub(this);
        if (pos.getX() < getX())
            return false;
        if (pos.getY() < getY())
            return false;
        return true;
    }

    public Vector copy() {
        return new Vector(x, y);
    }

    public void distort(float d) {
        x += Math.random() * d - d / 2;
        y += Math.random() * d - d / 2;
    }

    @Override
    public boolean equals(Object o) {
        if (o instanceof Vector) {
            Vector v = (Vector) o;
            return getLengthToSquared(v) < SMALL * SMALL;
        }
        return false;
    }

    private float getLengthToSquared(Vector v) {
        return sub(v).getLengthSquared();
    }

    private float getLengthSquared() {
        return x * x + y * y;
    }

    public boolean kindaEquals(Vector o, int i) {
        if (o.x + i < x)
            return false;
        if (o.x - i > x)
            return false;
        if (o.y + i < y)
            return false;
        if (o.y - i > y)
            return false;
        return true;
    }
    /*
     * Gets the direction, from 0 to 8.
     */
    public int getDirection() {
        return (getDirectionInDegrees()) / (360 / 8);
    }
    /*
     * Gets the direction in degrees.
     */
    public int getDirectionInDegrees() {
        return (int) positize((float) Math.toDegrees(Math.atan2(x, -y)), 360f);
    }

    private float positize(float f, float base) {
        while (f < 0)
            f += base;
        return f;
    }
    // 0 = north,
            // 1 = northeast,
            // 2 = east,
            // 3 = southeast,
            // 4 = south,
            // 5 = southwest,
            // 6 = west,
            // 7 = northwest
    public Vector moveInDir(int d) {
        d = d % 8;
        d = (int) positize(d, 8);

        if (d == 0)
            return this.add(new Vector(0, -1));
        if (d == 1)
            return this.add(new Vector(1, -1));
        if (d == 2)
            return this.add(new Vector(1, 0));
        if (d == 3)
            return this.add(new Vector(1, 1));
        if (d == 4)
            return this.add(new Vector(0, 1));
        if (d == 5)
            return this.add(new Vector(-1, 1));
        if (d == 6)
            return this.add(new Vector(-1, 0));
        if (d == 7)
            return this.add(new Vector(-1, -1));
        return this;
    }
    /*
     * Gets the angle in degrees to o.
     */
    public float getRotationTo(Vector o) {
        float d = (float) Math.toDegrees((Math.atan2(y - o.y, -(x - o.x))));
        while (d < 0)
            d += 360;
        while (d > 360)
            d -= 360;
        return d;
    }
    public float getRotation() {
        return getRotationTo(new Vector(0, 0));
    }
    /*
     * In degrees
     */
    public Vector rotate(double n) {
        n = Math.toRadians(n);
        float rx = (float) ((this.x * Math.cos(n)) - (this.y * Math.sin(n)));
        float ry = (float) ((this.x * Math.sin(n)) + (this.y * Math.cos(n)));
        return new Vector(rx, ry);
    }

    public int hashCode() {
        int xx = (int) x ^ (int)(x * Integer.MAX_VALUE);
        int yy = (int) y ^ (int)(y * Integer.MAX_VALUE);
        return new Random(12665 * xx).nextInt() ^ new Random(5349 * yy).nextInt() + new Random((30513 * xx) ^ (19972 * yy)).nextInt();
    }

    public boolean isPositive() {
        return x >= 0 && y >= 0;
    }

    public Vector clone() {
        return new Vector(x, y);
    }
}

But I don't want to compile a bunch of Java classes!

Here is a JAR file which you can run to generate these images yourself. Run as java -jar Soil.jar number, where number is the seed (can be anything up to 231-1), or run as java -jar Soil.jar, and it chooses a seed by itself. There will be some debug output.


Title: "Bit-borrow" two numbers

Body:
Clojure, 63 bytes

#(if(< % %2)(recur(bit-or %(inc %))(bit-and %2(dec %2)))[% %2])

Same method as used in my solution in J.

Usage

=> (def f #(if(< % %2)(recur(bit-or %(inc %))(bit-and %2(dec %2)))[% %2]))
=> (f 38 41)
[47 32]
=> (map (partial apply f) [[2 3] [3 2] [8 23] [42 81] [38 41] [16 73] [17 17]])
([3 2] [3 2] [31 0] [63 0] [47 32] [23 0] [17 17])


答:
Haskell, <s>278</s> <s>271</s> <s>262</s> 246 bytes

```<code>import Control.Concurrent.Chan
import Data.Time
import GHC.Conc
t=getCurrentTime
b!a=b=<<flip diffUTCTime<$>t<*>(a>>t)
w=threadDelay$5^10
0#_=t
i#a=a>>(i-1)#a
main=print!do r<-newChan;9#(forkIO$writeChan r!w);getChanContents r>>=print.sum.take 9
</code>```

! measures the time taken by action a (second argument) and applies b (first argument) to the result.

w is the sleep function.

main is measured itself, and result printed (print!...).

# is replicateM, repeating the given action N times (and returning t because golfing).

Inside the measured part, 9 threads (replicate 9 $ forkIO ...) sleep for 5^10 milliseconds (9.765625 seconds) and post the result (writeChan) to a pipe created by the main thread (newChan), which sums the 9 results up and prints the total (getChanContents >>= print . sum . take 9).

Output:

```<code>87.938546708s
9.772032144s
</code>```

Title: Wait a minute – in less than ten seconds

Body:
Task

Using any type of parallelisation, wait multiple periods, for a total sleep time of at least a minute (but less than a minute and a half).

The program/function must terminate within 10 seconds and return (by any means and in any format) two values: the total elapsed time, and the total executed sleep time. Both time values have to have a precision of at least 0.1 seconds.

This is similar to the concept of man-hours: a job that takes 60 hours can be completed in only 6 hours if 10 workers are splitting the job. Here we can have 60 seconds of sleep time e.g. in 10 parallel threads, thus requiring only 6 seconds for the whole job to be completed.

Example

The program MyProgram creates 14 threads, each thread sleeps for 5 seconds:

MyProgram → [5.016,70.105]

The execution time is greater than 5 seconds, and the total sleep time is greater than 70 seconds because of overhead.

Body:
Haskell, <s>278</s> <s>271</s> <s>262</s> 246 bytes

import Control.Concurrent.Chan
import Data.Time
import GHC.Conc
t=getCurrentTime
b!a=b=<<flip diffUTCTime<$>t<*>(a>>t)
w=threadDelay$5^10
0#_=t
i#a=a>>(i-1)#a
main=print!do r<-newChan;9#(forkIO$writeChan r!w);getChanContents r>>=print.sum.take 9

! measures the time taken by action a (second argument) and applies b (first argument) to the result.

w is the sleep function.

main is measured itself, and result printed (print!...).

# is replicateM, repeating the given action N times (and returning t because golfing).

Inside the measured part, 9 threads (replicate 9 $ forkIO ...) sleep for 5^10 milliseconds (9.765625 seconds) and post the result (writeChan) to a pipe created by the main thread (newChan), which sums the 9 results up and prints the total (getChanContents >>= print . sum . take 9).

Output:

87.938546708s
9.772032144s