问:
Making an acronym

Objective

Your goal is to make a program that converts an input to its acronym. Your input is guaranteed to have only letters and spaces. The input will have exactly one space between words. You must output the acronym of the input.

Rules

Your code cannot be case-sensitive(e.g. foo and Foo are the same)

Your code must ignore the following words and not put them in the acronym:
and or by of

You cannot assume that the words are all lowercase.

The output must be entirely capitalised, with no separation between characters.

A trailing newline is accepted but not necessary.

If your language has an acronym function builtin, you may not use it.

Examples

(inputs/outputs grouped)

```<code>United States of America
USA

Light Amplification by Stimulation of Emitted Radiation
LASER

united states of america
USA

Jordan Of the World
JTW
</code>```

Scoring

This is a code-golf challenge so the shortest code wins.

Leaderboard

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
IPOS - non competing, 27 bytes

```<code>uS`"AND|OR|BY|OF"ER`%S!h%S-
</code>```

This works in the current version (v0.2) of the interpreter.

Example run

```
python IPOS.py -i "United States of America" uS`\"AND|OR|BY|OF\"ER`%S!h%S-
USA
```

The backslashes there are only for escaping of the quotes and are not needed for the program.

Explanation

```
u                  # Make the input uppercase
S                  # Push a space to the stack
`"AND|OR|BY|OF"ER` # Push a command to the stack, that replaces matches of the regex
                   # with an empty string
%                  # Split the uppercased input string on spaces, apply the command and
                   # join back on spaces. This removes the required words from the input.
S                  # Push a space to the stack
!h                 # Push a command that only selects the first character of a string
%                  # Split on spaces, apply the command and join back on spaces
S-                 # Remove the remaining spaces (forgot to make this usuable
                   # with regexes, would have saved me some bytes here :( )
```

Title: Making an acronym

Body:
IPOS - non competing, 27 bytes

uS`"AND|OR|BY|OF"ER`%S!h%S-

This works in the current version (v0.2) of the interpreter.

Example run

python IPOS.py -i "United States of America" uS`\"AND|OR|BY|OF\"ER`%S!h%S-
USA

The backslashes there are only for escaping of the quotes and are not needed for the program.

Explanation

u                  # Make the input uppercase
S                  # Push a space to the stack
`"AND|OR|BY|OF"ER` # Push a command to the stack, that replaces matches of the regex
                   # with an empty string
%                  # Split the uppercased input string on spaces, apply the command and
                   # join back on spaces. This removes the required words from the input.
S                  # Push a space to the stack
!h                 # Push a command that only selects the first character of a string
%                  # Split on spaces, apply the command and join back on spaces
S-                 # Remove the remaining spaces (forgot to make this usuable
                   # with regexes, would have saved me some bytes here :( )


问:
Shortest code for infinite disk I/O
(Just open 50 tabs in Google Chrome :D (just kidding, no you can't))

Shortest code for infinite disk I/O any language, C# example:

using System.IO;

namespace FileApp {
    static class Program {
        public static void Main() {
            do {
                File.WriteAllText("a", "a");
                File.Delete("a");
            } while (true);
        }
    }
}
```

You can't just fill the entire disk though, as then it would halt in the end and would be finite.

And you can't do reading only, infinite writing has to happen. (It has to kill my SSD after enough runtime.)

Get cracking! :)

答:
cmd, 14 bytes

```<code>:a
cd>1
goto a
</code>```

Infinitly overwrites the file 1 with the string to the current directory

I'm new here:
Are windows new lines (CR LF) counted as two bytes?

ContentLicense: CC BY-SA 3.0

Title: Shortest code for infinite disk I/O

Body:
cmd, 14 bytes

:a
cd>1
goto a

Infinitly overwrites the file 1 with the string to the current directory

I'm new here:
Are windows new lines (CR LF) counted as two bytes?


答:
Pyth, 6 bytes

```<code>#.w]]0
</code>```

Pyth's only file output command is .w. When called on a string, it writes that string to a file in append mode, which is no good for the purpose of this question. When called on a 2-d array, it writes the corresponding image to that file, overwriting the file contents. That's what this program does. The default file output name is o.png, so this program infinitely overwrites the file o.png with a 1-pixel white image. # is an infinite loop.

Title: Shortest code for infinite disk I/O

Body:
(Just open 50 tabs in Google Chrome :D (just kidding, no you can't))

Shortest code for infinite disk I/O any language, C# example:

using System.IO;

namespace FileApp {
    static class Program {
        public static void Main() {
            do {
                File.WriteAllText("a", "a");
                File.Delete("a");
            } while (true);
        }
    }
}
```

You can't just fill the entire disk though, as then it would halt in the end and would be finite.

And you can't do reading only, infinite writing has to happen. (It has to kill my SSD after enough runtime.)

Get cracking! :)

Body:
Pyth, 6 bytes

#.w]]0

Pyth's only file output command is .w. When called on a string, it writes that string to a file in append mode, which is no good for the purpose of this question. When called on a 2-d array, it writes the corresponding image to that file, overwriting the file contents. That's what this program does. The default file output name is o.png, so this program infinitely overwrites the file o.png with a 1-pixel white image. # is an infinite loop.


问:
Passwordify the string
Your challenge is to passwordify the string! What is passwordifying, you ask?

Take a string as input. This string will only contain uppercase letters, lowercase letters, digits, and spaces.

You must replace all spaces with underscores and move all numbers to the end of the string in the order that they appear from left to right. Then, for every letter in the string, randomly change it to uppercase or lowercase.

Examples (case of characters should vary every time):

```<code>Input
Hello world
Output
HElLo_wORld

Input
pa55 w0rd
Output
pA_Wrd550

Input
14 35
Output
_1435

Input
0971
Output
0971

Input
[space]
Output
_
</code>```

Shortest code in bytes wins!

Whoever asks on Information Security SE if this is a good hashing algorithm wins!--Don't worry SE overlords, I'm just kidding.

答:
><>, 73 bytes

```<code> i:"@")?v:" ")?v0) ?\rl?!;o01!.<
 v8<    8>00.! <o"_"/
8<>x<%*4/^o+*
 ^c<
</code>```

Nothing crazy here, it :

prints _ when it encounters

takes the mod 32 of letters, then randomly adds 8*8 or 12*8 before printing them

stacks the number and print them once the end of the input is reached

You can try it here !

Title: Passwordify the string

Body:
><>, 73 bytes

 i:"@")?v:" ")?v0) ?\rl?!;o01!.<
 v8<    8>00.! <o"_"/
8<>x<%*4/^o+*
 ^c<

Nothing crazy here, it :

prints _ when it encounters

takes the mod 32 of letters, then randomly adds 8*8 or 12*8 before printing them

stacks the number and print them once the end of the input is reached

You can try it here !


答:
C, 92 bytes

```<code>#include <stdio.h>
main(){for(FILE*f=fopen("a","w+");fprintf(f," "),!fclose(f);;);return 0;}
</code>```

While it looks like you could save 1 byte by

```<code>  for(FILE*f=fopen("a","w+");fprintf(f," ")+fclose(f);;){}
</code>```

the problem with that loop is that + doesn't give you the guaranteed order.

Or recursive - shouldn't overflow if the compiler properly implements tail recursion (f is in an explicit inner scope)

85 bytes

```<code>#include <stdio.h>
main(){{FILE*f=fopen("a","w+");fprintf(f," ");fclose(f);}main();}
</code>```

Title: Shortest code for infinite disk I/O

Body:
C, 92 bytes

#include <stdio.h>
main(){for(FILE*f=fopen("a","w+");fprintf(f," "),!fclose(f);;);return 0;}

While it looks like you could save 1 byte by

  for(FILE*f=fopen("a","w+");fprintf(f," ")+fclose(f);;){}

the problem with that loop is that + doesn't give you the guaranteed order.

Or recursive - shouldn't overflow if the compiler properly implements tail recursion (f is in an explicit inner scope)

85 bytes

#include <stdio.h>
main(){{FILE*f=fopen("a","w+");fprintf(f," ");fclose(f);}main();}


问:
Write a program that converts unary input to binary, decimal, and hexadecimal equivalents
Write a program that accepts input (through stdin) as a string of unary numbers delimited by spaces, and prints the equivalent string of numbers in binary, decimal, and hexadecimal. These unary symbols are allowed:

stroke, '/' or '\'

Decimal 1

ASCII 'I'

ASCII '-'

Your program does not have to support all symbols, but it must use at least one. Zero should be represented as simply two spaces (the lack of unary symbols)

e.g. if the input is

Test Cases:

Input:

```<code>1 11 111 1111111111
</code>```

Example Output:

```<code>1 2 3 10

1 2 3 A

1 10 11 1010
</code>```

Output must be to standard output. If no standard output is available, use whatever output logging stream is available.

It does not have to print the converted strings in any particular order; it must print the binary, hexadecimal, and decimal string equivalents, but it does not have to print in that specific order.

This is code-golf, so shortest program wins!

答:
Java, 136 bytes

s->{String[]l=s.split(" ",-1);s="";for(int i=2;i<17;i+=i<3?8:6){for(String n:l)s+=Integer.toString(n.length(),i)+" ";s+="\n";}return s;}
```

Try it online!

This is an anonymous function (lambda) that takes a String and returns a String representing the output as described.

Full explanation will come later today.

Body:
Java, 136 bytes

s->{String[]l=s.split(" ",-1);s="";for(int i=2;i<17;i+=i<3?8:6){for(String n:l)s+=Integer.toString(n.length(),i)+" ";s+="\n";}return s;}

Try it online!

This is an anonymous function (lambda) that takes a String and returns a String representing the output as described.

Full explanation will come later today.


答:
Haskell, 20 bytes

```<code>f=writeFile"b""a">>f
</code>```

Write the string "a" to a file named "b" and repeat. writeFile overwrites the file if it exists.

Title: Shortest code for infinite disk I/O

Body:
Haskell, 20 bytes

f=writeFile"b""a">>f

Write the string "a" to a file named "b" and repeat. writeFile overwrites the file if it exists.


问:
Determine the type of an input
The challenge is simple: Determine the type of an input, and output an identifier telling what type it is.

"UI", Unsigned integer: 0, 1,34, 111111111111111111111111111111111111111111

"SI", Signed integer: +0, +1, +42, -1, -3, -111111111111111111111111111111111111111111

"UD", Unsigned decimal: 0.0, 1.23, 1234.1234

"SD", Signed decimal: -0.0, +0.0, -1.235

"LE", Letter: a-z and A-Z

"SY", Symbol: ASCII code points: [32-47, 58-64, 91-96, 123-126] (i.e. all characters except numbers and letters)

"ST", String: Two or more character that can't be parsed as any of the above number formats

Rules:

The input will be 1-99 characters long

The input will only contain printable ASCII characters, code points: 32-126.

The output should be the two identifier letters as defined above (UI, SI ...)

Standard I/O rules apply

Examples:

```<code>UI:
0
01
34
12938219383278319086135768712319838871631827319218923

SI:
-0
+01
+1
-123
+123

UD:
0.0
3.1415
2.718281828459045235360287471352662497757

SD:
+0.0
-3.1415
+2.718281828459045235360287471352662497757

LE:
a
k
L
Z

SY:
@
"
+
-

