问:
Calculate the Numpad Taxicab
Credit goes where credit is due

Given two digits, x, and y, calculate the shortest number of horizontal or vertical jumps to get from x to y on a standard numpad, e.g.

```<code>789
456
123
00
</code>```

You can safely assume that all inputs will be 0-9, and you do not have to handle invalid inputs. The input may be the same number twice, which has a distance of 0.

IO can be in any reasonable format, and standard loopholes are forbidden. Shortest answer in bytes wins!

Sample IO:

```<code>1, 4: 1
1, 8: 3
3, 7: 4
8, 2: 2
6, 1: 3
0, 9: 4
4, 4: 0
0, 4: 2
</code>```

答:
Java <s>149</s> 160 chars

The obligatory: Because... you know... Java!
Having fun with Java in under <s>150</s> 161 chars:

```<code>int d(int f,int t){if(f==t)return 0;if(Math.min(f,t)==0){int m=Math.max(f,t);return Math.min(d(1,m),d(2,m))+1;}return Math.abs(--t%3- --f%3)+Math.abs(t/3-f/3);}
</code>```

Ungolfed into a class:

```<code>public class Q80357 {

    static int distance(int from, int to) {
        if (from == to)
            return 0;
        if (Math.min(from, to) == 0) {
            int max = Math.max(from, to);
            return Math.min(distance(1, max), distance(2, max)) + 1;
        }
        return Math.abs(--to % 3 - --from % 3) + Math.abs(to / 3 - from / 3);
    }
}
</code>```

How it works

First it catches the standard case where we don't have to move anywhere.

Now we can assume that both integers differ, thus only the smaller one can be 0. If this is the case we calculate the distance from key 1 and 2 to the other key. We will use the one with the shorter distance and add one step to get from 1 or 2 to 0.

If we don't want to go to/from zero we only have to move in the 3x3 grid. We can determine the column and row of the key by using mod or div respectively. Then we calculate the column and row distance and add them. This is the distance we need to get from one key to another.

I hope the explanation could be understood, feel free to golf :)

Updates

Had to change it into an actual function as it uses recursion which isn't possible with lambdas :,(

Title: Calculate the Numpad Taxicab

Body:
Java <s>149</s> 160 chars

The obligatory: Because... you know... Java!
Having fun with Java in under <s>150</s> 161 chars:

int d(int f,int t){if(f==t)return 0;if(Math.min(f,t)==0){int m=Math.max(f,t);return Math.min(d(1,m),d(2,m))+1;}return Math.abs(--t%3- --f%3)+Math.abs(t/3-f/3);}

Ungolfed into a class:

public class Q80357 {

    static int distance(int from, int to) {
        if (from == to)
            return 0;
        if (Math.min(from, to) == 0) {
            int max = Math.max(from, to);
            return Math.min(distance(1, max), distance(2, max)) + 1;
        }
        return Math.abs(--to % 3 - --from % 3) + Math.abs(to / 3 - from / 3);
    }
}

How it works

First it catches the standard case where we don't have to move anywhere.

Now we can assume that both integers differ, thus only the smaller one can be 0. If this is the case we calculate the distance from key 1 and 2 to the other key. We will use the one with the shorter distance and add one step to get from 1 or 2 to 0.

If we don't want to go to/from zero we only have to move in the 3x3 grid. We can determine the column and row of the key by using mod or div respectively. Then we calculate the column and row distance and add them. This is the distance we need to get from one key to another.

I hope the explanation could be understood, feel free to golf :)

Updates

Had to change it into an actual function as it uses recursion which isn't possible with lambdas :,(


问:
Greatest Number in a Range When The Sum of Squares of its Prime Factors are Subtracted
The formula

Take for instance the number 300

The prime factors of 300 are [2, 3, 5] (unique numbers that are
factors of 300 and prime)

Squaring each of those numbers will give
you [4, 9, 25]

Summing that list will give you 4 + 9 + 25 = 38

Finally subtract that sum (38) from your original number 300-38 = 262 (this is the result)

Input

Your input will be a positive integer greater than 2. You must check all numbers from 2 to the input value (inclusive) and find the number that produces the greatest result with the formula above.

Output

Your output will be two numbers separated by a space, comma, newline or whatever you language allows (the separation is necessary to distinguish the two numbers). These can be output to a file, stdout, or whatever your language uses. Your goal is to find the number in the range that produces the maximum output when run through the formula above. The first number displayed should be the starting number (like 300) and the second number should be the output that the formula produced (like 262)

Test Cases

```<code>Input: 3       Output: 2, -2
Input: 10      Output: 8, 4
Input: 50      Output: 48, 35
Input: 1000    Output: 1000, 971
Input: 9999    Output: 9984, 9802
</code>```

Worked Through Example

Consider the input of 10, we must run the formula for all numbers from 2-10 (inclusive)

```<code>Num PrimeFacs PrimeFacs^2 SumPrimeFacs^2 Result
2   [2]       [4]         4              -2
3   [3]       [9]         9              -6
4   [2]       [4]         4               0
5   [5]       [25]        25             -20
6   [2, 3]    [4, 9]      13             -7
7   [7]       [49]        49             -42
8   [2]       [4]         4               4
9   [3]       [9]         9               0
10  [2, 5]    [4, 25]     29             -19
</code>```

As you can see the greatest result is 4, which was a result of inputting the value 8 into the formula. That means the output for an input of 10 should be 8, 4

Scoring & Rules

The default rules for inputs and outputs apply: Default for Code Golf: Input/Output methods

The standard loopholes are forbidden: Loopholes that are forbidden by default

Submissions can be functions or full programs

Shortest code in bytes wins

答:
Jelly, 13 bytes

```<code>ÆfQ²S_@,µ€ḊṀṚ
</code>```

Try it online! or verify all test cases.

How it works

