问:
A Fractional Year
My PPCG holiday is over :D

Intro

Fractional time is the year + (the value (minute of year) / number of minutes in the year).

Example calculation

You should assume that February always has 28 days and the year is always 365 days long.

Let's say we want to convert the time: 17:34 3rd March 2013 to fractional time. Firstly, you find how many minutes were in 2013: 525600 minutes. Let's call this x.

Next, you want to find out how many minutes there have been since the start of 2013. A few quick calculations will tell you that the answer is 88894 minutes:

There have been 61 days since the start of the year, which times 1440 (number of minutes in a day) equals 87840 minutes. In 17 hours are 1020 minutes (17*60). Now, we can add 87840, 1020 and 34 minutes to equal 88894 minutes.

Let's call this y.

Finally, you divide y by x and add the year, resulting in 2013.16912 (to 5 decimal places).

Input

The date and time will be given as a single string. The string will be in the following format:

```<code>YYYY-MM-DD hh:mm
</code>```

The time will always be in 24 hour format and the year will always be in the range 1900-2050 inclusive.

Examples

```<code>Input:  2016-08-06 23:48
Output: 2016.59723

Input:  2013-03-03 17:34
Output: 2013.16912

Input:  1914-11-11 11:11
Output: 1914.86155
</code>```

If you are going for the bounty, either ping me in the comments or in The Nineteenth Byte.

Challenge

Calculate the given date and time as a fractional year.

Give all output to five decimal places (you may round in anyway you wish: flooring, ceiling, or true rounding). Shortest code wins.

Bounty

I am offering a 100 rep bounty for the shortest program which also accepts the date in fractional year format and returns the time in YYYY-MM-DD hh:mm format. In essence, your program (or function) has to act in the following way:

```<code>f('1914-11-11 11:11') => 1914.86155
f('1914.86155')       => 1914-11-11 11:11
</code>```

t-clausen.dk - 154 bytes

Neil - 183 bytes

Leaderboard

var QUESTION_ID=88924,OVERRIDE_USER=30525;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

```

答:
JavaScript (ES6), 84 bytes

f=
s=>(Date.parse(1970+s.slice(4).replace(/ /,'T')+'Z')/31536e6+parseInt(s)).toFixed(5)
;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input placeholder=Input oninput=o.value=f(this.value)><input placeholder=Output id=o></code>```

Assuming no leap years or DST are required, I replace the year with 1970 which makes Date.parse directly return the time offset in milliseconds, of which there were 31536000000 in 1970 (or indeed any other non-leap year). All I need do then is to add back the year and round to 5 decimal places. Edit: Bidirectional conversion in <s>183</s> 178 bytes:

f=
s=>/:/.test(s,m=31536e6)?(Date.parse(1970+s.slice(4).replace(/ /,'T')+'Z')/m+parseInt(s)).toFixed(5):s.slice(0,4)+new Date(s.slice(4)*m+3e4).toJSON().slice(4,16).replace(/T/,' ')
;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input placeholder=Input oninput=o.value=f(this.value)><input placeholder=Output id=o></code>```

Assumes strings containing a : are time format, handled as above, otherwise strips off the year, converts to milliseconds, adds half a minute for rounding purposes, converts to a date in 1970, extracts the month, day, hour and minute, and prefixes the original year.

Title: A Fractional Year

Body:
JavaScript (ES6), 84 bytes

f=
s=>(Date.parse(1970+s.slice(4).replace(/ /,'T')+'Z')/31536e6+parseInt(s)).toFixed(5)
;

<input placeholder=Input oninput=o.value=f(this.value)><input placeholder=Output id=o>

Assuming no leap years or DST are required, I replace the year with 1970 which makes Date.parse directly return the time offset in milliseconds, of which there were 31536000000 in 1970 (or indeed any other non-leap year). All I need do then is to add back the year and round to 5 decimal places. Edit: Bidirectional conversion in <s>183</s> 178 bytes:

f=
s=>/:/.test(s,m=31536e6)?(Date.parse(1970+s.slice(4).replace(/ /,'T')+'Z')/m+parseInt(s)).toFixed(5):s.slice(0,4)+new Date(s.slice(4)*m+3e4).toJSON().slice(4,16).replace(/T/,' ')
;

<input placeholder=Input oninput=o.value=f(this.value)><input placeholder=Output id=o>

Assumes strings containing a : are time format, handled as above, otherwise strips off the year, converts to milliseconds, adds half a minute for rounding purposes, converts to a date in 1970, extracts the month, day, hour and minute, and prefixes the original year.


问:
A square of text

The Challenge

Given a string, output the text in the shape of a square.

You can assume that the text will always fit in a square, and that it will never be an empty string.

You can also assume it will never have newlines.

Example

```<code>Input:
Hi, world

Output:
Hi,
 wo
rld
</code>```

Test Cases

```<code>Input:
Hi, world! Hello

Output:
Hi,
worl
d! H
ello

Input:
Lorem ipsum dolor sit amt

Output:
Lorem
 ipsu
m dol
or si
t amt

Input:
H