ST:
Hello, World!
f2!"
+23df
1234A
'"!
.012
1.
UI
+-1
5+3
</code>```

答:
Tcl 414 Bytes

ungolfed implementation, readable:

```<code>proc a b {
  if {[string index $b 0] eq "+" || [string index $b 0] eq "-"} {
    set c S
  } elseif {[string match {[A-Za-z]} $b]} {
    return LE
  } elseif {[regexp {^(?![+-]?\d+(\.\d+)?$)..+} $b]} {
    return ST
  } elseif {[regexp {[^a-zA-Z0-9.]} $b]} {
    return SY
  } else {
    set c U
  }
  if {[string match *.* $b]} {
    return $c\U
  } else {
    return $c\I
  }
}
puts [a $argv]
</code>```

Title: Determine the type of an input

Body:
Tcl 414 Bytes

ungolfed implementation, readable:

proc a b {
  if {[string index $b 0] eq "+" || [string index $b 0] eq "-"} {
    set c S
  } elseif {[string match {[A-Za-z]} $b]} {
    return LE
  } elseif {[regexp {^(?![+-]?\d+(\.\d+)?$)..+} $b]} {
    return ST
  } elseif {[regexp {[^a-zA-Z0-9.]} $b]} {
    return SY
  } else {
    set c U
  }
  if {[string match *.* $b]} {
    return $c\U
  } else {
    return $c\I
  }
}
puts [a $argv]


问:
Open the browser to http://codegolf.stackexchange.com
Your job is to open a browser window of the default browser to http://codegolf.stackexchange.com.

Your code must open the browser itself, and cannot rely on an open one.

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

Moderator note: A large number of answers to this challenge use the URLs http://ppcg.lol or http://ppcg.ga. These URLs did direct to https://codegolf.stackexchange.com at the time, but have since expired. By this meta discussion, they have been allowed to stay, with the note that they are currently invalid.

答:
Game Maker Studio, 26 bytes

```<code>url_open('http://ppcg.ga')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Game Maker Studio, 26 bytes

url_open('http://ppcg.ga')


问:
Make this code explanation pretty again

Introduction

Most code-golfers here add explanations to their submissions, so it's easier to understand what's going on. Usually the codelines go on the left and the corresponding explanation to the right with some kind of separator. To make it look pretty, the separators are all on the same column. Also long explanation text is usually wrapped to the next line, so the readers don't have to scroll horizontally to read everything.

However, when you want to edit this explanation because you made some crazy golfs, you often end up spending time to make your explanation pretty again. Since this is a very repetitive task, you want to write a program for this.

The Challenge

Given several lines of code with explanation and a separator, output the nicely formatted code with explanation.

Example

Input

```
shM-crz1dc4."ANDBYOROF  # z = input

     rz1      # convert input to uppercase
    c   d        # split input on spaces
         c4."ANDBYOROF        # create a list of the words from a packed string which shall be ignored
   -          # filter those words out
 hM                # only take the first letter of all words
s                   # join them into one string
```

Output

```
shM-crz1dc4."ANDBYOROF     # z = input

     rz1                   # convert input to uppercase
    c   d                  # split input on spaces
         c4."ANDBYOROF     # create a list of the words from a packed string which shall be
                           # ignored
   -                       # filter those words out
 hM                        # only take the first letter of all words
s                          # join them into one string
```

One cookie for the first one who can find out what this code does.

The formatting algorithm

Find the longest code-line (excluding the explanation and the spaces between code and separator).

Add 5 spaces after this code-line and append the corresponding separator with explanation. This is now the reference line.

Adjust every other line to this reference line, so that the seperators are all in the same column.

Wrap all lines that are longer than 93 characters to a new line in the following way:

Find the last word which end is at column 93 or lower.

Take all words after this one and wrap them to a new line with the leading separator and the correct spacing. The space between those two words has to be deleted, so the first line ends with a word character and the second line starts with one after the separator.

If the resulting line is still longer than 93 characters do the same again until every line is below 94 characters.

Notes

A word consists of non-whitespace characters. Words are separated by a single space.

The word wrapping is always possible. This means that no word is so long that it would make the wrapping impossible.

The input will only contain printable ASCII and won't have any trailing whitespaces

The separator will only appear once per line.

While the explanation can have unlimited length, the separator and the code can only have a combined maximum length of 93 - 5 = 87 chars. The 5 chars are the spaces between code and separator. Code and separator will always be at least one character long.

The input may contain empty lines. Those will never contain any characters (except a newline if you take input as multiline string). Those empty lines have to be present in the output as well.

Every line will have some code, a separator and an explanation. Exceptions are empty lines.

You may take the input in any reasonable format, as long as it is not pre-processed. Make it clear in your answer which one you use.

Output can be a multiline string or a list of strings.

Rules

Function or full program allowed.

Default rules for input/output.

Standard loopholes apply.

This is code-golf, so lowest byte-count wins. Tiebreaker is earlier submission.

Test cases

Input format here is a list of string representing the lines and a single string for the separator. Both are separated by a comma. Output is a list of strings.

```
['shM-crz1dc4."ANDBYOROF  # z = input', '', '     rz1      # convert input to uppercase', '    c   d        # split input on spaces', '         c4."ANDBYOROF        # create a list of the words from a packed string which shall be ignored', '   -          # filter those words out', ' hM                # only take the first letter of all words', 's                   # join them into one string'], "# " -> ['shM-crz1dc4."ANDBYOROF     # z = input', '', '     rz1                   # convert input to uppercase', '    c   d                  # split input on spaces', '         c4."ANDBYOROF     # create a list of the words from a packed string which shall be', '                           # ignored', '   -                       # filter those words out', ' hM                        # only take the first letter of all words', 's                          # join them into one string']
['codecodecode   e#Explanation', 'sdf dsf sdf e#A Very very very very very very very very very long long long long long long long long long long long explanation and it keeps getting longer and longer', '', 'some more codee#  and some more explanation'], "e#" -> ['codecodecode       e#Explanation', 'sdf dsf sdf        e#A Very very very very very very very very very long long long long long ', '                   e#long long long long long long explanation and it keeps getting longer', '                   e#and longer', '', 'some more code     e# and some more explanation']
```

Happy Coding!

答:
MATLAB, <s>270</s> <s>265</s> 262 bytes

```<code>function d=f(I,s);S=@sprintf;R=@regexprep;m=regexp(I,['\s*\',s]);L=max([m{:}])+4;a=@(x)S('%-*s%s',L,x,s);b=@(x)R(R(x,S('(.{1,%d}(\\s+|$))',93-L),S('$1\n%*s ',L+1,s)),['\n\s*\',s,' $'],'');c=R(I,['(.*?)\s*\',s,'\s*(.*$)'],'${a($1)} ${b($2)}');d=S('%s\n',c{:});end
</code>```