```<code>ÆfQ²S_@,µ€ḊṀṚ  Main link. Argument: n

        µ      Combine the chain to the left into a link.
         €     Apply it to each k in [1, ..., n].
Æf               Yield k's prime factors as a list.
  Q              Unique; deduplicate the prime factors.
   ²             Square each unique prime factor.
    S            Compute their sum.
     _@          Subtract the result from k.
       ,         Pair with k, yielding [result(k), k].
          Ḋ    Dequeue; discard the first pair which corresponds to k = 1.
           Ṁ   Get the maximum (lexicographical order).
            Ṛ  Reverse the pair.
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Jelly, 13 bytes

ÆfQ²S_@,µ€ḊṀṚ

Try it online! or verify all test cases.

How it works

ÆfQ²S_@,µ€ḊṀṚ  Main link. Argument: n

        µ      Combine the chain to the left into a link.
         €     Apply it to each k in [1, ..., n].
Æf               Yield k's prime factors as a list.
  Q              Unique; deduplicate the prime factors.
   ²             Square each unique prime factor.
    S            Compute their sum.
     _@          Subtract the result from k.
       ,         Pair with k, yielding [result(k), k].
          Ḋ    Dequeue; discard the first pair which corresponds to k = 1.
           Ṁ   Get the maximum (lexicographical order).
            Ṛ  Reverse the pair.


答:
PowerShell v2+, <s>124</s> <s>120</s> 117 bytes

```<code>2..$args[0]|%{$y=$z=$_;2..$_|%{$y-=$_*$_*!($z%$_)*('1'*$_-match'^(?!(..+)\1+$)..')};if($y-gt$o){$o=$y;$p=$_}}
"$p $o"
</code>```

The first line calculates the values, the second is just output.

We start with creating a range from 2 up to our command-line argument $args[0] and loop that |%{...}. Each loop we set helper variables equal to our current value with $y=$z=$_. We then loop through every number from 2 up to our current number. Each inner loop we check whether that number is a divisor !($z%$_) and whether it's prime ('1'*$_-match'^(?!(..+)\1+$)..'), and if it's both we subtract the square from $y (the checks are done using Boolean multiplication).

Once we've gone through all prime divisors and subtracted the squares, if the number remaining is the largest we've seen so far $y-gt$o, we set our output variables $o=$y;$p=$_. After we've looped through the whole range, we simply output with a space between.

Title: Greatest Number in a Range When The Sum of Squares of its Prime Factors are Subtracted

Body:
The formula

Take for instance the number 300

The prime factors of 300 are [2, 3, 5] (unique numbers that are
factors of 300 and prime)

Squaring each of those numbers will give
you [4, 9, 25]

Summing that list will give you 4 + 9 + 25 = 38

Finally subtract that sum (38) from your original number 300-38 = 262 (this is the result)

Input

Your input will be a positive integer greater than 2. You must check all numbers from 2 to the input value (inclusive) and find the number that produces the greatest result with the formula above.

Output

Your output will be two numbers separated by a space, comma, newline or whatever you language allows (the separation is necessary to distinguish the two numbers). These can be output to a file, stdout, or whatever your language uses. Your goal is to find the number in the range that produces the maximum output when run through the formula above. The first number displayed should be the starting number (like 300) and the second number should be the output that the formula produced (like 262)

Test Cases

```<code>Input: 3       Output: 2, -2
Input: 10      Output: 8, 4
Input: 50      Output: 48, 35
Input: 1000    Output: 1000, 971
Input: 9999    Output: 9984, 9802
</code>```

Worked Through Example

Consider the input of 10, we must run the formula for all numbers from 2-10 (inclusive)

```<code>Num PrimeFacs PrimeFacs^2 SumPrimeFacs^2 Result
2   [2]       [4]         4              -2
3   [3]       [9]         9              -6
4   [2]       [4]         4               0
5   [5]       [25]        25             -20
6   [2, 3]    [4, 9]      13             -7
7   [7]       [49]        49             -42
8   [2]       [4]         4               4
9   [3]       [9]         9               0
10  [2, 5]    [4, 25]     29             -19
</code>```

As you can see the greatest result is 4, which was a result of inputting the value 8 into the formula. That means the output for an input of 10 should be 8, 4

Scoring & Rules

The default rules for inputs and outputs apply: Default for Code Golf: Input/Output methods

The standard loopholes are forbidden: Loopholes that are forbidden by default

Submissions can be functions or full programs

Shortest code in bytes wins

Body:
PowerShell v2+, <s>124</s> <s>120</s> 117 bytes

2..$args[0]|%{$y=$z=$_;2..$_|%{$y-=$_*$_*!($z%$_)*('1'*$_-match'^(?!(..+)\1+$)..')};if($y-gt$o){$o=$y;$p=$_}}
"$p $o"

The first line calculates the values, the second is just output.

We start with creating a range from 2 up to our command-line argument $args[0] and loop that |%{...}. Each loop we set helper variables equal to our current value with $y=$z=$_. We then loop through every number from 2 up to our current number. Each inner loop we check whether that number is a divisor !($z%$_) and whether it's prime ('1'*$_-match'^(?!(..+)\1+$)..'), and if it's both we subtract the square from $y (the checks are done using Boolean multiplication).

Once we've gone through all prime divisors and subtracted the squares, if the number remaining is the largest we've seen so far $y-gt$o, we set our output variables $o=$y;$p=$_. After we've looped through the whole range, we simply output with a space between.


答:
Pyke, 17 bytes

```<code>FODP}mXs-)DSei@Oi
</code>```

Try it here!

Body:
Pyke, 17 bytes

FODP}mXs-)DSei@Oi

Try it here!


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

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

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

If that number is 1, print out 1 forever.

Challenge

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

take input from STDIN or an acceptable alternative

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

must output to STDOUT or an acceptable alternative

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

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

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

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

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

Catalog

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

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

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

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

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

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

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

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

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
Scratch, 12 bytes

I love how Scratch can be so self-explanatory in the right contexts.

Title: Implement a Truth-Machine


问:
The Nine Pattern

Introduction

I stumbled across this (useless) pattern the other day while I was watching TV.
I named it "the 9 pattern" because the first number to use it was 9.
The gist of it is, you enter a number (let's say x), and then you get back:

x

x + (x / 3) [let's call this y]

two-thirds of y [let's call this z]

z + 1

So, if I put inside this pattern the number 9 as x, this is what would come out:

9 (9)

12 (9 + 9 / 3) [9 over 3 is 3, and 9 + 3 is 12]

8 (12 times two-thirds) [a third of 12 is 4, and 4 * 2 is 8]

9 (8 + 1 is 9)

Challenge

Write me a function (in any programming language) that takes in a number, and outputs an integer array using the pattern.

Somewhat like this psuedo-code:

```<code>function ninePattern(int myInt) returns IntegerArray {
    int iterationA = myInt + (myInt / 3);
    int iterationB = iterationA * (2 / 3);
    int iterationC = iterationB + 1;
    IntegerArray x = [myInt, iterationA, iterationB, iterationC];
    return x;
}
</code>```

Clarifications

Discussions have been arousing in comments regarding the specifications of the question. This section is meant to clarify some of those.

"better to count in bytes than characters"

I picked characters because (for me, at least) it would be easier to judge. Of course, I can't change that now. (lots of answers are already posted)

"rounding"

Rounding follows this rhyme:

If it's 5 or more, raise the score

  If it's 4 or less, let it rest

Simply, put, if it is something like 4.7 or 3.85, round them to 5 and 4 respectively.

Examples

```<code>Input => Result
9 => [9, 12, 8, 9]
8 => [8, 11, 7, 8]
6 => [6, 8, 5, 6]
23 => [23, 31, 21, 22]
159 => [159, 212, 141, 142]
</code>```

If, however, the numbers are something like 2.3 or 10.435446, round them to 2 and 10 respectively.

"language support"

You are free to not use functions and/or arrays IF AND ONLY IF the language of your choice does not support them.  If it does (even if it will increase your characters count), you must use them.

答:
Pyth, 20 bytes

```<code>m.RdZ[Jc*4Q3Kc*2J3hK
</code>```

Explanation:

```<code>            (Implicit print)
m           For each d in array, d =
.RdZ        Round d to zero decimal places
[           The array of
  J         The result of setting J to
    c       The float division of
      *4Q   Input * 4
      3     and 3
            ,
  K         The result of setting K to
    c       The float division of
      *2J   J * 2
      3     and 3
            , and
  hK        K + 1.
            (Implicit end array)
</code>```

Test here

Title: The Nine Pattern

Body:
Pyth, 20 bytes

m.RdZ[Jc*4Q3Kc*2J3hK

Explanation:

            (Implicit print)
m           For each d in array, d =
.RdZ        Round d to zero decimal places
[           The array of
  J         The result of setting J to
    c       The float division of
      *4Q   Input * 4
      3     and 3
            ,
  K         The result of setting K to
    c       The float division of
      *2J   J * 2
      3     and 3
            , and
  hK        K + 1.
            (Implicit end array)

Test here


答:
JavaScript (ES6), <s>111</s> 105 bytes

```<code>f=n=>{r=n<2?[]:f(n-1);for(s=[],j=n,i=2;j>1;k%i?i++:j/s[i]=i);s.map(i=>j-=i*i,j=n);return j<r[1]?r:[n,j]}
</code>```

No idea why I didn't think to do this recursively before.

Body:
JavaScript (ES6), <s>111</s> 105 bytes

f=n=>{r=n<2?[]:f(n-1);for(s=[],j=n,i=2;j>1;k%i?i++:j/s[i]=i);s.map(i=>j-=i*i,j=n);return j<r[1]?r:[n,j]}

No idea why I didn't think to do this recursively before.


答:
Scratch, 33 bytes

(source: cubeupload.com)

Asks for input, sets a to input rounded, sets b and c to their respective changes, then says all four numbers, seperated by commas.

Title: The Nine Pattern

Body:
Introduction

I stumbled across this (useless) pattern the other day while I was watching TV.
I named it "the 9 pattern" because the first number to use it was 9.
The gist of it is, you enter a number (let's say x), and then you get back:

x

x + (x / 3) [let's call this y]

two-thirds of y [let's call this z]

z + 1

So, if I put inside this pattern the number 9 as x, this is what would come out:

9 (9)

12 (9 + 9 / 3) [9 over 3 is 3, and 9 + 3 is 12]

8 (12 times two-thirds) [a third of 12 is 4, and 4 * 2 is 8]

9 (8 + 1 is 9)

Challenge

Write me a function (in any programming language) that takes in a number, and outputs an integer array using the pattern.

Somewhat like this psuedo-code:

```<code>function ninePattern(int myInt) returns IntegerArray {
    int iterationA = myInt + (myInt / 3);
    int iterationB = iterationA * (2 / 3);
    int iterationC = iterationB + 1;
    IntegerArray x = [myInt, iterationA, iterationB, iterationC];
    return x;
}
</code>```

Clarifications

Discussions have been arousing in comments regarding the specifications of the question. This section is meant to clarify some of those.

"better to count in bytes than characters"

I picked characters because (for me, at least) it would be easier to judge. Of course, I can't change that now. (lots of answers are already posted)

"rounding"

Rounding follows this rhyme:

If it's 5 or more, raise the score

  If it's 4 or less, let it rest

Simply, put, if it is something like 4.7 or 3.85, round them to 5 and 4 respectively.

Examples

```<code>Input => Result
9 => [9, 12, 8, 9]
8 => [8, 11, 7, 8]
6 => [6, 8, 5, 6]
23 => [23, 31, 21, 22]
159 => [159, 212, 141, 142]
</code>```

If, however, the numbers are something like 2.3 or 10.435446, round them to 2 and 10 respectively.

"language support"

You are free to not use functions and/or arrays IF AND ONLY IF the language of your choice does not support them.  If it does (even if it will increase your characters count), you must use them.

ContentLicense: CC BY-SA 4.0


答:
Bash + GNU utilities, 74

seq 2 $1|factor|sed -r 's/:?( \w+)\1*/-\1*\1/g'|bc|nl -v2|sort -nrk2|sed q
```

seq generates all integers 2 to n

factor gives the number followed by a colon, then a space separated list of all prime factors, including duplicates.  e.g. the result for 12 is 12: 2 2 3

sed removes the colon and duplicate factors, then generates the required arithmetic expression.  e.g. for 12: 12- 2* 2- 3* 3

bc evaluates this

nl prefixes n back in (starting at 2)

sort by the second column, numerically, in descending order

seq prints the first line and quits.

Ideone.

Body:
Bash + GNU utilities, 74

seq 2 $1|factor|sed -r 's/:?( \w+)\1*/-\1*\1/g'|bc|nl -v2|sort -nrk2|sed q

seq generates all integers 2 to n

factor gives the number followed by a colon, then a space separated list of all prime factors, including duplicates.  e.g. the result for 12 is 12: 2 2 3

sed removes the colon and duplicate factors, then generates the required arithmetic expression.  e.g. for 12: 12- 2* 2- 3* 3

bc evaluates this

nl prefixes n back in (starting at 2)

sort by the second column, numerically, in descending order

seq prints the first line and quits.

Ideone.


问:
Compress your code in an image
This is a quine variation.

Introduction

We all write short code, because some obscure reasons, but whatever we do, the'll take up at least 144 pixels/byte (with a 12px font). But what would happen, if we would encode our code in images? This is your task today.

Challenge

You task is to read in your own source code (non-proper quines are allowed, e.g. literally reading the source file), and create an image out of it, by setting the red, green and blue components of a pixel based on the ASCII value of the character.

Example:

We have the string "Hello world!"

```<code>Hello world!
</code>```

Let's convert this to ASCII values:

```<code>72 101 108 108 111 32 119 111 114 108 100 33
</code>```

Map the RGB values to it (If the source code's length is not divisible by 3, use 0s as the remaining characters):

```<code> __________________________________________________
| R | G | B || R | G | B || R | G | B || R | G | B |
----------------------------------------------------
|72 |101|108||108|111|32 ||119|111|114||108|100|33 |
----------------------------------------------------
</code>```

We then create the image with the smallest area out of it. We have 4 sets of RGB values, so the smallest image will be a 2*2 image, going from the top left pixel to the right:

And we get this awfully colored image (resized, so it's at least visible, also proves the fact how small it can get)

Rules/Additional information

There's no input

The output should be as a separate file, or in a separate window.

For multibyte characters, split the character in 2 bytes.

The source code must be at least 1 byte long

The image should be the one from the possible sizes, wich has the closest width/height ratio to 1

The pixel count on the image should exactly be ceil(byte count / 3), no extra pixels should be added

Scoring

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

答:
Java 511 chars

The length of the solution leads to a greater picture which is cool, because these pictures are really nice.

```<code>import java.awt.image.*;import java.io.*;import java.nio.file.*;import javax.imageio.*; public class Q{public static void main(String[]a)throws Throwable{int w=19,h=9;byte[]e=Files.readAllBytes(Paths.get("Q.java"));String t=new String(e);while(t.length()%3!=0)t+='\0';BufferedImage I=new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);int r,c=r=0;for(int i=0;i<t.length();i++){I.setRGB(c,r,255<<24|t.charAt(i)<< 16|t.charAt(++i)<< 8|t.charAt(++i));if(++c==w){c=0;r++;}}ImageIO.write(I,"png",new File("Q.png"));}}
</code>```

Note that there is an invisible trailing newline! It reads the source file, which has to be "Q.java" and creates a picture "Q.png" which looks like this:

or scaled 100x

Title: Compress your code in an image

Body:
Java 511 chars

The length of the solution leads to a greater picture which is cool, because these pictures are really nice.

import java.awt.image.*;import java.io.*;import java.nio.file.*;import javax.imageio.*; public class Q{public static void main(String[]a)throws Throwable{int w=19,h=9;byte[]e=Files.readAllBytes(Paths.get("Q.java"));String t=new String(e);while(t.length()%3!=0)t+='\0';BufferedImage I=new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);int r,c=r=0;for(int i=0;i<t.length();i++){I.setRGB(c,r,255<<24|t.charAt(i)<< 16|t.charAt(++i)<< 8|t.charAt(++i));if(++c==w){c=0;r++;}}ImageIO.write(I,"png",new File("Q.png"));}}

Note that there is an invisible trailing newline! It reads the source file, which has to be "Q.java" and creates a picture "Q.png" which looks like this:

or scaled 100x


问:
Flatten the Array!
In this challenge, your task is to create a program which takes in a nested array and returns a single-dimensional flattened array. For Example [10,20,[30,[40]],50] should output [10,20,30,40,50].

Input

The input will be a nested array (eg. [10,20,[[[10]]]]). It will contain only Integers (both negative and positive), Strings and Arrays. You can take the input as function argument, STDIN or whatever suits your language. You can assume that the input array won't have an empty array.

Output

The output will be a flatted single-dimensional array with the same elements of same type as in the nested array and in the SAME order.

Test Cases

```<code>[10,20,30] -> [10,20,30]
[[10]] -> [10]
[["Hi"],[[10]]] -> ["Hi",10]
[[[20],["Hi"],"Hi",20]] -> [20,"Hi","Hi",20]
[[["[]"],"[]"]] -> ["[]","[]"]
</code>```

Feel free to ask for any clarification by using comments. This is code-golf, so the shortest code in bytes wins!

Note: If your language contains a built-in for this, then you must NOT use it.

Edit

Please also include a link to a website where your code can be executed.

答:
Java 8 165 chars

```<code>import java.util.*;<T>T[]f(T[]a){List<T>l=new ArrayList<>();for(T e:a)if(e instanceof Object[])Collections.addAll(l,f((T[])e));else l.add(e);return(T[])l.toArray();}
</code>```

Ungolfed into a class:

```<code>public class Q80096 {

    public static <T> T[] flatten(T[] array) {
        List<T> flattenedList = new ArrayList<>();
        for (T element : array)
            if (element instanceof Object[])
                 Collections.addAll(flattenedList, flatten((T[]) element));
            else
                flattenedList.add(element);
        return (T[]) flattenedList.toArray();
    }
}
</code>```

This answer is based on Jeremy Harton's approach. I used it changed it in some places and created a more golf-like version.

Title: Flatten the Array!

Body:
Java 8 165 chars

import java.util.*;<T>T[]f(T[]a){List<T>l=new ArrayList<>();for(T e:a)if(e instanceof Object[])Collections.addAll(l,f((T[])e));else l.add(e);return(T[])l.toArray();}

Ungolfed into a class:

public class Q80096 {

    public static <T> T[] flatten(T[] array) {
        List<T> flattenedList = new ArrayList<>();
        for (T element : array)
            if (element instanceof Object[])
                 Collections.addAll(flattenedList, flatten((T[]) element));
            else
                flattenedList.add(element);
        return (T[]) flattenedList.toArray();
    }
}

This answer is based on Jeremy Harton's approach. I used it changed it in some places and created a more golf-like version.


问:
Largest Distinctly Sum-Free Partition
related and inspired by -- Finding sum-free partitions

A set A is defined here as being distinctly sum-free if

1) it consists of at least three elements, |A| ≥ 3, and

2) its distinct self-sum A + A = { x + y | x, y in A} (with x,y distinct, i.e., x≠y) has no elements in common with A.

(Obsolete - do not use this going forward. Left here only because some answers may have used it. It does not match with the above conditions. Alternatively, the equation x + y = z has no solution for x,y,z ∈ A (again with x,y,z distinct, i.e., x≠y, x≠z, y≠z).)

For a simple example, {1,3,5} is distinctly sum-free, but {1,3,4} is not. {1,3} and {3} are also not, since they're not at least three elements.

The challenge here is to find the largest distinctly sum-free subset of the given input.

Input

An unordered set A of integers in any convenient format.

The integers could be positive, negative, or zero, but can be assumed to fit in your language's native [int] datatype (or equivalent).

The set is guaranteed to have only distinct elements (no multisets here).

The set is not necessarily sorted.

Output

The largest subset of A (which could be A itself), that is distinctly sum-free. Output can be in any suitable format.

If no such subset exists, output an empty set or other falsey value.

If multiple subsets are tied for largest, output any or all of them.

The subset does not necessarily need be sorted, or in the same order as the input. For example, for input {1,3,5} output {5,1,3} is acceptable.

Additional Rules

Standard loopholes are forbidden.

This is code-golf, so all usual golfing rules apply, and the shortest code wins.

Examples

```<code>Input     -> Output (any or all)
{0}       -> {}
{1, 2, 3} -> {}
{1, 3, 5} -> {1, 3, 5}
{1, 2, 3, 4, 5} -> {1, 2, 5}  {1, 2, 4}  {1, 3, 5}  {2, 3, 4}  {2, 4, 5}  {3, 4, 5}
{-5, 4, 3, -2, 0} -> {-5, 4, 3}  {-5, 4, -2}  {4, 3, -2}
{-5, 4, 3, -2} -> {-5, 4, 3}  {-5, 4, -2}  {4, 3, -2}
{-17, 22, -5, 13, 200, -1, 1, 9} -> {-17, 22, -5, 13, 200, -1, 1}  {-17, 22, -5, 200, -1, 1, 9}  {-17, -5, 13, 200, -1, 1, 9}
</code>```

答:
Jelly, 17 bytes

```<code>8BḊ+œc2S€f
ŒPÇÐḟṪ
</code>```

Try it online! or verify all test cases.

Title: Largest Distinctly Sum-Free Partition

Body:
Jelly, 17 bytes

8BḊ+œc2S€f
ŒPÇÐḟṪ

Try it online! or verify all test cases.


问:
Find a function with cycles of every length
A function is said to have a cycle of length n if there exists an x in its domain such that fn(x) = x and fm(x) ≠ x for 0 < m < n, where the superscript n denotes n-fold application of f. Note that a cycle of length 1 is a fixed point f(x) = x.

Your task is to implement a bijective function from the integers to themselves, which has exactly one cycle of every positive length n. A bijective function is a one-to-one correspondence, i.e. every integer mapped to exactly once. Having exactly one cycle of length n means that there are exactly n distinct numbers x for which fn(x) = x and fm(x) ≠ x for 0 < m < n.

Here is an example of what such a function might look like around x = 0:

```<code>x     ... -7 -6 -5 -4 -3 -2 -1  0  1  2  3  4  5  6  7 ...
f(x)  ...  2  4  6 -3 -1  1 -4  0 -2  5  7 -7 -6  3 -5 ...
</code>```

This excerpt contains cycles of length 1 to 5:

```<code>n   cycle
1    0
2   -2  1
3   -4 -3 -1
4   -5  6  3  7
5   -7  2  5 -6  4
...
</code>```

Note that above I'm using "function" only in the mathematical sense. You may write either a function or a full program in your language of choice, as long as it takes a single (signed) integer as input and returns a single (signed) integer. As usual you may take input via STDIN, command-line argument, function argument etc. and output via STDOUT, function return value or function (out) argument etc.

Of course, many languages don't (easily) support arbitrary-precision integers. It's fine if your implementation only works on the range of your language's native integer type, as long as that covers at least the range [-127, 127] and that it would work for arbitrary integers if the language's integer type was replaced with arbitrary-precision integers.

Standard code-golf rules apply.

答:
MATL, 47 bytes

```<code>E|G0<-QXJ:tQ*2/0hStJ<f0))Q2MQ)&:J6M-)2/ttk>Eq*k
</code>```

Try it online!

General explanation

Function 2 below is the same as used in @Sp3000's answer to the related challenge. Thanks to @Agawa001 for noticing.

The function is the composition of three:

Bijection from Z (the integers) to N (the naturals).

Bijection from N to N with the desired characteristic (one cycle of each length).

Inverse of function 1.

Functions 1 and 3 are used because it's easier (I think) to achieve the desired behaviour in N than in Z.

Function 2 is as follows: upper line is domain, lower line is codomain. Commas are used for clarity:

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

The first block (from upper 1 to lower 1) is a cycle of length 1. The second (from 2 3 to 3 2) is a cycle of length 2, etc. In each block, the lower part (image of the function) is the upper part circularly shifted one step to the right.

Function 1 is as follows:

```<code> -5  -4  -3  -2  -1   0  +1  +2  +3  +4  ...
+10  +8  +6  +4  +2  +1  +3  +5  +7  +9  ...
</code>```

Function 3 is the same as 1 with the two lines swapped.

Examples

The image of 3 is -5. First 3 is mapped to 7 by function 1; then 7 is mapped to 10 by function 2; then 10 is mapped to -5` by function 3.

The length-1 cycle is 0. The length-2 cycle is -1 1. The length-3 cycle is -3 2 -2, etc.

Code explained

Functions 1 and 3 are straightforward.

Function 2 works by finding the lower endpoint of the corresponding input block. For example, if the input to this function is 9 it finds 7 (see blocks above). It then picks the upper endpoint, which is 10 in the example. The circular shift of the block is achieved thanks to MATL's 1-based, modular indexing.

```<code>         % FUNCTION 1
         % Implicit input
E|       % Multiply by two. Absolute value
G0<      % 1 if input is negative, 0 otherwise
-        % Subtract
Q        % Add 1
XJ       % Copy to clipboard J. Used as input to the next function

         % FUNCTION 2
:        % Range [1 2 ... J], where J denotes the input to this function
tQ*      % Duplicate, increment by 1, multiply
2/       % Divide by 2
0hS      % Prepend a 0. This is needed in case J is 0
tJ<f     % Duplicate. Find indices that are less than the input J
0)       % Pick the last index.
)        % Apply as index to obtain input value that ends previous block
Q        % Add 1: start of current block
2M       % Push the two arguments to second-to-last function call
Q)       % Add 1 and use as index: end of current block
&:       % Inclusive binary range: generate input block
J        % Push J (input to function 2)
6M-      % Subtract start of block
)        % Apply as index (1-based, modular). This realizes the shifting

         % FUNCTION 3