Output:
H
</code>```

Rules

This is code-golf, so shortest answer in bytes wins! Tiebreaker is most upvoted answer.

Standard loopholes are forbidden.

答:
PHP, 51 bytes

```<code><?=join("
",str_split($x=$argv[1],strlen($x)**.5));
</code>```

ContentLicense: CC BY-SA 3.0

Title: A square of text

Body:
PHP, 51 bytes

<?=join("
",str_split($x=$argv[1],strlen($x)**.5));


问:
Golf an InterpretMe interpreter
This is a very simple challenge.

The joke language InterpretMe consists of one command; *, which causes the program to take input of an InterpretMe program and execute it.

An InterpretMe  program will interpret as many InterpretMe programs as there are * in input.

Your goal is to create a program that interprets InterpretMe in as few bytes as possible.

Input

Input will consist of one line ASCII strings, unicode utf-8 strings if you really want, or any character encoding that your language uses, if you want it that much. These strings can either be inputted at the start, or at the start of every run of InterpretMe interpreter. If they are all inputted at the start, the program must output every program line as it begins it.

Output

In this challenge, there will be no output unless the option of one input is chosen, otherwise only termination and non-termination

Test cases consist not of input and output, but input and termination. A newline denotes a new input to be interpreted as InterpretMe.

If using one input at the start, this could be considered what is outputted when these programs are inputted, followed by inactive (do nothing) lines.

```<code>1. *   (executes input as an interpret me program, finishes)
2. *   (^same)
3. **  (executes input as an interpret me program, then does this again after the first program is done, finishes)
4. hi  (nothing, first star of previous line finishes)
5. **  (same as the other two star line)
6. hi  (nothing, first star of previous line finishes)
7. hi  (nothing, second star of line 5 finishes, so second star of line 3 finishes, so line 2 finishes, so line one finishes)
[termination] (not outputted)
</code>```

```<code>hi  (does nothing and finishes)
[termination]
</code>```

```<code>*hi  (executes inputted program, finishes)
*yo  (executes inputted program, finishes)
hey  (nothing)
[termination]
</code>```

Again, this is code-golf, so fewer bytes is better

答:
05AB1E, 11 bytes

Code:

```<code>[¬'*QiIJ}¦Ž
</code>```

Explanation:

```<code>[            # Enter an infinite loop
 ¬           # Get the first character of the input string (leaves the input on the stack)
  '*Qi  }    # If equal to an asterisk...
      I      # Request another line of input and
       J     # Join it to the string that was left on the stack
         ¦   # Remove the first character
          Ž  # If everything is processed, terminate
</code>```

Uses the CP-1252 encoding. Try it online?.

Title: Golf an InterpretMe interpreter

Body:
05AB1E, 11 bytes

Code:

[¬'*QiIJ}¦Ž

Explanation:

[            # Enter an infinite loop
 ¬           # Get the first character of the input string (leaves the input on the stack)
  '*Qi  }    # If equal to an asterisk...
      I      # Request another line of input and
       J     # Join it to the string that was left on the stack
         ¦   # Remove the first character
          Ž  # If everything is processed, terminate

Uses the CP-1252 encoding. Try it online?.


答:
JavaScript (ES7), 49 bytes

```<code>s=>s.match(eval(`/.{${s.length**.5}}/g`)).join`
`
</code>```

44 bytes in Firefox Nightly 43-46 only (** was introduced some time between Firefox Nightly 42 and 43 and g as a separate parameter was removed some time between Firefox Nightly 46 and 47):

```<code>s=>s.match(`.{${s.length**.5}}`,`g`).join`
`
</code>```

Title: A square of text

Body:
The Challenge

Given a string, output the text in the shape of a square.

You can assume that the text will always fit in a square, and that it will never be an empty string.

You can also assume it will never have newlines.

Example

```<code>Input:
Hi, world

Output:
Hi,
 wo
rld
</code>```

Test Cases

```<code>Input:
Hi, world! Hello

Output:
Hi,
worl
d! H
ello

Input:
Lorem ipsum dolor sit amt

Output:
Lorem
 ipsu
m dol
or si
t amt

Input:
H

Output:
H
</code>```

Rules

This is code-golf, so shortest answer in bytes wins! Tiebreaker is most upvoted answer.

Standard loopholes are forbidden.

Body:
JavaScript (ES7), 49 bytes

s=>s.match(eval(`/.{${s.length**.5}}/g`)).join`
`

44 bytes in Firefox Nightly 43-46 only (** was introduced some time between Firefox Nightly 42 and 43 and g as a separate parameter was removed some time between Firefox Nightly 46 and 47):

s=>s.match(`.{${s.length**.5}}`,`g`).join`
`


问:
Count of "a"s and "b"s must be equal. Did you get it computer?
In the popular (and essential) computer science book, An Introduction to Formal Languages and Automata by Peter Linz, the following formal language is frequently stated:

$$\large{L=\{a^n b^n:n\in\mathbb{Z}^+\}}$$

mainly because this language can not be processed with finite-state automata.
This expression mean "Language L consists all strings of 'a's followed by 'b's, in which the number of 'a's and 'b's are equal and non-zero".

Challenge

Write a working program/function which gets a string, containing "a"s and "b"s only, as input and returns/outputs a truth value, saying if this string is valid the formal language L.

Your program cannot use any external computation tools, including network, external programs, etc. Shells are an exception to this rule; Bash, e.g., can use command line utilities.

Your program must return/output the result in a "logical" way, for example: returning 10 instead of 0, "beep" sound, outputting to stdout etc. More info here.

Standard code golf rules apply.

This is a code-golf. Shortest code in bytes wins. Good luck!

Truthy test cases

```<code>"ab"
"aabb"
"aaabbb"
"aaaabbbb"
"aaaaabbbbb"
"aaaaaabbbbbb"
</code>```

Falsy test cases

```<code>""
"a"
"b"
"aa"
"ba"
"bb"
"aaa"
"aab"
"aba"
"abb"
"baa"
"bab"
"bba"
"bbb"
"aaaa"
"aaab"
"aaba"
"abaa"
"abab"
"abba"
"abbb"
"baaa"
"baab"
"baba"
"babb"
"bbaa"
"bbab"
"bbba"
"bbbb"
</code>```

Leaderboard

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

/* Configuration */

var QUESTION_ID = 85994; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 48934; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '
' + c.body.replace(OVERRIDE_REG, '') + '
';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });

  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (/ b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

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

```

答:
R, 79 bytes

```<code>a=function(s){all(nchar(strsplit(s,"ab")[[1]])==nchar(s)/2-1)&&!grepl("ba",s)}
</code>```

Tests if when split on "ab" all substrings are the same precalculated length, and it tests if the pattern "ba" occurs anywhere.

ContentLicense: CC BY-SA 4.0

Body:
R, 79 bytes

a=function(s){all(nchar(strsplit(s,"ab")[[1]])==nchar(s)/2-1)&&!grepl("ba",s)}

Tests if when split on "ab" all substrings are the same precalculated length, and it tests if the pattern "ba" occurs anywhere.


答:
Perl 6, 38 bytes

$_=get;.put for .comb: .chars.sqrt.Int
```

<h3>Explanation:</h3>

<pre class="lang-perl6 prettyprint-override"><code>$_ = get;          # get a single line of input

$_.put             # print with trailing newline

for                # every one of the following:

$_.comb:           # the input split into

$_.chars.sqrt.Int  # chunks of the appropriate size
</code>```

Title: A square of text

Body:
Perl 6, 38 bytes

$_=get;.put for .comb: .chars.sqrt.Int

Explanation:

$_ = get;          # get a single line of input

$_.put             # print with trailing newline

for                # every one of the following:

$_.comb:           # the input split into

$_.chars.sqrt.Int  # chunks of the appropriate size


问:
Permute a string using Bit-Reversal
Previously, we computed the Bit-Reversal Permutation where we found how the order of indices would be permuted. In that case, we received an input n which was the order of the permutation of the indices where the length was 2n. However, this time, we are given a string of length m = 2k for some k. Now we want to apply the permutation indices of order k to a string.

Task

Your goal is to create a function or program that given a string where the length is a power of 2, output the permutation of it using bit-reversal.

As an example, the string 'codegolf' has length 8 which is a power of 2, that is 8 = 23. We learned in the previous challenge that the bit-reversal permutation of order 3 is [0, 4, 2, 6, 1, 5, 3, 7] which means that we select the characters from the input string using that order of indices.

```<code>Input                  Output
0 1 2 3 4 5 6 7        0 4 2 6 1 5 3 7
c o d e g o l f        c g d l o o e f
</code>```

This is one possible method of solving this task. Since we do not require the order of indices as output, there may be shorter algorithms which avoid generating the indices and rely on permuting characters only.

Test Cases

```<code>Input = Output
"z" = "z"
"cg" = "cg"
"code" = "cdoe"
"golf" = "glof"
"codegolf" = "cgdlooef"
"aaaazzzz" = "azazazaz"
"LynngDaie dneers" = "Legendary Dennis"
"hieroglyphically" = "hpoaeillihglrcyy"
"Programming Puzzles N' Code-Golf" = "PliorNPGosgem zlrenda'uog  -mCzf"
"super spectacular dazzling dream" = "srenrzcrpdt sllau cg zueeaadpiam"
</code>```

Rules

This is code-golf so the shortest code wins.

Builtins are allowed.

The input string will only be in ASCII. The length of the input string will always be a power of 2.

答:
Haskell, 72 bytes

This is "permuting characters only", but is it shorter than a different approach?

```<code>s(a:b:c)|(x,y)<-s c=(a:x,b:y)
s n=(n,n)
r a|[_]<-a=a|(x,y)<-s a=r x++r y
</code>```

s is a helper function to seperate the characters from even and odd positions, r is the bit reversal permutation function:

```<code>Prelude> r "codegolf"
"cgdlooef"
</code>```

Title: Permute a string using Bit-Reversal

Body:
Haskell, 72 bytes

This is "permuting characters only", but is it shorter than a different approach?

s(a:b:c)|(x,y)<-s c=(a:x,b:y)
s n=(n,n)
r a|[_]<-a=a|(x,y)<-s a=r x++r y

s is a helper function to seperate the characters from even and odd positions, r is the bit reversal permutation function:

Prelude> r "codegolf"
"cgdlooef"


Title: A Fractional Year

Body:
My PPCG holiday is over :D

Intro

Fractional time is the year + (the value (minute of year) / number of minutes in the year).

Example calculation

You should assume that February always has 28 days and the year is always 365 days long.

Let's say we want to convert the time: 17:34 3rd March 2013 to fractional time. Firstly, you find how many minutes were in 2013: 525600 minutes. Let's call this x.

Next, you want to find out how many minutes there have been since the start of 2013. A few quick calculations will tell you that the answer is 88894 minutes:

There have been 61 days since the start of the year, which times 1440 (number of minutes in a day) equals 87840 minutes. In 17 hours are 1020 minutes (17*60). Now, we can add 87840, 1020 and 34 minutes to equal 88894 minutes.

Let's call this y.

Finally, you divide y by x and add the year, resulting in 2013.16912 (to 5 decimal places).

Input

The date and time will be given as a single string. The string will be in the following format:

```<code>YYYY-MM-DD hh:mm
</code>```

The time will always be in 24 hour format and the year will always be in the range 1900-2050 inclusive.

Examples

```<code>Input:  2016-08-06 23:48
Output: 2016.59723

Input:  2013-03-03 17:34
Output: 2013.16912

Input:  1914-11-11 11:11
Output: 1914.86155
</code>```

If you are going for the bounty, either ping me in the comments or in The Nineteenth Byte.

Challenge

Calculate the given date and time as a fractional year.

Give all output to five decimal places (you may round in anyway you wish: flooring, ceiling, or true rounding). Shortest code wins.

Bounty

I am offering a 100 rep bounty for the shortest program which also accepts the date in fractional year format and returns the time in YYYY-MM-DD hh:mm format. In essence, your program (or function) has to act in the following way:

```<code>f('1914-11-11 11:11') => 1914.86155
f('1914.86155')       => 1914-11-11 11:11
</code>```

t-clausen.dk - 154 bytes

Neil - 183 bytes

Leaderboard

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
Python 3, <s>163</s> 173 bytes

more bytes because of output format

doesn't use any date builtins, like the java answer.

def s(x):z=x[5:10].split("-");v=x[10:].split(":");return int(x[:4])+(sum(([-1,31,28]+[31,30,31,30,31]*2)[:int(z[0])],int(z[1]))*1440+int(v[0])*60+int(v[1]))/525600

slightly more readable

def s(x):
    date=x[5:10].split("-");time=x[10:].split(":")
    return int(x[:4])+(sum(([-1,31,28]+[31,30,31,30,31]*2)[:int(date[0])],int(date[1]))*1440+int(time[0])*60+int(time[1]))/525600


问:
Compute the Fibonomial Coefficient

Background

The Fibonacci sequence is defined as

$$f(1) = 1 \\ f(2) = 1 \\ f(n) = f(n-1) + f(n-2)$$

The Fibonorial, similar to the factorial, is the product of the first \$n\$ Fibonacci numbers.

$$g(n) = f(1) \times f(2) \times ... \times f(n-1) \times f(n)$$

The Fibonomial coefficient, similar to the binomial coefficient is defined as

$$\begin{align}a(n, 0) & = 1 \\
a(n, k) & = \frac {g(n)} {g(n-k) \times g(k)} \\
& = \frac {f(n) \times f(n-1) \times ... \times f(n-k+1)} {f(1) \times f(2) \times ... \times f(k)}
\end{align}$$

Task

Your goal is to create a function or program to compute the Fibonomial coefficient given two non-negative integers \$n\$ and \$k\$ with \$l \le n\$.

Test Cases

```<code>a(0, 0) = 1
a(1, 1) = 1
a(2, 0) = 1
a(3, 2) = 2
a(8, 3) = 1092
a(11, 5) = 1514513
a(22, 7) = 7158243695757340957617
a(25, 3) = 49845401197200
a(50, 2) = 97905340104793732225
a(100, 1) = 354224848179261915075
</code>```

Rules

This is code-golf so the shortest code wins.

Builtins are allowed.

Related

A000045 - Challenge - Fibonacci Sequence

A003266 - Challenge - Fibonorial

A010048 - Fibonomial coefficient

答:
JavaScript (ES6), 70 bytes

```<code>a=n=>n<2?1:a(--n)+a(--n);b=n=>n?a(--n)*b(n):1;c=n=>k=>b(n)/b(n-k)/b(k)
</code>```

Call using c(n)(k), pretty straightforward.

Title: Compute the Fibonomial Coefficient

Body:
JavaScript (ES6), 70 bytes

a=n=>n<2?1:a(--n)+a(--n);b=n=>n?a(--n)*b(n):1;c=n=>k=>b(n)/b(n-k)/b(k)

Call using c(n)(k), pretty straightforward.


问:
Bijection between binary strings and pairs thereof
Input: Either one or two strings consisting of '0's and '1's.  If there are 2, they are separated by a space. All strings are of length at least 1.

Output:

If a single input was given as input,  2 are output.

If 2 were input, 1 is output.

The output strings can be whatever you like, but if running your program with input A gives you B, then running it with B must give A (if inputting 111 11 gives 00000, then inputting 00000 must give 111 11).

That means if you pipe your program to itself, you should get back whatever you input.  If your program is called foo, you can test that like this:

```<code>>echo 101 101|foo|foo
101 101
</code>```

To prevent the use of brute force techniques, your code should be able to run with 1000 digit strings in under 10 seconds.  My Python solution for this takes less than 1 second on 10000 digit strings so this shouldn't be a problem.

Shortest code wins.

答:
Perl, 56 chars

added +1 char for -p command line switch

```<code>$s.=1;$h{$h{$_}||=(split>1?$s:"$s $s").$/}=$_;$_=$h{$_}
</code>```

Body:
Perl, 56 chars

added +1 char for -p command line switch

$s.=1;$h{$h{$_}||=(split>1?$s:"$s $s").$/}=$_;$_=$h{$_}


Title: A square of text

Body:
Ruby -p, <s>40</s> <s>33</s> 30 bytes

-7 bytes from @Jordan.

gsub(/#{?.*~/$/**0.5}/){$&+$/}

Try it online!


答:
C, 206 bytes:

```<code>#include <inttypes.h>
uint64_t F(x){return x<1 ? 0:x==1 ? 1:F(x-1)+F(x-2);}uint64_t G(H,B){uint64_t P=1;for(B=3;B<=H;B++)P*=F(B);return P;}main(U,Y){scanf("%d %d",&U,&Y);printf("%llu\n",G(U)/(G(U-Y)*G(Y)));}
</code>```

Upon execution, asks for 2 space separated integers as input. The #include preprocessor is required, as without it, uint_64 is not a valid type, and the only other way to make this work for fairly big outputs is using unsigned long long return types for both the F (Fibonacci) and G (Fibonorial) functions, which is much longer than just including the <inttypes.h> and using 3 uint64_t type declarations. However, even with that, it stops working correctly at input values 14 1 (confirmed by using this, which lists the first 1325 values in the Fibonomial Coefficient sequence), most likely because the Fibonacci and/or Fibnorial representation of numbers 15 and above overflow the 64-bit integer type used.

C It Online! (Ideone)

Title: Compute the Fibonomial Coefficient

Body:
Background

The Fibonacci sequence is defined as

$$f(1) = 1 \\ f(2) = 1 \\ f(n) = f(n-1) + f(n-2)$$

The Fibonorial, similar to the factorial, is the product of the first \$n\$ Fibonacci numbers.

$$g(n) = f(1) \times f(2) \times ... \times f(n-1) \times f(n)$$

The Fibonomial coefficient, similar to the binomial coefficient is defined as

$$\begin{align}a(n, 0) & = 1 \\
a(n, k) & = \frac {g(n)} {g(n-k) \times g(k)} \\
& = \frac {f(n) \times f(n-1) \times ... \times f(n-k+1)} {f(1) \times f(2) \times ... \times f(k)}
\end{align}$$

Task

Your goal is to create a function or program to compute the Fibonomial coefficient given two non-negative integers \$n\$ and \$k\$ with \$l \le n\$.

Test Cases

```<code>a(0, 0) = 1
a(1, 1) = 1
a(2, 0) = 1
a(3, 2) = 2
a(8, 3) = 1092
a(11, 5) = 1514513
a(22, 7) = 7158243695757340957617
a(25, 3) = 49845401197200
a(50, 2) = 97905340104793732225
a(100, 1) = 354224848179261915075
</code>```

Rules

This is code-golf so the shortest code wins.

Builtins are allowed.

Related

A000045 - Challenge - Fibonacci Sequence

A003266 - Challenge - Fibonorial

A010048 - Fibonomial coefficient

Body:
C, 206 bytes:

#include <inttypes.h>
uint64_t F(x){return x<1 ? 0:x==1 ? 1:F(x-1)+F(x-2);}uint64_t G(H,B){uint64_t P=1;for(B=3;B<=H;B++)P*=F(B);return P;}main(U,Y){scanf("%d %d",&U,&Y);printf("%llu\n",G(U)/(G(U-Y)*G(Y)));}

Upon execution, asks for 2 space separated integers as input. The #include preprocessor is required, as without it, uint_64 is not a valid type, and the only other way to make this work for fairly big outputs is using unsigned long long return types for both the F (Fibonacci) and G (Fibonorial) functions, which is much longer than just including the <inttypes.h> and using 3 uint64_t type declarations. However, even with that, it stops working correctly at input values 14 1 (confirmed by using this, which lists the first 1325 values in the Fibonomial Coefficient sequence), most likely because the Fibonacci and/or Fibnorial representation of numbers 15 and above overflow the 64-bit integer type used.

C It Online! (Ideone)


答:
Cheddar, 27  bytes

```<code>s->s.chunk(s.len**.5).vfuse
</code>```

I added the .chunk function a while ago but I removed it in the transition to the new stdlib format and forgot to re-add it. Cheddar has a dedicated sqrt operator but **.5 is shorter

Try it online!

Explanation

```<code>s ->              // Function with argument s
    s.chunk(      // Chunk it into pieces of size...
      s.len ** .5 // Square root of length.
    ).vfuse       // Vertical-fuse. Join on newlines
</code>```

Title: A square of text

Body:
Cheddar, 27  bytes

s->s.chunk(s.len**.5).vfuse

I added the .chunk function a while ago but I removed it in the transition to the new stdlib format and forgot to re-add it. Cheddar has a dedicated sqrt operator but **.5 is shorter

Try it online!

Explanation

s ->              // Function with argument s
    s.chunk(      // Chunk it into pieces of size...
      s.len ** .5 // Square root of length.
    ).vfuse       // Vertical-fuse. Join on newlines


答:
C, 64 bytes

Call f() with the string to square.

```<code>m;f(char*s){for(m=sqrt(strlen(s));*s;s+=m)printf("%.*s\n",m,s);}
</code>```

Try it on ideone.

Title: A square of text

Body:
C, 64 bytes

Call f() with the string to square.

m;f(char*s){for(m=sqrt(strlen(s));*s;s+=m)printf("%.*s\n",m,s);}

Try it on ideone.


答:
Ruby, 72 bytes

Special thanks to @st0le for the really short Fibonacci generation code.

```<code>->n,k{f=[a=b=1,1]+(1..n).map{b=a+a=b}
r=->i{f[i,k].inject:*}
k>0?r[n-k]/r[0]:1}
</code>```

Title: Compute the Fibonomial Coefficient

Body:
Ruby, 72 bytes

Special thanks to @st0le for the really short Fibonacci generation code.

->n,k{f=[a=b=1,1]+(1..n).map{b=a+a=b}
r=->i{f[i,k].inject:*}
k>0?r[n-k]/r[0]:1}


问:
Turtles All the Way Down
Write a program or function that takes in a positive integer and prints or returns a stack of that many ASCII-art turtles, where each turtle is larger than the one above it.

Specifically, if the input is 1, the output should be:

```<code> __
/,,\o
</code>```

If the input is 2:

```<code>  __
o/,,\
 ____
/,__,\o
</code>```

If the input is 3:

```<code>   __
  /,,\o
  ____
o/,__,\
 ______
/,____,\o
</code>```

If the input is 4:

```<code>    __
  o/,,\
   ____
  /,__,\o
  ______
o/,____,\
 ________
/,______,\o
</code>```

If the input is 5:

```<code>     __
    /,,\o
    ____
  o/,__,\
   ______
  /,____,\o
  ________
o/,______,\
 __________
/,________,\o
</code>```

And so on in the same pattern for larger inputs.

Note that:

The head (the o) of the bottom turtle is always on the right. The heads of the turtles above then alternate back and forth.

No lines may have trailing spaces.

Superfluous leading spaces are not allowed. (i.e. the back of the bottom turtle should be at the start of the line.)

A single optional trailing newline is allowed.

The shortest code in bytes wins.

答:
CJam, 88 bytes

```<code>ri_[S\_'_*_+N+\O\"/,"\('_*_++','\+'o]\({_[(S+\(2>\(S\+)'O^c+\(-2<\(\('o\{;O}&\;]}*]-1%N*
</code>```

Makes the biggest turtle first (because otherwise what would every other turtle stand on?), then gradually reduces the size until the smallest one is made. Works for any integer larger than 0.

Try it online!

Title: Turtles All the Way Down

Body:
CJam, 88 bytes

ri_[S\_'_*_+N+\O\"/,"\('_*_++','\+'o]\({_[(S+\(2>\(S\+)'O^c+\(-2<\(\('o\{;O}&\;]}*]-1%N*

Makes the biggest turtle first (because otherwise what would every other turtle stand on?), then gradually reduces the size until the smallest one is made. Works for any integer larger than 0.

Try it online!


答:
Cheddar, 57 bytes

```<code>n->(m->(|>m).map(i->n.slice(i*m,i*m+m)).vfuse)(n.len**.5)
</code>```

Since variables are broken, I would have to pass in variables through lambda application.

Also, it turns out that even if variables worked, it would still be shorter to use lambda application.

Usage

```<code>cheddar> (n->(m->(|>m).map(i->n.slice(i*m,i*m+m)).vfuse)(n.len**.5))("abcd")
"ab
cd"
</code>```

Title: A square of text

Body:
Cheddar, 57 bytes

n->(m->(|>m).map(i->n.slice(i*m,i*m+m)).vfuse)(n.len**.5)

Since variables are broken, I would have to pass in variables through lambda application.

Also, it turns out that even if variables worked, it would still be shorter to use lambda application.

Usage

cheddar> (n->(m->(|>m).map(i->n.slice(i*m,i*m+m)).vfuse)(n.len**.5))("abcd")
"ab
cd"


答:
Jelly, 16 bytes

```<code>0+⁸Ð¡1ḊP
;_/Ç€:/
</code>```

Try it online!

Credits to Dennis for the Fibonacci-orial helper link.

```<code>;_/Ç€:/     Main chain,  argument: [n,r]
 _/         Find n-r
;           Attach it to original: [n,r,n-r]
   Ç€       Apply helper link to each element, yielding [g(n),g(r),g(n-r)]
     :/     Reduce by integer division, yielding g(n)//g(r)//g(n-r)

0+⁸Ð¡1ḊP    Helper link, argument: n
0+⁸Ð¡1ḊP    Somehow return the n-th Fibonacci-orial.
</code>```

Title: Compute the Fibonomial Coefficient

Body:
Jelly, 16 bytes

0+⁸Ð¡1ḊP
;_/Ç€:/

Try it online!

Credits to Dennis for the Fibonacci-orial helper link.

;_/Ç€:/     Main chain,  argument: [n,r]
 _/         Find n-r
;           Attach it to original: [n,r,n-r]
   Ç€       Apply helper link to each element, yielding [g(n),g(r),g(n-r)]
     :/     Reduce by integer division, yielding g(n)//g(r)//g(n-r)

0+⁸Ð¡1ḊP    Helper link, argument: n
0+⁸Ð¡1ḊP    Somehow return the n-th Fibonacci-orial.


Title: Compute the Fibonomial Coefficient

Body:
Cheddar, <s>75</s> 64 bytes

a->b->(g->g((a-b+1)|>a)/g(1|>b))(n->n.map(Math.fib).reduce((*)))

Usage

cheddar> var f = a->b->(g->g((a-b+1)|>a)/g(1|>b))(n->n.map(Math.fib).reduce((*)))
cheddar> f(11)(5)
1514513


答:
Perl 5, 197 characters

```<code>sub n{'0'x$_[0].sprintf'%b',$_[1]}sub N{/0*(?=.)/;length$&,oct"0b$'"}$_=<>;print/ /?n map{($a,$b)=N;($a+$b)*($a+$b+1)/2+$b}split:"@{[map{$w=int((sqrt(8*$_+1)-1)/2);$y=$_-($w*$w+$w)/2;n$w-$y,$y}N]}"
</code>```

With some line breaks:

```<code>sub n{'0'x$_[0].sprintf'%b',$_[1]}
sub N{/0*(?=.)/;length$&,oct"0b$'"}
$_=<>;print/ /?n map{
  ($a,$b)=N;($a+$b)*($a+$b+1)/2+$b
}split:"@{[map{
  $w=int((sqrt(8*$_+1)-1)/2);$y=$_-($w*$w+$w)/2;n$w-$y,$y
}N]}"
</code>```

This program operates by composing two bijections:

A pair of natural numbers may be mapped to a binary string by converting one to a base-2 number and the other to extraneous leading zeroes. n is this function and N is its inverse (except that N uses $_ as its parameter).

A pair of natural numbers may be mapped to a single natural number using the Cantor pairing function. The first map's block is this function and the second is its inverse.

Thus two binary strings are split into four numbers, combined into two numbers, and then combined into one binary string — or vice versa.

Tested on 100 random inputs of each type with strings up to 8 symbols long. I've been finding lots of ways to make this a little bit shorter, but I'm going to stop and post it. If there's room to optimize further, it's probably in the arithmetic expressions.

Title: Bijection between binary strings and pairs thereof

Body:
Input: Either one or two strings consisting of '0's and '1's.  If there are 2, they are separated by a space. All strings are of length at least 1.

Output:

If a single input was given as input,  2 are output.

If 2 were input, 1 is output.

The output strings can be whatever you like, but if running your program with input A gives you B, then running it with B must give A (if inputting 111 11 gives 00000, then inputting 00000 must give 111 11).

That means if you pipe your program to itself, you should get back whatever you input.  If your program is called foo, you can test that like this:

```<code>>echo 101 101|foo|foo
101 101
</code>```

To prevent the use of brute force techniques, your code should be able to run with 1000 digit strings in under 10 seconds.  My Python solution for this takes less than 1 second on 10000 digit strings so this shouldn't be a problem.

Shortest code wins.

Body:
Perl 5, 197 characters

sub n{'0'x$_[0].sprintf'%b',$_[1]}sub N{/0*(?=.)/;length$&,oct"0b$'"}$_=<>;print/ /?n map{($a,$b)=N;($a+$b)*($a+$b+1)/2+$b}split:"@{[map{$w=int((sqrt(8*$_+1)-1)/2);$y=$_-($w*$w+$w)/2;n$w-$y,$y}N]}"

With some line breaks:

sub n{'0'x$_[0].sprintf'%b',$_[1]}
sub N{/0*(?=.)/;length$&,oct"0b$'"}
$_=<>;print/ /?n map{
  ($a,$b)=N;($a+$b)*($a+$b+1)/2+$b
}split:"@{[map{
  $w=int((sqrt(8*$_+1)-1)/2);$y=$_-($w*$w+$w)/2;n$w-$y,$y
}N]}"

This program operates by composing two bijections:

A pair of natural numbers may be mapped to a binary string by converting one to a base-2 number and the other to extraneous leading zeroes. n is this function and N is its inverse (except that N uses $_ as its parameter).

A pair of natural numbers may be mapped to a single natural number using the Cantor pairing function. The first map's block is this function and the second is its inverse.

Thus two binary strings are split into four numbers, combined into two numbers, and then combined into one binary string — or vice versa.

Tested on 100 random inputs of each type with strings up to 8 symbols long. I've been finding lots of ways to make this a little bit shorter, but I'm going to stop and post it. If there's room to optimize further, it's probably in the arithmetic expressions.


答:
zsh, <s>36</s> 33 bytes

fold -`tr -d .<<<$[$#1**.5]`<<<$1
```

<p>Try it online!</p>

<p>Takes input as a command line argument, outputs to STDOUT.</p>

<pre class="lang-sh prettyprint-override"><code>                   $#1             # get the length of the input string
                 $[   **.5]        # take it to the .5 power (sqrt)
              <<<                  # and pass the result to
       tr -d .                     # tr, to delete the trailing decimal point
                                   #    (sqrt(9) is 3. instead of 3)
     -`                    `       # give the result as a command line flag to
fold                               # the fold util, which wraps at nth column
                            <<<$1  # pass the input as input to fold
</code>```

Title: A square of text

Body:
The Challenge

Given a string, output the text in the shape of a square.

You can assume that the text will always fit in a square, and that it will never be an empty string.

You can also assume it will never have newlines.

Example

```<code>Input:
Hi, world

Output:
Hi,
 wo
rld
</code>```

Test Cases

```<code>Input:
Hi, world! Hello

Output:
Hi,
worl
d! H
ello

Input:
Lorem ipsum dolor sit amt

Output:
Lorem
 ipsu
m dol
or si
t amt

Input:
H

Output:
H
</code>```

Rules

This is code-golf, so shortest answer in bytes wins! Tiebreaker is most upvoted answer.

Standard loopholes are forbidden.

Body:
zsh, <s>36</s> 33 bytes

fold -`tr -d .<<<$[$#1**.5]`<<<$1

Try it online!

Takes input as a command line argument, outputs to STDOUT.

                   $#1             # get the length of the input string
                 $[   **.5]        # take it to the .5 power (sqrt)
              <<<                  # and pass the result to
       tr -d .                     # tr, to delete the trailing decimal point
                                   #    (sqrt(9) is 3. instead of 3)
     -`                    `       # give the result as a command line flag to
fold                               # the fold util, which wraps at nth column
                            <<<$1  # pass the input as input to fold


问:
A Formula for Congruences
The Chinese Remainder Theorem can be quite useful in modular arithmetic.

For example, consider the following set of congruence relations:

For sets of congruence relations like this, where all the bases (3, 5, 7 in this example) are co-prime with each other, there will be one and only one integer n between 1 and the product of the bases (3*5*7 = 105 in this example) inclusive that satisfies the relations.

In this example, the number would be 14, generated by this formula:

where 2, 4, and 0 are given from the above example.

70, 21, 15 are the coefficients of the formula and they are dependent on the bases, 3, 5, 7.

To calculate the coefficients of the formula (70, 21, 15 in our example) for a set of bases, we use the following procedure.

For each number a in a set of bases:

Find the product of all of the other bases, denoted as P.

Find the first multiple of P that leaves a remainder of 1 when divided by a. This is the coefficient of a.

For example, to calculate the coefficient that corresponds to the base 3, we find the product of all the other bases (i.e. 5*7 = 35) and then find the first multiple of that product that leaves a remainder of 1 when divided by the base.

In this case, 35 leaves a remainder of 2 when divided by 3, but 35*2 = 70 leaves a remainder of 1 when divided by 3, so 70 is the corresponding coefficient for 3. Similarly, 3*7 = 21 leaves a remainder of 1 when divided by 5 and 3*5 = 15 leaves a remainder of 1 when divided by 7.

In a nutshell

For each number a in a set of numbers:

Find the product of all of the other numbers, denoted as P.

Find the first multiple of P that leaves a remainder of 1 when divided by a. This is the coefficient of a.

The challenge

The challenge is, for a set of two or more bases, to find the set of corresponding coefficients.

The set of bases are guaranteed to be pairwise co-prime and each base is guaranteed to be larger than 1.

Your input is a list of integers as input [3,4,5] or space-separated string "3 4 5" or however your inputs work.

Your output should either be a list of integers or space-separated string that denotes the set of coefficients.

Test cases

```<code>input             output
[3,5,7]           [70,21,15]
[2,3,5]           [15,10,6]
[3,4,5]           [40,45,36]
[3,4]             [4,9]
[2,3,5,7]         [105,70,126,120]
[40,27,11]        [9801,7480,6480]
[100,27,31]       [61101,49600,56700]
[16,27,25,49,11]  [363825,2371600,2794176,5583600,529200]
</code>```

Many thanks to Leaky Nun for his help in writing this challenge. As always, if the problem is unclear, please let me know. Good luck and good golfing!

答:
Pyth, 14 bytes

```<code>mhfq1%Td*R/*FQ
</code>```

Test suite.

Naive implementation of the algorithm.

Title: A Formula for Congruences

Body:
Pyth, 14 bytes

mhfq1%Td*R/*FQ

Test suite.

Naive implementation of the algorithm.


答:
Python 2, <s>87</s> 84 bytes

A simple implementation of the algorithm. Golfing suggestions welcome.

a=input();p=1
for i in a:p*=i
print[p/i*j for i in a for j in range(i)if p/i*j%i==1]
```

Title: A Formula for Congruences

Body:
The Chinese Remainder Theorem can be quite useful in modular arithmetic.

For example, consider the following set of congruence relations:

For sets of congruence relations like this, where all the bases (3, 5, 7 in this example) are co-prime with each other, there will be one and only one integer n between 1 and the product of the bases (3*5*7 = 105 in this example) inclusive that satisfies the relations.

In this example, the number would be 14, generated by this formula:

where 2, 4, and 0 are given from the above example.

70, 21, 15 are the coefficients of the formula and they are dependent on the bases, 3, 5, 7.

To calculate the coefficients of the formula (70, 21, 15 in our example) for a set of bases, we use the following procedure.

For each number a in a set of bases:

Find the product of all of the other bases, denoted as P.

Find the first multiple of P that leaves a remainder of 1 when divided by a. This is the coefficient of a.

For example, to calculate the coefficient that corresponds to the base 3, we find the product of all the other bases (i.e. 5*7 = 35) and then find the first multiple of that product that leaves a remainder of 1 when divided by the base.

In this case, 35 leaves a remainder of 2 when divided by 3, but 35*2 = 70 leaves a remainder of 1 when divided by 3, so 70 is the corresponding coefficient for 3. Similarly, 3*7 = 21 leaves a remainder of 1 when divided by 5 and 3*5 = 15 leaves a remainder of 1 when divided by 7.

In a nutshell

For each number a in a set of numbers:

Find the product of all of the other numbers, denoted as P.

Find the first multiple of P that leaves a remainder of 1 when divided by a. This is the coefficient of a.

The challenge

The challenge is, for a set of two or more bases, to find the set of corresponding coefficients.

The set of bases are guaranteed to be pairwise co-prime and each base is guaranteed to be larger than 1.

Your input is a list of integers as input [3,4,5] or space-separated string "3 4 5" or however your inputs work.

Your output should either be a list of integers or space-separated string that denotes the set of coefficients.

Test cases

```<code>input             output
[3,5,7]           [70,21,15]
[2,3,5]           [15,10,6]
[3,4,5]           [40,45,36]
[3,4]             [4,9]
[2,3,5,7]         [105,70,126,120]
[40,27,11]        [9801,7480,6480]
[100,27,31]       [61101,49600,56700]
[16,27,25,49,11]  [363825,2371600,2794176,5583600,529200]
</code>```

Many thanks to Leaky Nun for his help in writing this challenge. As always, if the problem is unclear, please let me know. Good luck and good golfing!


答:
Haskell, <s>61</s> <s>55</s> 53 bytes

```<code>f x=[[p|p<-[0,product x`div`n..],p`mod`n==1]!!0|n<-x]
</code>```

Defines a function f that takes input and gives output as a list of integers.

```<code>f x=[                                          |n<-x]  (1)
              product x                                (2)
                       `div`n                          (3)
</code>```

First we loop over all integers in the input (1). Then we take the product of all of the integers (2) and divide by n to get just the product of the non-n integers, which is P (3).

```<code>           [0,               ..]                       (4)
     [p|p<-                     ,p`mod`n==1]           (5)
                                            !!0        (6)
</code>```

Then we use the result (P) as the step value for a range starting at zero (4). We take the result, [0, P, 2P, 3P, ...], and filter it on values for which the result of a mod-n operation is one (5). Finally, we take the first element, which works thanks to lazy evaluation (6).

Thanks to @xnor for 2 bytes!

Title: A Formula for Congruences

Body:
Haskell, <s>61</s> <s>55</s> 53 bytes

f x=[[p|p<-[0,product x`div`n..],p`mod`n==1]!!0|n<-x]

Defines a function f that takes input and gives output as a list of integers.

f x=[                                          |n<-x]  (1)
              product x                                (2)
                       `div`n                          (3)

First we loop over all integers in the input (1). Then we take the product of all of the integers (2) and divide by n to get just the product of the non-n integers, which is P (3).

           [0,               ..]                       (4)
     [p|p<-                     ,p`mod`n==1]           (5)
                                            !!0        (6)

Then we use the result (P) as the step value for a range starting at zero (4). We take the result, [0, P, 2P, 3P, ...], and filter it on values for which the result of a mod-n operation is one (5). Finally, we take the first element, which works thanks to lazy evaluation (6).

Thanks to @xnor for 2 bytes!


答:
J, 9 bytes

```<code>$~,~@%:@#
</code>```

This is a monadic hook over the input string:

```<code>$~ ,~@%:@#
</code>```

The right tine is a series of compositions:

```<code>,~ @ %: @ #
</code>```

The left is a shaping verb, switched such that it works in the hook format.

Here are some intermediate results:

```<code>   # 'hiya'
4
   %:@# 'hiya'
2
   ,~@%:@# 'hiya'
2 2
</code>```

In words:

```<code>   size =: #
   sqrt =: %:
   dup =: ,~
   on =: @
   shape =: $~
   block =: shape dup on sqrt on size
   block 'Hello, World! :)'
Hell
o, W
orld
! :)
</code>```

Title: A square of text

Body:
J, 9 bytes

$~,~@%:@#

This is a monadic hook over the input string:

$~ ,~@%:@#

The right tine is a series of compositions:

,~ @ %: @ #

The left is a shaping verb, switched such that it works in the hook format.

Here are some intermediate results:

   # 'hiya'
4
   %:@# 'hiya'
2
   ,~@%:@# 'hiya'
2 2

In words:

   size =: #
   sqrt =: %:
   dup =: ,~
   on =: @
   shape =: $~
   block =: shape dup on sqrt on size
   block 'Hello, World! :)'
Hell
o, W
orld
! :)


答:
Python 3.5, <s>112</s> 111 bytes:

```<code>from math import*;lambda d:''.join([d[int(bin(i)[2:].zfill(int(log2(len(d))))[::-1],2)]for i in range(len(d))])
</code>```

You really start to appreciate the all in one power and compactness of Python once you start using languages like C and Java. Anyways, this is an anonymous function that you call by first naming it, and then calling it like a normal function wrapped inside the print() function.

Try It Online! (Ideone)

Title: Permute a string using Bit-Reversal

Body:
Previously, we computed the Bit-Reversal Permutation where we found how the order of indices would be permuted. In that case, we received an input n which was the order of the permutation of the indices where the length was 2n. However, this time, we are given a string of length m = 2k for some k. Now we want to apply the permutation indices of order k to a string.

Task

Your goal is to create a function or program that given a string where the length is a power of 2, output the permutation of it using bit-reversal.

As an example, the string 'codegolf' has length 8 which is a power of 2, that is 8 = 23. We learned in the previous challenge that the bit-reversal permutation of order 3 is [0, 4, 2, 6, 1, 5, 3, 7] which means that we select the characters from the input string using that order of indices.

```<code>Input                  Output
0 1 2 3 4 5 6 7        0 4 2 6 1 5 3 7
c o d e g o l f        c g d l o o e f
</code>```

This is one possible method of solving this task. Since we do not require the order of indices as output, there may be shorter algorithms which avoid generating the indices and rely on permuting characters only.

Test Cases

```<code>Input = Output
"z" = "z"
"cg" = "cg"
"code" = "cdoe"
"golf" = "glof"
"codegolf" = "cgdlooef"
"aaaazzzz" = "azazazaz"
"LynngDaie dneers" = "Legendary Dennis"
"hieroglyphically" = "hpoaeillihglrcyy"
"Programming Puzzles N' Code-Golf" = "PliorNPGosgem zlrenda'uog  -mCzf"
"super spectacular dazzling dream" = "srenrzcrpdt sllau cg zueeaadpiam"
</code>```

Rules

This is code-golf so the shortest code wins.

Builtins are allowed.

The input string will only be in ASCII. The length of the input string will always be a power of 2.

Body:
Python 3.5, <s>112</s> 111 bytes:

from math import*;lambda d:''.join([d[int(bin(i)[2:].zfill(int(log2(len(d))))[::-1],2)]for i in range(len(d))])

You really start to appreciate the all in one power and compactness of Python once you start using languages like C and Java. Anyways, this is an anonymous function that you call by first naming it, and then calling it like a normal function wrapped inside the print() function.

Try It Online! (Ideone)


答:
dc, 67 bytes

```<code>?skdsn[si1d[sadlarla+zli>b*]sbzli>b*]dsgxsplnlk-lgxsqlklgxlprlqr*/f
</code>```

Input is taken as space-delimited decimal constants on a single line.

This uses my answer to the /Fibon(acci-)?orial/ question, which multiplies all numbers on the stack in the last step, requiring the other numbers to be stored elsewhere while the other Fibonorials are calculated.

```<code>?       # Take input from stdin
skdsn   # Store second number in register `k'; store a copy of first number in register `n'
[si1d[sadlarla+zli>b*]sbzli>b*] # Compute Fibonorial of top-of-stack, multiplying
                                #   until stack depth is 1
dsgx    # Store a copy of this function as g and execute it: g(n)
sp      # Store g(n) in register `p'
lnlk-   # Compute n-k
lgx     # Compute g(n-k)
sq      # Store g(n-k) in register `q'
lk lgx  # Compute g(k)
        # Top ---Down--->
lp      #  g(n)    g(k)
r       #  g(k)    g(n)
lq      #  g(n-k)  g(k)    g(n)
r       #  g(k)    g(n-k)  g(n)
*       # (g(k)g(n-k))     g(n)
/       #  g(n)/(g(k)g(n-k))
f       # Dump stack to stdout
</code>```

Title: Compute the Fibonomial Coefficient

Body:
Background

The Fibonacci sequence is defined as

$$f(1) = 1 \\ f(2) = 1 \\ f(n) = f(n-1) + f(n-2)$$

The Fibonorial, similar to the factorial, is the product of the first \$n\$ Fibonacci numbers.

$$g(n) = f(1) \times f(2) \times ... \times f(n-1) \times f(n)$$

The Fibonomial coefficient, similar to the binomial coefficient is defined as

$$\begin{align}a(n, 0) & = 1 \\
a(n, k) & = \frac {g(n)} {g(n-k) \times g(k)} \\
& = \frac {f(n) \times f(n-1) \times ... \times f(n-k+1)} {f(1) \times f(2) \times ... \times f(k)}
\end{align}$$

Task

Your goal is to create a function or program to compute the Fibonomial coefficient given two non-negative integers \$n\$ and \$k\$ with \$l \le n\$.

Test Cases

```<code>a(0, 0) = 1
a(1, 1) = 1
a(2, 0) = 1
a(3, 2) = 2
a(8, 3) = 1092
a(11, 5) = 1514513
a(22, 7) = 7158243695757340957617
a(25, 3) = 49845401197200
a(50, 2) = 97905340104793732225
a(100, 1) = 354224848179261915075
</code>```

Rules

This is code-golf so the shortest code wins.

Builtins are allowed.

Related

A000045 - Challenge - Fibonacci Sequence

A003266 - Challenge - Fibonorial

A010048 - Fibonomial coefficient

Body:
dc, 67 bytes

?skdsn[si1d[sadlarla+zli>b*]sbzli>b*]dsgxsplnlk-lgxsqlklgxlprlqr*/f

Input is taken as space-delimited decimal constants on a single line.

This uses my answer to the /Fibon(acci-)?orial/ question, which multiplies all numbers on the stack in the last step, requiring the other numbers to be stored elsewhere while the other Fibonorials are calculated.

?       # Take input from stdin
skdsn   # Store second number in register `k'; store a copy of first number in register `n'
[si1d[sadlarla+zli>b*]sbzli>b*] # Compute Fibonorial of top-of-stack, multiplying
                                #   until stack depth is 1
dsgx    # Store a copy of this function as g and execute it: g(n)
sp      # Store g(n) in register `p'
lnlk-   # Compute n-k
lgx     # Compute g(n-k)
sq      # Store g(n-k) in register `q'
lk lgx  # Compute g(k)
        # Top ---Down--->
lp      #  g(n)    g(k)
r       #  g(k)    g(n)
lq      #  g(n-k)  g(k)    g(n)
r       #  g(k)    g(n-k)  g(n)
*       # (g(k)g(n-k))     g(n)
/       #  g(n)/(g(k)g(n-k))
f       # Dump stack to stdout


答:
Brainfuck, <s>116</s> 112 bytes

```<code>>>>>,[[<]<<+>>>[>],]<[<]<+<[>>+<[-<-<+>>]<<++[->>+<<]>]>[-]>>[<[->.[-]<[->+<]<+[->+<]>>]++++++++++.[-]<[->+<]>>]
</code>```

Try it online!

Safe in flavours of BF that does not mask the cells with 256, does not support null bytes.

Remove the initial right arrows if the flavour supports negative memory for 4 bytes saved.

Explanation

The program is divided into 3 stages:

```<code>Stage 1: >>>>,[[<]<<+>>>[>],]<[<]
Stage 2: <+<[>>+<[-<-<+>>]<<++[->>+<<]>]>[-]>>
Stage 3: [<[->.[-]<[->+<]<+[->+<]>>]++++++++++.[-]<[->+<]>>]
</code>```

Stage 1

In this stage, we put all the characters onto the tape, while keeping count of the number of characters.

This is the tape for the input abcdefghi after this tape:

```<code>000 009 000 000 095 096 097 098 099 100 101 102 103
             ^
</code>```

The 009 is the count.

For each character, we move the the first zero on the left [<] and then add one to the count <<+>>>, and then move to the rightmost zero [>] to get ready for the next character.

Stage 2

This stage does the square root of the length stored in the second cell.

It keeps subtracting by 1, 3, 5, 7, ... until the number reaches zero, while keeping check of the number of iterations.

It works because square numbers can be expressed as 1 + 3 + 5 + ....

Stage 3

Denote the square root of the length found above as n.

This stage outputs n characters at a time, and then output a newline, until the tape is cleared.

Title: A square of text

Body:
Brainfuck, <s>116</s> 112 bytes

>>>>,[[<]<<+>>>[>],]<[<]<+<[>>+<[-<-<+>>]<<++[->>+<<]>]>[-]>>[<[->.[-]<[->+<]<+[->+<]>>]++++++++++.[-]<[->+<]>>]

Try it online!

Safe in flavours of BF that does not mask the cells with 256, does not support null bytes.

Remove the initial right arrows if the flavour supports negative memory for 4 bytes saved.

Explanation

The program is divided into 3 stages:

Stage 1: >>>>,[[<]<<+>>>[>],]<[<]
Stage 2: <+<[>>+<[-<-<+>>]<<++[->>+<<]>]>[-]>>
Stage 3: [<[->.[-]<[->+<]<+[->+<]>>]++++++++++.[-]<[->+<]>>]

Stage 1

In this stage, we put all the characters onto the tape, while keeping count of the number of characters.

This is the tape for the input abcdefghi after this tape:

000 009 000 000 095 096 097 098 099 100 101 102 103
             ^

The 009 is the count.

For each character, we move the the first zero on the left [<] and then add one to the count <<+>>>, and then move to the rightmost zero [>] to get ready for the next character.

Stage 2

This stage does the square root of the length stored in the second cell.

It keeps subtracting by 1, 3, 5, 7, ... until the number reaches zero, while keeping check of the number of iterations.

It works because square numbers can be expressed as 1 + 3 + 5 + ....

Stage 3

Denote the square root of the length found above as n.

This stage outputs n characters at a time, and then output a newline, until the tape is cleared.


答:
Matlab, 28 bytes

```<code>@(s)reshape(s,nnz(s)^.5,[])'
</code>```

reshape puts output in columns first, so we have to transpose the whole thing to get the desired output.

Title: A square of text

Body:
Matlab, 28 bytes

@(s)reshape(s,nnz(s)^.5,[])'

reshape puts output in columns first, so we have to transpose the whole thing to get the desired output.


答:
Pyke, 5 bytes

```<code>l,fnJ
</code>```

Try it here!

Title: A square of text

Body:
Pyke, 5 bytes

l,fnJ

Try it here!


答:
Jelly, <s>14</s> 13 bytes

```<code>P:×"Ḷð%"’¬æ.ḷ
</code>```

Saved a byte thanks to @Dennis!

Uses the process described in the challenge spec. The input is a list of bases and the output is a list of coefficients.

Try it online or Verify all test cases.

Explanation

```<code>P:×"Ḷð%"’¬æ.ḷ  Input: a list B
P              Get the product of the list
 :             Divide it by each value in the B, call it M
    Ḷ          Get a range from 0 to k for k in B
  ×"           Vectorized multiply, find the multiples of each M
     ð         Start a new dyadic chain. Input: multiples of M and B
      %"       Vectorized modulo, find the remainders of each multiple by B
        ’      Decrement every value
               If the remainder was 1, decrementing would make it 0
         ¬     Logical NOT, zeros become one and everything else becomes 0
            ḷ  Get the multiples of M
          æ.   Find the dot product between the modified remainders and the multiples
               Return
</code>```

Title: A Formula for Congruences

Body:
Jelly, <s>14</s> 13 bytes

P:×"Ḷð%"’¬æ.ḷ

Saved a byte thanks to @Dennis!

Uses the process described in the challenge spec. The input is a list of bases and the output is a list of coefficients.

Try it online or Verify all test cases.

Explanation

P:×"Ḷð%"’¬æ.ḷ  Input: a list B
P              Get the product of the list
 :             Divide it by each value in the B, call it M
    Ḷ          Get a range from 0 to k for k in B
  ×"           Vectorized multiply, find the multiples of each M
     ð         Start a new dyadic chain. Input: multiples of M and B
      %"       Vectorized modulo, find the remainders of each multiple by B
        ’      Decrement every value
               If the remainder was 1, decrementing would make it 0
         ¬     Logical NOT, zeros become one and everything else becomes 0
            ḷ  Get the multiples of M
          æ.   Find the dot product between the modified remainders and the multiples
               Return


答:
Jelly, <s>11</s> 7 bytes

```<code>P:*ÆṪ%P
</code>```

Try it online! or verify all test cases.

Background

Let P and a be strictly positive, coprime integers.

The two-step process in the question – finding a multiple of P that leaves a remainder of 1 when divided by a – can be described by the following congruence equation.

By the Euler-Fermat theorem, we have

where φ denotes Euler's totient function. From this result, we deduce the following.

Finally, since the challenge requires us to compute Px, we observe that

where Pa can be computed as the product of all moduli.

How it works

```<code>P:*ÆṪ%P  Main link. Argument: A (list of moduli)

P        Yield the product of all moduli.
 :       Divide the product by each modulus in A.
   ÆṪ    Apply Euler's totient function to each modulus.
  *      Raise each quotient to the totient of its denominator.
     %P  Compute the remainder of the powers and the product of all moduli.
</code>```

Title: A Formula for Congruences

Body:
Jelly, <s>11</s> 7 bytes

P:*ÆṪ%P

Try it online! or verify all test cases.

Background

Let P and a be strictly positive, coprime integers.

The two-step process in the question – finding a multiple of P that leaves a remainder of 1 when divided by a – can be described by the following congruence equation.

By the Euler-Fermat theorem, we have

where φ denotes Euler's totient function. From this result, we deduce the following.

Finally, since the challenge requires us to compute Px, we observe that

where Pa can be computed as the product of all moduli.

How it works

P:*ÆṪ%P  Main link. Argument: A (list of moduli)

P        Yield the product of all moduli.
 :       Divide the product by each modulus in A.
   ÆṪ    Apply Euler's totient function to each modulus.
  *      Raise each quotient to the totient of its denominator.
     %P  Compute the remainder of the powers and the product of all moduli.


问:
Medieval orthography

Task

Your task is to convert a text into medieval orthography.

Details

j is converted to i and J to I.

u and U at the beginning of words are converted to v and V respectively.

v and V at anywhere except the beginning of words are converted to u and U respectively.

s is converted to ſ (U+017F) unless at the end of the word or preceded by another s.

Specs

A word is defined as a sequence of letters in abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.

All words will have at least two letters.

The input will only consist of printable ASCII characters (U+0020 - U+007E).

There will be no occurrences of more than two consecutive s. That is, sss will not be a substring of the input.

Testcases

Individual words:

```<code>Input       Output
------------------------
Joy         Ioy
joy         ioy
Universe    Vniuerſe
universe    vniuerſe
Success     Succeſs
successfull ſucceſsfull
Supervise   Superuiſe
supervise   ſuperuiſe
Super-vise  Super-viſe
I've        I've
majors      maiors
UNIVERSE    VNIUERSE
0universe   0vniuerſe
0verify     0verify
I0ve        I0ve
_UU_          _VU_
_VV_          _VU_
ss_         ſs_
</code>```

Whole paragraph:

```<code>Input:  Christian Reader, I have for thy use collected this small Concordance, with no small labour. For being to comprise much in little roome, I was to make choyse of the most principall and usefull places, and to rank them under such words as I thought most essentiall and materiall in the sentence, because the scant roome allotted unto me, would not permit that I should expresse them under every word in the verse, as it is the manner in large Concordances.

Output: Chriſtian Reader, I haue for thy vſe collected this ſmall Concordance, with no ſmall labour. For being to compriſe much in little roome, I was to make choyſe of the moſt principall and vſefull places, and to rank them vnder ſuch words as I thought moſt eſsentiall and materiall in the ſentence, becauſe the ſcant roome allotted vnto me, would not permit that I ſhould expreſse them vnder euery word in the verſe, as it is the manner in large Concordances.
</code>```

The SHA-256 hash of the output of the last testcase is:

```<code>5641899e7d55e6d1fc6e9aa4804f2710e883146bac0e757308afc58521621644
</code>```

Disclaimer

Medievall orthographie is not that conſtante. Pleaſe do not complayne if you ſhall ſee olde bookes with a different orthographie.

答:
Python 3.5, <s>124</s> <s>116</s> <s>111</s> <s>118</s> <s>125</s> <s>144</s> 142 bytes:

```<code>import re;lambda k:re.sub("J|j|(?<![a-zA-Z])[uU]|(?<=[a-zA-Z])[Vv]|(?<!s)s(?=[a-zA-Z])",lambda g:dict(zip('jJuUvVs','iIvVuUſ'))[g.group()],k)
</code>```

Well, this seems like the perfect job for regular expressions!

Title: Medieval orthography

Body:
Python 3.5, <s>124</s> <s>116</s> <s>111</s> <s>118</s> <s>125</s> <s>144</s> 142 bytes:

import re;lambda k:re.sub("J|j|(?<![a-zA-Z])[uU]|(?<=[a-zA-Z])[Vv]|(?<!s)s(?=[a-zA-Z])",lambda g:dict(zip('jJuUvVs','iIvVuUſ'))[g.group()],k)

Well, this seems like the perfect job for regular expressions!


答:
Python 3 (128 126 bytes)

import re;lambda k:re.sub("(?<!s)s(?=[a-zA-Z])",'ſ',re.sub("(?i)j|(?<![a-z])u|(?<=[a-z])v",lambda c:chr(ord(c.group())^3),k))
```

chr(ord(c.group())^3) feels excessive to xor a single-character string, but maybe a real Pythonista can suggest a golf. However, it's very convenient that ^3 suffices to interchange i <-> j and u <-> v.

NB The only thing here which requires Python 3 is the Unicode character: Python 2 complains Non-ASCII character '\xc5' <snip> but no encoding declared.

Title: Medieval orthography

Body:
Task

Your task is to convert a text into medieval orthography.

Details

j is converted to i and J to I.

u and U at the beginning of words are converted to v and V respectively.

v and V at anywhere except the beginning of words are converted to u and U respectively.

s is converted to ſ (U+017F) unless at the end of the word or preceded by another s.

Specs

A word is defined as a sequence of letters in abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.

All words will have at least two letters.

The input will only consist of printable ASCII characters (U+0020 - U+007E).

There will be no occurrences of more than two consecutive s. That is, sss will not be a substring of the input.

Testcases

Individual words:

```<code>Input       Output
------------------------
Joy         Ioy
joy         ioy
Universe    Vniuerſe
universe    vniuerſe
Success     Succeſs
successfull ſucceſsfull
Supervise   Superuiſe
supervise   ſuperuiſe
Super-vise  Super-viſe
I've        I've
majors      maiors
UNIVERSE    VNIUERSE
0universe   0vniuerſe
0verify     0verify
I0ve        I0ve
_UU_          _VU_
_VV_          _VU_
ss_         ſs_
</code>```

Whole paragraph:

```<code>Input:  Christian Reader, I have for thy use collected this small Concordance, with no small labour. For being to comprise much in little roome, I was to make choyse of the most principall and usefull places, and to rank them under such words as I thought most essentiall and materiall in the sentence, because the scant roome allotted unto me, would not permit that I should expresse them under every word in the verse, as it is the manner in large Concordances.

Output: Chriſtian Reader, I haue for thy vſe collected this ſmall Concordance, with no ſmall labour. For being to compriſe much in little roome, I was to make choyſe of the moſt principall and vſefull places, and to rank them vnder ſuch words as I thought moſt eſsentiall and materiall in the ſentence, becauſe the ſcant roome allotted vnto me, would not permit that I ſhould expreſse them vnder euery word in the verſe, as it is the manner in large Concordances.
</code>```

The SHA-256 hash of the output of the last testcase is:

```<code>5641899e7d55e6d1fc6e9aa4804f2710e883146bac0e757308afc58521621644
</code>```

Disclaimer

Medievall orthographie is not that conſtante. Pleaſe do not complayne if you ſhall ſee olde bookes with a different orthographie.

Body:
Python 3 (128 126 bytes)

import re;lambda k:re.sub("(?<!s)s(?=[a-zA-Z])",'ſ',re.sub("(?i)j|(?<![a-z])u|(?<=[a-z])v",lambda c:chr(ord(c.group())^3),k))

chr(ord(c.group())^3) feels excessive to xor a single-character string, but maybe a real Pythonista can suggest a golf. However, it's very convenient that ^3 suffices to interchange i <-> j and u <-> v.

NB The only thing here which requires Python 3 is the Unicode character: Python 2 complains Non-ASCII character '\xc5' <snip> but no encoding declared.


答:
R, 120 bytes

Some more golfing is probably be possible, so comments are of course welcomed !

I used my answer of the Fibonacci-orial question in the begining of the code :

```<code>A=function(n,k){p=(1+sqrt(5))/2;f=function(N){x=1;for(n in 1:N){x=prod(x,(p^n-(-1/p)^n)/sqrt(5))};x};f(n)/(f(k)*f(n-k))}
</code>```

Ungolfed :

```<code>A=function(n,k){
p=(1+sqrt(5))/2
    f=function(N){
        x=1
        for(n in 1:N){
           x=prod(x,(p^n-(-1/p)^n)/sqrt(5))
                     }
        x
        }

f(n)/(f(k)*f(n-k))
}
</code>```

Title: Compute the Fibonomial Coefficient

Body:
R, 120 bytes

Some more golfing is probably be possible, so comments are of course welcomed !

I used my answer of the Fibonacci-orial question in the begining of the code :

A=function(n,k){p=(1+sqrt(5))/2;f=function(N){x=1;for(n in 1:N){x=prod(x,(p^n-(-1/p)^n)/sqrt(5))};x};f(n)/(f(k)*f(n-k))}

Ungolfed :

A=function(n,k){
p=(1+sqrt(5))/2
    f=function(N){
        x=1
        for(n in 1:N){
           x=prod(x,(p^n-(-1/p)^n)/sqrt(5))
                     }
        x
        }

f(n)/(f(k)*f(n-k))
}


问:
Output a shuffled deck using random input

Input/Output:

Input: A uniformly random, infinitely long, string of '0's and '1's, taken from stdin.  The string is assumed to be truly random, not pseudo-random.  It is uniform in that each character is equally likely to be a '0' or '1'.

Careful! The input is infinitely long, so you can't store it all in memory using a function like raw_input() in python.  If I'm not mistaken, golfscript will fail with infinite input, since it pushes the entire input onto the stack prior to running.

Output: A uniformly random shuffled standard deck, without jokers.  It is uniform in that all orderings are equally likely.

Each card in the output is it's rank, A, 2-9, T, J, Q or K concatenated with it's suit, c, d, h or s.  For example, the 10 of spades is Ts

The cards of the deck should be separated by spaces.

You may not use built-in random libraries or functions because they are not truly random, only pseudo-random.

Example input

You may use the following python script to pipe input into your program:

```<code>import sys, random
try:
    while True:
        sys.stdout.write(str(random.randint(0,1)))
except IOError:
    pass
</code>```

If you save the script as rand.py, test your program with python rand.py | your_program

In python 3 it runs as expected, but in python 2.7 I get an error message after my program's output, but only after everything's done, so just ignore the error message.

Example output:

Here's how the deck should be printed if it happened to be shuffled into a sorted order:

```<code>Ac 2c 3c 4c 5c 6c 7c 8c 9c Tc Jc Qc Kc Ad 2d 3d 4d 5d 6d 7d 8d 9d Td Jd Qd Kd Ah 2h 3h 4h 5h 6h 7h 8h 9h Th Jh Qh Kh As 2s 3s 4s 5s 6s 7s 8s 9s Ts Js Qs Ks
</code>```

Scoring:

This is a code golf.  Shortest code wins.

Example program:

Here is a python 2.7 solution, not golfed.

```<code>import sys
def next():
    return int(sys.stdin.read(1))==1
def roll(n):
    if n==1:
        return 0
    if n%2==0:
        r=roll(n/2)
        if next():
            r+=n/2
        return r
    else:
        r=n
        while(r==n):
            r=roll(n+1)
        return r
deck = [rank+suit for suit in 'cdhs' for rank in 'A23456789TJQK']
while len(deck)>0:
    print deck.pop(roll(len(deck))),
</code>```

答:
unix shell ~ 350

This is not short or pretty, nor is it efficient, however I was wondering how hard it would be to do this with standard unix shell utilities.

This answer chops up the infinite binary string into 6 bit lengths and only chooses those that are in the correct range (1-52), here the infinite binary string is simulated by urandom and xxd:

```<code></dev/urandom xxd -b | cut -d' ' -f2-7 | tr -d ' \n'
</code>```

The chopping and selection is done with fold, sed and bc:

```<code>random_source | {echo ibase=2; cat | fold -w6 | sed -r 's/^/if(/; s/([^\(]+)$/\1 <= 110100 \&\& \1 > 0) \1/'}
</code>```

This produces lines such as:

```<code>if(101010 <= 110100 && 101010 > 0) 101010
</code>```

Which can be directed into bc.

From this stream of numbers, the sequence of the deck is chosen like this (I'm using zsh, but most modern shells should be adaptable to this):

```<code>deck=({1..52})
seq_of_numbers | while read n; do
  if [[ -n $deck[n] ]]; then
    echo $n; deck[n]=""
    [[ $deck[*] =~ "^ *$" ]] && break
  fi
done
</code>```

The randomized number sequence now needs to be changed into card names. The card name sequence is easily generated with GNU parallel:

```<code>parallel echo '{2}{1}' ::: c d s h ::: A {2..9} T J Q K
</code>```

Combining the output from the last two commands with paste and sorting on the numbers:

```<code>paste random_deck card_names | sort -n | cut -f2 | tr '\n' ' '
</code>```

The whole thing as one monstrous one-liner (only tested in zsh):

```<code>paste \
  <(deck=({1..52}); \
    </dev/urandom xxd -b | cut -d' ' -f2-7 | tr -d ' \n' |
      {echo ibase=2; fold -w6 | sed -r 's/^/if(/; s/([^\(]+)$/\1 <= 110100 \&\& \1 > 0) \1/'} |
      bc |
      while read n; do
        if [[ -n $deck[n] ]]; then
          echo $n; deck[n]=""
          [[ -z ${${deck[*]}%% *} ]] && break
        fi
      done) \
  <(parallel echo '{2}{1}' ::: c d s h ::: A {2..9} T J Q K) |
sort -n | cut -f2 | tr '\n' ' '
</code>```

Edit - added bash version

Here is a version that works in bash. I removed the in-shell { } and array indexes are zero based. Array emptiness is checked with parameter expansion, slightly more efficient and also adopted in the example above.

```<code>paste \
  <(deck=($(seq 52)); \
    </dev/urandom xxd -b | cut -d' ' -f2-7 | tr -d ' \n' |
      (echo ibase=2; fold -w6 | sed -r 's/^/if(/; s/([^\(]+)$/\1 <= 110100 \&\& \1 > 0) \1/') |
        bc |
        while read n; do
          if [[ -n ${deck[n-1]} ]]; then
            echo $n
            deck[n-1]=""
            [[ -z ${deck[*]%% *} ]] && break
          fi
        done \
  ) \
  <(parallel echo '{2}{1}' ::: c d s h ::: A {2..9} T J Q K) |
sort -n | cut -f2 | tr '\n' ' '; echo
</code>```

Body:
unix shell ~ 350

This is not short or pretty, nor is it efficient, however I was wondering how hard it would be to do this with standard unix shell utilities.

This answer chops up the infinite binary string into 6 bit lengths and only chooses those that are in the correct range (1-52), here the infinite binary string is simulated by urandom and xxd:

</dev/urandom xxd -b | cut -d' ' -f2-7 | tr -d ' \n'

The chopping and selection is done with fold, sed and bc:

random_source | {echo ibase=2; cat | fold -w6 | sed -r 's/^/if(/; s/([^\(]+)$/\1 <= 110100 \&\& \1 > 0) \1/'}

This produces lines such as:

if(101010 <= 110100 && 101010 > 0) 101010

Which can be directed into bc.

From this stream of numbers, the sequence of the deck is chosen like this (I'm using zsh, but most modern shells should be adaptable to this):

deck=({1..52})
seq_of_numbers | while read n; do
  if [[ -n $deck[n] ]]; then
    echo $n; deck[n]=""
    [[ $deck[*] =~ "^ *$" ]] && break
  fi
done

The randomized number sequence now needs to be changed into card names. The card name sequence is easily generated with GNU parallel:

parallel echo '{2}{1}' ::: c d s h ::: A {2..9} T J Q K

Combining the output from the last two commands with paste and sorting on the numbers:

paste random_deck card_names | sort -n | cut -f2 | tr '\n' ' '

The whole thing as one monstrous one-liner (only tested in zsh):

paste \
  <(deck=({1..52}); \
    </dev/urandom xxd -b | cut -d' ' -f2-7 | tr -d ' \n' |
      {echo ibase=2; fold -w6 | sed -r 's/^/if(/; s/([^\(]+)$/\1 <= 110100 \&\& \1 > 0) \1/'} |
      bc |
      while read n; do
        if [[ -n $deck[n] ]]; then
          echo $n; deck[n]=""
          [[ -z ${${deck[*]}%% *} ]] && break
        fi
      done) \
  <(parallel echo '{2}{1}' ::: c d s h ::: A {2..9} T J Q K) |
sort -n | cut -f2 | tr '\n' ' '

Edit - added bash version

Here is a version that works in bash. I removed the in-shell { } and array indexes are zero based. Array emptiness is checked with parameter expansion, slightly more efficient and also adopted in the example above.

paste \
  <(deck=($(seq 52)); \
    </dev/urandom xxd -b | cut -d' ' -f2-7 | tr -d ' \n' |
      (echo ibase=2; fold -w6 | sed -r 's/^/if(/; s/([^\(]+)$/\1 <= 110100 \&\& \1 > 0) \1/') |
        bc |
        while read n; do
          if [[ -n ${deck[n-1]} ]]; then
            echo $n
            deck[n-1]=""
            [[ -z ${deck[*]%% *} ]] && break
          fi
        done \
  ) \
  <(parallel echo '{2}{1}' ::: c d s h ::: A {2..9} T J Q K) |
sort -n | cut -f2 | tr '\n' ' '; echo


答:
CJam (89 88 bytes)

```<code>{32|_'`>\'{<*}:A;SqS++3ew{_1="jJuUvVs"#[-4_{_0=A!3*}_{_0=A3*}_{_)A\0='s=>268*}W]=~f^1=}%
</code>```

Online demo

I never understood why CJam doesn't have regexes, but since it doesn't here's a solution which doesn't use them.

Title: Medieval orthography

Body:
CJam (89 88 bytes)

{32|_'`>\'{<*}:A;SqS++3ew{_1="jJuUvVs"#[-4_{_0=A!3*}_{_0=A3*}_{_)A\0='s=>268*}W]=~f^1=}%