The program accepts the input I in the form of a cell array of strings where each element of the cell array is a separate line of the input. It also accepts a second input which indicates what the comment character is (i.e. #). The function returns a multi-line string that is properly formatted.

Brief Explanation

```<code>function d = f(I,s)
    %// Setup some shortcuts for commonly-used functions
    S = @sprintf;
    R = @regexprep;

    %// Find the location of the space AFTER each code block but before a comment
    m = regexp(I, ['\s*\',s]);

    %// Compute the maximum column location of the code and add 4 (5 - 1)
    L = max([m{:}]) + 4;

    %// This is a callback for when we detect code
    %// It left justifies and pads the string to L width
    a = @(x)S('%-*s%s', L, x, s);

    %// This is a callback for when we detect a comment.
    b = @(x)R(...
            R(x, ...
                S('(.{1,%d}(\\s|$))', 93 - L), ... Regex for wrapping text to desired width
                S('$1\n%*s ', L+1, s)), ... Append a newline and padding for next line
            ['\n\s*\',s,' $'], ''); ... Remove the trailing newline (to be improved)

    %// Perform replacement of everything.
    c = R(I, ...
            ['(.*?)\s*\',s,'\s*(.*$)'], ... Match "code comment_char comment"
            '${a($1)} ${b($2)}');   ... Replace using the output of the callbacks

    %// Concatenate all of the strings together with a newline in between
    d=S('%s\n',c{:});
end
</code>```

Example Input

```<code>I = {
    'shM-crz1dc4."ANDBYOROF  # z = input'
    ''
    '     rz1      # convert input to uppercase'
    '    c   d        # split input on spaces'
    '         c4."ANDBYOROF        # create a list of the words from a packed string which shall be ignored'
    '   -          # filter those words out'
    ' hM                # only take the first letter of all words'
    's                   # join them into one string'
};

disp(f(I,'#'));
</code>```

Example Output

```<code>shM-crz1dc4."ANDBYOROF     # z = input

     rz1                   # convert input to uppercase
    c   d                  # split input on spaces
         c4."ANDBYOROF     # create a list of the words from a packed string which shall be
                           # ignored
   -                       # filter those words out
 hM                        # only take the first letter of all words
s                          # join them into one string
</code>```

Title: Make this code explanation pretty again

Body:
MATLAB, <s>270</s> <s>265</s> 262 bytes

function d=f(I,s);S=@sprintf;R=@regexprep;m=regexp(I,['\s*\',s]);L=max([m{:}])+4;a=@(x)S('%-*s%s',L,x,s);b=@(x)R(R(x,S('(.{1,%d}(\\s+|$))',93-L),S('$1\n%*s ',L+1,s)),['\n\s*\',s,' $'],'');c=R(I,['(.*?)\s*\',s,'\s*(.*$)'],'${a($1)} ${b($2)}');d=S('%s\n',c{:});end

The program accepts the input I in the form of a cell array of strings where each element of the cell array is a separate line of the input. It also accepts a second input which indicates what the comment character is (i.e. #). The function returns a multi-line string that is properly formatted.

Brief Explanation

function d = f(I,s)
    %// Setup some shortcuts for commonly-used functions
    S = @sprintf;
    R = @regexprep;

    %// Find the location of the space AFTER each code block but before a comment
    m = regexp(I, ['\s*\',s]);

    %// Compute the maximum column location of the code and add 4 (5 - 1)
    L = max([m{:}]) + 4;

    %// This is a callback for when we detect code
    %// It left justifies and pads the string to L width
    a = @(x)S('%-*s%s', L, x, s);

    %// This is a callback for when we detect a comment.
    b = @(x)R(...
            R(x, ...
                S('(.{1,%d}(\\s|$))', 93 - L), ... Regex for wrapping text to desired width
                S('$1\n%*s ', L+1, s)), ... Append a newline and padding for next line
            ['\n\s*\',s,' $'], ''); ... Remove the trailing newline (to be improved)

    %// Perform replacement of everything.
    c = R(I, ...
            ['(.*?)\s*\',s,'\s*(.*$)'], ... Match "code comment_char comment"
            '${a($1)} ${b($2)}');   ... Replace using the output of the callbacks

    %// Concatenate all of the strings together with a newline in between
    d=S('%s\n',c{:});
end

Example Input

I = {
    'shM-crz1dc4."ANDBYOROF  # z = input'
    ''
    '     rz1      # convert input to uppercase'
    '    c   d        # split input on spaces'
    '         c4."ANDBYOROF        # create a list of the words from a packed string which shall be ignored'
    '   -          # filter those words out'
    ' hM                # only take the first letter of all words'
    's                   # join them into one string'
};

disp(f(I,'#'));

Example Output

shM-crz1dc4."ANDBYOROF     # z = input

     rz1                   # convert input to uppercase
    c   d                  # split input on spaces
         c4."ANDBYOROF     # create a list of the words from a packed string which shall be
                           # ignored
   -                       # filter those words out
 hM                        # only take the first letter of all words
s                          # join them into one string


问:
Tweetable hash function challenge
In this code-challenge you will write a hash function in 140 bytes1 or less of source code. The hash function must take an ASCII string as input, and return a 24-bit unsigned integer ([0, 224-1]) as output.

Your hash function will be evaluated for every word in this large British English dictionary2. Your score is the amount of words that share a hash value with another word (a collision).

The lowest score wins, ties broken by first poster.

Test case

Before submitting, please test your scoring script on the following input:

```<code>duplicate
duplicate
duplicate
duplicate
</code>```

If it gives any score other than 4, it is buggy.

Clarifying rules:

Your hash function must run on a single string, not a whole array. Also, your hash function may not do any other I/O than the input string and output integer.

Built-in hash functions or similar functionality (e.g. encryption to scramble bytes) is disallowed.

Your hash function must be deterministic.

Contrary to most other contests optimizing specifically for the scoring input is allowed.

1 I am aware Twitter limits characters instead of bytes, but for simplicity we will use bytes as a limit for this challenge.

2 Modified from Debian's wbritish-huge, removing any non-ASCII words.

答:
Java 8, 7054 6467

This is inspired by (but not copied from) the builtin java.lang.String.hashCode function, so feel free to disallow according to rule #2.

```<code>w -> { return w.chars().reduce(53, (acc, c) -> Math.abs(acc * 79 + c)) % 16777216; };
</code>```

To score:

```<code>import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

public class TweetableHash {
    public static void main(String[] args) throws Exception {
        List<String> words = Files.readAllLines(Paths.get("british-english-huge.txt"));

        Function<String, Integer> hashFunc = w -> { return w.chars().reduce(53, (acc, c) -> Math.abs(acc * 79 + c)) % 16777216; };

        Map<Integer, Integer> hashes = new HashMap<>();
        for (String word : words) {
            int hash = hashFunc.apply(word);
            if (hash < 0 || hash >= 16777216) {
                throw new Exception("hash too long for word: " + word + " hash: " + hash);
            }

            Integer numOccurences = hashes.get(hash);
            if (numOccurences == null) {
                numOccurences = 0;
            }
            numOccurences++;

            hashes.put(hash, numOccurences);
        }

        int numCollisions = hashes.values().stream().filter(i -> i > 1).reduce(Integer::sum).get();
        System.out.println("num collisions: " + numCollisions);
    }
}
</code>```

Title: Tweetable hash function challenge

Body:
Java 8, 7054 6467

This is inspired by (but not copied from) the builtin java.lang.String.hashCode function, so feel free to disallow according to rule #2.

w -> { return w.chars().reduce(53, (acc, c) -> Math.abs(acc * 79 + c)) % 16777216; };

To score:

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

public class TweetableHash {
    public static void main(String[] args) throws Exception {
        List<String> words = Files.readAllLines(Paths.get("british-english-huge.txt"));

        Function<String, Integer> hashFunc = w -> { return w.chars().reduce(53, (acc, c) -> Math.abs(acc * 79 + c)) % 16777216; };

        Map<Integer, Integer> hashes = new HashMap<>();
        for (String word : words) {
            int hash = hashFunc.apply(word);
            if (hash < 0 || hash >= 16777216) {
                throw new Exception("hash too long for word: " + word + " hash: " + hash);
            }

            Integer numOccurences = hashes.get(hash);
            if (numOccurences == null) {
                numOccurences = 0;
            }
            numOccurences++;

            hashes.put(hash, numOccurences);
        }

        int numCollisions = hashes.values().stream().filter(i -> i > 1).reduce(Integer::sum).get();
        System.out.println("num collisions: " + numCollisions);
    }
}


答:
sh, 11 bytes

```<code>w>w;exec $0
</code>```

Save this to a file without special characters, such as loop.sh, make it executable, and run it with ./loop.sh or similar.

This writes the output of the command w to the file w, overwriting the previous value each time. Then, it replaces itself with a fresh version of the same program, so it can run infinitely.

Title: Shortest code for infinite disk I/O

Body:
sh, 11 bytes

w>w;exec $0

Save this to a file without special characters, such as loop.sh, make it executable, and run it with ./loop.sh or similar.

This writes the output of the command w to the file w, overwriting the previous value each time. Then, it replaces itself with a fresh version of the same program, so it can run infinitely.


答:
Pyth - 47 bytes

Can prolly golf a few bytes off with some slicing tricks.

```<code>.x-+?@z"+-"\S\U?@z\.\D\Isz?!tz?}rzZG"LE""SY""ST
</code>```

Test Suite.

Title: Determine the type of an input

Body:
The challenge is simple: Determine the type of an input, and output an identifier telling what type it is.

"UI", Unsigned integer: 0, 1,34, 111111111111111111111111111111111111111111

"SI", Signed integer: +0, +1, +42, -1, -3, -111111111111111111111111111111111111111111

"UD", Unsigned decimal: 0.0, 1.23, 1234.1234

"SD", Signed decimal: -0.0, +0.0, -1.235

"LE", Letter: a-z and A-Z

"SY", Symbol: ASCII code points: [32-47, 58-64, 91-96, 123-126] (i.e. all characters except numbers and letters)

"ST", String: Two or more character that can't be parsed as any of the above number formats

Rules:

The input will be 1-99 characters long

The input will only contain printable ASCII characters, code points: 32-126.

The output should be the two identifier letters as defined above (UI, SI ...)

Standard I/O rules apply

Examples:

```<code>UI:
0
01
34
12938219383278319086135768712319838871631827319218923

SI:
-0
+01
+1
-123
+123

UD:
0.0
3.1415
2.718281828459045235360287471352662497757

SD:
+0.0
-3.1415
+2.718281828459045235360287471352662497757

LE:
a
k
L
Z

SY:
@
"
+
-

ST:
Hello, World!
f2!"
+23df
1234A
'"!
.012
1.
UI
+-1
5+3
</code>```

Body:
Pyth - 47 bytes

Can prolly golf a few bytes off with some slicing tricks.

.x-+?@z"+-"\S\U?@z\.\D\Isz?!tz?}rzZG"LE""SY""ST

<a href="http://pyth.herokuapp.com/?code=.x-%2B%3F%40z%22%2B-%22%5CS%5CU%3F%40z%5C.%5CD%5CIsz%3F%21tz%3F%7DrzZG%22LE%22%22SY%22%22ST&test_suite=1&test_suite_input=0%0A01%0A34%0A12938219383278319086135768712319838871631827319218923%0A-0%0A%2B01%0A%2B1%0A-123%0A%2B123%0A0.0%0A3.1415%0A2.718281828459045235360287471352662497757%0A%2B0.0%0A-3.1415%0A%2B2.718281828459045235360287471352662497757%0Aa%0Ak%0AL%0AZ%0A%40%0A%22%0A%2B%0A-%0AHello%2C+World%21%0Af2%21%22%0A%2B23df%0A1234A%0A%27%22%21%0A.012%0A1.%0AUI%0A%2B-1%0A5%2B3&debug=0" rel="nofollow noreferrer">Test Suite.


问:
Ravenity of Cube Distance Numbers
Inspired by this Numberphile entry

Background

The cube distance numbers of an integer n are defined here as the set of integers that are x³ distance away for a given x. For a simple example, with n=100 and x=2, the cube distance numbers are {92,108}.

This can be extended into a larger set simply by varying x. With x ∈ {1,2,3,4} and the same n=100, we have the resultant set {36,73,92,99,101,108,127,164}.

Let's define CD(n,x) as the set of all integers n ± z³ with z ∈ {1,2,3,...,x}.

Now we can focus on some of the special properties of these cube distance numbers. Of the many special properties that numbers can have, the two properties we're interested in here are primality and prime divisors.

For the above example CD(100,4), note that 73, 101, 127 are all prime. If we remove those from the set, we're left with {36,92,99,108,164}. All prime divisors of these numbers are (in order) {2,2,3,3,2,2,23,3,3,11,2,2,3,3,3,2,2,41}, which means we have 5 distinct prime divisors {2,3,23,11,41}. We can therefore define that CD(100,4) has ravenity1 of 5.

The challenge here is to write a function or program, in the fewest bytes, that outputs the ravenity of a given input.

Input

Two positive integers, n and x, in any convenient format.

Output

A single integer describing the ravenity of the two input numbers, when calculated with CD(n,x).

Rules

Input/output can be via any suitable method.

Standard loophole restrictions apply.

For ease of calculation, you can assume that the input data will be such that CD(n,x) will only have positive numbers in the set (i.e., no CD(n,x) will ever have negative numbers or zero).

The function or program should be able to handle input numbers so that n + x³ fits in your language's native integer data type. For example, for a 32-bit signed integer type, all input numbers with n + x³ < 2147483648 are possible.

Examples

```<code>n,x   - output
2,1   - 0   (since CD(2,1)={1,3}, distinct prime divisors={}, ravenity=0)
5,1   - 2
100,4 - 5
720,6 - 11
</code>```

Footnotes

1 - So named because we're not interested in the cardinality of the set, but a different type of bird. Since we're dealing with "common" divisors, I chose to use the common raven.

答:
Pyth - <s>21</s> <s>19</s> 18 bytes

I wonder if there's a trick.

```<code>l{st#mP+Q^d3s_BMSE
</code>```

Test Suite.

```<code>l                   Length
 {                  Uniquify
  s                 Combine divisor lists
   t#               Filter by if more than one element
     PM             Take prime factorization of each number
       +RQ          Add each num in list to input
          s_BM      Each num in list and its negative (with bifurcate)
              ^R3   Cube each num in list
                 SE Inclusive unary range - [1, 2, 3,... n] to input
</code>```

Title: Ravenity of Cube Distance Numbers

Body:
Pyth - <s>21</s> <s>19</s> 18 bytes

I wonder if there's a trick.

l{st#mP+Q^d3s_BMSE

Test Suite.

l                   Length
 {                  Uniquify
  s                 Combine divisor lists
   t#               Filter by if more than one element
     PM             Take prime factorization of each number
       +RQ          Add each num in list to input
          s_BM      Each num in list and its negative (with bifurcate)
              ^R3   Cube each num in list
                 SE Inclusive unary range - [1, 2, 3,... n] to input


答:
Julia, 107 bytes

f(n,x)=endof(∪(foldl(vcat,map(k->[keys(factor(k))...],filter(i->!isprime(i),[n+z^3for z=[-x:-1;1:x]])))))
```

<p>This is a function that accepts two integers and returns an integer.</p>

<p>Ungolfed:</p>

<pre class="lang-default prettyprint-override"><code>function f(n, x)
    # Get all cube distance numbers
    cubedist = [n + z^3 for z = [-x:-1; 1:x]]

    # Filter out the primes and zeros
    noprimes = filter(i -> !isprime(i) && i > 0, cubedist)

    # Factor each remaining number
    factors = map(k -> [keys(factor(k))...], noprimes)

    # Flatten the list of factors
    flat = foldl(vcat, factors)

    # Return the number of unique elements
    return endof(∪(flat))
end
</code>```

Title: Ravenity of Cube Distance Numbers

Body:
Inspired by this Numberphile entry

Background

The cube distance numbers of an integer n are defined here as the set of integers that are x³ distance away for a given x. For a simple example, with n=100 and x=2, the cube distance numbers are {92,108}.

This can be extended into a larger set simply by varying x. With x ∈ {1,2,3,4} and the same n=100, we have the resultant set {36,73,92,99,101,108,127,164}.

Let's define CD(n,x) as the set of all integers n ± z³ with z ∈ {1,2,3,...,x}.

Now we can focus on some of the special properties of these cube distance numbers. Of the many special properties that numbers can have, the two properties we're interested in here are primality and prime divisors.

For the above example CD(100,4), note that 73, 101, 127 are all prime. If we remove those from the set, we're left with {36,92,99,108,164}. All prime divisors of these numbers are (in order) {2,2,3,3,2,2,23,3,3,11,2,2,3,3,3,2,2,41}, which means we have 5 distinct prime divisors {2,3,23,11,41}. We can therefore define that CD(100,4) has ravenity1 of 5.

The challenge here is to write a function or program, in the fewest bytes, that outputs the ravenity of a given input.

Input

Two positive integers, n and x, in any convenient format.

Output

A single integer describing the ravenity of the two input numbers, when calculated with CD(n,x).

Rules

Input/output can be via any suitable method.

Standard loophole restrictions apply.

For ease of calculation, you can assume that the input data will be such that CD(n,x) will only have positive numbers in the set (i.e., no CD(n,x) will ever have negative numbers or zero).

The function or program should be able to handle input numbers so that n + x³ fits in your language's native integer data type. For example, for a 32-bit signed integer type, all input numbers with n + x³ < 2147483648 are possible.

Examples

```<code>n,x   - output
2,1   - 0   (since CD(2,1)={1,3}, distinct prime divisors={}, ravenity=0)
5,1   - 2
100,4 - 5
720,6 - 11
</code>```

Footnotes

1 - So named because we're not interested in the cardinality of the set, but a different type of bird. Since we're dealing with "common" divisors, I chose to use the common raven.

Body:
Julia, 107 bytes

f(n,x)=endof(∪(foldl(vcat,map(k->[keys(factor(k))...],filter(i->!isprime(i),[n+z^3for z=[-x:-1;1:x]])))))

This is a function that accepts two integers and returns an integer.

Ungolfed:

function f(n, x)
    # Get all cube distance numbers
    cubedist = [n + z^3 for z = [-x:-1; 1:x]]

    # Filter out the primes and zeros
    noprimes = filter(i -> !isprime(i) && i > 0, cubedist)

    # Factor each remaining number
    factors = map(k -> [keys(factor(k))...], noprimes)

    # Flatten the list of factors
    flat = foldl(vcat, factors)

    # Return the number of unique elements
    return endof(∪(flat))
end


答:
Matlab, 30828 8620 6848

It builds the hash by assigning a prime number to each ascii character/position combo and calculating their product for each word modulo the largest prime smaller than 2^24.  Note that for testing I moved the call to primes outside into the tester directly before the while loop and passed it into the hash function, because it sped it up by about a factor of 1000, but this version works, and is self-contained.  It may crash with words longer than about 40 characters.

```<code>function h = H(s)
p = primes(1e6);
h = 1;
for i=1:length(s)
    h = mod(h*p(double(s(i))*i),16777213);
end
end
</code>```

Tester:

```<code>clc
clear variables
close all

file = fopen('british-english-huge.txt');
hashes = containers.Map('KeyType','uint64','ValueType','uint64');

words = 0;
p = primes(1e6);
while ~feof(file)
    words = words + 1;
    word = fgetl(file);
    hash = H(word,p);
    if hashes.isKey(hash)
        hashes(hash) = hashes(hash) + 1;
    else
        hashes(hash) = 1;
    end
end

collisions = 0;
for key=keys(hashes)

    if hashes(key{1})>1
        collisions = collisions + hashes(key{1});
    end
end
</code>```

Title: Tweetable hash function challenge

Body:
In this code-challenge you will write a hash function in 140 bytes1 or less of source code. The hash function must take an ASCII string as input, and return a 24-bit unsigned integer ([0, 224-1]) as output.

Your hash function will be evaluated for every word in this large British English dictionary2. Your score is the amount of words that share a hash value with another word (a collision).

The lowest score wins, ties broken by first poster.

Test case

Before submitting, please test your scoring script on the following input:

```<code>duplicate
duplicate
duplicate
duplicate
</code>```

If it gives any score other than 4, it is buggy.

Clarifying rules:

Your hash function must run on a single string, not a whole array. Also, your hash function may not do any other I/O than the input string and output integer.

Built-in hash functions or similar functionality (e.g. encryption to scramble bytes) is disallowed.

Your hash function must be deterministic.

Contrary to most other contests optimizing specifically for the scoring input is allowed.

1 I am aware Twitter limits characters instead of bytes, but for simplicity we will use bytes as a limit for this challenge.

2 Modified from Debian's wbritish-huge, removing any non-ASCII words.

Body:
Matlab, 30828 8620 6848

It builds the hash by assigning a prime number to each ascii character/position combo and calculating their product for each word modulo the largest prime smaller than 2^24.  Note that for testing I moved the call to primes outside into the tester directly before the while loop and passed it into the hash function, because it sped it up by about a factor of 1000, but this version works, and is self-contained.  It may crash with words longer than about 40 characters.

function h = H(s)
p = primes(1e6);
h = 1;
for i=1:length(s)
    h = mod(h*p(double(s(i))*i),16777213);
end
end

Tester:

clc
clear variables
close all

file = fopen('british-english-huge.txt');
hashes = containers.Map('KeyType','uint64','ValueType','uint64');

words = 0;
p = primes(1e6);
while ~feof(file)
    words = words + 1;
    word = fgetl(file);
    hash = H(word,p);
    if hashes.isKey(hash)
        hashes(hash) = hashes(hash) + 1;
    else
        hashes(hash) = 1;
    end
end

collisions = 0;
for key=keys(hashes)

    if hashes(key{1})>1
        collisions = collisions + hashes(key{1});
    end
end


答:
CJam, 6273

```<code>{49f^245b16777213%}
</code>```

XOR each character with 49, reduce the resulting string via x, y ↦ 245x + y, and take the residue modulo 16,777,213 (the largest 24-bit prime).

Scoring

```<code>$ cat hash.cjam
qN% {49f^245b16777213%} %N*N
$ all=$(wc -l < british-english-huge.txt)
$ unique=$(cjam hash.cjam < british-english-huge.txt | sort | uniq -u | wc -l)
$ echo $[all - unique]
6273
</code>```

Title: Tweetable hash function challenge

Body:
CJam, 6273

{49f^245b16777213%}

XOR each character with 49, reduce the resulting string via x, y ↦ 245x + y, and take the residue modulo 16,777,213 (the largest 24-bit prime).

Scoring

$ cat hash.cjam
qN% {49f^245b16777213%} %N*N
$ all=$(wc -l < british-english-huge.txt)
$ unique=$(cjam hash.cjam < british-english-huge.txt | sort | uniq -u | wc -l)
$ echo $[all - unique]
6273


答:
Javascript (ES5), 6765

This is CRC24 shaved down to 140 Bytes.  Could golf more but wanted to get my answer in :)

function(s){c=0xb704ce;i=0;while(s[i]){c^=(s.charCodeAt(i++)&255)<<16;for(j=0;j++<8;){c<<=1;if(c&0x1000000)c^=0x1864cfb}}return c&0xffffff}
```

<p>Validator in node.js:</p>

<pre class="lang-js prettyprint-override"><code>var col = new Array(16777215);
var n = 0;

var crc24_140 =
function(s){c=0xb704ce;i=0;while(s[i]){c^=(s.charCodeAt(i++)&255)<<16;for(j=0;j++<8;){c<<=1;if(c&0x1000000)c^=0x1864cfb}}return c&0xffffff}

require('fs').readFileSync('./dict.txt','utf8').split('\n').map(function(s){
    var h = crc24_140(s);
    if (col[h]===1) {
        col[h]=2;
        n+=2;
    } else if (col[h]===2) {
        n++;
    } else {
        col[h]=1;
    }
});

console.log(n);
</code>```

Title: Tweetable hash function challenge

Body:
Javascript (ES5), 6765

This is CRC24 shaved down to 140 Bytes.  Could golf more but wanted to get my answer in :)

function(s){c=0xb704ce;i=0;while(s[i]){c^=(s.charCodeAt(i++)&255)<<16;for(j=0;j++<8;){c<<=1;if(c&0x1000000)c^=0x1864cfb}}return c&0xffffff}

Validator in node.js:

var col = new Array(16777215);
var n = 0;

var crc24_140 =
function(s){c=0xb704ce;i=0;while(s[i]){c^=(s.charCodeAt(i++)&255)<<16;for(j=0;j++<8;){c<<=1;if(c&0x1000000)c^=0x1864cfb}}return c&0xffffff}

require('fs').readFileSync('./dict.txt','utf8').split('\n').map(function(s){
    var h = crc24_140(s);
    if (col[h]===1) {
        col[h]=2;
        n+=2;
    } else if (col[h]===2) {
        n++;
    } else {
        col[h]=1;
    }
});

console.log(n);


答:
Ruby, <s>132</s> <s>120</s> 114 bytes

I'm well aware that this solution still needs a lot of golfing. Any golfing tips are welcome.

require'prime'
->n,x{(-x..x).map{|i|j=n+i**3;j.prime?||(j==n)?[]:j.prime_division.map{|z|z[0]}}.flatten.uniq.size}
```

<p><strong>Ungolfing:</strong></p>

<pre class="lang-ruby prettyprint-override"><code>require 'prime'

def ravenity(n, x)
  z = []
  (-x..x).each do |i|
    j = n + i**3
    m = j.prime_division
    if j.prime? || j == n
      z << []
    else
      z << m.map{|q| q[0]}
    end
  return z.flatten.uniq.size
end
</code>```

Title: Ravenity of Cube Distance Numbers

Body:
Ruby, <s>132</s> <s>120</s> 114 bytes

I'm well aware that this solution still needs a lot of golfing. Any golfing tips are welcome.

require'prime'
->n,x{(-x..x).map{|i|j=n+i**3;j.prime?||(j==n)?[]:j.prime_division.map{|z|z[0]}}.flatten.uniq.size}

Ungolfing:

require 'prime'

def ravenity(n, x)
  z = []
  (-x..x).each do |i|
    j = n + i**3
    m = j.prime_division
    if j.prime? || j == n
      z << []
    else
      z << m.map{|q| q[0]}
    end
  return z.flatten.uniq.size
end


问:
Which is better - Emacs or Vim? (Google fight)
Greetings, noble code golfers. Today you will resolve the most ancient and distinguished of debates - Emacs or Vim?

Your challenge is to take two search terms as input, and output which of those terms has the most Google search results. (This is obviously completely fair. What do you mean, biased?)

Here are some example inputs and outputs:

Input: emacs and vim

Output: vim (totally not creating any flamewars in the comments)

Input: google and microsoft

Output: google

Input: code golf stack exchange and code review stack exchange

Output: code golf stack exchange (yeah!)

And here are some edge cases just for fun (and for testing your solutions):

Input: About 1,000,000 results and About 100,000 results

Output: About 100,000 results

Input: This will autocotrect and Another testcase

Output: Another testcase (if you don't consider autocorrecting, then the first one will win)

For the following test cases, you must remove the # signs in the search terms first, since they rely on the term having a specific amount of results and posting the term here would ruin that.

Input: Thissear#chter#mhasno#results and Another testcase

Output: Another testcase (just a test for zero results)

Input: "These exact wo#rds do#n't exi#st# on the Internet" and Another testcase

Output: Another testcase (testing "s)

Input: Abo#ut 1,65#2,85#3,2#86 re#sults and Another testcase

Output: Another testcase (this one is tricky - the above search term has one result)

Input: "Abo#ut 4#8,234,8#75,14#7 res#ults" and Another testcase

Output: Another testcase (also tricky - no results, so it displays the search term)

You don't need to handle the corner-case of "quoted" searches returning "No results, showing results without quotes instead" because that would just be too complicated. You don't need to handle inputs with the same number of results either.

This is code-golf, so the shortest code in bytes will win!

答:
Powershell, <s>175</s>, 172 bytes

```<code>($args|%{[pscustomobject]@{'a'=$_;'b'=[int]((iwr "google.com/search?nord=1&q=$_&nfpr=1").parsedhtml.getelementbyid('resultstats').innertext-split" ")[1]}}|sort -des b).a[0]
</code>```

Showing the score as well as the name would cut 2 more bytes.

This uses the same unkillable feature as the 196 Byte Factor answer (Parsed HTML) and cuts down from the previous regex answer.

Body:
Powershell, <s>175</s>, 172 bytes

($args|%{[pscustomobject]@{'a'=$_;'b'=[int]((iwr "google.com/search?nord=1&q=$_&nfpr=1").parsedhtml.getelementbyid('resultstats').innertext-split" ")[1]}}|sort -des b).a[0]

Showing the score as well as the name would cut 2 more bytes.

This uses the same unkillable feature as the 196 Byte Factor answer (Parsed HTML) and cuts down from the previous regex answer.


答:
J, 30 bytes

```<code>#@~.@(,@:q:-.0&,)@:+(|#^&3)@i:
</code>```

This is a dyadic verb, used as follows:

```<code>   f =: #@~.@(,@:q:-.0&,)@:+(|#^&3)@i:
   100 f 4
5
</code>```

Try it here.

Explanation

```<code>#@~.@(,@:q:-.0&,)@:+(|#^&3)@i:
                            i:  Range from -x to x
                    (     )@    Apply this verb to the range:
                       ^&3        a) every item cubed
                     |            b) absolute value of every item
                      #           c) every item in a) repeated b) times; this removes 0
                                     and produces some harmless duplication
                   +            Add n to every element of the resulting list
     (          )@:             Apply this verb to the resulting vector:
             0&,                  a) the vector with 0 appended
      ,@:q:                       b) flat list of prime divisors in the vector
                                     (and some extra 0s since we flatten an un-even matrix)
           -.                     c) list b) with elements of a) removed; this gets rid of
                                     the extra 0s and all primes that were in the list
#@~.@                           Remove duplicates and take length
</code>```

Title: Ravenity of Cube Distance Numbers

Body:
J, 30 bytes

#@~.@(,@:q:-.0&,)@:+(|#^&3)@i:

This is a dyadic verb, used as follows:

   f =: #@~.@(,@:q:-.0&,)@:+(|#^&3)@i:
   100 f 4
5

Try it here.

Explanation

#@~.@(,@:q:-.0&,)@:+(|#^&3)@i:
                            i:  Range from -x to x
                    (     )@    Apply this verb to the range:
                       ^&3        a) every item cubed
                     |            b) absolute value of every item
                      #           c) every item in a) repeated b) times; this removes 0
                                     and produces some harmless duplication
                   +            Add n to every element of the resulting list
     (          )@:             Apply this verb to the resulting vector:
             0&,                  a) the vector with 0 appended
      ,@:q:                       b) flat list of prime divisors in the vector
                                     (and some extra 0s since we flatten an un-even matrix)
           -.                     c) list b) with elements of a) removed; this gets rid of
                                     the extra 0s and all primes that were in the list
#@~.@                           Remove duplicates and take length


答:
MATL, 21 bytes

```<code>:3^t_h+tZp~)"@Yf!]vun
</code>```

Input is x, n separated by a newline.

Try it online!

Explanation

```<code>:       % take n implicitly. Generate [1,2,...,n]
3^      % raise to 3, element-wise
t_h     % duplicate, negate, concatenate horizontally: [1,2,...,n,-1,2,...-n]
+       % take x implicitly. Add to that array
t       % duplicate
Zp      % array that contains true for primes
~       % logical negate
)       % apply index to keep only non-primes
"       % for each number in that array
  @     %   push that number
  Yf!   %   prime factors, as a column array
]       % end for each
v       % concatenate vertically all factors
u       % remove repeated factors
n       % number of elements of that array. Implicitly display
</code>```

Title: Ravenity of Cube Distance Numbers

Body:
MATL, 21 bytes

:3^t_h+tZp~)"@Yf!]vun

Input is x, n separated by a newline.

Try it online!

Explanation

:       % take n implicitly. Generate [1,2,...,n]
3^      % raise to 3, element-wise
t_h     % duplicate, negate, concatenate horizontally: [1,2,...,n,-1,2,...-n]
+       % take x implicitly. Add to that array
t       % duplicate
Zp      % array that contains true for primes
~       % logical negate
)       % apply index to keep only non-primes
"       % for each number in that array
  @     %   push that number
  Yf!   %   prime factors, as a column array
]       % end for each
v       % concatenate vertically all factors
u       % remove repeated factors
n       % number of elements of that array. Implicitly display