2/       % Divide by 2
ttk>     % Duplicate. 1 if decimal part is not 0; 0 otherwise
Eq       % Multiply by 2, add 1
*        % Multiply
k        % Round down
         % Implicit display
</code>```

Body:
MATL, 47 bytes

E|G0<-QXJ:tQ*2/0hStJ<f0))Q2MQ)&:J6M-)2/ttk>Eq*k

Try it online!

General explanation

Function 2 below is the same as used in @Sp3000's answer to the related challenge. Thanks to @Agawa001 for noticing.

The function is the composition of three:

Bijection from Z (the integers) to N (the naturals).

Bijection from N to N with the desired characteristic (one cycle of each length).

Inverse of function 1.

Functions 1 and 3 are used because it's easier (I think) to achieve the desired behaviour in N than in Z.

Function 2 is as follows: upper line is domain, lower line is codomain. Commas are used for clarity:

1,  2  3,  4  5  6,  7  8  9  10  ...
1,  3  2,  6  4  5, 10  7  8   9  ...

The first block (from upper 1 to lower 1) is a cycle of length 1. The second (from 2 3 to 3 2) is a cycle of length 2, etc. In each block, the lower part (image of the function) is the upper part circularly shifted one step to the right.

Function 1 is as follows:

 -5  -4  -3  -2  -1   0  +1  +2  +3  +4  ...
+10  +8  +6  +4  +2  +1  +3  +5  +7  +9  ...

Function 3 is the same as 1 with the two lines swapped.

Examples

The image of 3 is -5. First 3 is mapped to 7 by function 1; then 7 is mapped to 10 by function 2; then 10 is mapped to -5` by function 3.

The length-1 cycle is 0. The length-2 cycle is -1 1. The length-3 cycle is -3 2 -2, etc.

Code explained

Functions 1 and 3 are straightforward.

Function 2 works by finding the lower endpoint of the corresponding input block. For example, if the input to this function is 9 it finds 7 (see blocks above). It then picks the upper endpoint, which is 10 in the example. The circular shift of the block is achieved thanks to MATL's 1-based, modular indexing.

         % FUNCTION 1
         % Implicit input
E|       % Multiply by two. Absolute value
G0<      % 1 if input is negative, 0 otherwise
-        % Subtract
Q        % Add 1
XJ       % Copy to clipboard J. Used as input to the next function

         % FUNCTION 2