Online demo

I never understood why CJam doesn't have regexes, but since it doesn't here's a solution which doesn't use them.


答:
J, 13 bytes

```<code>*/|5&p:^~*/%]
</code>```

Based on @Dennis' amazing answer.

Usage

Some test cases will need the input as extended integers which have a suffix x.

```<code>   f =: */|5&p:^~*/%]
   f 3 5 7
70 21 15
   f 40x 27 11
9801 7480 6480
   f 16x 27 25 49 11
363825 2371600 2794176 5583600 529200
</code>```

Explanation

```<code>*/|5&p:^~*/%]  Input: list B
         */    Reduce B using multiplication to get the product of the values
            ]  Identity function, get B
           %   Divide the product by each value in B, call the result M
   5&p:        Apply the totient function to each value in B, call the result P
       ^~      Raise each value in M to the power of its corresponding value in P
*/             The product of the values in B
  |            Compute each power modulo the product and return
</code>```

Try it here.

Title: A Formula for Congruences

Body:
The Chinese Remainder Theorem can be quite useful in modular arithmetic.

For example, consider the following set of congruence relations:

For sets of congruence relations like this, where all the bases (3, 5, 7 in this example) are co-prime with each other, there will be one and only one integer n between 1 and the product of the bases (3*5*7 = 105 in this example) inclusive that satisfies the relations.