答:
05AB1E, <s>20</s> 19 bytes

Code:

```<code>L3mD(«-Dp_Ïvyf`})Úg
</code>```

Input in the form x, n. Uses CP-1252 encoding.

Try it online!

Title: Ravenity of Cube Distance Numbers

Body:
05AB1E, <s>20</s> 19 bytes

Code:

L3mD(«-Dp_Ïvyf`})Úg

Input in the form x, n. Uses CP-1252 encoding.

Try it online!


答:
Bash + coreutils, 10

yes \>b|sh
```

Writes a continuous stream of >b, which is piped to sh for evaluation.  >b simply truncates a file called b to zero bytes each time.

Title: Shortest code for infinite disk I/O

Body:
(Just open 50 tabs in Google Chrome :D (just kidding, no you can't))

Shortest code for infinite disk I/O any language, C# example:

using System.IO;

namespace FileApp {
    static class Program {
        public static void Main() {
            do {
                File.WriteAllText("a", "a");
                File.Delete("a");
            } while (true);
        }
    }
}
```

You can't just fill the entire disk though, as then it would halt in the end and would be finite.

And you can't do reading only, infinite writing has to happen. (It has to kill my SSD after enough runtime.)

Get cracking! :)

Body:
Bash + coreutils, 10

yes \>b|sh