:        % Range [1 2 ... J], where J denotes the input to this function
tQ*      % Duplicate, increment by 1, multiply
2/       % Divide by 2
0hS      % Prepend a 0. This is needed in case J is 0
tJ<f     % Duplicate. Find indices that are less than the input J
0)       % Pick the last index.
)        % Apply as index to obtain input value that ends previous block
Q        % Add 1: start of current block
2M       % Push the two arguments to second-to-last function call
Q)       % Add 1 and use as index: end of current block
&:       % Inclusive binary range: generate input block
J        % Push J (input to function 2)
6M-      % Subtract start of block
)        % Apply as index (1-based, modular). This realizes the shifting

         % FUNCTION 3
2/       % Divide by 2
ttk>     % Duplicate. 1 if decimal part is not 0; 0 otherwise
Eq       % Multiply by 2, add 1
*        % Multiply
k        % Round down
         % Implicit display


问:
The game of Sevens! Who said what?
The game of Sevens is played as follows: n players sit in a circle, and start counting up from 1, passing to the left (or from player A to player B).

When a number p that has a 7 in it OR is divisible by 7 is reached, then the player who spoke the number p-1, after the next player says p, must say p+1 and the order of people speaking reverses. For example, if player B speaks 6, player C says 7, B says 8, and player A says 9.

Note: For those who want to play in real life, if a person forgets a number (or in the version where sevens are not said, accidentally says a seven), they are eliminated from the circle, but we will omit this detail from this challenge.

The challenge itself is to print which numbers each player should say in a perfect game of Sevens up to an input m for an input n players.

As an example, where five people, A, B, C, D, and E, are to play till they reach 30. They play in this manner

```<code>A: 1 6 8 13    15 19       23    30
B: 2 7*  12    16 18       24
C: 3     11    17*         25
D: 4     10          21*   26 28*
E: 5      9 14*      20 22 27*29
</code>```

where sevens are marked with *. Note that at 27 and 28, we're reversing twice, and play continues "as normal" from D to E.

Please note that the output does not have to be in the above format. I simply printed it that way for some clarity.

Rules

The input is two integers in any order, m representing the last number to say, n representing the number of players.

The output can be several arrays or several strings, one for each player. If you use strings, you do not have to use separators (though, if you could add some in your code tests, we would appreciate the readability). If you can actually print them in a circle somehow, that is acceptable as well, and it would be pretty cool too.

The output does not have to designate which players are which (it's fairly obvious that the first player is the one who says 1), though if the output isn't sorted for whatever reason, you should make clear which player is speaking which set of numbers. Omitting players who do not say anything is also allowed if you make it clear which players are speaking. I will add some more examples of possible outputs below.

This is code golf, so the smallest number of bytes wins.

As always, if the problem is unclear, please let me know. Good luck and good golfing!

Examples

```<code>>>> sevens_string(30, 5, " ")
'1 6 8 13 15 19 23 30'
'2 7 12 16 18 24'
'3 11 17 25'
'4 10 21 26 28'
'5 9 14 20 22 27 29'
>>> sevens_string(42, 5)
'16813151923303539'
'27121618243140'
'31117253241'
'410212628333742'
'591420222729343638'
>>> sevens_array(20, 3)
[1, 4, 7, 10, 13, 15, 19]
[2, 5, 9, 12, 16, 18]
[3, 6, 8, 11, 14, 17, 20]
>>> sevens_array(18, 10)
[1, 13, 15]
[2, 12, 16, 18]
[3, 11, 17]
[4, 10]
[5, 9]
[6, 8]
[7]
[]
[]
[14]
</code>```

答:
Ruby, 81

```<code>->n,m{g=[""]*n
k=j=0
i=1
m.times{g[j%n]+=w="#{k+=1}"
j+=i=k%7<1||w[/7/]?-i :i}
g}
</code>```

Pretty straightforward implementation.  Returns an ugly glommed string (you can add a space to make it "#{k+=1} " for... well, a spaced string).  I wonder if there's a more mathematical algorithm out there.

Title: The game of Sevens! Who said what?

Body:
Ruby, 81

->n,m{g=[""]*n
k=j=0
i=1
m.times{g[j%n]+=w="#{k+=1}"
j+=i=k%7<1||w[/7/]?-i :i}
g}

Pretty straightforward implementation.  Returns an ugly glommed string (you can add a space to make it "#{k+=1} " for... well, a spaced string).  I wonder if there's a more mathematical algorithm out there.


答:
C#, 194 bytes

My first Code Golf :). I used my favorite language despite its verbosity. I started this as a C# function port of @Frozn's Java but found several ways to shrink the code further with optimizations.

```<code>string R(int a){int u,f,g,N=g=1<<31;for(int n=1;++n<=a;){u=n;int[]P=new int[a+1];for(f=1;++f<=u;){if(u%f<1){u/=f;P[f]=f--;}}f=0;foreach(var p in P){f+=p*p;}if(n-f>g){g=(N=n)-f;}}return N+","+g;}
</code>```

This uses an array to store the prime factors. Because it is indexed by the factor it will replace repeated factors with copies of the factor. This allows the function to have no imports. This does not even require System.

Body:
C#, 194 bytes

My first Code Golf :). I used my favorite language despite its verbosity. I started this as a C# function port of @Frozn's Java but found several ways to shrink the code further with optimizations.

string R(int a){int u,f,g,N=g=1<<31;for(int n=1;++n<=a;){u=n;int[]P=new int[a+1];for(f=1;++f<=u;){if(u%f<1){u/=f;P[f]=f--;}}f=0;foreach(var p in P){f+=p*p;}if(n-f>g){g=(N=n)-f;}}return N+","+g;}

This uses an array to store the prime factors. Because it is indexed by the factor it will replace repeated factors with copies of the factor. This allows the function to have no imports. This does not even require System.


答:
Julia, 56 bytes

!n=maximum(k->(k-sumabs2(k|>factor|>keys),k),2:n)[[2,1]]
```

Try it online!

How it works

Given an input n, for each integer k such that 2 ≤ k ≤ n, we generate the tuple (f(k), k), where f(k) is the difference between k and the sum of the squares of its prime factors.

f(k) itself is calculated with k-sumabs2(k|>factor|>keys), which factors k into a Dict of prime keys and exponent values, extracts all the keys (prime factors), takes the sum of their squares and subtracts the resulting integer from k.

Finally, we take the lexicographical maximum of the generated tuples and reverse it by accesing it at indices 2 and 1.

Body:
Julia, 56 bytes

!n=maximum(k->(k-sumabs2(k|>factor|>keys),k),2:n)[[2,1]]

Try it online!

How it works

Given an input n, for each integer k such that 2 ≤ k ≤ n, we generate the tuple (f(k), k), where f(k) is the difference between k and the sum of the squares of its prime factors.

f(k) itself is calculated with k-sumabs2(k|>factor|>keys), which factors k into a Dict of prime keys and exponent values, extracts all the keys (prime factors), takes the sum of their squares and subtracts the resulting integer from k.

Finally, we take the lexicographical maximum of the generated tuples and reverse it by accesing it at indices 2 and 1.


问:
AppleSauce Fader
Back in the day, all the 1337 kids used text faders in chatrooms. I don't know about you guys, but I want to feel cool like they did. The only problem is that their old scripts and applications were heavily coupled to the software they were made for, so I can't just make use of this amazing functionality wherever I want. I also want the solution to be easily portable so you're going to need to make the code as small as possible so that it will fit on my floppy disk (I'd rather only carry one floppy but if your source code is too big I can carry more than one :P).

Input

A list of colors (rgb, hex, names, etc)

Text to format

Your program should expect the list of colors to contain at least 2 colors.

Text to format can be any length greater than zero and characters will be limited to printable ascii. (Hint: Longer text inputs may require you to reuse intermediate colors for consecutive characters)

Output

The output text should not differ from the input text in any way other than font  and/or markup/styling (Note: if your output contains html markup then you'll need to html encode the input). You may output text with markup/styling (html style tags, console colors, etc.) or a picture of the faded text. All color hexes should be present in the output unless the input does not contain enough characters to meet this requirement. If this is the case, then consult the priority rules to determine which color hexes should be present in your output. The order or these colors in your output should still be input order.

Color Priority Rules

In the event that the input is one character, the first color will be used

In the event that there are only two characters, the first and last color will be used

In the event that there are more than three colors and more colors than characters, the first and last colors should be prioritized, then the rest of the colors in their inputted order.

In the event that there are more characters than colors, the characters should fade from one color to the next using intermediate colors

Examples (Priority rules 1-3 respectively):

# Colors | Color0 | ... | Colorn | Text

3 ff0000 0000ff ffff00 M ->

3 ff0000 0000ff ffff00 hi ->

4 ff0000 0000ff ffff00 0fff00 sup ->

To be clear, the text color should fade from one color hex to the next. The fade does not have to be perfectly uniform but it shouldn't be an abrupt color change unless there aren't enough characters to fade nicely. Generally this fade is achieved by choosing intermediate colors for each of the characters by incrementing/decrementing the rgb values by some interval determined by the number of characters you have to work with and the difference between the colors. For example if we needed a single color between  (#ff0000) and  (#000000), we might choose  as it sits right in the middle.  Optimal output will look rather pretty.

Example (Priority rule 4):

3 ff0000 ff7f00 f0ff00 To be or not to be, that is the question... ->

-OR-

```<code><span style="color:#ff0000;">T</span><span style="color:#ff0600;">o</span><span style="color:#ff0c00;"> </span><span style="color:#ff1200;">b</span><span style="color:#ff1800;">e</span><span style="color:#ff1e00;"> </span><span style="color:#ff2400;">o</span><span style="color:#ff2a00;">r</span><span style="color:#ff3000;"> </span><span style="color:#ff3600;">n</span><span style="color:#ff3c00;">o</span><span style="color:#ff4300;">t</span><span style="color:#ff4900;"> </span><span style="color:#ff4f00;">t</span><span style="color:#ff5500;">o</span><span style="color:#ff5b00;"> </span><span style="color:#ff6100;">b</span><span style="color:#ff6700;">e</span><span style="color:#ff6d00;">,</span><span style="color:#ff7300;"> </span><span style="color:#ff7900;">t</span><span style="color:#ff7f00;">h</span><span style="color:#fe8500;">a</span><span style="color:#fe8b00;">t</span><span style="color:#fd9100;"> </span><span style="color:#fc9700;">i</span><span style="color:#fb9d00;">s</span><span style="color:#fba400;"> </span><span style="color:#faaa00;">t</span><span style="color:#f9b000;">h</span><span style="color:#f9b600;">e</span><span style="color:#f8bc00;"> </span><span style="color:#f7c200;">q</span><span style="color:#f6c800;">u</span><span style="color:#f6ce00;">e</span><span style="color:#f5d400;">s</span><span style="color:#f4da00;">t</span><span style="color:#f4e100;">i</span><span style="color:#f3e700;">o</span><span style="color:#f2ed00;">n</span><span style="color:#f1f300;">.</span><span style="color:#f1f900;">.</span><span style="color:#f0ff00;">.</span>
</code>```

In your answer please specify how your output should be displayed (as html, in a console, as an image, etc.).

* All black backgrounds are only for color emphasis and are not required

Scoring

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

If you manage to add fade to individual characters then I'll forever think you're cool (but no bonus to score as this will not be fair for some langs)

答:
Java, <s>702</s> 662 characters

Two functions golfed:

import java.awt.*;String f(Color C,char c){return""+c+"";}String c(String t,String[]h){String r="";int l=h.length,e=t.length(),i=0,s=0,g=1,c=-1,p,q,u;double d,m=0,v;char[]T=t.toCharArray();Color C[]=new Color[l],H[],a,b;for(;i<l;)C[i]=Color.decode(h[i++]);if(l>e){H=java.util.Arrays.copyOfRange(C,0,e);H[e-1]=C[l-1];H[0]=C[0];C=H;l=e;}d=--e/(l-1.);for(;++c<e;){a=C[s];b=C[g];p=b.getRed()-a.getRed();q=b.getGreen()-a.getGreen();u=b.getBlue()-a.getBlue();v=m/d;r+=f(new Color(a.getRGB()+((int)(v*p)<<16|(int)(v*q)<<8|(int)(v*u))),T[c]);if(++m>d){m-=d;s=g++;}}return r+f(C[l-1],T[e]);}
```