In this example, the number would be 14, generated by this formula:

where 2, 4, and 0 are given from the above example.

70, 21, 15 are the coefficients of the formula and they are dependent on the bases, 3, 5, 7.

To calculate the coefficients of the formula (70, 21, 15 in our example) for a set of bases, we use the following procedure.

For each number a in a set of bases:

Find the product of all of the other bases, denoted as P.

Find the first multiple of P that leaves a remainder of 1 when divided by a. This is the coefficient of a.

For example, to calculate the coefficient that corresponds to the base 3, we find the product of all the other bases (i.e. 5*7 = 35) and then find the first multiple of that product that leaves a remainder of 1 when divided by the base.

In this case, 35 leaves a remainder of 2 when divided by 3, but 35*2 = 70 leaves a remainder of 1 when divided by 3, so 70 is the corresponding coefficient for 3. Similarly, 3*7 = 21 leaves a remainder of 1 when divided by 5 and 3*5 = 15 leaves a remainder of 1 when divided by 7.

In a nutshell

For each number a in a set of numbers:

Find the product of all of the other numbers, denoted as P.

Find the first multiple of P that leaves a remainder of 1 when divided by a. This is the coefficient of a.

The challenge

The challenge is, for a set of two or more bases, to find the set of corresponding coefficients.