Writes a continuous stream of >b, which is piped to sh for evaluation.  >b simply truncates a file called b to zero bytes each time.


答:
If you want a shorter (but more boring than my other one) answer:

Bash, 5 bytes

```<code>>w;$0
</code>```

I could make that shorter if there's a command (less than 3 bytes long) that writes something to disk I/O.  Something like sync would work, but sync is 4 bytes

Note: this doesn't work when run straight from bash, only when put in a script and run as the script name. (i.e. echo 'w>w;$0' > bomb; chmod 755 bomb; ./bomb)

Title: Shortest code for infinite disk I/O

Body:
If you want a shorter (but more boring than my other one) answer:

Bash, 5 bytes

>w;$0

I could make that shorter if there's a command (less than 3 bytes long) that writes something to disk I/O.  Something like sync would work, but sync is 4 bytes

Note: this doesn't work when run straight from bash, only when put in a script and run as the script name. (i.e. echo 'w>w;$0' > bomb; chmod 755 bomb; ./bomb)


答:
Python, 5333 4991

I believe this is the first contender to score significantly better than a random oracle.

def H(s):n=int(s.encode('hex'),16);return n%(8**8-ord('+%:5O![/5;QwrXsIf]\'k#!__u5O}nQ~{;/~{CutM;ItulA{uOk_7"ud-o?y<Cn~-`bl_Yb'[n%70]))
```

Title: Tweetable hash function challenge


答:
PARI/GP, 79 bytes

```<code>(n,x)->omega(factorback(select(k->!isprime(k),vector(2*x,i,n+(i-(i<=x)-x)^3))))
</code>```

Here is my original straightforward implementation. The optimized version above combines the two vectors into a single, slightly more complicated vector.

```<code>(n,x)->omega(factorback(select(k->!isprime(k),concat(vector(x,i,n-i^3),vector(x,i,n+i^3)))))
</code>```

Title: Ravenity of Cube Distance Numbers

Body:
PARI/GP, 79 bytes

(n,x)->omega(factorback(select(k->!isprime(k),vector(2*x,i,n+(i-(i<=x)-x)^3))))

Here is my original straightforward implementation. The optimized version above combines the two vectors into a single, slightly more complicated vector.

(n,x)->omega(factorback(select(k->!isprime(k),concat(vector(x,i,n-i^3),vector(x,i,n+i^3)))))


答:
Jelly, 16 bytes

```<code>ŒRḟ0*3+µÆfFœ-µQL
</code>```

Takes x and n as command-line arguments, in that order. Try it online!

How it works

```<code>ŒRḟ0*3+µÆfFœ-µQL  Main link. Arguments, x, n

ŒR                Range; yield [-x, ..., x].
  ḟ0              Filter out 0.
    *3            Cube each remaining integer.
      +           Add n to all cubes.
       µ          Begin a new, monadic link. Argument: A (list of sums)
        Æf        Factorize each k in A.
          F       Flatten the resulting, nested list.
           œ-     Perform multiset difference with A.
                  If k in A is prime, Æf returns [k], adding on k too many to the
                  flat list. Multiset difference with A removes exactly one k from
                  the results, thus getting rid of primes.
                  If k is composite (or 1), it cannot appear in the primes in the
                  flat list, so subtracting it does nothing.
             µ    Begin a new, monadic link. Argument: D (list of prime divisors)
              Q   Unique; deduplicate D.
               L  Compute the length of the result.