<p>As nobody can read this: here are both functions in there ungolfed version in a class:</p>

<pre class="lang-java prettyprint-override"><code>import java.awt.*;

public class Q80554 {

    static String format(Color color, char character) {
        return "<span style=\"color:#" + Integer.toHexString(color.getRGB()).substring(2) + ";\">" + character + "</span>";
    }

    static String colorizeB(String text, String[] hexColors) {
        String result = "";
        int colorsLength = hexColors.length, textLength = text.length(), i, currentStartColorPos = 0, currentGoalColorPos = 1, currentCharPos = -1, diffColorRed, diffColorGreen, diffColorBlue;
        double difference, goneDifference = 0, relativeChange;
        char[] textArray = text.toCharArray();
        Color colors[] = new Color[colorsLength], changer[], currentStartColor, currentGoalColor;

        for (i = 0; i < colorsLength;)
            colors[i] = Color.decode(hexColors[i++]);

        if (colorsLength > textLength) {
            changer = Arrays.copyOfRange(colors, 0, textLength);
            changer[textLength - 1] = colors[colorsLength - 1];
            changer[0] = colors[0];

            colors = changer;
            colorsLength = textLength;
        }

        // fade
        difference = --textLength / (colorsLength - 1.); // space between colors

        for (; ++currentCharPos < textLength;) {
            currentStartColor = colors[currentStartColorPos];
            currentGoalColor = colors[currentGoalColorPos];

            diffColorRed = currentGoalColor.getRed() - currentStartColor.getRed();
            diffColorGreen = currentGoalColor.getGreen() - currentStartColor.getGreen();
            diffColorBlue = currentGoalColor.getBlue() - currentStartColor.getBlue();

            relativeChange = goneDifference / difference;

            result += format(new Color(currentStartColor.getRGB() + ((int) (relativeChange * diffColorRed) << 16 | (int) (relativeChange * diffColorGreen) << 8 | (int) (relativeChange * diffColorBlue))), textArray[currentCharPos]);

            if (++goneDifference > difference) {
                goneDifference -= difference;
                currentStartColorPos = currentGoalColorPos++;
            }
        }

        // last character always has last color
        return result + format(colors[colorsLength - 1], textArray[textLength]);
    }
}
</code>```

Here you have an upper bound for your own code. Usage is by calling colorize (or c in the golfed version) and pass the text and an array of hex color codes. The function will return a String with HTML-tags like the OP did, thus you need some way to render the HTML.

The algorithm is easier as the question looks like. The first character always gets the first color, the last one always the last. <s>If we have more colors than chars in the text we just iterate over the text and colors and apply these.</s> The fun part is the one with the fades: I started of by finding out in what distance the colors are on the text. I basically calculate the red, green and blue difference between two given colors and then add a part of this difference to the first color, depending on where the char is between the colors. If it leaves the interval of two colors we start from new with the next two colors. This is repeated for all but the last character, which we know is always the last color. This gives a very beautiful fading.

That question was very much fun! Thanks!

Updates

Now I don't handle all the cases specially. Instead I trim the colors if there are two much and apply the fade function to every string. If there were more colors than text then the colors will be trimmed and the fading function will work exactly as a simple mapping.

Title: AppleSauce Fader

Body:
Java, <s>702</s> 662 characters

Two functions golfed:

import java.awt.*;String f(Color C,char c){return"<span style=\"color:#"+Integer.toHexString(C.getRGB()).substring(2)+";\">"+c+"</span>";}String c(String t,String[]h){String r="";int l=h.length,e=t.length(),i=0,s=0,g=1,c=-1,p,q,u;double d,m=0,v;char[]T=t.toCharArray();Color C[]=new Color[l],H[],a,b;for(;i<l;)C[i]=Color.decode(h[i++]);if(l>e){H=java.util.Arrays.copyOfRange(C,0,e);H[e-1]=C[l-1];H[0]=C[0];C=H;l=e;}d=--e/(l-1.);for(;++c<e;){a=C[s];b=C[g];p=b.getRed()-a.getRed();q=b.getGreen()-a.getGreen();u=b.getBlue()-a.getBlue();v=m/d;r+=f(new Color(a.getRGB()+((int)(v*p)<<16|(int)(v*q)<<8|(int)(v*u))),T[c]);if(++m>d){m-=d;s=g++;}}return r+f(C[l-1],T[e]);}

As nobody can read this: here are both functions in there ungolfed version in a class:

import java.awt.*;

public class Q80554 {

    static String format(Color color, char character) {
        return "<span style=\"color:#" + Integer.toHexString(color.getRGB()).substring(2) + ";\">" + character + "</span>";
    }

    static String colorizeB(String text, String[] hexColors) {
        String result = "";
        int colorsLength = hexColors.length, textLength = text.length(), i, currentStartColorPos = 0, currentGoalColorPos = 1, currentCharPos = -1, diffColorRed, diffColorGreen, diffColorBlue;
        double difference, goneDifference = 0, relativeChange;
        char[] textArray = text.toCharArray();
        Color colors[] = new Color[colorsLength], changer[], currentStartColor, currentGoalColor;

        for (i = 0; i < colorsLength;)
            colors[i] = Color.decode(hexColors[i++]);

        if (colorsLength > textLength) {
            changer = Arrays.copyOfRange(colors, 0, textLength);
            changer[textLength - 1] = colors[colorsLength - 1];
            changer[0] = colors[0];

            colors = changer;
            colorsLength = textLength;
        }

        // fade
        difference = --textLength / (colorsLength - 1.); // space between colors

        for (; ++currentCharPos < textLength;) {
            currentStartColor = colors[currentStartColorPos];
            currentGoalColor = colors[currentGoalColorPos];

            diffColorRed = currentGoalColor.getRed() - currentStartColor.getRed();
            diffColorGreen = currentGoalColor.getGreen() - currentStartColor.getGreen();
            diffColorBlue = currentGoalColor.getBlue() - currentStartColor.getBlue();

            relativeChange = goneDifference / difference;

            result += format(new Color(currentStartColor.getRGB() + ((int) (relativeChange * diffColorRed) << 16 | (int) (relativeChange * diffColorGreen) << 8 | (int) (relativeChange * diffColorBlue))), textArray[currentCharPos]);

            if (++goneDifference > difference) {
                goneDifference -= difference;
                currentStartColorPos = currentGoalColorPos++;
            }
        }

        // last character always has last color
        return result + format(colors[colorsLength - 1], textArray[textLength]);
    }
}

Here you have an upper bound for your own code. Usage is by calling colorize (or c in the golfed version) and pass the text and an array of hex color codes. The function will return a String with HTML-tags like the OP did, thus you need some way to render the HTML.

The algorithm is easier as the question looks like. The first character always gets the first color, the last one always the last. <s>If we have more colors than chars in the text we just iterate over the text and colors and apply these.</s> The fun part is the one with the fades: I started of by finding out in what distance the colors are on the text. I basically calculate the red, green and blue difference between two given colors and then add a part of this difference to the first color, depending on where the char is between the colors. If it leaves the interval of two colors we start from new with the next two colors. This is repeated for all but the last character, which we know is always the last color. This gives a very beautiful fading.

That question was very much fun! Thanks!

Updates

Now I don't handle all the cases specially. Instead I trim the colors if there are two much and apply the fade function to every string. If there were more colors than text then the colors will be trimmed and the fading function will work exactly as a simple mapping.


问:
Generate Dennis Numbers
This challenge is a tribute to PPCG user Dennis for winning the robbers' part of The Programming Language Quiz.

Looking at Dennis' PPCG profile page we can see some pretty impressive stuff:

He currently has over sixty-eight thousand reputation, making him second in rep overall, surpassing third place by almost thirty thousand. He recently won our election for a new moderator and got a shiny new diamond next to his name. But I personally think the most interesting part about Dennis is his PPCG user ID number: 12012.

At first glance 12012 almost looks like a palindrome, a number that reads the same when reversed, but it's a little off. It can become the palindrome 21012 if we swap the positions of the first 1 and 2, and it can become the palindrome 12021 if we swap the last 1 and 2. Also, following the convention that leading zeroes in a number are not written, swapping the first 1 and the 0 results in 02112 or rather 2112 which is another palindrome.

Let's define a Dennis number as a positive integer that is not palindromic itself but can be made into a palindrome by swapping the positions of at least one pair of any two digits. The order of a Dennis number is the number of distinct pairs of digits that can be swapped to make a (not necessarily distinct) palindrome.

So the order of 12012 is 3 since 3 distinct pairs of its digits (12012, 12012, 12012) can be swapped around to produce palindromes. 12012 happens to be the smallest order 3 Dennis number.

10 is the smallest Dennis number and has order 1 because switching around the 1 and 0 gives 01 a.k.a. 1 which is a palindrome.

The imaginary leading zeroes of a number don't count as switchable digits. For example, changing 8908 to 08908 and swapping the first two digits to get the palindrome 80908 is invalid. 8908 is not a Dennis number.

Non-Dennis numbers could be said to have order 0.

Challenge

Write a program or function that takes in a positive integer N and prints or returns the Nth smallest Dennis number along with its order in some reasonable format such as 12012 3 or (12012, 3).

For example, 12012 is the 774th Dennis number so if 774 is the input to your program, the output should be something like 12012 3. (Curiously, 774 is another Dennis number.)

The shortest code in bytes wins.

Here is are the first 20 Dennis numbers and their orders for reference:

```<code>N       Dennis  Order
1       10      1
2       20      1
3       30      1
4       40      1
5       50      1
6       60      1
7       70      1
8       80      1
9       90      1
10      100     1
11      110     2
12      112     1
13      113     1
14      114     1
15      115     1
16      116     1
17      117     1
18      118     1
19      119     1
20      122     1
</code>```

Here is the same list up to N = 1000.

答:
Jelly, 33 bytes

```<code>ṚḌ=
=ċ0^2°;ḌÇ
DŒ!Qç@ÐfDL©Ṡ>Ñµ#Ṫ,®
</code>```

Try it online!

How it works

```<code>DŒ!Qç@ÐfDL©Ṡ>Ñµ#Ṫ,®  Main link. No arguments.

              µ      Combine the chain to the left into a link.
               #     Find; execute the chain with arguments k = 0, 1, 2, ...
                     until n values of k result in a truthy value, where n is an
                     integer read implicitly from STDIN. Return those n values.

