title: Find the reference angle

text:
# Question
Title: Find the reference angle
This is a fairly simple question. According to this random website I found — Web Archive, a reference angle is `the acute angle formed by the terminal side of the given angle and the x-axis.` You have to write a program to find these.

## I don't remember anything from algebra 2, what does this mean?

Angles are usually given in **standard form**, which is measured by placing one side of the angle and measuring to the other side, counterclockwise, like so:

This will be your input. Your output will be the reference angle of this. You can think of this as basically the smallest distance from the terminal side to the x-axis. Except it's an angle, not a distance. Here are some examples:

## Clarifications

* All the defaults on inputs and submissions.
* Angles is in **degrees**.
* Negative angles, non-integer angles, and angles \> 360 deg **are** allowed.
* Output in form `60 deg`.
* This is , so shortest code in bytes wins!

Another helpful link.

## Test Cases

```
70      ->  70 deg
135     ->  45 deg
210     ->  30 deg
-60     ->  60 deg
91      ->  89 deg
610     ->  70 deg
-1000   ->  80 deg

```

# Answer
> 7 votes
# Pyth, 17 bytes

```
+hS%R180,Q_Q" deg

```

Coincidentally, this is equivalent to @xnor's answer.

Try it online.

# Answer
> 6 votes
## Pyth, 18 bytes

```
+.a-%+QK90yKK" deg

```

Try it online.

# Answer
> 5 votes
# Python 2, 34 bytes

```
lambda x:`90-abs(x%180-90)`+' deg'

```

Using `"%d deg"` string formatting would be longer because of the needed parentheses.

# Answer
> 5 votes
## CJam (21 bytes)

```
180qd1$%z_@@-e<" deg"

```

Online demo

# Answer
> 4 votes
# dc, 25

```
90?90+d*v180%-d*vn[ deg]p

```

Note `dc` uses `_` as a -ve sign instead of `-`.

### Test output:

```
$ for test in 70 135 210 _60 91 610 _1000; do dc -e'90?90+d*v180%-d*vn[ deg]p' <<< $test ; done
70 deg
45 deg
30 deg
60 deg
89 deg
70 deg
80 deg
$

```

# Answer
> 3 votes
## Python 2, 35

```
lambda x:`min(x%180,-x%180)`+' deg'

```

The smaller of the angle and its negative modulo `180`. Effectively converts the angle to the range from 0 to 180 and takes the distance to the closer of the endpoints. Note that `-x%180` groups as `(-x)%180`.

Same length with string formatting for Python 3:

```
lambda x:'%d deg'%min(x%180,-x%180)

```

# Answer
> 3 votes
# Mathematica, ~~22~~ 31

```
ToString@Abs@Mod[#,180,-90]deg&

```

# Answer
> 3 votes
# Pyth ~~25~~ 30 bytes

Painfully uncreative solution, using trig functions. Permalink

```
+.R.t.a.t.t.tQ7Z3 6?%Q1Q0" deg

```

Any suggestions welcome.

# Answer
> 1 votes
## JavaScript (ES6), 43 bytes

Similar to Sp3000's answer, though the modulo is quite lengthy due to the behaviour in JavaScript.

```
f=x=>90-Math.abs((x%180+180)%180-90)+' deg'

```

### Demo

Code is rewritten in ES5 for browser compatibility:

```
function f(x){return 90-Math.abs((x%180+180)%180-90)+' deg'}

// Snippet stuff
console.log = function(x){document.body.innerHTML += x + '<br>'};
[70,135,210,-60,91,610,-1000].map(function(v){console.log(f(v))});
```

## CoffeeScript, 45 bytes

```
f=(x)->90-Math.abs((x%180+180)%180-90)+' deg'

```

# Answer
> 1 votes
# J, 26 bytes

```
m=:180&|
' deg',~m@-":@<.m

```

Same as xnor's method.

# Answer
> 1 votes
## Matlab, 44

Using an anonymous function:

```
f=@(x)[num2str(min(mod([x -x],180))) ' deg']

```

Example:

```
>> f=@(x)[num2str(min(mod([x -x],180))) ' deg']
f =
    @(x)[num2str(min(mod([x,-x],180))),' deg']

>> f(70)
ans =
70 deg

>> f(210)
ans =
30 deg

>> f(-1000)
ans =
80 deg

```

# Answer
> 1 votes
# Scala, ~~40~~ 35 Characters

```
(a:Int)⇒s"${90-(a%180-90).abs} deg"

```

# Answer
> 0 votes
# Tcl, 83 bytes

```
proc R a {puts [expr [set a $a%360]>90?$a>180?$a>270?360-$a:$a-180:180-$a:$a]\ deg}

```

Try it online!

# Answer
> -1 votes
## PHP, 44 bytes

Takes one command line parameter. Again PHP suffers from the same issue as JavaScript.

```
<?=90-abs(($argv[1]%180+180)%180-90)+' deg';

```

Using the canonical solution requires 53 bytes (the degrees and radians conversion takes a lot of characters):

```
<?=rad2deg(abs(asin(sin(deg2rad($argv[1])))))+' deg';

```

---
Tags: code-golf, math, geometry
---


title: Clock Hand Syzygy

text:
# Question
Title: Clock Hand Syzygy
(massive thanks to El'endia Starman and Sp3000 for helping me design test cases for this!)

Given a positive integer `n` and a list of positive integer rotational periods for a number of clock hands (in seconds), output the smallest positive integer `x` where `x` seconds after starting the clock with all of the hands aligned, exactly `n` of the hands are aligned. They do not have to be aligned at the starting position - any position is fine, as long as `x` is an integer and is minimized. In addition, not all of the hands have to be aligned at the same position - for `n=4`, a solution where 2 groups of 2 hands are aligned is valid. Groups must be of size 2 or greater - two unaligned hands do not constitute 2 groups of 1 aligned hand, and thus is not a valid solution.

You may assume that only inputs where it is possible to have exactly `n` hands aligned after an integer number of seconds will be given - `2, [3,3,3]` is not a valid input, because after any number of seconds, all 3 hands will be aligned, and so it is impossible to get exactly 2 aligned.

Examples:

```
2, [3,4] -> 12
(the only option is a multiple of 12, so we pick 12 - 4 and 3 full rotations, respectively)

3, [3,5,6,9,29] -> 18
(picking 3, 6, and 9, the hands would align after 6, 3, and 2 rotations, respectively)

2, [1,1,4,5,10] -> 1
(picking 1 and 1 - note that 0 is not a valid answer because it is not a positive integer)

3, [2,2,6,7,11] -> 3
(picking 2, 2, and 6 - the 2s would be halfway through their second revolution, and the 6 would be halfway through its first revolution)

2, [2,7,5,3,3] -> 1
(picking 3 and 3, they are always aligned, so 1 is the minimum)

5, [4, 14, 36, 50, 63, 180, 210] -> 45
(after 45 seconds, the first, third, and sixth are aligned, as well as the second and seventh, for a total of 5)

```

### Test Data:

```
7, [10, 22, 7, 6, 12, 21, 19] -> 87780
6, [25, 6, 2, 19, 11, 12] -> 62700
6, [23, 1, 8, 10, 9, 25] -> 41400
7, [6, 4, 1, 8, 10, 24, 23] -> 920
3, [18, 5, 23, 20, 21] -> 180
5, [10, 8, 14, 17, 5, 9] -> 2520
6, [1, 18, 12, 9, 8, 10, 23] -> 360
6, [12, 11, 6, 23, 25, 18, 13] -> 118404
4, [18, 11, 2, 9, 12, 8, 3] -> 8
7, [18, 25, 9, 13, 3, 5, 20] -> 11700
2, [17, 20, 15, 8, 23, 3] -> 15
3, [16, 3, 24, 13, 15, 2] -> 24
5, [7, 23, 24, 8, 21] -> 1932
6, [16, 10, 12, 24, 18, 2, 21] -> 720
6, [1, 17, 16, 13, 19, 4, 15] -> 53040
2, [3, 4, 20] -> 5
3, [9, 4, 16, 14, 1, 21] -> 16
5, [5, 17, 10, 20, 12, 11] -> 330
2, [21, 5, 22, 18] -> 90
4, [7, 25, 2, 8, 13, 24] -> 84
4, [13, 19, 2, 20, 7, 3] -> 420
5, [4, 14, 36, 50, 63, 180, 210] -> 45
5, [43, 69, 16, 7, 13, 57, 21] -> 27664
3, [22, 46, 92, 43, 89, 12] -> 276
4, [42, 3, 49, 88, 63, 81] -> 882
6, [2, 4, 7, 10, 20, 21, 52, 260] -> 65
6, [2, 3, 4, 7, 10, 20, 21, 52, 260] -> 35
2, [3, 4] -> 12
3, [3, 5, 6, 9, 29] -> 18
2, [1, 1, 4, 5, 10] -> 1
3, [2, 2, 6, 7, 11] -> 3
3, [41, 13, 31, 35, 11] -> 4433
3, [27, 15, 37, 44, 20, 38] -> 540
5, [36, 11, 14, 32, 44] -> 22176
3, [171, 1615, 3420] -> 3060
3, [46, 36, 12, 42, 28, 3, 26, 40] -> 36
5, [36, 25, 20, 49, 10, 27, 38, 42] -> 1350
4, [40, 28, 34, 36, 42, 25] -> 2142
5, [24, 26, 47, 22, 6, 17, 39, 5, 37, 32] -> 1248
4, [9, 27, 12, 6, 44, 10] -> 108

```

### Rules:

* Standard loopholes are forbidden
* This is , so shortest code wins!

# Leaderboard

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

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

```
## Language Name, N bytes

```

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

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

```

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

```
## Perl, 43 + 2 (-p flag) = 45 bytes

```

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

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

```

```
<style>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; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 64424; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 45941; 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,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\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 = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); 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; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) 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); } }</script>
```

# Answer
# Pyth, ~~28~~ ~~27~~ 24 bytes

```
fqs-hMrS.RR7%R1cLTQ8 1vz

```

Try it online in the Pyth Compiler.

### How it works

```
fqs-hMrS.RR7%R1cLTQ8 1vz

                          (implicit) Save the input number in z (as string).
                          (implicit) Save the input list in Q.

f                         Find the first positive integer T such that:
               cLTQ         Compute T/α for each α in Q.
            %R1             Get the fractional part of each result.
        .RR7                Round each fractional part to 7 decimal digits.
       S                    Sort the resulting numbers.
      r            8        Perform run-length encoding.
    hM                      Get the lengths of the runs.
   -                 1      Discard runs of length 1.
  s                         Add the remaining runs.
 q                    vz    Check is the sum matches the input number.
                          If it does, break and return T.

```

### Test cases

```
$ cat input
7\n[10, 22, 7, 6, 12, 21, 19]\n87780
6\n[25, 6, 2, 19, 11, 12]\n62700
6\n[23, 1, 8, 10, 9, 25]\n41400
7\n[6, 4, 1, 8, 10, 24, 23]\n920
3\n[18, 5, 23, 20, 21]\n180
5\n[10, 8, 14, 17, 5, 9]\n2520
6\n[1, 18, 12, 9, 8, 10, 23]\n360
6\n[12, 11, 6, 23, 25, 18, 13]\n118404
4\n[18, 11, 2, 9, 12, 8, 3]\n8
7\n[18, 25, 9, 13, 3, 5, 20]\n11700
2\n[17, 20, 15, 8, 23, 3]\n15
3\n[16, 3, 24, 13, 15, 2]\n24
5\n[7, 23, 24, 8, 21]\n1932
6\n[16, 10, 12, 24, 18, 2, 21]\n720
6\n[1, 17, 16, 13, 19, 4, 15]\n53040
2\n[3, 4, 20]\n5
3\n[9, 4, 16, 14, 1, 21]\n16
5\n[5, 17, 10, 20, 12, 11]\n330
2\n[21, 5, 22, 18]\n90
4\n[7, 25, 2, 8, 13, 24]\n84
4\n[13, 19, 2, 20, 7, 3]\n420
5\n[4, 14, 36, 50, 63, 180, 210]\n45
5\n[43, 69, 16, 7, 13, 57, 21]\n27664
3\n[22, 46, 92, 43, 89, 12]\n276
4\n[42, 3, 49, 88, 63, 81]\n882
6\n[2, 4, 7, 10, 20, 21, 52, 260]\n65
6\n[2, 3, 4, 7, 10, 20, 21, 52, 260]\n35
2\n[3, 4]\n12
3\n[3, 5, 6, 9, 29]\n18
2\n[1, 1, 4, 5, 10]\n1
3\n[2, 2, 6, 7, 11]\n3
3\n[41, 13, 31, 35, 11]\n4433
3\n[27, 15, 37, 44, 20, 38]\n540
5\n[36, 11, 14, 32, 44]\n22176
3\n[171, 1615, 3420]\n3060
3\n[46, 36, 12, 42, 28, 3, 26, 40]\n36
5\n[36, 25, 20, 49, 10, 27, 38, 42]\n1350
4\n[40, 28, 34, 36, 42, 25]\n2142
5\n[24, 26, 47, 22, 6, 17, 39, 5, 37, 32]\n1248
4\n[9, 27, 12, 6, 44, 10]\n108
$ while read -r; do echo -e "$REPLY" | pyth -c 'qvwfqs-hMrS.RR7%R1cLTQ8 1vz'; done < input
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True

```
> 6 votes

# Answer
# Jelly, ~~19~~ 16 bytes

```
P:×ⱮP%PĠẈḟ1Sʋ€iƓ

```

Takes the array as argument, the integer from STDIN.

Way too slow and memory hungry for most of the test cases.

Try it online!

### Alternate version, 14 bytes

```
P÷€%1ĠẈḟ1Sʋ€iƓ

```

This works in theory, but it may fail due to floating-point inaccuracies.

Try it online!

### How it works

```
P:×ⱮP%PĠẈḟ1Sʋ€iƓ  Main link. Argument: A (array)

P   P P           Yield the product of A.
 :                Divide the product by each n in A.
  ×Ɱ              Multiply the quotients by each k in [1, ..., prod(A)].
     %            Take the results modulo the product.
             €    Map the link to the left over the array of remainders.
            ʋ       Combine the links to the left into a dyadic chain.
       Ġ              Group indices of identical elements.
        Ẉ             Widths; yield the lengths of the groups.
         ḟ1           Filterfalse; remove all copies of 1.
           S          Take the sum.
               Ɠ  Read an integer j from STDIN.
              i   Find the first index of j in the array of sums.

```
> 2 votes

# Answer
# CJam, ~~42~~ ~~34~~ 33 bytes

```
0{)_eas~@d\f/1f%7fmO$e`0f=1m1b-}g