The set of bases are guaranteed to be pairwise co-prime and each base is guaranteed to be larger than 1.

Your input is a list of integers as input [3,4,5] or space-separated string "3 4 5" or however your inputs work.

Your output should either be a list of integers or space-separated string that denotes the set of coefficients.

Test cases

```<code>input             output
[3,5,7]           [70,21,15]
[2,3,5]           [15,10,6]
[3,4,5]           [40,45,36]
[3,4]             [4,9]
[2,3,5,7]         [105,70,126,120]
[40,27,11]        [9801,7480,6480]
[100,27,31]       [61101,49600,56700]
[16,27,25,49,11]  [363825,2371600,2794176,5583600,529200]
</code>```

Many thanks to Leaky Nun for his help in writing this challenge. As always, if the problem is unclear, please let me know. Good luck and good golfing!

Body:
J, 13 bytes

*/|5&p:^~*/%]

Based on @Dennis' amazing answer.

Usage

Some test cases will need the input as extended integers which have a suffix x.

   f =: */|5&p:^~*/%]
   f 3 5 7
70 21 15
   f 40x 27 11
9801 7480 6480
   f 16x 27 25 49 11
363825 2371600 2794176 5583600 529200

Explanation

*/|5&p:^~*/%]  Input: list B
         */    Reduce B using multiplication to get the product of the values
            ]  Identity function, get B
           %   Divide the product by each value in B, call the result M
   5&p:        Apply the totient function to each value in B, call the result P
       ^~      Raise each value in M to the power of its corresponding value in P