D                      Decimal; convert k to the list of its digits in base 10.
 Œ!                    Generate all permutations of the digits.
   Q                   Unique; deduplicate the list of permutations.
      Ðf               Filter:
    ç@  D                Call the helper link on the second line with the
                         unpermuted digits (D) as left argument, and each
                         permutation as the right one.
                       Keep permutations for which ç returns a truthy value.
         L©            Compute the length (amount of kept permutations) and save
                       it in the register.
           Ṡ           Sign; yield 1 if the length is positive, and 0 otherwise.
            >Ṅ         Compare the sign with the result from the helper link on
                       the first line. This will return 1 if and only if the
                       length is positive and Ñ returns 0.
                Ṫ      Tail; extract the last value of k.
                 ,®    Pair it with the value in the register.

=ċ0^2°;ḌÇ              Helper link. Arguments: A, B (lists of digits)

=                      Compare the corresponding integers in A and B.
 ċ0                    Count the zeroes, i.e., the non-matching integers.
   ^2                  Bitwise XOR the amount with 2.
     °                 Convert to radians. This will yield 0 if exactly two
                       corresponding items of A and B are different ,and a
                       non-integral number otherwise.
      ;                Prepend the result to B.
       Ḍ               Convert the result from decimal to integer. Note that
                       leading zeroes in the argument won't alter the outcome.
        Ç              Call the helper link on the first line.

ṚḌ=                    Helper link. Argument: m (integer)

Ṛ                      Convert m to decimal and reverse the digits.
 Ḍ                     Convert back to integer.
  =                    Compare the result with m.