</code>```

Title: Ravenity of Cube Distance Numbers

Body:
Jelly, 16 bytes

ŒRḟ0*3+µÆfFœ-µQL

Takes x and n as command-line arguments, in that order. Try it online!

How it works

ŒRḟ0*3+µÆfFœ-µQL  Main link. Arguments, x, n

ŒR                Range; yield [-x, ..., x].
  ḟ0              Filter out 0.
    *3            Cube each remaining integer.
      +           Add n to all cubes.
       µ          Begin a new, monadic link. Argument: A (list of sums)
        Æf        Factorize each k in A.
          F       Flatten the resulting, nested list.
           œ-     Perform multiset difference with A.
                  If k in A is prime, Æf returns [k], adding on k too many to the
                  flat list. Multiset difference with A removes exactly one k from
                  the results, thus getting rid of primes.
                  If k is composite (or 1), it cannot appear in the primes in the
                  flat list, so subtracting it does nothing.
             µ    Begin a new, monadic link. Argument: D (list of prime divisors)
              Q   Unique; deduplicate D.
               L  Compute the length of the result.


答:
C#, 6251 6335

```<code>int H(String s){int h = 733;foreach (char c in s){h = (h * 533 + c);}return h & 0xFFFFFF;}
</code>```

The constants 533 and 733 889 and 155 give the best score out of all of the ones I've searched so far.

Title: Tweetable hash function challenge

Body:
C#, 6251 6335

int H(String s){int h = 733;foreach (char c in s){h = (h * 533 + c);}return h & 0xFFFFFF;}

The constants 533 and 733 889 and 155 give the best score out of all of the ones I've searched so far.


问:
Is this a Lucas number?
Write a program or function that takes an input greater than or equal to 2. It should output a truthy or falsy value corresponding to whether the input is a Lucas number or not. You may take input from STDIN, or whichever source is most suitable to you.

This question is different to this one because this question is specifically for Lucas numbers only, and not Fibonacci numbers at all, whereas that question was Lucas number, Fibonacci numbers and both possible combinations of them. This question was, however, inspired by that question and is similar in some regards.

Lucas numbers are the numbers that result from the rules following: the first Lucas number is a 2, the second is a 1, and each term after that is the sum of the previous two. Yes, it is very similar to the Fibonacci sequence, but this has the added advantage of converging closer to the golden ratio, phi, faster than Fibonacci numbers do.

Example inputs/outputs

```<code>Input   Output
--------------
3       True
4       True
7       True
8      False
10     False
3421   False
9349    True
</code>```

etc.

Some limitations

Your program/function must run in a reasonable amount of time. It should terminate within seconds and minutes, not hours and days.

Your program must not calculate all the Lucas numbers up to the input number

This is code golf, so the shortest code in bytes wins.

答:
Python, <s>69</s> <s>67</s> 53 characters

```<code>lambda x:0in(((5*x**2+20)**.5)%1,((5*x**2-20)**.5)%1)
</code>```

This works in both Python 2.x and 3.x.

See this answer to see how it works - n is a Lucas number if either 5n^2+20 or 5n^2-20 is a perfect square. My program checks to see if either of their square roots are integers and checks if 0 is in the tuple that results.

Title: Is this a Lucas number?

Body:
Python, <s>69</s> <s>67</s> 53 characters

lambda x:0in(((5*x**2+20)**.5)%1,((5*x**2-20)**.5)%1)

This works in both Python 2.x and 3.x.

See this answer to see how it works - n is a Lucas number if either 5n^2+20 or 5n^2-20 is a perfect square. My program checks to see if either of their square roots are integers and checks if 0 is in the tuple that results.


答:
Python, <s>45</s> 43 characters

lambda n:0in[(5*n*n+k)**.5%1for k in-20,20]
```

Based on a proof given here.

Title: Is this a Lucas number?

Body:
Write a program or function that takes an input greater than or equal to 2. It should output a truthy or falsy value corresponding to whether the input is a Lucas number or not. You may take input from STDIN, or whichever source is most suitable to you.

This question is different to this one because this question is specifically for Lucas numbers only, and not Fibonacci numbers at all, whereas that question was Lucas number, Fibonacci numbers and both possible combinations of them. This question was, however, inspired by that question and is similar in some regards.

Lucas numbers are the numbers that result from the rules following: the first Lucas number is a 2, the second is a 1, and each term after that is the sum of the previous two. Yes, it is very similar to the Fibonacci sequence, but this has the added advantage of converging closer to the golden ratio, phi, faster than Fibonacci numbers do.

Example inputs/outputs

```<code>Input   Output
--------------
3       True
4       True
7       True
8      False
10     False
3421   False
9349    True
</code>```

etc.

Some limitations

Your program/function must run in a reasonable amount of time. It should terminate within seconds and minutes, not hours and days.

Your program must not calculate all the Lucas numbers up to the input number

This is code golf, so the shortest code in bytes wins.

Body:
Python, <s>45</s> 43 characters

lambda n:0in[(5*n*n+k)**.5%1for k in-20,20]

Based on a proof given here.


答:
Ruby, 6473 collisions, 129 bytes

```<code>h=->(w){@p=@p||(2..999).select{|i|(2..i**0.5).select{|j|i%j==0}==[]};c=w.chars.reduce(1){|a,s|(a*@p[s.ord%92]+179)%((1<<24)-3)}}
</code>```

The @p variable is filled with all the primes below 999.

This converts ascii values into primes numbers and takes their product modulo a large prime. The fudge factor of 179 deals with the fact that the original algorithm was for use in finding anagrams, where all words that are rearrangements of the same letters get the same hash. By adding the factor in the loop, it makes anagrams have distinct codes.

I could remove the **0.5 (sqrt test for prime) at the expense of poorer performance to shorten the code. I could even make the prime number finder execute in the loop to remove nine more characters, leaving 115 bytes.

To test, the following tries to find the best value for the fudge factor in the range 1 to 300. It assume that the word file in in the /tmp directory:

```<code>h=->(w,y){
  @p=@p||(2..999).
    select{|i|(2..i**0.5).
    select{|j|i%j==0}==[]};
  c=w.chars.reduce(1){|a,s|(a*@p[s.ord%92]+y)%((1<<24)-3)}
}

american_dictionary = "/usr/share/dict/words"
british_dictionary = "/tmp/british-english-huge.txt"
words = (IO.readlines british_dictionary).map{|word| word.chomp}.uniq
wordcount = words.size

fewest_collisions = 9999
(1..300).each do |y|
  whash = Hash.new(0)
  words.each do |w|
    code=h.call(w,y)
    whash[code] += 1
  end
  hashcount = whash.size
  collisions = whash.values.select{|count| count > 1}.inject(:+)
  if (collisions < fewest_collisions)
    puts "y = #{y}. #{collisions} Collisions. #{wordcount} Unique words. #{hashcount} Unique hash values"
    fewest_collisions = collisions
  end
end
</code>```

Title: Tweetable hash function challenge

Body:
In this code-challenge you will write a hash function in 140 bytes1 or less of source code. The hash function must take an ASCII string as input, and return a 24-bit unsigned integer ([0, 224-1]) as output.

Your hash function will be evaluated for every word in this large British English dictionary2. Your score is the amount of words that share a hash value with another word (a collision).

The lowest score wins, ties broken by first poster.

Test case

Before submitting, please test your scoring script on the following input:

```<code>duplicate
duplicate
duplicate
duplicate
</code>```

If it gives any score other than 4, it is buggy.

Clarifying rules:

Your hash function must run on a single string, not a whole array. Also, your hash function may not do any other I/O than the input string and output integer.

Built-in hash functions or similar functionality (e.g. encryption to scramble bytes) is disallowed.

Your hash function must be deterministic.

Contrary to most other contests optimizing specifically for the scoring input is allowed.

1 I am aware Twitter limits characters instead of bytes, but for simplicity we will use bytes as a limit for this challenge.

2 Modified from Debian's wbritish-huge, removing any non-ASCII words.

Body:
Ruby, 6473 collisions, 129 bytes

h=->(w){@p=@p||(2..999).select{|i|(2..i**0.5).select{|j|i%j==0}==[]};c=w.chars.reduce(1){|a,s|(a*@p[s.ord%92]+179)%((1<<24)-3)}}

The @p variable is filled with all the primes below 999.

This converts ascii values into primes numbers and takes their product modulo a large prime. The fudge factor of 179 deals with the fact that the original algorithm was for use in finding anagrams, where all words that are rearrangements of the same letters get the same hash. By adding the factor in the loop, it makes anagrams have distinct codes.

I could remove the **0.5 (sqrt test for prime) at the expense of poorer performance to shorten the code. I could even make the prime number finder execute in the loop to remove nine more characters, leaving 115 bytes.

To test, the following tries to find the best value for the fudge factor in the range 1 to 300. It assume that the word file in in the /tmp directory:

h=->(w,y){
  @p=@p||(2..999).
    select{|i|(2..i**0.5).
    select{|j|i%j==0}==[]};
  c=w.chars.reduce(1){|a,s|(a*@p[s.ord%92]+y)%((1<<24)-3)}
}

american_dictionary = "/usr/share/dict/words"
british_dictionary = "/tmp/british-english-huge.txt"
words = (IO.readlines british_dictionary).map{|word| word.chomp}.uniq
wordcount = words.size

fewest_collisions = 9999
(1..300).each do |y|
  whash = Hash.new(0)
  words.each do |w|
    code=h.call(w,y)
    whash[code] += 1
  end
  hashcount = whash.size
  collisions = whash.values.select{|count| count > 1}.inject(:+)
  if (collisions < fewest_collisions)
    puts "y = #{y}. #{collisions} Collisions. #{wordcount} Unique words. #{hashcount} Unique hash values"
    fewest_collisions = collisions
  end
end


答:
MATLAB, 43 bytes

```<code>@(n)~all(rem(real(sqrt(5*n^2+[-20 20])),1))
</code>```

Inspired by Anders Kaseorg's answer

Title: Is this a Lucas number?

Body:
MATLAB, 43 bytes

@(n)~all(rem(real(sqrt(5*n^2+[-20 20])),1))

Inspired by Anders Kaseorg's answer


答:
Python 3.5, 218 198 bytes:

(Thanks to @Blue for saving me 20 bytes.)

```<code>lambda r,n:len({z for z in{v for f in{t for u in[[r-q**3,r+q**3]for q in range(1,n+1)]for t in u if any(t%g<1 for g in range(2,t))}for v in range(2,f)if f%v<1}if all(z%g>0 for g in range(2,z))})
</code>```

A nice one-lined lambda function, although it may be a bit long. Since I was using Python, I had to come up with my own way of finding the composites for the first step, and then the prime divisors for the last step, so it was not very easy, and this was the shortest I, by myself. could get it to. Nonetheless, it does what it needs to, and I am proud of it. :) However, any tips for golfing this down a bit more are welcome.

Title: Ravenity of Cube Distance Numbers

Body:
Inspired by this Numberphile entry

Background

The cube distance numbers of an integer n are defined here as the set of integers that are x³ distance away for a given x. For a simple example, with n=100 and x=2, the cube distance numbers are {92,108}.

This can be extended into a larger set simply by varying x. With x ∈ {1,2,3,4} and the same n=100, we have the resultant set {36,73,92,99,101,108,127,164}.

Let's define CD(n,x) as the set of all integers n ± z³ with z ∈ {1,2,3,...,x}.

Now we can focus on some of the special properties of these cube distance numbers. Of the many special properties that numbers can have, the two properties we're interested in here are primality and prime divisors.

For the above example CD(100,4), note that 73, 101, 127 are all prime. If we remove those from the set, we're left with {36,92,99,108,164}. All prime divisors of these numbers are (in order) {2,2,3,3,2,2,23,3,3,11,2,2,3,3,3,2,2,41}, which means we have 5 distinct prime divisors {2,3,23,11,41}. We can therefore define that CD(100,4) has ravenity1 of 5.

The challenge here is to write a function or program, in the fewest bytes, that outputs the ravenity of a given input.

Input

Two positive integers, n and x, in any convenient format.

Output

A single integer describing the ravenity of the two input numbers, when calculated with CD(n,x).

Rules

Input/output can be via any suitable method.

Standard loophole restrictions apply.

For ease of calculation, you can assume that the input data will be such that CD(n,x) will only have positive numbers in the set (i.e., no CD(n,x) will ever have negative numbers or zero).

The function or program should be able to handle input numbers so that n + x³ fits in your language's native integer data type. For example, for a 32-bit signed integer type, all input numbers with n + x³ < 2147483648 are possible.

Examples

```<code>n,x   - output
2,1   - 0   (since CD(2,1)={1,3}, distinct prime divisors={}, ravenity=0)
5,1   - 2
100,4 - 5
720,6 - 11
</code>```

Footnotes

1 - So named because we're not interested in the cardinality of the set, but a different type of bird. Since we're dealing with "common" divisors, I chose to use the common raven.