*/             The product of the values in B
  |            Compute each power modulo the product and return

Try it here.


答:
ListSharp, 157 bytes

```<code>STRG a=READ[<here>+"\\a.txt"]
NUMB b=(int)Math.Sqrt(a LENGTH)
[FOREACH NUMB IN 0 TO b-1 AS x]
{
STRG t=GETRANGE a FROM [x*b+1] TO [x*b+b]
ROWS f=f+t
}
SHOW=f
</code>```

reads text from local file a.txt , im using embedded c# code and other tricks to make this work. feel free to ask me questions about this code or listsharp in general

Title: A square of text

Body:
The Challenge

Given a string, output the text in the shape of a square.

You can assume that the text will always fit in a square, and that it will never be an empty string.

You can also assume it will never have newlines.

Example

```<code>Input:
Hi, world

Output:
Hi,
 wo
rld
</code>```

Test Cases

```<code>Input:
Hi, world! Hello

Output:
Hi,
worl
d! H
ello

Input:
Lorem ipsum dolor sit amt

Output:
Lorem
 ipsu
m dol
or si
t amt

Input:
H

Output:
H
</code>```

Rules

This is code-golf, so shortest answer in bytes wins! Tiebreaker is most upvoted answer.

Standard loopholes are forbidden.

Body:
ListSharp, 157 bytes