</code>```

Title: Generate Dennis Numbers

Body:
Jelly, 33 bytes

ṚḌ=
=ċ0^2°;ḌÇ
DŒ!Qç@ÐfDL©Ṡ>Ñµ#Ṫ,®

Try it online!

How it works

DŒ!Qç@ÐfDL©Ṡ>Ñµ#Ṫ,®  Main link. No arguments.

              µ      Combine the chain to the left into a link.
               #     Find; execute the chain with arguments k = 0, 1, 2, ...
                     until n values of k result in a truthy value, where n is an
                     integer read implicitly from STDIN. Return those n values.

D                      Decimal; convert k to the list of its digits in base 10.
 Œ!                    Generate all permutations of the digits.
   Q                   Unique; deduplicate the list of permutations.
      Ðf               Filter:
    ç@  D                Call the helper link on the second line with the
                         unpermuted digits (D) as left argument, and each
                         permutation as the right one.
                       Keep permutations for which ç returns a truthy value.
         L©            Compute the length (amount of kept permutations) and save
                       it in the register.
           Ṡ           Sign; yield 1 if the length is positive, and 0 otherwise.
            >Ṅ         Compare the sign with the result from the helper link on
                       the first line. This will return 1 if and only if the
                       length is positive and Ñ returns 0.
                Ṫ      Tail; extract the last value of k.
                 ,®    Pair it with the value in the register.

=ċ0^2°;ḌÇ              Helper link. Arguments: A, B (lists of digits)

=                      Compare the corresponding integers in A and B.
 ċ0                    Count the zeroes, i.e., the non-matching integers.
   ^2                  Bitwise XOR the amount with 2.
     °                 Convert to radians. This will yield 0 if exactly two
                       corresponding items of A and B are different ,and a
                       non-integral number otherwise.
      ;                Prepend the result to B.
       Ḍ               Convert the result from decimal to integer. Note that
                       leading zeroes in the argument won't alter the outcome.
        Ç              Call the helper link on the first line.

ṚḌ=                    Helper link. Argument: m (integer)

Ṛ                      Convert m to decimal and reverse the digits.
 Ḍ                     Convert back to integer.
  =                    Compare the result with m.


问:
Generate ASCII TetraVex
TetraVex is a tile-based edge-matching game that was originally coded by Scott Ferguson for the Microsoft Entertainment Pack 3 back in 1990. The game consists of a grid upon which square tiles are placed. The tiles have numbers or letters on each edge, and the goal is to place all tiles in the grid, with each pair of edges matching, in the fastest time. Since solving TetraVex is known to be NP-Complete, we're instead just going to generate a solved board.

For our purposes, each TetraVex tile is 5 characters wide by 3 tall, and follows the pattern:

```<code>\ # /
# X #
/ # \
</code>```

where each # is replaced with an alphanumeric symbol matching [A-Z0-9] (capitals, not lowercase).

When placed on the board, the tiles have additional spaces between them on the grid, in order to differentiate the tiles horizontally from each other. The grid is composed of |, -, and + symbols, as shown below. Note that there is no border on the outside of the gameplay area, and no trailing spaces to the right of the tiles.

```<code>\ # / | \ # /
# X # | # X #
/ # \ | / # \
------+------
\ # / | \ # /
# X # | # X #
/ # \ | / # \
</code>```

Input

Two integers 1 < n,m <= 255 in any convenient format (tuple, array, function argument, etc.). The numbers can be taken in either order (please specify in your answer which order).

These represent a board of n tiles wide by m tiles tall.

The smallest board output will thus be 2x2 tiles, or 13 characters wide by 7 characters tall.

The largest is 255x255 tiles, or 2037 characters wide by 1019 characters tall.

Output

An ASCII representation of a TetraVex board of size n x m.

The board must follow the tile construction rules above, and must be a solved board (meaning the paired edges match). Non-paired edges (i.e., the border) can be any legal character.

Rules

Each individual tile in the output must be unique.

Reflected or rotated tiles count as distinct, since during actual gameplay you're not permitted to rotate or flip the tiles in any manner.

For example, a tile with 1 A on top and 3 Bs on the other edges is considered distinct from a tile with 1 A on the right and 3 Bs on the other edges.

The output must be somewhat non-deterministic, meaning different runs of the code with the same n and m input should yield different boards. However, in the interests of complexity, not all possible n x m boards need have non-zero probability in your output -- only at least two of the possible boards must have non-zero probability of actually being produced.

For example, a 3 x 3 board, with full alphanumeric edges, already has somewhere around 36^24 ~= 2.25e37 possible boards. Since that number grows exponentially as the size increases, ensuring equal probability for all boards may become infeasible for many languages.

This does mean you could have two separate deterministic code paths produce two separate boards and then simply flip a coin to determine which to output -- that's fine. (For example, starting with the first tile all A in one path and all B in the other, and then generate the rest of the board using the same algorithm from there will guarantee two unique boards and is allowed)

Any of our usual definitions for randomness will suffice for determining this non-zero probability.

Rotations or reflections of the board are considered "different" boards, but note that you're not guaranteed a square grid, only a rectangular one. ;-)

Generating a board and then replacing a certain character with another (e.g., replacing all A with Z) is allowed, provided that each tile in the output is still unique.

Trailing spaces are not allowed but trailing newline(s) are OK.

Standard loopholes are forbidden.

This is code-golf, so all usual golfing rules apply, and the shortest code wins.

Examples

1) Input: 3 3

```<code>\ A / | \ B / | \ C /
D X E | E X G | G X I
/ J \ | / K \ | / L \
------+-------+------
\ J / | \ K / | \ L /
M X N | N X O | O X P
/ Q \ | / R \ | / S \
------+-------+------
\ Q / | \ R / | \ S /
T X U | U X V | V X W
/ X \ | / Y \ | / Z \
</code>```

2) Input: 5 3

```<code>\ 0 / | \ B / | \ C / | \ A / | \ Z /
D X E | E X F | F X I | I X A | A X Q
/ J \ | / 9 \ | / L \ | / L \ | / 6 \
------+-------+-------+-------+------
\ J / | \ 9 / | \ L / | \ L / | \ 6 /
M X N | N X 4 | 4 X P | P X P | P X T
/ R \ | / R \ | / S \ | / B \ | / K \
------+-------+-------+-------+------
\ R / | \ R / | \ S / | \ B / | \ K /
T X Z | Z X V | V X W | W X J | J X G
/ X \ | / Y \ | / Z \ | / X \ | / A \
</code>```

答:
CJam, 116

```<code>26mr:D;q~:B;){[7B),f#10222@#f*2G#)f%_2ew:+23f%\W<26f%]{D+26%'A+}f%~"\/"f*_:$@2/'Xf*[@]'|f*Sf*~_'{f>"-+"f=\@}%2>-3<N*
</code>```

Try it online

Uses only letters.

Explanation:

The first observation is that any rectangular piece of a solved board is a solved board. Since the program needs to work up to 255×255, it is enough to solve it for that case and use a piece of that board with the requested dimensions.

I am using a fixed 255×255 board that I determined to be correct. I actually did 256×256 tiles first, choosing 2 numbers per tile (top and left), then copied the other numbers from adjacent tiles, discarding some edge numbers from the last row and last column.

Each tile is first given an associated number, and then I calculate the remainders of that number modulo two other numbers (I used 23 and 26) to get the 2 numbers chosen for that tile.

In order to avoid patterns which lead to duplication, I decided to make the associated numbers pseudo-random and unique. I used my favorite distinct not-very-random number generator, which is based on primitive roots: take a prime number slightly bigger than the desired range (65537) and a small prime number (7), then use the powers of the small number modulo the big number. After a few trials, I found that the combination of 7, 23 and 26 works well, giving 65025 (255²) unique tiles.

For the random factor, I am just applying a random cyclic permutation to the value of each number. Then the numbers (0-25) are converted to letters (A-Z).

Code explanation to follow.

Title: Generate ASCII TetraVex

Body:
CJam, 116

26mr:D;q~:B;){[7B),f#10222@#f*2G#)f%_2ew:+23f%\W<26f%]{D+26%'A+}f%~"\/"f*_:$@2/'Xf*[@]'|f*Sf*~_'{f>"-+"f=\@}%2>-3<N*

Try it online

Uses only letters.

Explanation:

The first observation is that any rectangular piece of a solved board is a solved board. Since the program needs to work up to 255×255, it is enough to solve it for that case and use a piece of that board with the requested dimensions.

I am using a fixed 255×255 board that I determined to be correct. I actually did 256×256 tiles first, choosing 2 numbers per tile (top and left), then copied the other numbers from adjacent tiles, discarding some edge numbers from the last row and last column.

Each tile is first given an associated number, and then I calculate the remainders of that number modulo two other numbers (I used 23 and 26) to get the 2 numbers chosen for that tile.

In order to avoid patterns which lead to duplication, I decided to make the associated numbers pseudo-random and unique. I used my favorite distinct not-very-random number generator, which is based on primitive roots: take a prime number slightly bigger than the desired range (65537) and a small prime number (7), then use the powers of the small number modulo the big number. After a few trials, I found that the combination of 7, 23 and 26 works well, giving 65025 (255²) unique tiles.

For the random factor, I am just applying a random cyclic permutation to the value of each number. Then the numbers (0-25) are converted to letters (A-Z).

Code explanation to follow.


问:
Include a JavaScript script with JavaScript
To dynamically include a JavaScript file in a web page, you'd normally insert a

答:
75 bytes

```<code>document.body.appendChild(document.createElement`script`).src="//v.ht/Xa33"
</code>```

@Neil's answer was quite similar to this, but he found an ingenious shortcut involving with(...). I will not copy it here, because he came up with it.

Thanks to @Bálint for the short URL.

Body:
75 bytes

document.body.appendChild(document.createElement`script`).src="//v.ht/Xa33"

@Neil's answer was quite similar to this, but he found an ingenious shortcut involving with(...). I will not copy it here, because he came up with it.

Thanks to @Bálint for the short URL.


答:
Python 3,  146 bytes

For every number greater than 0, there are even loops (len 2,4,6,8...), and less than 0, odd loops (1,3,5,7). 0 maps to 0.

(-3,-2,-1),(0),(1,2),(3,4,5,6)

maps to

(-2,-1,-3),(0),(2,1),(6,3,4,5)

```<code>f=lambda x:1+2*int(abs(x)**.5)if x<1 else 2*int(x**.5+.5)
x=int(input());n=f(x)
if x>0:b=n*(n-2)/4
else:b=-((n+1)/2)**2
print(b+1+(x-b-2)%n)
</code>```

Edit: @TuukkaX took off 8 bytes from the previous solution. And another 3.

Title: Find a function with cycles of every length

Body:
A function is said to have a cycle of length n if there exists an x in its domain such that fn(x) = x and fm(x) ≠ x for 0 < m < n, where the superscript n denotes n-fold application of f. Note that a cycle of length 1 is a fixed point f(x) = x.

Your task is to implement a bijective function from the integers to themselves, which has exactly one cycle of every positive length n. A bijective function is a one-to-one correspondence, i.e. every integer mapped to exactly once. Having exactly one cycle of length n means that there are exactly n distinct numbers x for which fn(x) = x and fm(x) ≠ x for 0 < m < n.

Here is an example of what such a function might look like around x = 0:

```<code>x     ... -7 -6 -5 -4 -3 -2 -1  0  1  2  3  4  5  6  7 ...
f(x)  ...  2  4  6 -3 -1  1 -4  0 -2  5  7 -7 -6  3 -5 ...
</code>```

This excerpt contains cycles of length 1 to 5:

```<code>n   cycle
1    0
2   -2  1
3   -4 -3 -1
4   -5  6  3  7
5   -7  2  5 -6  4
...
</code>```

Note that above I'm using "function" only in the mathematical sense. You may write either a function or a full program in your language of choice, as long as it takes a single (signed) integer as input and returns a single (signed) integer. As usual you may take input via STDIN, command-line argument, function argument etc. and output via STDOUT, function return value or function (out) argument etc.

Of course, many languages don't (easily) support arbitrary-precision integers. It's fine if your implementation only works on the range of your language's native integer type, as long as that covers at least the range [-127, 127] and that it would work for arbitrary integers if the language's integer type was replaced with arbitrary-precision integers.

Standard code-golf rules apply.

Body:
Python 3,  146 bytes

For every number greater than 0, there are even loops (len 2,4,6,8...), and less than 0, odd loops (1,3,5,7). 0 maps to 0.

(-3,-2,-1),(0),(1,2),(3,4,5,6)

maps to

(-2,-1,-3),(0),(2,1),(6,3,4,5)

f=lambda x:1+2*int(abs(x)**.5)if x<1 else 2*int(x**.5+.5)
x=int(input());n=f(x)
if x>0:b=n*(n-2)/4
else:b=-((n+1)/2)**2
print(b+1+(x-b-2)%n)

Edit: @TuukkaX took off 8 bytes from the previous solution. And another 3.


答:
Python 2, 55 bytes

g=lambda n,k=1:n/k and~g(~n+k*(n>0),k+1)+k*(n>0)or-~n%k
```
<hr />
<p><strong>59 bytes:</strong></p>
<pre class="lang-python prettyprint-override"><code>g=lambda n,k=1:n<0and~g(~n,2)or n/k and k+g(n-k,k+2)or-~n%k
</code>```

Creates the cycles

[0]
[-1, -2]
[1, 2, 3]
[-3, -4, -5, -6]
[4, 5, 6, 7, 8]
...
```
<p>Modified from my solution on the earlier challenge, which is modified from Sp3000's construction.</p>
<p>The function</p>
<pre class="lang-python prettyprint-override"><code>g=lambda n,k=1:n/k and k+g(n-k,k+2)or-~n%k
</code>```

makes odd-size cycles of non-negative numbers

[0]
[1, 2, 3]
[4, 5, 6, 7, 8]
...
```
<p>To find the correct cycle size <code>k</code>, shift the input <code>n</code> down by <code>k=1,3,5,7,...</code> until the result is in the interval <code>[0,k)</code>. Cycle this interval with the operation <code>n->(n+1)%k</code>, then undo all the subtractions done on the input. This is implemented recursively by <code>k+g(n-k,k+2)</code>.</p>
<p>Now, we need the negative to make the even cycles. Note that if we modify <code>g</code> to start with <code>k=2</code> in <code>g</code>, we'd get even-size cycles</p>
<pre class="lang-python prettyprint-override"><code>[0, 1]
[2, 3, 4, 5]
[6, 7, 8, 9, 10, 11]
...
</code>```

These biject to negatives via bit-complement ~. So, when n is negative, we simply evaluate g(n) as ~g(~n,2).

Body:
Python 2, 55 bytes

g=lambda n,k=1:n/k and~g(~n+k*(n>0),k+1)+k*(n>0)or-~n%k

59 bytes:

g=lambda n,k=1:n<0and~g(~n,2)or n/k and k+g(n-k,k+2)or-~n%k

Creates the cycles

[0]
[-1, -2]
[1, 2, 3]
[-3, -4, -5, -6]
[4, 5, 6, 7, 8]
...

Modified from my solution on the earlier challenge, which is modified from Sp3000's construction.

The function

g=lambda n,k=1:n/k and k+g(n-k,k+2)or-~n%k

makes odd-size cycles of non-negative numbers

[0]
[1, 2, 3]
[4, 5, 6, 7, 8]
...

To find the correct cycle size k, shift the input n down by k=1,3,5,7,... until the result is in the interval [0,k). Cycle this interval with the operation n->(n+1)%k, then undo all the subtractions done on the input. This is implemented recursively by k+g(n-k,k+2).

Now, we need the negative to make the even cycles. Note that if we modify g to start with k=2 in g, we'd get even-size cycles

[0, 1]
[2, 3, 4, 5]
[6, 7, 8, 9, 10, 11]
...

These biject to negatives via bit-complement ~. So, when n is negative, we simply evaluate g(n) as ~g(~n,2).


答:
<s>77</s> <s>75</s> 71 bytes

with(document)body.appendChild(createElement`script`).src=`//v.ht/Xa33````

Edit: Saved 2 bytes thanks to @jrich. Saved 4 bytes thanks to @Bálint.

Title: Include a JavaScript script with JavaScript

Body: To dynamically include a JavaScript file in a web page, you'd normally insert a

Body:
<s>77</s> <s>75</s> 71 bytes

with(document)body.appendChild(createElement`script`).src=`//v.ht/Xa33`

Edit: Saved 2 bytes thanks to @jrich. Saved 4 bytes thanks to @Bálint.


答:
Jolf, 17 bytes

```<code>Ώ‘Hγ+H/H3Βώ/γ3hΒ’
</code>```

Defines a function Ώ. It takes input implicitly, so it also doubles as a full program. Try it here!

Title: The Nine Pattern

Body:
Introduction

I stumbled across this (useless) pattern the other day while I was watching TV.
I named it "the 9 pattern" because the first number to use it was 9.
The gist of it is, you enter a number (let's say x), and then you get back:

x

x + (x / 3) [let's call this y]

two-thirds of y [let's call this z]

z + 1

So, if I put inside this pattern the number 9 as x, this is what would come out:

9 (9)

12 (9 + 9 / 3) [9 over 3 is 3, and 9 + 3 is 12]

8 (12 times two-thirds) [a third of 12 is 4, and 4 * 2 is 8]

9 (8 + 1 is 9)

Challenge

Write me a function (in any programming language) that takes in a number, and outputs an integer array using the pattern.

Somewhat like this psuedo-code:

```<code>function ninePattern(int myInt) returns IntegerArray {
    int iterationA = myInt + (myInt / 3);
    int iterationB = iterationA * (2 / 3);
    int iterationC = iterationB + 1;
    IntegerArray x = [myInt, iterationA, iterationB, iterationC];
    return x;
}
</code>```

Clarifications

Discussions have been arousing in comments regarding the specifications of the question. This section is meant to clarify some of those.

"better to count in bytes than characters"

I picked characters because (for me, at least) it would be easier to judge. Of course, I can't change that now. (lots of answers are already posted)

"rounding"

Rounding follows this rhyme:

If it's 5 or more, raise the score

  If it's 4 or less, let it rest

Simply, put, if it is something like 4.7 or 3.85, round them to 5 and 4 respectively.

Examples

```<code>Input => Result
9 => [9, 12, 8, 9]
8 => [8, 11, 7, 8]
6 => [6, 8, 5, 6]
23 => [23, 31, 21, 22]
159 => [159, 212, 141, 142]
</code>```

If, however, the numbers are something like 2.3 or 10.435446, round them to 2 and 10 respectively.

"language support"

You are free to not use functions and/or arrays IF AND ONLY IF the language of your choice does not support them.  If it does (even if it will increase your characters count), you must use them.

Body:
Jolf, 17 bytes

Ώ‘Hγ+H/H3Βώ/γ3hΒ’

Defines a function Ώ. It takes input implicitly, so it also doubles as a full program. Try it here!


答:
Matlab(423)

```<code>function u=f(n),if(~n)u=n;else,x=abs(n);y=factor(x);for o=1:nnz(y),e=prod(nchoosek(y,o)',1);a=log(x)./log(e);b=find(a-fix(a)<exp(-9),1);if ~isempty(b),k=e(b);l=fix(a(b));break;end;end,if(abs(n)==1)k=2;l=0;end,if(k==2)l=l+1;x=x*2;end,e=dec2base(l,k)-48;o=xor(e,circshift(e,[0 1]));g=~o(end);if(~o|nnz(o==1)~=numel(e)-g),u=n*k;else,if((-1)^g==sign(n)),u=sign(n)*k^(base2dec([e(2:end-1) 1]+48,k)-(k==2));else,u=n*k;end,end,end
</code>```

Non-competing because it breaks a good record of being condidate for the last ranking, whilst I am struggling to shorten it as possible as i can.

Some nonesensical bugs concerning accuracy in matlab that I couldnt find any way out except making my code sarcatistically big, in other hand the mapping I opt for was in terms of prime facors and n-ary logarithm.

Execution

```<code> f(2)

 1

 f(1)

 2

 f(-2)

 -4

 f(-4)

 -8

 f(-8)

 -1

 f(0)

 0

 ----------------------------
</code>```

Explanation

Knonwing, first off, that any number can be written as product of exponents of primes N=e1^x1*e2^x2... from this base i chose to map images of cycles C which are extracted from the biggest exponent of the smallest factor (not necessarily prime) that N is a perfect power of.

in simpler words, let N=P^x where P is the smallest perfect root, x denotes precisely two essential terms for the cycle : x=Ʃ(r*P^i), a term P is the base of cycle as well a perfect root for the main number N, and k is the degree of the cycle C=p^k, where i varies between 1 and k, the coeffecient r is incremented by 1 and bounded by P-1 for any following pre-image until all coeffecients are set to r=1, so we move to the start of that cycle.

To avoid collisions between cycles the choice of exponentiation of primes rather than their products is accurate, because as an example of two cycles of bases 3 and 2 a meetpoint between them can be 3*2, so this is avoided since a cycle is defined by its degree more than its base , and for the meetpoint there is another cycle of base 6 and degree 1.

Negative numbers place an exception, as for it, i reserved odd degrees for negative numbers, and even degrees for the rest. How so ?

for any number N embedded within a cycle P^k, is written as P^(a0*P^i0+a1*P^i1+...), the amount (a0*P^i0+a1*P^i1+...) is transalted in P-ary base as a0,a1,.... , to clarify this point if (p=2) the sequence must be in binary base. As is known prealably without setting the condition of positive/negative degrees and the (+/-1) exception, a number N is on the edges of a cycle of degree k if and only if the sequence A is written as 1111..{k+1}..10 or 111..{k}..1 for all bases, otherwise no rotation is needed, thus assigning negative/positive condition for a respective odd/even degrees k/k' for both makes an odd sequence written in the form 101..{k}..100, an even sequence is written in the form 101..{k'}..10 for a beginning edge of a respectively negative/positive number-cycle.

Example:

Taking a number N=2^10, x=10=2^1+2^3 , the sequence A is written A=1010, this type of sequence symptomizes a finite edge of positive number-cycle, which is C=2^3, so the next image is that of beginning edge A=011 which is 8, But, by standarizing this result to (+/-)1 exception 2^10/2 maps to 8/2 and the previous image mustnt be rotated.

Taking a number N=-3^9, x=9=3^2 , the sequence A is written A=100, this type of sequence symptomizes a finite edge of negative number-cycle, which is C=3^1, so the next image is that of beginning edge A=01 which is 3, But, by adapting this result to negative/positive condition -3^9 maps to -3 .

for the couple (-/+)1, i envisaged to intrude it within numbers of cycle-bases 2, in a guise that an ordinary sequence of cyclic groups {2,4}{8,16,32,64}.. are made up in another form {1,2}{4,8,16,32}.., this prevents any loss of previous elements, and the opeation done is just shifting with popping a new element in.

Results:

running this little code-sheet to verify the first reasonable ranges of cyclic numbers:

```<code>for (i=1:6)
index=1;if(max(factor(i))>=5) index=0;end
for ind=0:index
j=f(((-1)^ind)*i); while(((-1)^ind)*i~=j)fprintf('%d ',j);j=f(j);end,fprintf('%d \n',(-1)^ind*i),pause,end,
end
</code>```

This leads to this results

```<code> 2 1
 -2 -4 -8 -1
 1 2
 -4 -8 -1 -2
 9 27 3
 -9 -27 -81 -243 -729 -2187 -6561 -19683 -3
 8 16 32 64 128 256 512 4
 -8 -1 -2 -4
 25 125 625 3125 5
 36 216 1296 7776 46656 6
 -36 -216 -1296 -7776 -46656 -279936 -1679616 -10077696 -60466176 -362797056 -2.176782e+009 -1.306069e+010 ??? Error using ==> factor at 27
</code>```

The last one is segmentation-error but it fits the [-127,127] standard signed-integer range.

Body:
Matlab(423)

function u=f(n),if(~n)u=n;else,x=abs(n);y=factor(x);for o=1:nnz(y),e=prod(nchoosek(y,o)',1);a=log(x)./log(e);b=find(a-fix(a)<exp(-9),1);if ~isempty(b),k=e(b);l=fix(a(b));break;end;end,if(abs(n)==1)k=2;l=0;end,if(k==2)l=l+1;x=x*2;end,e=dec2base(l,k)-48;o=xor(e,circshift(e,[0 1]));g=~o(end);if(~o|nnz(o==1)~=numel(e)-g),u=n*k;else,if((-1)^g==sign(n)),u=sign(n)*k^(base2dec([e(2:end-1) 1]+48,k)-(k==2));else,u=n*k;end,end,end

Non-competing because it breaks a good record of being condidate for the last ranking, whilst I am struggling to shorten it as possible as i can.

Some nonesensical bugs concerning accuracy in matlab that I couldnt find any way out except making my code sarcatistically big, in other hand the mapping I opt for was in terms of prime facors and n-ary logarithm.

Execution

 f(2)

 1

 f(1)

 2

 f(-2)

 -4

 f(-4)

 -8

 f(-8)

 -1

 f(0)

 0

 ----------------------------

Explanation

Knonwing, first off, that any number can be written as product of exponents of primes N=e1^x1*e2^x2... from this base i chose to map images of cycles C which are extracted from the biggest exponent of the smallest factor (not necessarily prime) that N is a perfect power of.

in simpler words, let N=P^x where P is the smallest perfect root, x denotes precisely two essential terms for the cycle : x=Ʃ(r*P^i), a term P is the base of cycle as well a perfect root for the main number N, and k is the degree of the cycle C=p^k, where i varies between 1 and k, the coeffecient r is incremented by 1 and bounded by P-1 for any following pre-image until all coeffecients are set to r=1, so we move to the start of that cycle.

To avoid collisions between cycles the choice of exponentiation of primes rather than their products is accurate, because as an example of two cycles of bases 3 and 2 a meetpoint between them can be 3*2, so this is avoided since a cycle is defined by its degree more than its base , and for the meetpoint there is another cycle of base 6 and degree 1.

Negative numbers place an exception, as for it, i reserved odd degrees for negative numbers, and even degrees for the rest. How so ?

for any number N embedded within a cycle P^k, is written as P^(a0*P^i0+a1*P^i1+...), the amount (a0*P^i0+a1*P^i1+...) is transalted in P-ary base as a0,a1,.... , to clarify this point if (p=2) the sequence must be in binary base. As is known prealably without setting the condition of positive/negative degrees and the (+/-1) exception, a number N is on the edges of a cycle of degree k if and only if the sequence A is written as 1111..{k+1}..10 or 111..{k}..1 for all bases, otherwise no rotation is needed, thus assigning negative/positive condition for a respective odd/even degrees k/k' for both makes an odd sequence written in the form 101..{k}..100, an even sequence is written in the form 101..{k'}..10 for a beginning edge of a respectively negative/positive number-cycle.

Example:

Taking a number N=2^10, x=10=2^1+2^3 , the sequence A is written A=1010, this type of sequence symptomizes a finite edge of positive number-cycle, which is C=2^3, so the next image is that of beginning edge A=011 which is 8, But, by standarizing this result to (+/-)1 exception 2^10/2 maps to 8/2 and the previous image mustnt be rotated.

Taking a number N=-3^9, x=9=3^2 , the sequence A is written A=100, this type of sequence symptomizes a finite edge of negative number-cycle, which is C=3^1, so the next image is that of beginning edge A=01 which is 3, But, by adapting this result to negative/positive condition -3^9 maps to -3 .

for the couple (-/+)1, i envisaged to intrude it within numbers of cycle-bases 2, in a guise that an ordinary sequence of cyclic groups {2,4}{8,16,32,64}.. are made up in another form {1,2}{4,8,16,32}.., this prevents any loss of previous elements, and the opeation done is just shifting with popping a new element in.

Results:

running this little code-sheet to verify the first reasonable ranges of cyclic numbers:

for (i=1:6)
index=1;if(max(factor(i))>=5) index=0;end
for ind=0:index
j=f(((-1)^ind)*i); while(((-1)^ind)*i~=j)fprintf('%d ',j);j=f(j);end,fprintf('%d \n',(-1)^ind*i),pause,end,
end

This leads to this results

 2 1
 -2 -4 -8 -1
 1 2
 -4 -8 -1 -2
 9 27 3
 -9 -27 -81 -243 -729 -2187 -6561 -19683 -3
 8 16 32 64 128 256 512 4
 -8 -1 -2 -4
 25 125 625 3125 5
 36 216 1296 7776 46656 6
 -36 -216 -1296 -7776 -46656 -279936 -1679616 -10077696 -60466176 -362797056 -2.176782e+009 -1.306069e+010 ??? Error using ==> factor at 27

The last one is segmentation-error but it fits the [-127,127] standard signed-integer range.


答:
Python 2, <s>108</s> <s>105</s> 100 bytes

f=lambda n,m=2,p=1:m>n or-~f(n,m+1,p*m*m)-(n%m<p%m)*m*m
r=max(range(2,input()+1),key=f)
print r,f(r)
```

Test it on Ideone.

Body:
The formula

Take for instance the number 300

The prime factors of 300 are [2, 3, 5] (unique numbers that are
factors of 300 and prime)

Squaring each of those numbers will give
you [4, 9, 25]

Summing that list will give you 4 + 9 + 25 = 38

Finally subtract that sum (38) from your original number 300-38 = 262 (this is the result)

Input

Your input will be a positive integer greater than 2. You must check all numbers from 2 to the input value (inclusive) and find the number that produces the greatest result with the formula above.

Output

Your output will be two numbers separated by a space, comma, newline or whatever you language allows (the separation is necessary to distinguish the two numbers). These can be output to a file, stdout, or whatever your language uses. Your goal is to find the number in the range that produces the maximum output when run through the formula above. The first number displayed should be the starting number (like 300) and the second number should be the output that the formula produced (like 262)

Test Cases

```<code>Input: 3       Output: 2, -2
Input: 10      Output: 8, 4
Input: 50      Output: 48, 35
Input: 1000    Output: 1000, 971
Input: 9999    Output: 9984, 9802
</code>```

Worked Through Example

Consider the input of 10, we must run the formula for all numbers from 2-10 (inclusive)

```<code>Num PrimeFacs PrimeFacs^2 SumPrimeFacs^2 Result
2   [2]       [4]         4              -2
3   [3]       [9]         9              -6
4   [2]       [4]         4               0
5   [5]       [25]        25             -20
6   [2, 3]    [4, 9]      13             -7
7   [7]       [49]        49             -42
8   [2]       [4]         4               4
9   [3]       [9]         9               0
10  [2, 5]    [4, 25]     29             -19
</code>```

As you can see the greatest result is 4, which was a result of inputting the value 8 into the formula. That means the output for an input of 10 should be 8, 4

Scoring & Rules

The default rules for inputs and outputs apply: Default for Code Golf: Input/Output methods

The standard loopholes are forbidden: Loopholes that are forbidden by default

Submissions can be functions or full programs

Shortest code in bytes wins

Body:
Python 2, <s>108</s> <s>105</s> 100 bytes

f=lambda n,m=2,p=1:m>n or-~f(n,m+1,p*m*m)-(n%m<p%m)*m*m
r=max(range(2,input()+1),key=f)
print r,f(r)

Test it on Ideone.


答:
C++0x - 95 102 185 189 109 129 chars

```<code>int * n(int p){static int a[3];a[0]=p;a[1]=round(p+(p/3));a[2]=round((a[1]/3)*2);a[3]=a[2]+1;return a;}
</code>```

This requires the cmath header to work.

Degolfed

```<code>#include <cmath>
int * ninePattern(int p) {
        static int a[3]; // pattern array
        a[0] = p; // sets first iteration
        a[1] = round(p + (p / 3)); // sets second iteration
        a[2] = round((a[1] / 3) * 2); // sets third iteration
        a[3] = a[2] + 1; // sets fourth iteration
        return a; // returns array
}
</code>```

Title: The Nine Pattern

Body:
C++0x - 95 102 185 189 109 129 chars

int * n(int p){static int a[3];a[0]=p;a[1]=round(p+(p/3));a[2]=round((a[1]/3)*2);a[3]=a[2]+1;return a;}

This requires the cmath header to work.

Degolfed

#include <cmath>
int * ninePattern(int p) {
        static int a[3]; // pattern array
        a[0] = p; // sets first iteration
        a[1] = round(p + (p / 3)); // sets second iteration
        a[2] = round((a[1] / 3) * 2); // sets third iteration
        a[3] = a[2] + 1; // sets fourth iteration
        return a; // returns array
}