```

Try this fiddle or this test suite in the CJam interpreter.

### How it works

```
0       e# Push 0 (accumulator).
{       e# Do:
  )_    e#   Increment the accumulator and push a copy.
  eas~  e#   Push the command-line args, flatten and evaluate.
        e#   This pushes a number and an array.
  @d    e#   Rotate the accumulator copy on top and cast to Double.
  \f/   e#   Divide it by each of the integers in the array.
  1f%   e#   Get the fractional part of each result.
  7fmO  e#   Round all fractional parts to seven decimal digits.
  $e`   e#   Sort and perform run-length encoding.
  0f=   e#   Select the lengths of the runs.
  X-    e#   Discard runs of length 1.
  Xb    e#   Compute the sum of the remaining runs.
  -     e#   Subtract the sum from the input number (target).
}g      e# If this pushes a non-zero value, we've missed the target;
        e# repeat the loop.

```
> 1 votes

# Answer
# Jelly, 15 bytes

```
÷_:ĠẈḟ1S⁼⁴
1ç1#

```

Try it online!

Full program.

Suffers from floating-point inaccuracies.
> 0 votes

---
Tags: code-golf, math
---


# Question
Title: Align function arguments on their own lines
Given an input of a string representing a function definition, output the string with newlines and spaces inserted so that the function's arguments are newline-separated and aligned.

The input string will follow the following pattern:

* First, it will start with a prefix, which is always at least one character long and does not contain any of the characters `,()`.
* An open parenthesis (`(`) will then mark the beginning of the argument list.
* A list of zero or more arguments will then follow. These are separated by the string `", "` (a comma and then a space). None of the arguments will contain any of the characters `,()`.
* A close parenthesis (`)`) will mark the end of the argument list.
* Lastly, a postfix may be found, which is zero or more characters long and **may** contain the characters `,()`.

The input string will consist solely of printable ASCII (which means it will never contain a newline).

The output must be:

* The prefix, copied down verbatim, and the open parenthesis.
* The argument list, this time separated not by `", "` but by a comma, newline, and as many spaces as is needed to vertically align the first character of each argument.
* The close paren and postfix (if it exists) verbatim.

Since this is , the shortest code in bytes will win.

Test cases (format: single-line input followed by output followed by double newline):

```
def foo(bar, baz, quux):
def foo(bar,
        baz,
        quux):

int main() {
int main() {

fn f(a: i32, b: f64, c: String) -> (String, Vec<i32>) {
fn f(a: i32,
     b: f64,
     c: String) -> (String, Vec<i32>) {

function g(h) {
function g(h) {

def abc(def, ghi, jkl, mno)
def abc(def,
        ghi,
        jkl,
        mno)

x y z(x, y, z) x, y, z)
x y z(x,
      y,
      z) x, y, z)

```

# Answer
## Haskell, 115 bytes

```
import Data.Lists
f x|(a,b:c)<-span(/='(')x,(d,e)<-span(/=')')c=a++b:intercalate(",\n "++(a>>" "))(splitOn", "d)++e

```

Usage example:

```
*Main> putStrLn $ f "fn f(a: i32, b: f64, c: String) -> (String, Vec<i32>) {"
fn f(a: i32,
     b: f64,
     c: String) -> (String, Vec<i32>) {

```

How it works:

```
bind
  a: everything before the first (
  b: the first (
  c: everything after the first (
  d: everything of c before the first )
  e: everything of c from the first ) to the end

construct the output string by concatenating
  a
  b
  splitting d at the argument separator ", " and rejoining it with ",\n " followed by (length a) spaces
  e

```
> 7 votes

# Answer
# Japt, 23 bytes

```
¡Y?X:Xr',",
"+SpUb'(}')

```

Test it online!

### How it works

```
               // Implicit: U = input string
¡        }')   // Map each item X and index Y in U.split(")") to:
Y?X            //  If Y is non-zero, X. This keeps e.g. "(String, Vec<i32>)" from being parsed.
:Xr',",\n"+    //  Otherwise, X with each comma replaced with ",\n" concatenated with
SpUb'(         //  U.indexOf("(") spaces.
               // Implicit: re-join with ")", output

```
> 4 votes

# Answer
## Perl, ~~62~~ 52 + 2 = 54 bytes

```
s/\(.*?\)/$a=$"x length$`;$&=~s|(?<=,)[^,]+|\n$a$&|gr/e