Body:
Python 3.5, 218 198 bytes:

(Thanks to @Blue for saving me 20 bytes.)

lambda r,n:len({z for z in{v for f in{t for u in[[r-q**3,r+q**3]for q in range(1,n+1)]for t in u if any(t%g<1 for g in range(2,t))}for v in range(2,f)if f%v<1}if all(z%g>0 for g in range(2,z))})

A nice one-lined lambda function, although it may be a bit long. Since I was using Python, I had to come up with my own way of finding the composites for the first step, and then the prime divisors for the last step, so it was not very easy, and this was the shortest I, by myself. could get it to. Nonetheless, it does what it needs to, and I am proud of it. :) However, any tips for golfing this down a bit more are welcome.


问:
Javascript left-pad golf

Introduction

In the wake of the left-pad npm package fallout, let's have a code golf for implementing left-pad.

The left-pad function consists of 2 default arguments and 1 additional argument, in the form string, length, (padchar). If the padchar is not given, this is standardized to a space character. Let's take an example with two arguments:

```<code>left_pad("abc", 6)
</code>```

First, we observe the length of the string, which is 3. After this, we need to pad this string in the left until the length of the full string has reached the length given in the function. In this case 6. Since the padchar is not given, we need to pad this with spaces:

```<code>   abc
</code>```

This is a string with 3 spaces and the initial string, resulting into a string with length 6. Here is an example with the padchar given:

```<code>left_pad("abc", 6, "-")
</code>```

We just do the same as the example above, but replace the spaces with the padchar. In this case, the hyphen:

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

The Task

Given the string, length, and maybe the additional argument padchar, output the left-padded string. You can assume that the length number is equal or greater than the length of the string. The padchar will always consist of 1 character.

Test cases

```<code>left_pad("string", length, ("padchar")) === "left-padded string"

left_pad("foo", 5) === "  foo"
left_pad("foobar", 6) === "foobar"
left_pad("1", 2, "0") === "01"
left_pad("1", 2, "-") === "-1"
</code>```

This is code-golf, so the submission with the smallest number of bytes wins!

答:
Ruby, 42 bytes

```<code>def left_pad(s,t,p=" ");p*(t-s.size)+s;end
</code>```

Parameters: string, size, padchar.

Test suite below; should print all "true"s, just put everything in the same file.

```<code>puts left_pad("foo", 5) == "  foo"
puts left_pad("foobar", 6) == "foobar"
puts left_pad("1", 2, "0") == "01"
puts left_pad("1", 2, "-") == "-1"
</code>```

Title: Javascript left-pad golf

Body:
Ruby, 42 bytes

def left_pad(s,t,p=" ");p*(t-s.size)+s;end

Parameters: string, size, padchar.

Test suite below; should print all "true"s, just put everything in the same file.

puts left_pad("foo", 5) == "  foo"
puts left_pad("foobar", 6) == "foobar"
puts left_pad("1", 2, "0") == "01"
puts left_pad("1", 2, "-") == "-1"


答:
MATL, <s>19</s> <s>17</s> <s>16</s> 18 bytes

```<code>2^5*20t_h+X^Xj1\~a
</code>```

Try it Online!

Explanation

```<code>2^          % Implicitly grab the input and square it
5*          % Multiply the result by 5
20          % Create the literal number 20
t_          % Duplicate and negate the second 20
h           % Concatenate 20 and -20 to get [20 -20]
+           % Add the array to the result of 5*n^2
X^          % Compute the square root
Xj          % Ensure that the result is a real number
1\          % Compute the remainder to test for perfect squares
~a          % Check to see if any had a remainder of zero (returns a boolean)
</code>```

Title: Is this a Lucas number?

Body:
MATL, <s>19</s> <s>17</s> <s>16</s> 18 bytes

2^5*20t_h+X^Xj1\~a

Try it Online!

Explanation

2^          % Implicitly grab the input and square it
5*          % Multiply the result by 5
20          % Create the literal number 20
t_          % Duplicate and negate the second 20
h           % Concatenate 20 and -20 to get [20 -20]
+           % Add the array to the result of 5*n^2
X^          % Compute the square root
Xj          % Ensure that the result is a real number
1\          % Compute the remainder to test for perfect squares
~a          % Check to see if any had a remainder of zero (returns a boolean)


答:
bash / GNU coreutils, 60 bytes

sed -e's/\b'{and,o[rf],by}'\W*//Ig' -re's/(\w)\S* ?/\u\1/g'

Title: Making an acronym

Body:
Objective

Your goal is to make a program that converts an input to its acronym. Your input is guaranteed to have only letters and spaces. The input will have exactly one space between words. You must output the acronym of the input.

Rules

Your code cannot be case-sensitive(e.g. foo and Foo are the same)

Your code must ignore the following words and not put them in the acronym:
and or by of

You cannot assume that the words are all lowercase.

The output must be entirely capitalised, with no separation between characters.

A trailing newline is accepted but not necessary.

If your language has an acronym function builtin, you may not use it.

Examples

(inputs/outputs grouped)

```<code>United States of America
USA

Light Amplification by Stimulation of Emitted Radiation
LASER

united states of america
USA

Jordan Of the World
JTW
</code>```

Scoring

This is a code-golf challenge so the shortest code wins.

Leaderboard

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```


答:
TI-BASIC, 12 bytes

```<code>While 1
Archive A
UnArchive A
End
</code>```

Alternate solution by user lirtosiast with the same size:

```<code>While 1
SetUpEditor
Archive ∟1
End
</code>```

This will work on the TI-83+ and TI-84+ series of calculators.

Yes, this also works if A is already archived or is not initialized at all at the start of the program! The program is only 12 bytes because of tokenization.

Title: Shortest code for infinite disk I/O

Body:
(Just open 50 tabs in Google Chrome :D (just kidding, no you can't))

Shortest code for infinite disk I/O any language, C# example:

using System.IO;

namespace FileApp {
    static class Program {
        public static void Main() {
            do {
                File.WriteAllText("a", "a");
                File.Delete("a");
            } while (true);
        }
    }
}
```

You can't just fill the entire disk though, as then it would halt in the end and would be finite.

And you can't do reading only, infinite writing has to happen. (It has to kill my SSD after enough runtime.)

Get cracking! :)

Body:
TI-BASIC, 12 bytes

While 1
Archive A
UnArchive A
End

Alternate solution by user lirtosiast with the same size:

While 1
SetUpEditor
Archive ∟1
End

This will work on the TI-83+ and TI-84+ series of calculators.

Yes, this also works if A is already archived or is not initialized at all at the start of the program! The program is only 12 bytes because of tokenization.


答:
Ruby, 9309 collisions, 107 bytes

```<code>def hash(s);require'prime';p=Prime.first(70);(0...s.size).reduce(0){|a,i|a+=p[i]**(s[i].ord)}%(2**24-1);end
</code>```

Not a good contender, but I wanted to explore a different idea from other entries.

Assign the first n primes to the first n positions of the string, then sum all prime[i] ** (ascii code of string[i]), then mod 2**24-1.

Title: Tweetable hash function challenge

Body:
Ruby, 9309 collisions, 107 bytes

def hash(s);require'prime';p=Prime.first(70);(0...s.size).reduce(0){|a,i|a+=p[i]**(s[i].ord)}%(2**24-1);end

Not a good contender, but I wanted to explore a different idea from other entries.

Assign the first n primes to the first n positions of the string, then sum all prime[i] ** (ascii code of string[i]), then mod 2**24-1.


问:
Trump needs your help to stop the Starman!
A man from the stars has come to Earth! Luckily the president of the United States, Donald Trump, has an infinity-sided die. Using this die, he can conjure up a number which you, the mayor of Podunk, must use to determine who should be sent to stop the invader! But be careful, you can only send a limited amount of bytes on the back of your frog!

Given a user input (which will be a positive integer), you must return a string depending on what category the number is in.

If the number is a Fibonacci number, you must output Ness.

If the number is a Lucas number, you must output Lucas.

If the number is both a Lucas number and a Fibonacci number, you must output Travis.

If the number is neither a a Lucas number nor a Fibonacci number, you must output Pippi.

Examples

Here are a bunch of test cases:

```
1 => Travis
2 => Travis
3 => Travis
4 => Lucas
5 => Ness
6 => Pippi
7 => Lucas
8 => Ness
610 => Ness
722 => Pippi
843 => Lucas
```

Rules

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

You program may be a full program or a(n anonymous) function.

Bonuses

There are a couple bonuses that you can use to help your frog get the data to President Trump faster:

For -15 bytes: If the input number is 2016, you must output Trump, as he is at the peak of his presidency.

答:
MATLAB, <s>122</s> 119 bytes

```<code>@(n)subsref({'Pippi','Lucas','Ness','Travis'},substruct('{}',{(1:2)*any(~rem(real(sqrt(5*n^2+[-20,-4;20,4])),1)).'+1}))
</code>```

Brief Explanation

We first create a cell array containing the values to print: {'Pippi', 'Lucas', 'Ness', 'Travis'}. Then to figure out which value to display, we check to see whether n is a Fibonacci or Lucas number.

For Fibonnaci, we use the following formula:

```<code>any(~rem(sqrt(5*n^2 + [-4 4]), 1))
</code>```

This checks to see if either 5*n^2 + 4 or 5*n^2 - 4 are a perfect square. If any of them are, then it is a Fibonacci number.

The formula for a Lucas number is very similar with the exception that we use +/- 20 instead of 4:

```<code>any(~rem(sqrt(5*n^2 + [-20 20]), 1))
</code>```

In this solution I combined these two cases into one by using the matrix:

```<code>M = [-20 -4
      20  4]

</code>```

By applying the same equation as those above, but force any to consider only the first dimension, I get a two element logical array where if the first element is true, then it is a Lucas number and if the second element is true, it is a fibonacci number.

```<code>any(~rem(sqrt(5*n^2 + [-20 -4;20 4]), 1))
</code>```

Then to compute the index into my initial cell array, I treat this as a binary sequence by performing element-wise multiplication of this boolean with [2^0, 2^1] or simply [1,2]. And sum the elements. Obviously I have to add 1 because of MATLAB's one-based indexing.

```<code>index = (1:2) * any(~rem(real(sqrt(5*n^2+[-20,-4;20,4])),1)).' + 1;
</code>```

Then I have to use subsref and substruct to index into the initial cell array to obtain the final result.

Body:
MATLAB, <s>122</s> 119 bytes