STRG a=READ[<here>+"\\a.txt"]
NUMB b=(int)Math.Sqrt(a LENGTH)
[FOREACH NUMB IN 0 TO b-1 AS x]
{
STRG t=GETRANGE a FROM [x*b+1] TO [x*b+b]
ROWS f=f+t
}
SHOW=f

reads text from local file a.txt , im using embedded c# code and other tricks to make this work. feel free to ask me questions about this code or listsharp in general


问:
Alphabet triangle
You are to print this exact text:

```<code>A
ABA
ABCBA
ABCDCBA
ABCDEDCBA
ABCDEFEDCBA
ABCDEFGFEDCBA
ABCDEFGHGFEDCBA
ABCDEFGHIHGFEDCBA
ABCDEFGHIJIHGFEDCBA
ABCDEFGHIJKJIHGFEDCBA
ABCDEFGHIJKLKJIHGFEDCBA
ABCDEFGHIJKLMLKJIHGFEDCBA
ABCDEFGHIJKLMNMLKJIHGFEDCBA
ABCDEFGHIJKLMNONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWXWVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWXYXWVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWXYZYXWVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWXYXWVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWXWVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVWVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUVUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTUTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSTSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRSRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQRQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPQPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNOPONMLKJIHGFEDCBA
ABCDEFGHIJKLMNONMLKJIHGFEDCBA
ABCDEFGHIJKLMNMLKJIHGFEDCBA
ABCDEFGHIJKLMLKJIHGFEDCBA
ABCDEFGHIJKLKJIHGFEDCBA
ABCDEFGHIJKJIHGFEDCBA
ABCDEFGHIJIHGFEDCBA
ABCDEFGHIHGFEDCBA
ABCDEFGHGFEDCBA
ABCDEFGFEDCBA
ABCDEFEDCBA
ABCDEDCBA
ABCDCBA
ABCBA
ABA
A
</code>```