```

Requires the `-p` flag:

```
$ echo "x y z(x, y, z) x, y, z)
fn f(a: i32, b: f64, c: String) -> (String, Vec<i32>) {" | \
perl -pe's/\(.*?\)/$a=$"x length$`;$&=~s|(?<=,)[^,]+|\n$a$&|gr/e'
x y z(x,
      y,
      z) x, y, z)
fn f(a: i32,
     b: f64,
     c: String) -> (String, Vec<i32>) {

```

How it works:

```
# '-p' reads first line into $_ and will also auto print at the end
s/\(.*?\)/             # Match (...) and replace with the below
  $a=$"x length$`;     # $` contains all the content before the matched string
                       # And $" contains a literal space
  $&=~s|               # Replace in previous match
    (?<=,)[^,]+        # Check for a , before the the string to match
                       # This will match ' b: f64', ' c: String'
  |\n$a$&|gr/e         # Replace with \n, [:spaces:] and all the matched text

```
> 3 votes

# Answer
# Retina, 31 bytes

```
(?<=^([^(])*\([^)]*,)
¶ $#1$*

```

Note the spaces at the end of both lines.

We replace every space which has the regex `^([^(])*\([^)]*,` before it. The replacing string will be a newline, and the number of the captures with `([^(])*` plus one spaces.

A more coherent explanation comes later.

Try it online here.
> 3 votes

# Answer
## ES6, ~~68~~ 67 bytes

```
s=>s.replace(/\(.*?\)/,(s,n)=>s.replace/, /g, `,
 `+` `.repeat(n)))

```

This works by extracting the argument list from the original string, and replacing each argument separator with indentation calculated from the position of the argument list within the original string.

Edit: Saved 1 byte thanks to @ETHproductions.
> 3 votes

# Answer
# Pyth, ~~35~~ 30 bytes

```
+j++\,b*dhxz\(c<zKhxz\)", ">zK

```

Try it here!

### Explanation:

```
+j++\,b*dhxz\(c<zKhxz\)", ">zK    # z = input()

                 Khxz\)           # Get index of the first ")"
               <z                 # Take the string until there...
              c        ", "       # ...and split it on the arguments
 j                                # Join the splitted string on...
  ++                              # ...the concatenation of...
    \,b                           # ...a comma followed by a newline...
       *dhxz\(                    # ...followed by the right amount of spaces = index of the first "(" + 1
+                         >zK     # Concat the resulting string with the postfix

```
> 2 votes

# Answer
# Groovy, ~~137~~ ~~89~~ 95 bytes

~~Groovy is ***not*** the "Right Tool for the Job"™.~~ Edit: It works just fine when you have someone with a brain using it...

```
f={s=(it+' ').split(/\0/)
s[0].replace(',',',\n'+(' '*it.indexOf('(')))+')'+s[1..-1].join(')')}

```

Tests:

```
println f("def foo(bar, baz, quux):")
println f("int main() {")
println f("fn f(a: i32, b: f64, c: String) -> (String, Vec<i32>) {")
println f("function g(h) {")
println f("def abc(def, ghi, jkl, mno)")
println f("x y z(x, y, z) x, y, z)")

```

Somewhat ungolfed:

```
f = {String it ->
    def str = (it + ' ').split(/\)/)
    return (str[0].replace (',', ',\n'+(' ' * it.indexOf('('))) + ')' + str[1])
}

```
> 2 votes

# Answer
## Retina, 47 bytes

Byte count assumes ISO 8859-1 encoding.

```
m+`^(([^(]+.)[^,)]+,) (.+)
$1¶$2$3
T`p` `¶.+?\(

```

Try it online!
> 1 votes

# Answer
# JavaScript (ES6), 85

```
s=>s.replace(/^.*?\(|[^),]+, |.+/g,(x,p)=>[a+x,a=a||(p?`
`+' '.repeat(p):a)][0],a='')

```

**Test**

```
f=s=>s.replace(/^.*?\(|[^),]+, |.+/g,(x,p)=>[a+x,a=a||(p?`
`+' '.repeat(p):a)][0],a='')

console.log=x=>O.textContent+=x+'\n'

;['def foo(bar, baz, quux):',
  'int main() {',
  'fn f(a: i32, b: f64, c: String) -> (String, Vec<i32>) {',
  'function g(h) {',
  'def abc(def, ghi, jkl, mno)',
  'x y z(x, y, z) x, y, z)']
.forEach(t=>console.log(t+'\n'+f(t)+'\n'))
```

```
<pre id=O></pre>
```
> 1 votes

# Answer
# Jelly, 39 bytes

```
ṣ”)Ḣṣ”(Ṫ©œṣ⁾, ji”(⁶ẋƊ⁾,¶;ƊḢ,j®${jʋ@œṣ®$

```

Try it online!
> 0 votes

---
Tags: code-golf, string
---


# Question
Title: Expand shorthand increasing integer sequences
Given an input of a list of numbers in the format of a shorthand increasing integer sequence, output the sequence in full.

Shorthand increasing integer sequence format works by finding every number *n* with fewer digits than the number preceding it, *m*. With *d* as the number of digits in *n*, the last *d* digits of *m* are replaced with all the digits of *n*. Here's an example input:

```
123 45 6 7 89 200

```

Applying the replacement rule, we first turn 45 into 145 because 45 \< 123:

```
123 145 6 7 89 200

```

Repeatedly applying the same rule, this becomes:

```
123 145 146 7 89 200
123 145 146 147 89 200
123 145 146 147 189 200

```

The sequence is now sorted (there are no numbers for which the rule applies), so this is the final output.

You may assume that

* shorthand notation is always used when possible. For example, input will be `12 3`, never `12 13`.
* numbers will never decrease while remaining the same number of digits. For example, input will never be `333 222`.
* applying the shorthand rule will never result in a number that is still less than the previous number in the sequence. For example, input will never be `123 12`.
* numbers will always be positive integers and never contain leading 0s (if using a string format).
* the full, expanded sequence will never contain duplicate numbers. (However, the shorthand sequence might; ex. `10 1 20 1` -\> `10 11 20 21`.)
* there will be at least one number in the input.

Input and output can be either lists/arrays of numbers/strings or a single string with elements separated by any non-digit.

Since this is , the shortest code in bytes will win.

Test cases, with input and output on alternating lines:

```
1 2 3 10 1 2 20 5 100 200 10 3 5 26 9 99 999 9999
1 2 3 10 11 12 20 25 100 200 210 213 215 226 229 299 999 9999
223 1184 334 441 5 927 2073 589 3022 82 390 5 9
223 1184 1334 1441 1445 1927 2073 2589 3022 3082 3390 3395 3399
5 10 5 20 5 30 5 40 5 50 5
5 10 15 20 25 30 35 40 45 50 55
7 8 9 70 80 90 700 800 900 7000 8000 9000
7 8 9 70 80 90 700 800 900 7000 8000 9000
42
42

```

# Answer
> 7 votes
# Jelly, 7 bytes

```
DUṛ"\UḌ

```

Try it online! or verify all test cases.

### How it works

```
DUṛ"\UḌ  Main link. Input: A (list of integers)

D        Convert each integer to a list of its base 10 digits.
 U       Reverse each digit list.
    \    Do a cumulative reduce, applying the dyadic link to the left:
   "       For each pair of corresponding digits:
  ṛ          Select the right one.
           Vectorization leaves digits that do not have a counterpart untouched.
     U   Reverse the resulting digit arrays.
      Ḍ  Convert from base 10 to integer.

```

# Answer
> 5 votes
# Javascript, ~~45~~ 42 bytes

3 bytes off thanks @Neil.

```
a=>a.map(x=>z=z.slice(0,-x.length)+x,z='')

```

The above function expects an array of strings.

```
f=
a=>a.map(x=>z=z.slice(0,-x.length)+x,z='')

F=a=>document.body.innerHTML+='<pre>'+a+'\n'+f(a)+'\n</pre>';

F(['1','2','3','10','1','2','20','5','100','200','10','3','5','26','9','99','999','9999'])
F(['223','1184','334','441','5','927','2073','589','3022','82','390','5','9'])
F(['5','10','5','20','5','30','5','40','5','50','5'])
F(['7','8','9','70','80','90','700','800','900','7000','8000','9000'])
```

# Answer
> 1 votes
# Retina, 45 bytes

```
+`(?=(?<1>\d)+)(?<=(\d)(?(1)x)(?<-1>\d)+ )
$1

```

Uses balancing groups to count the digits which costs a lot. Haven't found a better approach yet but I'm interested in it.

Try it online here.

# Answer
> 0 votes
# Gema, 35 characters

```
<D>=@set{p;@fill-right{${p;};$0}}$p

```

Input: string with numbers separated by anything, output string.

Sample run:

```
bash-4.3$ gema '<D>=@set{p;@fill-right{${p;};$0}}$p' <<< '123 45 6 7 89 200'
123 145 146 147 189 200

```

# Answer
> 0 votes
# Ruby, 39 characters

```
->a{l='';a.map{|c|l=l[0..-c.size-1]+c}}

```

Input: array of strings, output: array of strings.

Sample run:

```
2.1.5 :001 > ->a{l='';a.map{|c|l=l[0..-c.size-1]+c}}[%w{123 45 6 7 89 200}]
 => ["123", "145", "146", "147", "189", "200"]

```

# Answer
> 0 votes
# Python 2, 58 bytes

```
s=''
for i in input():s=s[:max(len(s)-len(i),0)]+i;print s

```

Try it online!

---
Tags: code-golf
---


title: Greet according to the time of day

text:
# Question
Title: Greet according to the time of day
# Challenge

Write a program that greets a user depending on what time of day (GMT) it is.

# Output

A string (printed or returned) according to these rules:

* If the time is 06:00 to 11:59 the greeting has to be "Good morning"
* If the time is 12:00 to 17:59 the greeting has to be "Good afternoon"
* If the time is 18:00 to 19:59 the greeting has to be "Good evening"
* If the time is 20:00 to 05:59 the greeting has to be "Zzz"

# Clarifications

* There is no input
* The times and greetings must be *exactly* as shown
* The time zone is +0 GMT

# Examples

```
Time: 14:45 -> Good afternoon

Time: 05:59 -> Zzz

Time: 9:23 -> Good morning

Time: 18:00 -> Good evening

```

# Answer
# JavaScript (ES6), 87 bytes

*As noticed by TFeld, my original formula was overcomplicated. We can just do:*

```
_=>['Zzz','Good morning','Good afternoon','Good evening'][new Date().getHours()%20/6|0]

```

Try it online!

Or test this version that takes the hour as parameter.

---

# JavaScript (ES6), 90 bytes

```
_=>['Zzz','Good morning','Good afternoon','Good evening'][new Date().getHours()*7%20%7>>1]

```

Try it online!

Or test this version that takes the hour as parameter.

### Formula

Given the current hour \\$h\\$, we find the appropriate greeting index \\$i\\$ with:

$$i=\left\lfloor\frac{((7\times h) \bmod 20) \bmod 7}{2}\right\rfloor$$

A good thing about this formula is that it does not require any parenthesis once converted to JS:

```
h * 7 % 20 % 7 >> 1

```

### Table

```
 Hour |  *7 | mod 20 | mod 7 | >> 1
------+-----+--------+-------+------
   0  |   0 |    0   |   0   |   0
   1  |   7 |    7   |   0   |   0
   2  |  14 |   14   |   0   |   0
   3  |  21 |    1   |   1   |   0
   4  |  28 |    8   |   1   |   0
   5  |  35 |   15   |   1   |   0
   6  |  42 |    2   |   2   |   1
   7  |  49 |    9   |   2   |   1
   8  |  56 |   16   |   2   |   1
   9  |  63 |    3   |   3   |   1
  10  |  70 |   10   |   3   |   1
  11  |  77 |   17   |   3   |   1
  12  |  84 |    4   |   4   |   2
  13  |  91 |   11   |   4   |   2
  14  |  98 |   18   |   4   |   2
  15  | 105 |    5   |   5   |   2
  16  | 112 |   12   |   5   |   2
  17  | 119 |   19   |   5   |   2
  18  | 126 |    6   |   6   |   3
  19  | 133 |   13   |   6   |   3
  20  | 140 |    0   |   0   |   0
  21  | 147 |    7   |   0   |   0
  22  | 154 |   14   |   0   |   0
  23  | 161 |    1   |   1   |   0

```
> 12 votes

# Answer
# Python 2, ~~120~~ ~~106~~ 102 bytes

```
import time
print['Zzz','Good morning','Good afternoon','Good evening'][int(time.time()/3600%24%20/6)]

```

Try it online!

Testable here: Try it online!

---

Similar to Arnauld's answer, but slightly different:

```
h  %20 /6
---------
0   0   0
1   1   0
2   2   0
3   3   0
4   4   0
5   5   0
6   6   1
7   7   1
8   8   1
9   9   1
10  10  1
11  11  1
12  12  2
13  13  2
14  14  2
15  15  2
16  16  2
17  17  2
18  18  3
19  19  3
20  0   0
21  1   0
22  2   0
23  3   0

```

---

Saved:

* -3 bytes, thanks to Arnauld
* -1 byte, thanks to N. P.
> 6 votes

# Answer
**R, ~~97~~ ~~95~~ 93 Bytes**

Using methods found above in R

```
c("Zzz","Good morning","Good afternoon","Good evening")[as.POSIXlt(Sys.time(),"G")$h%%20/6+1]

```

**Explanation:**

```
c("Zzz","Good morning","Good afternoon","Good evening")      # Creates a vector with the greetings
[                                                            # Open bracket. The number in the bracket will extract the corresponding greeting from the vector below
as.POSIXlt(                                                  # as.POSIXlt converts the object to one of the two classes used to represent date/times
Sys.time(),                                                  # Retrieves the current time on the OS
"G")                                                         # Converts the time to the desired time zone. Does output a warning, but still converts properly to GMT
$h                                                           # Extracts the hour from the object created by as.POSIXlt
%%20/6                                                       # Methodology as used by other golfers
+1]                                                          # Vectors in R start from 1, and not 0 like in other languages, so adding 1 to the value ensures values range from 1 to 4, not 0 to 3

```

**Example**

Notice how this line of code, without adding 1, is short 10 elements

```
c('Zzz','Good morning','Good afternoon','Good evening')[0:23%%20/6]

[1] "Zzz"            "Zzz"            "Zzz"            "Zzz"            "Zzz"            "Zzz"
[7] "Good morning"   "Good morning"   "Good morning"   "Good morning"   "Good morning"   "Good morning"
[13] "Good afternoon" "Good afternoon"

```

Adding 1 ensures that the result obtained is greater than 0

```
c('Zzz','Good morning','Good afternoon','Good evening')[as.integer(0:23)%%20/6+1]

[1] "Zzz"            "Zzz"            "Zzz"            "Zzz"            "Zzz"            "Zzz"
[7] "Good morning"   "Good morning"   "Good morning"   "Good morning"   "Good morning"   "Good morning"
[13] "Good afternoon" "Good afternoon" "Good afternoon" "Good afternoon" "Good afternoon" "Good afternoon"
[19] "Good evening"   "Good evening"   "Zzz"            "Zzz"            "Zzz"            "Zzz"

```
> 4 votes

# Answer
# T-SQL, 153 bytes

```
SELECT CASE WHEN a>18THEN'Good afternoon'WHEN a>12THEN'Good morning'WHEN a>2THEN'Zzz'ELSE'Good evening'END
FROM(SELECT(DATEPART(hh,GETUTCDATE())+6)%24a)a

```

Try the SQL Fiddle

### Explanation:

```
SELECT
  CASE WHEN a>18 THEN'Good afternoon' --CASE returns the first value in order whose condition is met
       WHEN a>12 THEN'Good morning'
       WHEN a>2  THEN'Zzz'
       ELSE 'Good evening'
       END
FROM( SELECT (      --Use a subquery to treat the time like a 1x1 table - shorter than declaring a variable
    DATEPART(hh,    --Returns the hour part (hh) of the date
      GETUTCDATE()) --Returns current UTC time (as far as the SQL Server is concerned)
        +6)%24      --Virtual time zone where no period crosses midnight, so everything is ordered
        a)          --Give column a 1-letter alias
        a           --Give subquery an alias so SQL Server doesn't complain

```
> 3 votes

# Answer
## Perl 5, 77 bytes

```
$_=(gmtime)[2]%20;say$_<6?Zzz:"Good ".($_<12?morning:$_<18?afternoon:evening)

```

Try it online!
> 2 votes

# Answer
# Excel, 97 bytes

```
=VLOOKUP(Hour(Now()),{0,"Zzz";6,"Good morning";12,"Good afternoon";18,"Good evening";20,"Zzz"},2)

```

Start with the list of cases

> 0 \<= HOUR \< 6 : "Zzz"
> 6 \<= HOUR \< 12 : "Good morning"
> 12 \<= HOUR \< 18 : "Good afternoon"
> 18 \<= HOUR \< 20 : "Good evening"
> 20 \<= HOUR : "Zzz"

Then just use a Range-based `Vlookup` (default if you ommit the 4th argument) with an Array of values:

> `H= 0` | `"Zzz"`
> `H= 6` | `"Good morning"`
> `H=12` | `"Good afternoon"`
> `H=18` | `"Good evening"`
> `H=20` | `"Zzz"`

```
{0,"Zzz"; 6,"Good morning"; 12,"Good afternoon"; 18, "Good evening"; 20,"Zzz"}

```

I experimented with using `MOD(HOUR(NOW())+18,24` to shift the hour back by 6 and reduce the cases by 1, but that resulted in 99 bytes. :(
> 2 votes

# Answer
# 05AB1E, 36 bytes

```
”‚¿”…•´¯âžÖ#1ú«…Zzz¸«ža•1Ý;`{ùí4²•èè

```

Try it online!

---

```
”‚¿”                                 # Push 'Good'
    …•´¯âžÖ                          # Push 'morning afternoon evening'
           #                         # Split on spaces.
            1ú                       # Pad each with 1 space.
              «                      # Concat good onto it: ['Good morning',...,'Good evening']
               …Zzz¸«                # Concat 'Zzz' onto it.
                     ža              # Get current hour.
                       •1Ý;`{ùí4²•   # Push 33333000000111111222.
                                  è  # indexes[current_hour]->i[6:00AM]->0
                                   è # phrases[indexes[current_hour]]->p[i[6AM]]->'Good morning'.

```
> 2 votes

# Answer
# C# (Visual C# Interactive Compiler), 91 bytes

```
Write("Zzz,Good morning,Good afternoon,Good evening".Split(',')[DateTime.UtcNow.Hour%20/6])

```

Try it online!

Uses Utc Now to get the UTC time.

# If it can be a function instead of a full program:

# C# (Visual C# Interactive Compiler), 88 bytes

```
()=>"Zzz,Good morning,Good afternoon,Good evening".Split(',')[DateTime.UtcNow.Hour%20/6]

```

Try it online!

Test with all the hours(code stolen shamelessly from Arnauld)
> 2 votes

# Answer
# Powershell, ~~82~~ 72 bytes

Port of TFeld's answer

```
('Zzz','Good morning','Good afternoon','Good evening')[(date).Hour%20/6]

```
> 1 votes

# Answer
## Batch, 178 bytes

```
@for /f "tokens=3" %%a in ('wmic path Win32_UTCTime') do @set/ag=%%a%%20/6
@for %%a in (Zzz.0 "Good morning.1" "Good afternoon.2" "Good evening.3") do @if %%~xa==.%g% echo %%~na

```

Uses @TFeld's formula. Locale-dependent version is only 128 bytes:

```
@set/ag=%time:~,2%%%20/6
@for %%a in (Zzz.0 "Good morning.1" "Good afternoon.2" "Good evening.3") do @if %%~xa==.%g% echo %%~na

```
> 1 votes

# Answer
# Common Lisp, 103 bytes

```
(nth(floor(mod(nth-value 2(get-decoded-time))20)6)'("Zzz""Good morning""Good afternoon""Good evening"))

```

Ungolfed

```
(nth (floor (mod (nth-value 2 (get-decoded-time))
                 20)
            6)
     '("Zzz" "Good morning" "Good afternoon" "Good evening"))

```

Common Lisp mostly ignores whitespace as long as it can unambiguously determine where each sub-expression ends, so much of the golfing here is just removing whitespace. Common Lisp also provides the ability for functions to return multiple values, with all but the first discarded if the caller hasn't explicitly requested the 2nd/3rd/etc return values. This allows functions to return auxiliary data, like the `floor` function performs floor division, but as a secondary return value returns the remainder. This also allows for functions to avoid the overhead of having to package up their return values in a datastructure if the caller is likely to immediately destructure it again. `(get-decoded-time)` (really itself a shorthand for `(decode-universal-time (get-universal-time))`) returns the most values of just about any standard function in common lisp... 9, to be exact. The 3rd return value (`(nth-value 2 ...)` ) is the current hour in 24 hour time. Then it's just computing the proper index into the list of responses and passing that to `nth`. I have to use `floor` here as CL would return a proper fraction if I used `/` for division.

Try it online!
> 1 votes

# Answer
# C# (.NET Core), 177 bytes

```
using System;namespace a{class b{static void Main(string[] a){Console.WriteLine(new String[]{"Zzz","Good morning","Good afternoon","Good evening"}[DateTime.Now.Hour%20/6|0]);}}}

```

Try it online!
> 1 votes

# Answer
# Japt, 52 bytes

```
`Zzz,Good ¶rÍÁ,Good af’rÍ9,Good evÀxg`q, gKd %20/6|0

```

Try it online!
> 1 votes

# Answer
# 05AB1E, ~~45~~ 42 bytes

```
ža7*20%7%2÷U”‚¿”Xi'•´ëX<i'¯âë'žÖ]ðýX>i…Zzz

```

`(h*7%20%7)//2` ported from @Arnauld's JavaScript (ES6) answer.

Try it online or verify all hours.

---

**Original 45 bytes answer:**

```
žaDV6÷U”‚¿”Xi'•´ëX<i'¯âë'žÖ]ðýX3%>iY2÷9Êi…Zzz

```

Try it online or verify all hours.

**Explanation:**

```
ža                 # Get the current hours
  DV               # Duplicate it, and store it in variable `Y`
    6÷U            # Integer-divide it by 6, and store it in variable `X`
”‚¿”               # String "Good"
    Xi             # If `X` is 1:
      '•´          #  Use string 'morning'
    ëX<i           # Else-if `X` is 2:
        '¯â        #  Use string 'afternoon'
    ë              # Else:
     'žÖ           #  Use string 'evening'
           ]       # Close all if-elses
            ðý     # Join the two string literals with a space
X3%>i              # If `X` modulo-3 is 0:
     Y2÷9Êi        # And if `Y` integer-divided by 2 is not 9:
           …Zzz    #  Output string "Zzz" instead
                   # (Implicit else:
                   #   output top of stack, which is the "Good ...")

```

See the explanation here to understand why `”‚¿”` is "Good"; `'•´` is "morning"; `'¯â` is "afternoon"; and `'žÖ` is "evening".
> 0 votes

# Answer
# Noether, 106 bytes

```
"Good "~g{2D~d5>d12<&}{g"morning"+P}d{11>d18<&}{g"afternoon"+P}d{17>d20<&}{g"evening"+P}d{20>d6<&}{"Zzz"P}

```

**Try it online!**

The command `2D` returns the hour part of the current the time and the rest is a load of if statements.
> 0 votes

# Answer
# Haskell, 174 bytes

```
import Data.UnixTime
v h|h<10="Zzz"|1>0="Good "++y h
y h|h<16="morning"|h<22="afternoon"|1>0="evening"
main=do;t<-getUnixTime;print$v$mod(div(read.show.utSeconds$t)3600+4)24

```
> 0 votes

# Answer
# C (gcc), 127 bytes

The only really sneaky trick is coercing the hours into `unsigned int` so that I can force the night values to \>14. As the `struct tm` structure only has integers, I can pretend that it's an array being passed from `gmtime_r`.

```
char*s[]={"morning","afternoon","evening"};t,u[9];f(){t=time(0);gmtime_r(&t,u);printf(u[2]-6U>13?"Zzz":"Good %s",s[u[2]/6-1]);}

```

Try it online!
> 0 votes

# Answer
# J, 65 bytes

Another port of TFeld's answer.

```
('Zzz','Good '&,&>;:'morning afternoon evening'){~<.6%~20|3{6!:0''

```
* `3{6!:0''` gets the hour, which is index 3 of the current time vector, from the builtin `6!:0''`
* `<.6%~20|` is floor of ((hour mod 20) divided by 6)
* use that as an index `{~` into a 4x14 character array containing the greetings.
* save a few chars by concatenating (`,`) the string `Good` to the words `morning`, `afternoon`, and `evening` which are split on whitespace by the J "words" tokenizer (`;:`). It technically is for tokenizing J sentences, but since J has bare words it ends up splitting on whitespace.
> 0 votes

---
Tags: code-golf, date
---


title: What year is it?

text:
# Question
Title: What year is it?
It is December 2014, and 2015 has almost started. However, it appears not everyone has realized this.

But the people of PPCG come to the rescue!

## Input

Your program is given a grid like the one one the wall, where days that are in the month December look different from those in November and January. Each week starts with Sunday and ends with Saturday.

Days within the month are represented by a `#`. Days that fall outside the month are represented by a  (space, ASCII code 32). Each week is on a separate line. Lines are separated by a newline character (`\n`). Your program may require either the ommission or inclusion of a newline at the end of the input.

For example, this is the input for December 2009:

```
  #####
#######
#######
#######
#####

```

The calendar is always of the month December.

## Task

Given the input, you must find the year associated with the calendar. Since there are multiple years for which a calendar matches, you must return the year (before 2015) that is the closest to 2015. (Excluding 2015 itself.)

Your program must produce the correct output for any year \< 2015, excluding those which have a calendar layout for December that is equal to that of another year (before 2015) closer to 2015.

If the year is \< 2014, you must also calculate the difference of the year to 2014. For example, for 2012 the difference is `2`.

## Output

Your program's output must be:

* The text: `Your calendar is for <year>.` (Note: since this was originally spelled as “calender“, I’ll accept that spelling as well.)
* Followed by a newline (`\n` or `\r\n`).
* Followed by the text: `It's almost 2015.`
* If the year is \< 2014, this must be followed by the text: `You're <difference> years behind.` This must be on a separate line.
* Followed by a newline (`\n` or `\r\n`).
* Followed by the text: `Go buy a new calendar!`
* Optionally followed by a newline (`\n` or `\r\n`).

## Rules

* You can choose whether you want to receive the calendar as a command-line argument (e.g. `yourprogram.exe <calendar>`) or prompt for user input.
* You may assume your program won't receive invalid input. Invalid input includes calendar layout for which there exists no year.
* The shortest code (in bytes, in any language) wins.
* Any non-standard command-line arguments (arguments that aren't normally required to run a script) count towards the total character count.
* What your program **must not** do:

+ Depend on any external resources.
    + Depend on having a specific file name.
    + Output anything other than the required output.
    + Take exceptionally long to run. If your program runs over a minute on an average home user's computer, it's invalid.
* Your program must not be written in a programming language for which there did not exist a publicly available compiler / interpreter before this challenge was posted.

## Examples

**Input:**

```
  #####
#######
#######
#######
#####

```

**Output:**

```
Your calendar is for 2009.
It's almost 2015.
You're 5 years behind.
Go buy a new calendar!

```

**Input:**

```
 ######
#######
#######
#######
####

```

**Output:**

```
Your calendar is for 2014.
It's almost 2015.
Go buy a new calendar!

```

**Input:**

```
      #
#######
#######
#######
#######
##

```

**Output:**

```
Your calendar is for 2012.
It's almost 2015.
You're 2 years behind.
Go buy a new calendar!

```

# Answer
> 2 votes
# CJam, 126 bytes

```
"Your calendar is for "2e3q'##"DE9AB6C"=~+".
It's almost "2015_(".
You're 5 years behind"9@5$-:TtTg*".
Go buy a new calendar!"

```

# Answer
> 3 votes
# Python 3, 178 bytes

```
s=input();i=42157313>>s.index("#")*4&15;print("Your calendar is for %d.\nIt's almost 2015.\n%sGo buy a new calendar!"%(2014-i,(i>0)*("You're %d year%s behind.\n"%(i,"s"*(i>1)))))

```

A simple lookup table based on the location of the first `#`.

Expanded:

```
s=input()
i=42157313>>s.index("#")*4&15
print("Your calendar is for %d.\nIt's almost 2015.\n%sGo buy a new calendar!"\
    %(2014-i,(i>0)*("You're %d year%s behind.\n"%(i,"s"*(i>1)))))

```

# Answer
> 2 votes
# Perl - 187

```
$ARGV[0]=~/^( *)/;my@a=(7,8,3..5,0,6);my$b=($a[length$1]+2006);print"Your calendar is for $b.\nIt's almost 2015.\n".($b<2014?"You're ".2014-$b." years behind.\nGo buy a new calendar!":"")

```

# Answer
> 2 votes
# Perl 5: 137 143

```
#!perl -p
$_="Your calendar is for ".(2014-($%=w834506&s/#/?/r)).".
It's almost 2015.
".("You're $% years behind.
")x!!$%."Go buy a new calendar!"

```

Previous approach:

```
#!perl -p
/#/;$_="Your calendar is for ".(2014-($b=1558279/9**"@-"%9)).".
It's almost 2015.
".("You're $b years behind.
")x!!$b."Go buy a new calendar!"

```

Calendar on standard input (only the first line is significant of course)

```
perl 2014.pl <<<" ######"

```

# Answer
> 2 votes
## C#, 384, 363 325 Bytes

C# Time, please tell me if i missed out on one of the rules etc.

```
string a(string s){var l=s.IndexOf('#');var x=(DayOfWeek)Enum.Parse(typeof(DayOfWeek),""+l);l=1;for(;;){var y=DateTime.Now.Year-l;var t=(new DateTime(y,12,1).DayOfWeek==x)?"Your calendar is for "+y+"\nIt's almost 2015\n"+((y < 2014)?"You're "+--l+"years behind\n":"")+"Go buy a new calendar":null;if(t!=null){return t;}l++;}}

```

Input

```
" ######"
"#######"
"#######"
"#######"
"#####  "

```

Output

```
"Your calendar is for 2014
 It's almost 2015
 Go buy a new calendar

```

Input 2

```
"  #####"
"#######"
"#######"
"#######"
"#####  "

```

Output 2

```
"Your calendar is for 2009
 It's almost 2015
 You're 5 years behind
 Go buy a new calendar"

```

Edit: Updated, managed to remove some bytes

# Answer
> 2 votes
# C# 235

**minified:**

```
class P{static void Main(string[] a){var y=new[]{1,0,5,4,3,8,2}[a[0].IndexOf('#')];var z=2014-y;System.Console.Write("Your calendar is for "+z+"\nIt's almost 2015.\n"+(z>0?"You're "+z+" years behind.":"")+"\nGo buy a new calendar!");}}

```

**Ungolfed**

```
class P
{
    static void Main(string[] a)
    {
        var y = new[]{1,0,5,4,3,8,2}[a[0].IndexOf('#')];
        var z = 2014-y;
        System.Console.Write("Your calendar is for "+z+"\nIt's almost 2015.\n"+(z>0 ? "You're "+z+" years behind.":"")+"\nGo buy a new calendar!");
    }
}

```

Well, the language is verbose :)

# Answer
> 2 votes
# Java, 243 bytes

It's a verbose language :-)

```
class A{public static void main(String[]s){int y=2005+new int[]{8,9,4,5,0,6,7}[s[0].indexOf("#")],d=2014-y;System.out.print("Your calendar is for "+y+".\nIt's almost 2015.\n"+(d>0?"You're "+d+" years behind.\n":"")+"Go buy a new calendar!");}}

```

### Unminified

```
class A {
    public static void main(String[] s) {
        int y = 2005 + new int[]{8,9,4,5,0,6,7}[s[0].indexOf("#")],
            d = 2014 - y;
        System.out.print("Your calendar is for " + y + ".\nIt's almost 2015.\n"
            + (d > 0 ? "You're " + d + " years behind.\n" : "") + "Go buy a new calendar!");
    }
}

```

# Answer
> 1 votes
# PHP, ~~215~~ 181 bytes

## Lookup table, 181 bytes

Due to short array syntax, only works on PHP 5.4+:

```
function a($i){$y=2005+[8,9,4,5,0,6,7][strpos($i,'#')];$f=2014-$y;echo "Your calendar is for $y.\nIt's almost 2015.\n".($f?"You're $f years behind.\n":'')."Go buy a new calendar!";}

```

### Unminified

```
function a($input) {
    $year = 2005 + [8,9,4,5,0,6,7][strpos($input, '#')];
    $difference = 2014 - $year;
    echo "Your calendar is for $year.\nIt's almost 2015.\n" . ($difference ? "You're $difference years behind.\n" : '') . "Go buy a new calendar!";
}

```

## Original, 215 bytes

Works with most (if not all) versions of PHP 5:

```
<?function a($c){$y=2015;$f=-1;do{$f++;$d=strtotime(--$y."-12-1");}while(date(w,$d)!=strpos($c,'#'));echo"Your calendar is for $y.\nIt's almost 2015.\n".($f?"You're $f years behind.\n":'')."Go buy a new calendar!";}

```

### Unminified

```
<?php

function a($input) {
    $year = 2015;
    $difference = -1;
    do {
        $difference++;
        $date = strtotime(--$year . "-12-1");
    } while (date('w', $date) != strpos($input, '#'));
    echo "Your calendar is for $year.\nIt's almost 2015.\n" . ($difference ? "You're $difference years behind.\n" : '') . "Go buy a new calendar!";
}

```

# Answer
> 1 votes
# CoffeeScript, ~~211~~ 177 bytes

Similar to my PHP answer, but CoffeeScript doesn't have `do-while` loops nor does it have a short ternary operator:

```
a=(i)->y=2015;f=-1;loop(f++;d=new Date y--+"-12-01";break if d.getDay()==i.indexOf '#');"Your calendar is for "+y+".\nIt's almost 2015.\n"+(if f then"You're "+f+" years behind.\n"else'')+'Go buy a new calendar!'

```

### Unminifed

```
a = (i)->
    y = 2015
    f = -1
    loop
        f++
        d = new Date y-- + "-12-01"
        break if d.getDay() == i.indexOf '#'
    "Your calendar is for " + y + ".\nIt's almost 2015.\n" + (if f then "You're " + f + " years behind.\n" else '') + 'Go buy a new calendar!'

```

## Shortened by using a lookup table:

```
a=(i)->y=[8,9,4,5,0,6,7][i.indexOf '#']+2005;f=2014-y;"Your calendar is for "+y+".\nIt's almost 2015.\n"+(if f then"You're "+f+" years behind.\n"else'')+'Go buy a new calendar!'

```

# Answer
> 1 votes
# JavaScript (ES6), ~~199~~ 170 bytes

I'm not used to writing ES6 yet so any tips would be appreciated:

# Lookup table, 170 bytes

```
a=(i)=>{y=[8,9,4,5,0,6,7][i.search('#')]+2005,f=2014-y;return`Your calendar is for ${y}.\nIt's almost 2015.\n${f?`You're ${f} years behind.\n`:''}Go buy a new calendar!`}

```

# Original, 199 bytes

```
a=i=>{y=2015,f=-1;do{f++;d=new Date(`${y--}-12-01`)}while(d.getDay()!=i.search('#'))return`Your calendar is for ${y}.\nIt's almost 2015.\n${f?`You're ${f} years behind.\n`:''}Go buy a new calendar!`}

```

### Unminified

```
a = i => {
    y = 2015;
    f = -1;
    do {
        f++;
        d = new Date(`${y--}-12-01`);
    } while (d.getDay() != i.search('#'));
    return `Your calendar is for ${y}.\nIt's almost 2015.\n${f ? `You're ${f} years behind.\n` : ''}Go buy a new calendar!`;
}

```

# JavaScript (ES5), ~~212~~ 182 bytes

I've also included my original version below

## Lookup array, 182 bytes

```
function a(i){y=[8,9,4,5,0,6,7][i.indexOf('#')]+2005,f=2014-y;return"Your calendar is for "+y+".\nIt's almost 2015.\n"+(f?"You're "+f+" years behind.\n":'')+"Go buy a new calendar!"}

```

### Unminified

```
function a(i) {
    y = [8,9,4,5,0,6,7][i.indexOf('#')] + 2005;
    f = 2014 - y;
    return "Your calendar is for " + y + ".\nIt's almost 2015.\n" + (f ? "You're " + f + " years behind.\n" : '') + "Go buy a new calendar!";
}

```

## Original, 212 bytes

```
function a(i){y=2015,f=-1;do{f++;d=new Date(y--+"-12-01")}while(d.getDay()!=i.indexOf('#'));return"Your calendar is for "+y+".\nIt's almost 2015.\n"+(f?"You're "+f+" years behind.\n":'')+"Go buy a new calendar!"}

```

### Unminified

```
function a(i) {
    y = 2015;
    f = -1;
    do {
        f++;
        d = new Date(y-- + "-12-01");
    } while (d.getDay() != i.indexOf('#'));
    return "Your calendar is for "+y+".\nIt's almost 2015.\n" + (f ? "You're "+f+" years behind.\n" : '') + "Go buy a new calendar!";
}

```

# Answer
> 1 votes
# Ruby, 174

```
def a(i)y=2005+[8,9,4,5,0,6,7][i.index('#')];d=2014-y;puts"Your calendar is for #{y}.\nIt's almost 2015.\n"+(d>0?"You're #{d} years behind.\n":'')+"Go buy a new calendar!"end

```

# Answer
> 1 votes
# PHP, 145 bytes

two linebreaks behind the closing tag because PHP will ignore the first one

```
Your calendar is for <?=2014-$y=_1054382[1+strspn($argv[1]," ")],".
It´s almost 2015.",$y?"
You're $y years behind.":""?>

Go buy a new calendar!

```

takes input from command line argument;

requires PHP 5.6 (released 18th Dec 2014) or later for indexing the string literal.

# Answer
> 1 votes
# SmileBASIC, 159 bytes

```
DEF C C
Y=VAL("2834501"[INSTR(C,"#")])?"Your calender is for ";2014-Y;".
?"It's almost 2015.
IF Y THEN?"You're ";Y;" years behind.
?"Go buy a new calendar!
END

```

# Answer
> 1 votes
# C# (Visual C# Interactive Compiler), ~~178~~ ~~175~~ 172 bytes

```
s=>{int p=2014,a=p-"1054382"[s.IndexOf("#")]+48;Write($"Your calendar is for {a}.\nIt's almost 2015.{(p-a>0?$"\nYou're {p-a} years behind.":"")}\nGo buy a new calendar!");}

```

Try it online!

---
Tags: kolmogorov-complexity, code-golf
---


title: Dungeon Crawler

text:
# Question
Title: Dungeon Crawler
## Input

* A binary matrix \\$M\\$ representing the walls of a dungeon.
* The position \\$(x,y)\\$ of the player within the dungeon.
* The direction \\$d\\$ that the player is currently facing (0 = North, 1 = East, 2 = South, 3 = West)

## Output

A pseudo-3D representation of the walls that are in the field of view of the player, as an ASCII art of \\$30\times 10\\$ characters.

Below are several possible output frames, along with the corresponding map and compass to help getting the hang of it (but drawing the map and the compass is not part of the challenge).

## Specification

### Field of view

The player has \\$13\\$ walls in his field of view, labeled from \\$A\\$ to \\$M\\$. Below are the positions of the walls relative to the player (in yellow), in all possible directions.

### Drawing the walls

The walls are supposed to be drawn from \\$A\\$ to \\$M\\$ in this exact order, given that any part drawn previously may be overwritten by closer walls. You may of course implement it differently as long as the final result is the same.

The entire output is drawn with 7 distinct characters: `" "`, `"'"`, `"."`, `"|"`, `"-"`, `"_"` and `":"`.

Because detailing the shapes of the walls in the body of this challenge would make it too lengthy, they are instead provided in the following TIO link:

**Try it online!**

The characters that are not part of a given wall are marked with a `"?"` in these diagrams. They must be treated as 'transparent' characters that are not drawn at all. On the other hand, all spaces within a wall are 'solid' and must overwrite any other characters that may have been previously drawn there.

## Rules

### About the input

* You may take \\$M\\$, \\$x\\$, \\$y\\$ and \\$d\\$ in any reasonable format.
* You may use either 0-indexed or 1-indexed coordinates.
* You may use 4 distinct values of your choice for the directions.
* The matrix is guaranteed to be at least \\$3\times 3\\$.
* You may assume that there will always be surrounding walls on the edges.
* The player is guaranteed to be located on an empty square.
* The input is guaranteed to be valid.

### About the output

* The walls must be drawn exactly as described.
* However, the output format is also flexible: single string, array of strings, matrix of characters, etc.
* Leading and trailing whitespace is acceptable as long as it's consistent.

This is .

## Test cases

All test cases are using the following matrix:

```
[ [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],
  [ 1, 0, 1, 1, 1, 0, 0, 0, 0, 1 ],
  [ 1, 0, 1, 0, 1, 0, 0, 1, 0, 1 ],
  [ 1, 0, 0, 0, 0, 0, 1, 1, 0, 1 ],
  [ 1, 0, 0, 1, 0, 0, 0, 1, 0, 1 ],
  [ 1, 0, 0, 1, 1, 0, 1, 1, 0, 1 ],
  [ 1, 1, 1, 1, 0, 0, 0, 0, 0, 1 ],
  [ 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 ],
  [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ] ]

```

The following inputs are using 0-indexed coordinates, with \\$(0,0)\\$ pointing to the top-left corner.

```
x=3, y=3, d=0
x=6, y=4, d=3
x=4, y=4, d=1
x=1, y=5, d=2
x=7, y=7, d=3
x=6, y=6, d=1
x=8, y=1, d=2
x=7, y=6, d=1

```

Expected outputs:

```
------------------------------    ------------------------------
 x=3, y=3, d=0:                    x=6, y=4, d=3:
------------------------------    ------------------------------
__                          __    '.                          .'
  |'.                    .'|        |                        |
  |   '.--------------.'   |        |----.                   |
  |    |              |    |        |    | '.--------.       |
  |    |              |    |        |    |  |        |       |
  |    |              |    |        |    |  |        |       |
  |    |              |    |        |    | .'--------'       |
  |   .'--------------'.   |        |----'                   |
__|.'                    '.|__      |                        |
                                  .'                          '.
------------------------------    ------------------------------
 x=4, y=4, d=1:                    x=1, y=5, d=2:
------------------------------    ------------------------------
                            .'    __ ________________________ .'
                           |        |                        |
-------.              .----|        |                        |
       | '.--------.' |    |        |                        |
       |  |        |  |    |        |                        |
       |  |        |  |    |        |                        |
       | .'--------'. |    |        |                        |
-------'              '----|        |                        |
                           |      __|________________________|
                            '.                                '.
------------------------------    ------------------------------
 x=7, y=7, d=3:                    x=6, y=6, d=1:
------------------------------    ------------------------------
'.                                '.
  |'.                               |'.
  |   '.                            |   '.
  |    | '.                 .-      |    |--.--------.--------.-
  |    |  |:               :|       |    |  |        |        |
  |    |  |:               :|       |    |  |        |        |
  |    | .'                 '-      |    |--'--------'--------'-
  |   .'                            |   .'
  |.'                               |.'
.'                                .'
------------------------------    ------------------------------
 x=8, y=1, d=2:                    x=7, y=6, d=1:
------------------------------    ------------------------------
'.                          __    '.
  |'.                    .'|        |
  |   '.              .'   |        |----.--------------.-------
  |    | '.        .' |    |        |    |              |
  |    |  |:      :|  |    |        |    |              |
  |    |  |:      :|  |    |        |    |              |
  |    | .'        '. |    |        |    |              |
  |   .'              '.   |        |----'--------------'-------
  |.'                    '.|__      |
.'                                .'

```

---

***Related challenge:***

*This challenge from 2013 is closely related. But it has a different winning criterion (code-challenge), a much looser specification of the output, and requires interactive I/O.*

# Answer
# Clean (with Snappy), ~~800~~ ~~785~~ ~~670~~ 644 bytes

*~~460~~ 402 bytes of code + ~~360~~ 242-byte string literal<br>(escaped here and on TIO because it isn't valid UTF-8)*

You can verify the length of the literal here.

```
import StdEnv,Data.List,Data.Maybe,Codec.Compression.Snappy,Text
@a b|b<'~'=b=a
$m x y d=map(@' ')(foldl(\a b=[@u v\\u<-a&v<-b])['~~'..][join['
']k\\Just(Just 1)<-[mapMaybe(\e=e!?(x+[u,v,~u,~v]!!d))(m!?(y+[~v,u,v,~u]!!d))\\u<-[-2,2,-1,1,0,-1,1,0,-1,1,0,-1,1]&v<-[3,3,3,3,3,2,2,2,1,1,1,0,0]]&k<-nub[q\\w<-split"#"(snappy_uncompress"\211\6\44\41\41\41\55\56\40\41\40\174\72\5\4\60\55\47\40\41\41\41\43\41\41\41\176\56\55\r\1\24\56\40\41\176\174\40\r\1\4\174\72\72\r\0\0\47\r\46\35\72\25\1\31\103\0\41\25\24\35\113\176\25\0\31\133\11\224\r\152\20\56\40\40\40\41\21\217\10\40\47\56\31\14\4\40\174\126\14\0\4\56\47\21\74\0\47\1\74\1\340\r\220\25\242\11\1\25\250\25\360\11\1\25\253\376\30\0\21\30\25\333\11\1\24\47\41\41\43\137\137\11\154\20\41\40\40\174\47\r\344\1\157\5\341\1\11\5\336\172\11\0\34\56\47\41\137\137\174\56\47\1\347\20\43\176\176\40\137\132\1\0\4\40\41\75\211\76\1\0\1\356\5\150\116\1\0\376\35\0\376\35\0\126\35\0\132\347\0\20\137\174\41\43\47\101\337\51\74\41\133\122\4\0\10\56\47\40"),q<-let l=[[c\\c<-:rpad s 30'~']\\s<-split"!"w]in[l,map reverse l]]])

```

Try it online!

Snappy compression actually does pretty well in this case, despite being speed-focused, because there are so many single-character runs in the string being compressed.

The uncompressed string (with `#` replaced with `\n` for clarity) is:

```
!!!-. ! |:! |:!-' !!!
!!!~.--------. !~|        |:!~|        |:!~'--------' !!!
!!!~~~~~~~~~~.--------.!~~~~~~~~~~|        |!~~~~~~~~~~|        |!~~~~~~~~~~'--------'!!!
!!-------.   !       | '.!       |  |!       |  |!       | .'!-------'   !!
!!~~~~~~~.--------------.!~~~~~~~|              |!~~~~~~~|              |!~~~~~~~|              |!~~~~~~~|              |!~~~~~~~'--------------'!!
__      !  |'.   !  |   '.!  |    |!  |    |!  |    |!  |    |!  |   .'!__|.'   !
~~ ________________________ !~~|                        |!~~|                        |!~~|                        |!~~|                        |!~~|                        |!~~|                        |!~~|                        |!~~|________________________|!
'. !  |!  |!  |!  |!  |!  |!  |!  |!.'

```

This encodes the left-side versions of the different screen components with `!` instead of newlines, and `~` instead of `?`, which are then right-padded with `~` to 30 characters before having themselves and their line-reversals added to a lookup list.

The rest of the code simply handles coordinate lookup with out-of-bounds cases ignored.
> 10 votes

# Answer
# Python 2, ~~864~~ ~~854~~ ~~848~~ ~~826~~ 810 bytes

```
L=[zip(*[iter(w)]*30)for w in zip(*[iter("eJzdllESgyAMRL+5Rf7yRQ7AZbhIDl9BwTqzSVtHrbKffR0Mm13HEM5SFHIoadpNI3snDyaS6NCknhU+JfZOvq8kLoIBU1oEI+RTbiePGzBa3QM0rf78TGl17+CZr5ZrUXBN+ECfY1GvGKEqtDsSI4s6xTn5jgqyqNcTTnUjTQO2FAEqTC0ngCrtpywenX5le6or1SsGi9ZLBKt0HuXtVEeUNGdzG6EsRNmo2EzLxuBbqFH8njmfwnqGcl+VY+s5+5ezSYXVel4dxaRK/6F15SatK1frvm//y4aoT4Ckj6XWfY2cbvz2fLSCPiiVvR+3ZuerzDwPSqeSvgAP9woa".decode('base64').decode('zip'))]*300)]
E=enumerate
def f(m,x,y,d):
 D=eval(`[[' ']*30]*10`);w,h=len(m[0]),len(m);a=[m,zip(*m)[::-1]][d%2];x,y=[x,y,w+~x,h+~y,y,w+~x,h+~y,x][d::4];X=sum([[0]*(x<2)+list(l)[x-2+(x<2):x+3]for l in[l*2for l in[a,[l[::-1]for l in a[::-1]]][d/2]*2][y:y+4]],[])
 for d,w in zip(L,'sropqmklhfgca'):
  for j,l in E(d):
   for i,q in E(l):
    if q*X[ord(w)%32]>=' ':D[j][i]=q
 for l in D:print''.join(l)

```

Try it online!
> 5 votes

# Answer
# Charcoal, ~~500~~ 332 bytes

```
Ｆ⁴≔⮌Ｅ§θ⁰⁺00⭆θ§μλθ≔Ｅ✂θ⊖ζ⁺⁶ζ¹✂ι⊖η⁺⁶η¹θＦε≔⮌Ｅ§θ⁰⭆θ§μλθＢ³⁰χ Ｆ²«‖ＦΦ⪪⟦“ ｜0⟧Ｐ+Ｎ？⟧‹Ｇ”³¦⁰”{➙d⊟ＥＸ⍘k↧D({Ｖt⍘gＲd◨ⅉ^δ#T；”³¦¹“ ¶↖+9Ｇ₂pＦ^c1e⌈¬；”³χω⁰χ”{➙∧⊟∧◨ηü∧↖z↨⁸\G'λＩ∧¡∕⪫θＪoΣ³⊖Ｉ⊟ζ⊙”²¦⁰”{➙∧⊟∧◨ηü∨§·◧﹪d‹⟲ ＯzºκＦⅉＲï⎇”²¦⁷ω⁰χ”{➙∧⊟≔⊘⬤|↔3Ｚθ✂≔÷t⍘ε✂↨≔⧴×ld≕≡⌕m⟧6ψ=Ｚ”⁰¦⁰”}∧80ＫυgCAêＪm⟦↘/§‖Ｃk⮌Ｃ₂¡μ↗Ｗ”⁰¦²ω⁰χ”{⊟∨·◧¤∨¶⧴⬤2ＧＬ▷⁸ê5Ｇψ”⁰¦⁰⟧³Ｉ§⭆θ⭆³§μ⎇ι⊕ξ⁻⁵ξλ«Ｊ⁻⊟κ×²⁹¬ι⊟κ⊟κ

```

Try it online! Link is to verbose version of code. Somewhat boring approach, I'm afraid; lots of printing of compressed string literals. Explanation:

```
Ｆ⁴≔⮌Ｅ§θ⁰⁺00⭆θ§μλθ

```

Pad the array with two extra `0`s on each side.

```
≔Ｅ✂θ⊖ζ⁺⁶ζ¹✂ι⊖η⁺⁶η¹θ

```

Slice a `7x7` subsection of the array centred on the given coordinates.

```
Ｆε≔⮌Ｅ§θ⁰⭆θ§μλθ

```

Rotate the array as appropriate for the given direction.

```
Ｂ³⁰χ

```

(note trailing space) Draw an empty `30×10` box so that the output is always a consistent size.

```
Ｆ²«‖

```

Draw each half separately, reflecting in between.

```
ＦΦ⪪⟦...⟧³Ｉ§⭆θ⭆³§μ⎇ι⁻⁵ξ⊕ξλ«

```

Take an array of wall descriptors, split into chunks of (string, y-coordinate, x-coordinate), filter on those chunks that have a wall at the relevant position in the relevant half of the array, and loop over the walls. The position is calculated by extracting 12 walls from the array and indexing them using the chunk index as this is golfier than locating the wall directly using the chunk index.

```
Ｊ⁻⊟κ×²⁹¬ι⊟κ⊟κ

```

Jump to the coordinates of the wall and print it. Note that reflecting negates the X-coordinates from `[0, 30)` to `(-30, 0]` so that on one pass the canvas is effectively shifted 29 characters to the left.
> 5 votes

# Answer
# Ruby, ~~412 391 385~~ 383 bytes

```
->a,x,y,d{b=Array.new(97){[" "]*10}
e=[-1,0,1,0]
14.times{|i|m=-i%3-1
w=[31,25,15,9][n=i>2?4-i/3:(m*=2;3)]
(a*3)[y+n*e[d]+m*c=e[d-3]][x+n*c-m*e[d]]&&[p=w*(m*2-1)/2,r=[12,7,4,3][n]*m*m.abs+m/3].min.upto([q=w*(m*2+1)/2,r].max){|j|t=" .'"*9
b[j+15]=(p<j&&j<q ?%w{-%2s- -%4s- _%7s_}[-n]%"":t[k=(j^j>>9)%(36/-~n)]+"   :|  |    |"[k%13]*(k/3*2)+t[-k]).center(10).chars}}
b[0,30].transpose}

```

Try it online!

Takes input as an array of truthy/falsy values (note `0` is truthy in Ruby, but `nil` is falsy.)

Outputs an array of characters.

**Explanation**

Blocks are drawn front to back with distance `n` decreasing and side to side position `m` cycling through `-1,1,0` left,right,middle. The middle block E in the furthest row is actually drawn twice because we need to check both blocks A/B and blocks C/D. `n,m` and `d` are used to modify the `x` and `y` values to search array `a`. If `x` is out of range `nil` is returned for an out of range cell and no error is thrown, but if `y` is out of range `nil` will be returned for the row and Ruby will throw a type error when it tries to search for the cell. To avoid this the array is triplicated in the vertical direction prior to searching. If a truthy value is found a block is drawn.

The output is built in an array `b` of 10-element arrays representing the columns of the output, and is transposed into 10 rows at the end of the function. The full front face of all blocks is drawn (whether it appears in the viewport or not) so additional space is needed in the array to avoid out of range errors. The range of `j` values in the viewport is from `-15` to `+14`, this is offset by 15 when saving to the array to give a range of `0` to `29`. For each block drawn three values are calculated: `p` and `q` for the left and right corners of the front wall respectively, and `r` for the back of the side wall. `j` is iterated from the minimum to the maximum of these three values drawing the columns in turn.

There are 3 types of lines: horizontal `-` or `_`, vertical `|` or `:`, and diagonal with a repeating `" .'"` pattern. Where `p < j < q` columns containing spaces capped with `-` or `_` are drawn to form the front face. Where `j` is outside this range, columns containing space, `|` or `:` are drawn capped with symbols from `t=" .'"` to form the edges and/or side face. This is managed by variable `k=j` where `j` is positive or `k=-j-1` where `j` is negative. The number of characters between the top and bottom caps is `k/3*2`. In order to correctly handle the outer edges of the furthest blocks where `n=3`, `k` must be taken modulo 9, but this must not be done for smaller values of `n`. `k` is therefore taken modulo `36/-~n`, where `-~n` evaluates to `n+1`.

**Ungolfed code**

```
->a,x,y,d{
  b=Array.new(97){[" "]*10}                                        #Set up array for output, allow space for plotting outside viewport
  e=[-1,0,1,0]                                                     #Direction offsets from player position
  14.times{|i|                                                     #Iterate through all blocks including block E twice
    m=-i%3-1                                                       #Cycle -1,1,0 = left, right, centre
    n=i>2?4-i/3:(m*=2;3)                                           #Distance n=4-i/3. But if i/3==0 n=3 and double m for blocks A,B
    w=[31,25,15,9][n]                                              #Width of front face of block
    r=[12,7,4,3][n]*m*m.abs+m/3                                    #Value of j for back edge of block. m/3 offsets by -1 when m negative
    (a*3)[y+n*e[d]+m*c=e[d-3]][x+n*c-m*e[d]]&&(                    #If a block is present at the location then
      [p=w*(m*2-1)/2,r].min.upto([q=w*(m*2+1)/2,r].max){|j|        #Calculate left and right edges of front of block p,q and iterate
        t=" .'"*9                                                  #t=character constant for diagonal lines
        k=(j^j>>9)%(36/-~n)                                        #k=j for positive j=distance from centre. For negative j, k=-1-j by XOR with j>>9=-1. If n=3 take modulo 9 for correct output of outer side of block.
        b[j+15]=(p<j&&j<q ?%w{-%2s- -%4s- _%7s_}[-n]%"":           #If j between p&q, draw horizontal lines separated by 2,4 or 7 spaces depending on value of n
        t[k]+"   :|  |    |"[k%13]*(k/3*2)+t[-k]).center(10).chars #else draw space or vertical line capped by diagonal markers
      }
    )
  }
b[0,30].transpose}                                                 #Truncate values outside viewport, transpose, and return value.

```
> 2 votes

---
Tags: code-golf, ascii-art, game, binary-matrix
---


title: Concise case changing code

text:
# Question
Title: Concise case changing code
Create the shortest program that given an input string it outputs the opposite-cased string. For example if I pass the string `"HeLlO"` the program should output `"hElLo"`.

Of course, neither aggregate functions can be used, nor framework functions like `toupper()` or `tolower()`. Any language is welcome.

# Answer
> 14 votes
# Bash shell, 16 characters

```
tr A-Za-z a-zA-Z

```

Sample runs:

```
llama@llama:~$ tr A-Za-z a-zA-Z
ThIs is a TeSt!
tHiS IS A tEsT!
llama@llama:~$ echo 'Programming Puzzles & Code Golf Stack Exchange' | tr A-Za-z a-zA-Z
pROGRAMMING pUZZLES & cODE gOLF sTACK eXCHANGE

```

It works in a file, too (of course):

```
llama@llama:~$ echo 'tr A-Za-z a-zA-Z' > swapcase.sh
llama@llama:~$ echo 'This is a test!' | bash swapcase.sh
tHIS IS A TEST!

```

# Answer
> 14 votes
# CJam - 5

```
q32f^

```

Try it at http://cjam.aditsu.net/

Let me know if I missed something.

# Answer
> 6 votes
# C, 67 chars

```
main(c,d){while(~(c=getchar()))d=c|32,putchar(d>96&&d<123?c^32:c);}

```

Input/output via STDIN/STDOUT:

```
$ ./swapcase <<< "HELLO world!"
hello WORLD!
$

```

---

# C, 41 chars

```
main(){while(putchar(getchar()^32)<127);}

```

If we strictly only care about alphabetical letters.

```
$ printf %s {a..z} {A..Z} | ./swapcase
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz$
$

```

# Answer
> 5 votes
# Perl, 16 (17 counting -p flag as 1)

```
y/A-Za-z/a-zA-Z/

```

Fundamentally the same as the sh solution. The only room for golfing is using the `y` synonym for `tr`.

I'd like to protest that all of these solutions are only correct for ASCII, though. I'd like to see someone produce a solution that's correct for Unicode 7.0, without using library functions or external data :-P

# Answer
> 5 votes
## Vim, 2

```
~G

```

In Normal mode, with the cursor on the first line, and with `'tildeop'` set, this command will swap the case of every character in the current buffer. This probably shouldn't count, but it's also very likely the fewest number of characters one need type to perform the operation in question, so I figured I'd share.

# Answer
> 3 votes
# Marbelous - 249

```
00 @0 00 @1
&2 &0 // &0
.. /\ @0 \/
]] !! 0A
RR .. \\ &2
=0 \\ 00
&2 @1 /\
:R
}0 .. 00 @2
=A .. &1 +Z @3
@0 .. {0 +U //
.. /\ .. &0
>Z {0 >Z @4
-Z .. -Z
>T @2 >Z
-U .. -Z
<Q @3 >Q
+Z .. -S
+Z .. <Q &0
+R @4 +Z \/
\\ .. +S @0
.. &2 // &1
.. {0 .. \/

```

# Answer
> 2 votes
## Python, 109 bytes

```
import sys
s=''
for c in sys.argv[1]:
  n=ord(c)
  if 64<n<91:n+=32
  elif 96<n<123:n-=32
  s+=chr(n)
print s

```

# Answer
> 2 votes
# Cobra - 100 (or 81)

```
class P
    def main
        for c in Console.readLine,Console.write(if(c.isLetter,((c to int)^32)to char,c))

```

If only letters matter

```
class P
    def main
        for c as int in Console.readLine,Console.write((c^32)to char)

```

# Answer
> 2 votes
# Befunge 93 - 45

```
>~:55+-#v_@>
_v#`g19:<] ^,-g29
 >92g+,    ^

```

Terminates when a NL is entered.

# Answer
> 2 votes
# Python - 44

```
print''.join(chr(ord(c)^32)for c in input())

```

The program expects an input string quotes `"HeLLo"`, which should be legit. Using Python 3 we can easily pass the string without quotes like `HeLLo` at the cost of two more characters for the `print`-brackets.

# Answer
> 1 votes
# Python - 68

```
import sys
print''.join(chr((ord(l)-33)%64+65) for l in sys.argv[1])

```

Simple python script featuring no ifs or elses.

# Answer
> 1 votes
# Rebol - 25

```
forall s[s/1: s/1 xor 32]

```

Usage example (in Rebol console):

```
>> ;; s is the input string

>> s: "HeLlO"
== "HeLlO"

>> forall s [s/1: s/1 xor 32]
== #"o"

>> s
== "hElLo"

>> forall s [s/1: s/1 xor 32]
== #"O"

>> s
== "HeLlO"

```

# Answer
> 1 votes
# Japt, 3 bytes

```
c^H

```

Try it

XORs (`^`) the charcode (`c`) of each character with 32 (`H`).

# Answer
> 0 votes
# Lua - 78

```
while""do a=io.read(1)b=a<']'and 32 or-32 io.write(string.char(a:byte()+b))end

```

Nothing special, and it ups any character smaller '\]' and downs any one larger.

# Answer
> 0 votes
# CoffeeScript - 85 (or 77 67)

Since non-alphabetic characters don't matter:

```
f=(x)->x.split('').map((c)->String.fromCharCode((c.charCodeAt(0)-33)%64+65)).join('')

```

Discarding whitespace and other non-alphabetic characters:

```
f=(x)->x.split('').map((c)->String.fromCharCode(c.charCodeAt(0)^32)).join('')

```

Even shorter:

```
f=(x)->(String.fromCharCode(c.charCodeAt(0)^32)for c in x).join('')

```

# Answer
> 0 votes
## Clojure - 182 chars

I'm a Clojure newbie. Golfed:

```
(defn b[i x y](if(and(> i x)(< i y)) true false))(print(apply str(map #(let[i(int %)](if(b i 64 92)(char (+ i 32))(if(b i 96 123)(char (+ i -32)) %))) (first *command-line-args*))))

```

Ungolfed:

```
(defn b[i x y] (if (and(> i x)(< i y)) true false))
(print (apply str (map
        #(let [i (int %)] (if (b i 64 92)
                             (char (+ i 32))
                             (if (b i 96 123) (char (+ i -32)) %)))
        (first *command-line-args*))))

```

---
Tags: code-golf, string
---


# Question
Title: Monday Mini-Golf #1: Reverse Fibonacci Solver
**Monday Mini-Golf:** A series of short challenges, posted (hopefully!) every Monday.

A **Fibonacci-like sequence** is obtained using the same method as the famous Fibonacci sequence; that is, each number *F(n)* is found by adding the previous two numbers in the sequence (*F(n) = F(n-1) + F(n-2)*), or by subtracting the next two numbers (*F(n) = F(n+2) - F(n+1)*). The main difference is that these sequences can start with any two numbers. The zero-indexing of these sequences is disputable, but for now, we're going to use this rule:

* The 0th number in a Fibonacci-like sequence is the last number which is smaller than the preceding number.

As an example, the Fibonacci sequence could be written as `1, 0, 1, 1, 2, 3, 5...`, so the 0th number in the sequence is the lone `0`.

# Challenge

The goal of the challenge is to write a program or function that takes in three integers, in any format:

* *A* and *B*, the two numbers with which to start generating a sequence.
* *N*, the length of the resulting sequence to output.

And outputs the first *N* numbers of the sequence, starting at the 0th.

# Details

* *A*, *B*, and *N* may be taken in any order and format, as long as they are visibly separated. If you use a different order/format, please specify what it is.
* You may assume that *A*, *B*, and *N* are always positive integers.
* You may assume that *N* is no more than 100, and the resulting sequence will not contain `x >= 2^31`.
* If *A* is larger than *B*, then *B* is the 0th number in the sequence.
* The output must be separated by spaces, commas, and/or newlines.
* A trailing space or newline is allowed, but *not* a trailing comma.

# Test-cases

### Example 1:

```
8 13 10

```

Working backward from `8 13` until we find a number larger than the previous, we get `13 8 5 3 2 1 1 0 1`. Thus, `0` is the 0th number in this sequence. Working forward from this, we print out `0` and the next 9 members:

```
0 1 1 2 3 5 8 13 21 34

```

### Example 2:

```
23 37 5

```

Again working backward to find the 0th number, we find `37 23 14 9 5 4 1 3`. The 0th number this time is `1`, so we print it out, along with the next 4 members:

```
1 4 5 9 14

```

### Example 3:

```
4 3 8

```

With this one, we don't have to work backward to find the 0th number, because `3` is smaller than `4`:

```
3 7 10 17 27 44 71 115

```

### Example 4:

```
29 47 11

```

Result:

```
1 3 4 7 11 18 29 47 76 123 199

```

# Scoring

This is , so shortest valid code in bytes wins. Tiebreaker goes to earlier posted submission. ~~The winner will be chosen next Monday, Sep 28. Good luck!~~

**Edit:** Congrats to your winner, @Jakube, using Pyth for an amazing **23 bytes!**

# Answer
# Pyth, 23 bytes

```
AQWgHGA,-HGG)VvwHA,H+GH

```

Try it online: Demonstration or Test Suite

Quite unusual style of Pyth programming. Sometimes functional programming has its downsides.

### Explanation:

```
AQWgHGA,-HGG)VvwHA,H+GH  Q = input list of the two starting numbers
AQ                       G, H = Q (unpacking Q)
  WgHG                   while H >= G:
      A,-HGG                G, H = [H - G, G]
            )            end while
              vw         read a number from input
             V           for N in range(^):
                H           print H
                 A,H+GH     G, H = [H, G + H]

```
> 12 votes

# Answer
# Retina, ~~65~~ 54 bytes

```
+`(1*),\1(1*)
$2,$1
+`(1*)(,1*);1\B
$1$2$2$1;
^1*,|;1
<empty>

```

Here, `<empty>` represents an empty trailing line. Run the code as a single file with the `-s` flag.

The input format is

```
A,B;N

```

where the numbers are represented in unary. The output is a comma-separated list, also in unary. For instance:

```
8 13 10

```

would be

```
11111111,1111111111111;1111111111

```

and yield

```
,1,1,11,111,11111,11111111,1111111111111,111111111111111111111,1111111111111111111111111111111111

```

## Explanation

```
+`(1*),\1(1*)
$2,$1

```

First, we reduce `A` and `B` to the 0th and -1st element. The `+` tells Retina to keep repeating this regex substitution until either the regex stops matching or the substitution doesn't modify the string. The regex captures `A` into group 1 with `(1*)`, and then makes sure that `B` is at least as big as `A` while capturing `B-A` with `\1(1*)` into group 2. This ensures that this loop terminates once `A>B`.

The substitution simply turns `A,B` into `B-A,A` by setting the match to `$2,$1`.

```
+`(1*)(,1*);1\B
$1$2$2$1;

```

Now we've already got the first number of the required output in the string (as well as the one before it, which we'll need to get rid off later). This substitution now adds another number as the sum of the last two numbers while taking a `1` from `N`. Because we already have one number we want this to happen only `N-1`. We do this by ensuring with `\B` that there is still at least `;11` at the end of the string. If we call the last two values of the sequence `C` and `D`, then the regex captures `C` into group 1 and `,D` into group two. We write those back with `$1$2`. Then we also write `$2$1` which translates to `,D+C`. Note that we *don't* write back the single `1` we matched in `N`, thereby decrementing it.

```
^1*,|;1
<empty>

```

Finally, we need to get rid of -1st element of the sequence, as well the leftover `;1` from `N`, which we simply do by matching either of those and replacing it with the empty string.
> 12 votes

# Answer
# Python 2, ~~93~~ ~~87~~ ~~67~~ ~~61~~ 60 bytes

```
i,j,l=input()
while j/i:i,j=j-i,i
exec"i,j=j,i+j;print i;"*l

```

Gets the input (as a literal python list `[8,10,13]`)

Works out the 0th term

Then prints out the sequence of additions until the length has been reached
> 7 votes

# Answer
# CJam, ~~26~~ 23 bytes

*Thanks to Dennis for saving 3 bytes.*

```
q~{_@\-_g)}g\@{_@+_p}*t

```

Takes input in order `N B A` (separated by any kind of white space). Prints the result as a newline-separated list and terminates with an error.

Test it here.

## Explanation

This goes one step further when finding the 0th element. That is, it terminates once one of the values is negative.

```
q~      e# Read and evaluate input, pushing N, B and A on the stack.
{       e# do while...
  _@\-  e#   B, A = A, B-A
  _W>   e#   Check if A is still non-negative.
}g
\@      e# Reorder N B A into A B N.
{       e# Run the following N times...
  _@+   e#   A, B = B, A+B
  _p    e#   Print B.
}*
t       e# The last A, B are still on the stack. We remove them by trying to
        e# execute a ternary operator: it pops the first two values but then
        e# terminates the program with an error, because there is no third value.

```
> 6 votes

# Answer
# C, ~~105~~ ~~102~~ 100 bytes

```
main(a,b,n,t){for(scanf("%d%d%d",&a,&b,&n);t=b-a,t>=0;a=t)b=a;for(;n--;b=t)t=a+b,printf("%d ",a=b);}

```

*Thanks to @C0deH4cker for golfing off 2 bytes!*

Try it online on Ideone.
> 5 votes

# Answer
# Labyrinth, ~~58~~ ~~54~~ ~~49~~ ~~46~~ 44 bytes

*Thanks to Sp3000 for suggesting the use of bitwise negation, which saved two bytes.*

```
??#"{=
  ;  -
@"~~:}
~""
?
"}}:=
(   +
{{\!:

```

Input format is `B A N`. The output is a newline separated list.

# Explanation

*(Slightly outdated. The basic idea is still the same, but the layout of the code is different now.)*

This uses the same idea as my CJam answer (so credits still go to Dennis): when backtracking the sequence we don't stop until we get a negative value (which leaves us with the -1st and -2nd element of the sequence). Then, we start adding them *before* printing the first value.

This uses a couple of nifty Labyrinth golfing tricks. Let's go through the code in sections:

```
?"
}

```

The IP starts on the `?` going right (which reads `A`). On the `"` (a no-op) it hits a dead end, so it turns around, executing the `?` again (reading `B`). Lastly, `}` moves `B` over to the auxiliary stack. The dead end saves a byte over the naive

```
?
?
}

```

Now the loop which finds the beginning of the sequence:

```
)(:{
"  -
" "`?...
=}""

```

The `)(` (increment-decrement) is a no-op, but it's necessary to ensure that the top of the stack is positive on the junction (such that the IP turns east). `:` duplicates `A`, `{` moves `B` back to the main stack, `-` computes `A-B`. What we really want is `B-A` though, so ``` negates the value.

This is now a four-way junction. For negative results, the IP takes a left-turn towards the `?`, reading `N` and moving to the next part of the program. If the result is zero, the IP keeps moving south, takes a turn in the corner, and remains in the loop. If the result is positive, the IP takes a right-turn (west), turns in the corner, and takes another right-turn (west again) so it also remains in the loop. I think this might become a common pattern, to distinguish negative from non-negative (or positive from non-positive) values:

```
                v
                "
               """>negative
non-negative <"""

```

At least I haven't been able to find a more compact/useful layout for this case yet.

Anyway, while `A` is non-negative, the loop continue, `}` moves `A` to the auxiliary stack and `=` swaps `A` and `B`.

Once `A` is negative, `?` reads `N` and we move into the second loop:

```
 }:=+:
 }   !
?"({{\

```

We know that `N` is positive, so we can rely on the IP taking a left-turn (north). The loop body is now simply:

```
}}:=+:!\{{(

```

In words: moves both `N` and `A` onto the auxiliary stack. Duplicate `B`, swap the copy with `A` and add `A` to the other copy of `B`. Duplicate it again to print the current value of `B`. Print a newline. Move `B` and `N` back to the main stack and decrement `N`.

While `N` is positive, the IP will take a right-turn (north) continuing the loop. Once `N` reaches zero, the code terminates in a rather fancy way:

The IP keeps moving straight ahead (west). The `?` tries to read another integer, but we've already reached EOF, so it actually pushes `0` instead. ``` tries negating that, but that's still zero. So the IP still moves west, takes a turn in the corner, and then keeps moving downwards onto the `@` which terminates the program.

I wonder if I could place the `@` in an even cheaper position (it currently costs 3 whitespace characters) by turning the three `"` around the ``` into compound no-ops (like `)(`), but I haven't been able to make that work yet.
> 5 votes

# Answer
# Matlab / Octave, 115 ~~125~~ bytes

```
function x=f(x,n)
while x(2)>=x(1)
x=[abs(x(1)-x(2)) x];end
x=x([2 1]);for k=1:n-1
x=[x(1)+x(2) x];end
x=x(n:-1:1);

```

The function should be called as `f([8 13],10)`.

Example (Matlab):

```
>> f([8 13],10)
ans =
     0     1     1     2     3     5     8    13    21    34

```

Or try it online (Octave).
> 4 votes

# Answer
# \>\<\>, ~~33~~ 31+1 for -v = 32 bytes

```
&:{:@(?v:}-$&
-1;!?:&<$+{oan::$&

```

Input must be pushed on stack using -v since parsing decimal numbers is non-trivial in \>\<\>.

## Explanation :

I will represent the stack after each (group of) operation. It starts with \[F(n), F(n+1), N\]

The first lines goes down the serie to its 0th term :

```
& removes N from the stack to put it into a register. [F(n), F(n+1)]
:{:@ move the stack and duplicate items to get [F(n+1), F(n), F(n+1), F(n)]
(?v compares the two top items of the stack and branch to the second line if F(n+1) < F(n) [F(n+1), F(n)]
:} move the stack and duplicate its top to get [F(n), F(n+1), F(n)]
- substracts the two top items and put the result on top of the stack [F(n), F(n+1) - F(n)]
$ switchs the top two values of the stack. [F(n+1) - F(n), F(n)]
& retrieve the value from the register. iteration complete, since [F(n+1) - F(n), F(n), N] can also be read as [F(n-1), F(n), N]

```

The second line goes up the serie until it has printed N terms :

```
< changes the code pointer direction to the left [F(0), F(-1)]
& retrieves the stored value back from the stack [F(0), F(-1), N]
:?!; copies N to compare it to 0, stops if it is [F(0), F(-1), N]
1- decreases it [F(0), F(-1), N-1]
& stores it back [F(0), F(-1)]
$:: makes the stack [F(-1), F(0), F(0), F(0)]
n{ prints the top of the stack then left shifts it [F(0), F(0), F(-1)]
ao displays a line feed (ascii character 0x0a) [F(0), F(0), F(-1)]
+ adds the two top values [F(0), F(-1) + F(0)]
$ switch the two top values. iteration complete since [F(-1) + F(0), F(0)] which can be read as [F(1), F(0)]

```
> 3 votes

# Answer
# Haskell, ~~67 65~~ 56 bytes

```
a#b|a>b=b:scanl(+)(a+b)(a#b)|1>0=(b-a)#a
n%a=take n.(a#)

```

*Thanks to @nimi for suggestions*

This defines a ternary infix function `%`, which is invoked in the format `(n%a)b`, for example:

```
> (10%8)13
[0,1,1,2,3,5,8,13,21,34]

```

### Explanation

The binary infix function `#`, defined on the first line, takes in two integers `a` and `b` and returns the infinite Fibonacci-like sequence where `a` and `b` occur as consecutive elements.

```
a#b                                       -- Define a#b:
   |a>b=                                  -- if a>b, then a#b is
        b:                                -- the sequence that starts with b and
          scanl(+)     (a#b)              -- continues with the sums of prefixes of a#b
                  (a+b)                   -- plus the additional term a+b;
                            |1>0=(b-a)#a  -- otherwise, it's (b-a)#a.

```

The function `%` simply takes the first `n` elements of `a#b`.
> 3 votes

# Answer
# Javascript (ES6), ~~83~~ ~~73~~ 63 bytes

This might have been golfed to the max. We'll see.

```
(a,b,n)=>{while(a<=b)b-=a=b-a;for(;n--;console.log(a=b-a))b+=a}

```

### Ungolfed:

```
function f(a,b,n) {
  // repeat until we find the 0th item...
  while (a <= b) {  // if a = 5, b = 8:
    a = b - a;      // a = (8 - 5) = 3
    b = b - a;      // b = (8 - 3) = 5
  }
  // repeat n times...
  while (n-- > 0) { // if a = 5, b = 8:
    b += a;         // b = (8 + 5) = 13
    a = b - a;      // a = (13 - 5) = 8
    console.log(a); // print out each item
  }
}

```
> 2 votes

# Answer
# Java, ~~113~~ ~~78~~ 76 bytes

Credit goes to ETHproduction for providing the algorithm I use in this answer.

```
(a,b,n)->{for(;a<=b;b-=a)a=b-a;for(;n-->0;b+=a,a=b-a)System.out.println(b);}

```

Try here.

**Explanation:**

```
(a,b,n)->{
    for (;a<=b;b=b-a)a=b-a;  //Compute previous terms while a <= b
    for (;n-->0;b=a+b,a=b-a) //Compute and print next terms while n > 0
    System.out.println(b);   //Print term
}

```

### Original approach, ~~113~~ 93 bytes

Looks more golfy ;)

```
String a(int a,int b,int n){return n<0?a+" "+a(b,a+b,n+1):n>0?a>b?a(b,a+b,-n):a(b-a,a,n):"";}

```

Try it out here.

**Explanation:**

```
String a(int a, int b, int n){
    return
    n < 0 ?                           //If n < 0
        a + " " + a(b, a + b, n + 1)  //Return a + next terms and increment n.
    :                                 //Else
        n > 0 ?                       //If n > 0
            a > b ?                   //If a > b
                a(b, a + b, -n)       //Negate n and return terms.
            :                         //If a <= b
                a(b - a, a, n)        //Generate previous term.
        :                             //If n == 0
            ""                        //Return nothing.
    ;
}

```
> 2 votes

# Answer
## Mathematica 112

Will golf it eventually

```
z[a_, b_, n_] := (
  f[0] := Min[a, b];
  f[1] := Max[a, b];
  f[x_] := f[x - 1] + f[x - 2];
  f /@ Range[n]
  )

```
> 1 votes

# Answer
# CJam, 40 bytes

```
l~:A;{_@_@)<}{_@\-\}w\{A(:A0>}{_p_@+}w\;

```

Baby steps. This is my first CJam program ever, so I'm proud it works at all.

It takes input in the same form as in the examples.

I've now seen I could reduce it to 33 bytes using the `{ ... }*` construct.

```
l~:A;{_@_@)<}{_@-z\}w\A{_p_@+}*;;

```

And I could even reduce it by one more by using the ternary operator to clean the stack and produce an error.
> 1 votes

# Answer
# Ruby, 141 bytes

```
def u a,b,n,z=""
n<1 ? z.chop : u(b,a+b,n-1,z+"#{a} ")
end
def d a,b,z=0
a.abs>b ? z : d(b-a,a,[a,b])
end
def f a,b,n
x,y=d a,b
u x,y,n
end

```

## Execution

f function produces the desired output, argument names match the variable names from the question

```
f(8,13,10) # returns => "0 1 1 2 3 5 8 13 21 34"

```

## Nothing clever:

* u (*up*) function computes n elements in the fibonacci sequence starting with a,b using recursion
* d (*down*) function finds the 0th and 1st element given two end elements using recursion
* f (*fibonacci*) function puts the two together
> 1 votes

# Answer
# Mathematica, 59 bytes

```
If[#>#2,LinearRecurrence[{1,1},#2+{0,#},#3],#0[#2-#,#,#3]]&

```
> 1 votes

# Answer
# Ruby, ~~81~~ ~~75~~ 73

```
a,b,n=23,37,5;while(c=b-a)<a;b,a=a,c;end;p a;[*2..n].map{b=c+a;c,a=a,b;p b}

```

Shortened by 6 Bytes when replacing for-loop with range.map

```
a,b,n=23,37,5;while(c=b-a)<a;b,a=a,c;end;p a;[*2..n].map{p b=c+a;c,a=a,b}

```

Saved another 2 bytes by moving print statement
> 0 votes

# Answer
## Pyke, 24 bytes

```
DA/IDA-],X_r)QVDsRe
R]);

```

Try it here!
> 0 votes

# Answer
# Jelly, 14 bytes

```
Ḋ;_/Ɗ>/¿+⁹Ð¡/Ṗ

```

Try it online!
> 0 votes

# Answer
# Common Lisp, 91 bytes

```
(lambda(a b n)(do((x a(- y x))(y b x))((> x y)(dotimes(k n)(print y)(psetf y(+ y x)x y)))))

```

Try it online!
> 0 votes

---
Tags: code-golf, number, sequence, fibonacci
---