@(n)subsref({'Pippi','Lucas','Ness','Travis'},substruct('{}',{(1:2)*any(~rem(real(sqrt(5*n^2+[-20,-4;20,4])),1)).'+1}))

Brief Explanation

We first create a cell array containing the values to print: {'Pippi', 'Lucas', 'Ness', 'Travis'}. Then to figure out which value to display, we check to see whether n is a Fibonacci or Lucas number.

For Fibonnaci, we use the following formula:

any(~rem(sqrt(5*n^2 + [-4 4]), 1))

This checks to see if either 5*n^2 + 4 or 5*n^2 - 4 are a perfect square. If any of them are, then it is a Fibonacci number.

The formula for a Lucas number is very similar with the exception that we use +/- 20 instead of 4:

any(~rem(sqrt(5*n^2 + [-20 20]), 1))

In this solution I combined these two cases into one by using the matrix:

M = [-20 -4
      20  4]

By applying the same equation as those above, but force any to consider only the first dimension, I get a two element logical array where if the first element is true, then it is a Lucas number and if the second element is true, it is a fibonacci number.

any(~rem(sqrt(5*n^2 + [-20 -4;20 4]), 1))

Then to compute the index into my initial cell array, I treat this as a binary sequence by performing element-wise multiplication of this boolean with [2^0, 2^1] or simply [1,2]. And sum the elements. Obviously I have to add 1 because of MATLAB's one-based indexing.

index = (1:2) * any(~rem(real(sqrt(5*n^2+[-20,-4;20,4])),1)).' + 1;

Then I have to use subsref and substruct to index into the initial cell array to obtain the final result.


答:
Octave, 93 bytes

```<code>@(n){'Pippi','Lucas','Ness','Travis'}{(1:2)*any(~rem(real(sqrt(5*n^2+[-20,-4;20,4])),1)).'+1}
</code>```

This approach is similar to my MATLAB answer with the exception that Octave allows you to index directly into a fresh array:

```<code>{'a', 'b', 'c'}{2}    %// b
</code>```

Title: Trump needs your help to stop the Starman!

Body:
A man from the stars has come to Earth! Luckily the president of the United States, Donald Trump, has an infinity-sided die. Using this die, he can conjure up a number which you, the mayor of Podunk, must use to determine who should be sent to stop the invader! But be careful, you can only send a limited amount of bytes on the back of your frog!

Given a user input (which will be a positive integer), you must return a string depending on what category the number is in.

If the number is a Fibonacci number, you must output Ness.

If the number is a Lucas number, you must output Lucas.

If the number is both a Lucas number and a Fibonacci number, you must output Travis.

If the number is neither a a Lucas number nor a Fibonacci number, you must output Pippi.

Examples

Here are a bunch of test cases:

```
1 => Travis
2 => Travis
3 => Travis
4 => Lucas
5 => Ness
6 => Pippi
7 => Lucas
8 => Ness
610 => Ness
722 => Pippi
843 => Lucas
```

Rules

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

You program may be a full program or a(n anonymous) function.

Bonuses

There are a couple bonuses that you can use to help your frog get the data to President Trump faster:

For -15 bytes: If the input number is 2016, you must output Trump, as he is at the peak of his presidency.

Body:
Octave, 93 bytes

@(n){'Pippi','Lucas','Ness','Travis'}{(1:2)*any(~rem(real(sqrt(5*n^2+[-20,-4;20,4])),1)).'+1}

This approach is similar to my MATLAB answer with the exception that Octave allows you to index directly into a fresh array:

{'a', 'b', 'c'}{2}    %// b


答:
Perl 5, <s>27</s> <s>32</s> 22 bytes

```<code>{{open my$h,'>o'}redo}
</code>```

If simply changing the modification timestamp of a file suffices...

Quick explanation:

```<code>{ # Braces implicitly create/mark a loop.
    { # They also create closures, for `my` variables.
        open my $filehandle, '>', 'o';    # Writing to file "o".
        # close $filehandle;   # Called implicitly when
                               # variable gets destroyed.
    } # $filehandle gets destroyed because there are no references to it.
    redo; # ...the loop.
}
</code>```

Previous solution (32 bytes): {{open my$h,'>o';print$h 1}redo}

Edit: {open F,'O';print F 1;redo} ← Didn't test the code before posting; now I had to correct it.

Title: Shortest code for infinite disk I/O

Body:
Perl 5, <s>27</s> <s>32</s> 22 bytes

{{open my$h,'>o'}redo}

If simply changing the modification timestamp of a file suffices...

Quick explanation:

{ # Braces implicitly create/mark a loop.
    { # They also create closures, for `my` variables.
        open my $filehandle, '>', 'o';    # Writing to file "o".
        # close $filehandle;   # Called implicitly when
                               # variable gets destroyed.
    } # $filehandle gets destroyed because there are no references to it.
    redo; # ...the loop.
}

Previous solution (32 bytes): {{open my$h,'>o';print$h 1}redo}

Edit: {open F,'O';print F 1;redo} ← Didn't test the code before posting; now I had to correct it.


答:
JavaScript (ES6), 97 bytes

```<code>x=>[['Pippi','Lucas'],['Ness','Travis'],f=(a,x,y=1)=>a>x?f(a,y,x+y):a==x||a==1][+f(x,0)][+f(x,2)]
</code>```

The a==1 check is needed otherwise I don't notice that 1 is a Lucas number.

Body:
JavaScript (ES6), 97 bytes

x=>[['Pippi','Lucas'],['Ness','Travis'],f=(a,x,y=1)=>a>x?f(a,y,x+y):a==x||a==1][+f(x,0)][+f(x,2)]

The a==1 check is needed otherwise I don't notice that 1 is a Lucas number.


答:
Ruby, 138 bytes

```<code>->(n,x){require'prime'
v=((-x..x).to_a-[0]).map{|i|n+i**3}.reject{|e|Prime.prime?(e)}
Prime.each(v[-1]).select{|i|v.any?{|e|e%i==0}}.size}
</code>```

It was a puny challenge. :-)

Title: Ravenity of Cube Distance Numbers

Body:
Ruby, 138 bytes

->(n,x){require'prime'
v=((-x..x).to_a-[0]).map{|i|n+i**3}.reject{|e|Prime.prime?(e)}
Prime.each(v[-1]).select{|i|v.any?{|e|e%i==0}}.size}

It was a puny challenge. :-)


答:
MATL, <s>57</s> <s>55</s> <s>54</s> (67-15) = 52 bytes

```<code>20Kht_vi2^5*+X^Xj1\~a2:*sG2016=-'Lucas Ness Travis Trump Pippi'Ybw)
</code>```

Try it Online!

Explanation

Again, similar logic to my other answers here and here.

```<code>20      % Number literal
K       % Retrieve the number 4 from the K clipboard (the default value)
h       % Horizontal concatenation to produce [20 4]
t       % Duplicate elements
_v      % Negate and vertically append elements (yields [20, 4; -20 -4])
i2^     % Explicitly grab the input and square it
5*      % Multiply by 5
+       % Add this to the matrix ([20, 4; -20 -4])
X^      % Take the square root
Xj      % Ensure that the result is a real number
1\      % Get the decimal component
~       % Create a logical arrays where we have TRUE when no remainder
a       % For each column determine if any element is TRUE
2:      % Create the array 1:2
*       % Perform element-wise multiplication with boolean
s       % Sum the result to yield an index
G       % Explicitly grab the input (again)
2016=   % Check to see if it is 2016 (yields TRUE (1) if equal)
-       % Then subtract the boolean from the index. Since 2016 is NOT a
        % Fibonacci or Lucas number, the original index is 0. Subtracting
        % this boolean, will make this index now -1. For all other non-2016
        % numbers this will have no effect on the index.
'Lucas Ness Travis Trump Pippi' % Create the possible strings values
        % Note: the 0 index wraps around to the end hence Pippi being at the end.
        % The next to last entry ('Trump') is ONLY accessible via a -1 index as
        % discussed above
Yb      % Split at the spaces to create a cell array
w       % Flip the top two stack elements
)       % Retrieve the desired value from the cell array
</code>```

Body:
MATL, <s>57</s> <s>55</s> <s>54</s> (67-15) = 52 bytes

20Kht_vi2^5*+X^Xj1\~a2:*sG2016=-'Lucas Ness Travis Trump Pippi'Ybw)

Try it Online!

Explanation

Again, similar logic to my other answers here and here.

20      % Number literal
K       % Retrieve the number 4 from the K clipboard (the default value)
h       % Horizontal concatenation to produce [20 4]
t       % Duplicate elements
_v      % Negate and vertically append elements (yields [20, 4; -20 -4])
i2^     % Explicitly grab the input and square it
5*      % Multiply by 5
+       % Add this to the matrix ([20, 4; -20 -4])
X^      % Take the square root
Xj      % Ensure that the result is a real number
1\      % Get the decimal component
~       % Create a logical arrays where we have TRUE when no remainder
a       % For each column determine if any element is TRUE
2:      % Create the array 1:2
*       % Perform element-wise multiplication with boolean
s       % Sum the result to yield an index
G       % Explicitly grab the input (again)
2016=   % Check to see if it is 2016 (yields TRUE (1) if equal)
-       % Then subtract the boolean from the index. Since 2016 is NOT a
        % Fibonacci or Lucas number, the original index is 0. Subtracting
        % this boolean, will make this index now -1. For all other non-2016
        % numbers this will have no effect on the index.
'Lucas Ness Travis Trump Pippi' % Create the possible strings values
        % Note: the 0 index wraps around to the end hence Pippi being at the end.
        % The next to last entry ('Trump') is ONLY accessible via a -1 index as
        % discussed above
Yb      % Split at the spaces to create a cell array
w       % Flip the top two stack elements
)       % Retrieve the desired value from the cell array


答:
Mathematica, 14 bytes

```<code>For[,1>0,a>>a]
</code>```

Repeatedly writes the string "a" to a file named a in the current directory, creating it if it doesn't exist.

Title: Shortest code for infinite disk I/O

Body:
Mathematica, 14 bytes

For[,1>0,a>>a]

Repeatedly writes the string "a" to a file named a in the current directory, creating it if it doesn't exist.


问:
Code a code page

Introduction

A code page maps integer values to a specific character. We can visualize a code page like this:

```
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
|   | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| 0 | q | w | e | r | t | z | u | i | o | p | a | s | d | f | g | j |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| 1 | k | l | y | x | c | v | b | n | m | Q | W | E | R | T | Z | U |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| 2 | I | O | P | A | S | D | F | G | H | J |   |   |   |   |   |   |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
```

The rows specify the first digit and the columns the second digit of the hex-number.

The Challenge

Given a string of 16-255 unique characters, output the corresponding code page using the zero-based index of each character in the string as it's value.
The input qwertzuiopasdfgjklyxcvbnmQWERTZUIOPASDFGHJ for example would yield the table above.

The output has to be in the exact same format as the table above. Only a trailing newline is optional.

If the input length is not a multiple of 16, you need to start a new row for the remaining characters and leave the unused cells empty (=filled with 3 spaces).

Each character is placed exactly in the middle of a cell, padded by one space to the left and right.

The values in the first row and column are given by hex-numbers with the digits 0123456789ABCDEF. Those are padded with one space to the left and right as well. You may choose to use lowercase hex-digits but you need to stick to one.

The only characters present in the output are hyphens -, pluses +, pipes |, spaces  , the digits for hexadecimal numbers and the characters from the input.

Any builtins that are related to ASCII-art tables or trivialize the problem in any way are forbidden.

You may assume that the input consists only of characters of a specific encoding. Please specify if that is the case.

If your language can only handle ASCII input, you may assume ASCII-only input and repeated characters.

Rules

Function or full program allowed.

Default rules for input/output.

Standard loopholes apply.

This is code-golf, so lowest byte-count wins. Tiebreaker is earlier submission.

Happy Coding!

答:
Pyth, 60 bytes

```<code>
K+*"+---"hJ16\+Vm++"| "j" | "d" |"+]+]d.HMJ.e+.Hk.[bdJczJNK
</code>```

The leading newline is significant.

Try it here.

Title: Code a code page

Body:
Pyth, 60 bytes

K+*"+---"hJ16\+Vm++"| "j" | "d" |"+]+]d.HMJ.e+.Hk.[bdJczJNK

The leading newline is significant.

Try it here.