Specs

Extra trailing newlines are allowed at the end of the output.

Extra trailing spaces (U+0020) are allowed at the end of each line, including the extra trailing newlines.

You can use all lowercase instead of all uppercase, but you cannot print partially lowercase partially uppercase.

You can return the text as a function output instead of printing it in a full program.

Scoring

Since this is a triangle, and a triangle has 3 sides, and 3 is a small number, your code should be small in terms of byte-count.

答:
HTML + CSS, 884 characters

(763 characters HTML + 121 characters CSS)

Just expanding Leaky Nun's comment on MonkeyZeus's answer. (Though I might misread the comment…)

p{margin:0}p:before{content:"ABCDEFGH"}p:after{content:"HGFEDCBA"}a:before{content:"IJKLMNOP"}a:after{content:"PONMLKJI"}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>```A
ABA
ABCBA
ABCDCBA
ABCDEDCBA
ABCDEFEDCBA
ABCDEFGFEDCBA
ABCDEFGHGFEDCBA

I

IJI

IJKJI

IJKLKJI

IJKLMLKJI

IJKLMNMLKJI

IJKLMNONMLKJI

IJKLMNOPONMLKJI

Q

QRQ

QRSRQ

QRSTSRQ

QRSTUTSRQ

QRSTUVUTSRQ

QRSTUVWVUTSRQ

QRSTUVWXWVUTSRQ

QRSTUVWXYXWVUTSRQ

QRSTUVWXYZYXWVUTSRQ

QRSTUVWXYXWVUTSRQ

QRSTUVWXWVUTSRQ

QRSTUVWVUTSRQ

QRSTUVUTSRQ

QRSTUTSRQ

QRSTSRQ

QRSRQ

QRQ

Q

IJKLMNOPONMLKJI

IJKLMNONMLKJI

IJKLMNMLKJI

IJKLMLKJI

IJKLKJI

IJKJI

IJI

I
ABCDEFGHGFEDCBA
ABCDEFGFEDCBA
ABCDEFEDCBA
ABCDEDCBA
ABCDCBA
ABCBA
ABA
A```

Title: Alphabet triangle

Body:
HTML + CSS, 884 characters

(763 characters HTML + 121 characters CSS)

Just expanding Leaky Nun's comment on MonkeyZeus's answer. (Though I might misread the comment…)

p{margin:0}p:before{content:"ABCDEFGH"}p:after{content:"HGFEDCBA"}a:before{content:"IJKLMNOP"}a:after{content:"PONMLKJI"}

<pre>A
ABA
ABCBA
ABCDCBA
ABCDEDCBA
ABCDEFEDCBA
ABCDEFGFEDCBA
ABCDEFGHGFEDCBA
<p>I</p><p>IJI</p><p>IJKJI</p><p>IJKLKJI</p><p>IJKLMLKJI</p><p>IJKLMNMLKJI</p><p>IJKLMNONMLKJI</p><p>IJKLMNOPONMLKJI</p><p><a>Q</p><p><a>QRQ</p><p><a>QRSRQ</p><p><a>QRSTSRQ</p><p><a>QRSTUTSRQ</p><p><a>QRSTUVUTSRQ</p><p><a>QRSTUVWVUTSRQ</p><p><a>QRSTUVWXWVUTSRQ</p><p><a>QRSTUVWXYXWVUTSRQ</p><p><a>QRSTUVWXYZYXWVUTSRQ</p><p><a>QRSTUVWXYXWVUTSRQ</p><p><a>QRSTUVWXWVUTSRQ</p><p><a>QRSTUVWVUTSRQ</p><p><a>QRSTUVUTSRQ</p><p><a>QRSTUTSRQ</p><p><a>QRSTSRQ</p><p><a>QRSRQ</p><p><a>QRQ</p><p><a>Q</a></p><p>IJKLMNOPONMLKJI</p><p>IJKLMNONMLKJI</p><p>IJKLMNMLKJI</p><p>IJKLMLKJI</p><p>IJKLKJI</p><p>IJKJI</p><p>IJI</p><p>I</p>ABCDEFGHGFEDCBA
ABCDEFGFEDCBA
ABCDEFEDCBA
ABCDEDCBA
ABCDCBA
ABCBA
ABA
A


问:
Can you outgolf me? (Cops section)

Cops section

The robbers section can be found here.

Thanks to FryAmTheEggman, Peter Taylor, Nathan Merrill, xnor, Dennis, Laikoni and Mego for their contributions.

Challenge

Your task is to write 2 different programs (full programs/functions/etc.) in the same language and the same version (e.g. Python 3.5 ≠ Python 3.4, so that is not allowed), and when given n (using STDIN/function arguments/etc.), compute a(n) where a is an OEIS sequence of your choice. One of those programs is shorter than the other. You only need to submit the longer program of the two. The other one needs to be saved in case of not being cracked after 7 days. Your submission is cracked when your program has been outgolfed (whether it is by 1 byte or more).

For example, if the task you chose was to perform 2 × n, this could be a valid submission (in Python 2):

Python 2, 16 bytes, score = 15 / 16 = 0.9375

```<code>print(2*input())
</code>```

Computes A005843, (offset = 0).

If your submission has been cracked, then you need to state that in your header like so:

Python 2, 16 bytes, score = 15 / 16 = 0.9375, [cracked] + link

```<code>print(2*input())
</code>```

Computes A005843, (offset = 0).

Offset

This can be found on every OEIS page. For example, for A005843, the offset is 0,2. We only need to use the first one, which is 0. This means that the function is defined for all numbers ≥ 0.

In other words, the function OEIS(n) starts with n = 0. Your program needs to work for all cases given by OEIS.

More information can be found here.

Scoring

The score you get for your submission is equal to the following formula:

Score = Length (in bytes) of secret code ÷ Length (in bytes) of public code

The example above has the score 15 ÷ 16 = 0.9375.

The submission with the lowest score wins. Only submissions that have posted their solution will be eligible for winning.

Rules

The task you need to do is an OEIS sequence of your choice.

Given n, output OEIS(n). Deviation is not allowed, so you need to produce the exact same sequence (when given n, you need to output OEIS(n)).

Submissions that are not cracked within a period of 7 days are considered safe after the solution has been posted (submissions older than 7 days that do not have their solution posted are still vulnerable in being cracked).

In your submission, you need to post the following things: language name, byte count, full code, so no pastebin links etc. (to prevent answers like Unary), OEIS sequence, score with lengths of both programs and additionally, the encoding that is used.

Note: the same sequence cannot be posted twice in the same language. (For example, if the sequence A005843 has been done in Pyth, you cannot use Pyth again for that same sequence.)

Input and output are both in decimal (base 10)

Leaderboard

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

Uncracked submissions

 Language	 Score	 User

Sort by: score creation

Safe submissions

 Language	 Score	 User

```

Note

This challenge is finished. The final winner is feersum with his Seed answer. Congratulations! :).

You can still submit new cops, but be aware that they are no longer competing.

答:
Sesos, 14 bytes, score = 0.8571 (12/14) (cracked)

```<code>0000000: 16f8be 760e1e 7c5f3b 07ddc7 ce3f                  ...v..|_;....?
</code>```

Computes A000290.

Try it online!

Hints

This binary file has been generated by the following assembler:

set numin
set numout
get
jmp,sub 1,fwd 1,add 1,fwd 1,add 1,rwd 2,jnz
fwd 1
jmp
  sub 1,fwd 1
  jmp,sub 1,fwd 1,add 1,fwd 1,add 1,rwd 2,jnz
  fwd 1
  jmp,sub 1,rwd 1,add 1,fwd 1,jnz
  rwd 2
jnz
fwd 3
put
```

Title: Can you outgolf me? (Cops section)

Body:
Sesos, 14 bytes, score = 0.8571 (12/14) (cracked)

0000000: 16f8be 760e1e 7c5f3b 07ddc7 ce3f                  ...v..|_;....?

Computes A000290.

Try it online!

Hints

This binary file has been generated by the following assembler:

set numin
set numout
get
jmp,sub 1,fwd 1,add 1,fwd 1,add 1,rwd 2,jnz
fwd 1
jmp
  sub 1,fwd 1
  jmp,sub 1,fwd 1,add 1,fwd 1,add 1,rwd 2,jnz
  fwd 1
  jmp,sub 1,rwd 1,add 1,fwd 1,jnz
  rwd 2
jnz
fwd 3
put


答:
PowerShell, 56 <s>58</s> <s>61</s> bytes

```<code>param($i)$i-replace".{$([Math]::Sqrt($i.Length))}",'$&
'
</code>```

Title: A square of text

Body:
PowerShell, 56 <s>58</s> <s>61</s> bytes

param($i)$i-replace".{$([Math]::Sqrt($i.Length))}",'$&
'