title: Shortest Mirror Quine Challenge

text:
# Question
Title: Shortest Mirror Quine Challenge
Find the shortest mirror quine in a language of your choice.

A mirror quine is a quine whose source code is equal to the reverse of its own source code.

**Note:**

1) Length of source code should be **atleast 2**.

2) Quines **not allowed are the one whose text can be echoed directly.**

Example: Let L' be any language, then a quine with source code like ABBA or ABCBA is a mirror quine.

# Answer
# HQ9+, 3 Characters

Am I cheating?

```
+Q+

```
> 14 votes

# Answer
## Perl, 53 characters

Perl's multifaceted text-handling features once again prove useful for golfing.

```
---BEGIN---

say$/.reverse$_=<<'';say
yas;''<<=_$esrever./$yas

----END----

```

Ignore the `BEGIN` and `END` markers; they're just there to keep the blank lines at the beginning and end from being suppressed from display. Yes, the source really does have two blank lines at the top and one blank line at the bottom. This apparent lack of symmetry may throw you at first, but that's just the nature of line breaks. What's really happening, of course, is that the source both begins and ends with two line break characters.
> 13 votes

# Answer
# Golfscript, 33 characters

```
""~.{'""~.'print tnirp'.~""'}.~""

```

Since every language uses parentheses of some form, I assert the "`(` mirrors to `(`" version of this challenge is impossible (under rule #2), and assume `(` mirrors to `)`. Additionally, this version provides more visual symmetry.

If trailing whitespace is allowed, empty strings can be replaced with newlines (**29 characters**):

```
n~.{'n~.'print tnirp'.~n'}.~n

```

Proceeds as follows:

* `""~.` pushes an empty string onto the stack, evaluates it and clones the input (empty string)
* `{...}` is a block
* `.~""` clones the block, evaluates one copy and pushes an empty string to the stack.

That block:

* `'""~.'` pushes the string `""~.` onto the stack
* `print` outputs it directly and removes it from the stack
* `tnirp` is an undefined symbol and does nothing
* `'.~""'` pushes the string `.~""` onto the stack

After the program finishes, the stack contents are printed:

* the empty string (twice)
* the main block, including delimiters
* the program suffix as a string
* another empty string
> 7 votes

# Answer
# Befunge 98 - ~~40~~ ~~35~~ 31 or 29 characters

```
#r:0g,:a3*`!e*j@j*e!`*3a:,g0:r#

```

Saved another 4 characters, for 31 total, and complied with specs.

Or, if the other code can just be filler (29):

```
>:0g,:e2*`!e*j@j*e!`*2e:,g0:>

```

---

# Old Version

```
#r:0g,:'#`3+ja+1r@r1+aj+3`#':,g0:r#

```

Saved 5 characters by using `'` to fetch the length of the program

---

```
#r:0g,:a4*`3+jb+1r@  @r1+bj+3`*4a:,g0:r#

```

Just a variation on a normal quine, but made into a palindrome.

```
:0g get the character at a location (counter, 0)
,   print it
:   take the counter
a4* get 10 * 4 (40, length of program)
`   compare them (0 if counter is less or equal, 1 if greater)
3+  add 3
j   jump that amount (4 or 3)

if 4:
@   end program

if 3:
r   head the other way (to the left)
1+  increment counter
bj  jump 11 chars (to beginning r (reverse direction again))

```
> 1 votes

# Answer
# Mouse-2002, 73 bytes

```
2 0&FOPEN (x.74<^2&F?' !'x.1+x:)36!'~'!63):x+1.x'!'? F&2^<75.x( NEPOF&0 2

```
> 1 votes

---
Tags: code-golf, restricted-source, quine, palindrome
---


title: Programming Puzzles and Taco Truck

text:
# Question
Title: Programming Puzzles and Taco Truck
Programming Puzzles & Code Golf has opened a taco truck! The word is out and now users from all over the Stack Exchange network are coming to try our tasty, authentic ASCII tacos. We need your help to ensure that everyone gets their orders in a timely manner. There isn't a whole lot of room inside food trucks, so you'll need your code to be as short as possible.

Now for some on-the-job training.

## Your job

Write a full program that reads an order from STDIN or a function that gets a single string order as input. Tacos are printed to STDOUT, made to order.

## Taking orders

Customers will give you their orders via STDIN or function argument. Orders will be in the form of a comma-delimited list of desired toppings. The order in which the toppings are given dictates the order in which they appear in the taco, with the first listed topping on the bottom and the last on the top. Here's what we keep in stock:

* Beans
* Rice
* Veggies
* Lettuce
* Guacamole
* Sour cream
* Salsa

Customers may order as few as 1 topping but no more than 5 toppings. Toppings need not be distinct.

You may assume that the customers are familiar with the menu before ordering and thus all orders will only contain ingredients that we stock. That is, the input will always be valid.

## Serving tacos

Customers demand their tacos be printed to STDOUT. They're fine with some leading or trailing whitespace in their food.

Market research shows that everyone wants to eat tacos as words, and words in all caps are much more flavorful. Thus we will list toppings in ALL CAPS with no spaces.

In the interest of artsy presentation, we can't just plop stuff in a tortilla and call it good, we have to gently lay toppings left to right, wrapping and repeating as needed. Each topping gets a minimum of 2 lines to itself. This will all become clearer once we inspect the sample platter.

## Sample platter

Let's take a look at some sample orders.

The customer orders: `Beans,Veggies,Rice,Lettuce,Sour Cream`

We deliver:

```
   SOUR
  CREAMS
T LETTUC L
O ELETTU I
R RICERI T
T CERICE R
I VEGGIE O
L SVEGGI T
L BEANSB A
 A EANS L
  TORTIL

```

Looks pretty tasty, right? The toppings wrap after 6 characters to a new line and are repeated to fill 2 lines each, truncated to 12 characters. The first ingredient gets 6 characters on its top line but only 4 on its second line. This ensures that it fits in the fold of the tortilla. Similarly, the last ingredient always gets 4 characters on its top line and 6 on its second.

What happens if a customer orders two of the same topping in a row? Keep wrapping that ingredient for all consecutive lines of that ingredient.

The customer orders: `Lettuce,Lettuce,Lettuce,Salsa`

We deliver:

```
T  SALS  L
O ASALSA I
R LETTUC T
T ELETTU R
I CELETT O
L UCELET T
L TUCELE A
 A TTUC L
  TORTIL

```

The customer orders: `Guacamole`

```
T        L
O        I
R        T
T        R
I        O
L  GUAC  T
L AMOLEG A
 A UACA L
  TORTIL

```

Only one ingredient? Give 4 extra characters' worth on the top.

## Employees of the month

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

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<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="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><div id="language-list"> <h2>Winners 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><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>
```

---

Happy cooking!

# Answer
# JavaScript (ES6), ~~269~~ 263 bytes

```
x=>eval('x=x.split`,`;p=o="";for(i=10;i--;){t=x[1]?x[i/2|0]:x[i>2|0];t!=p?r=(n=0,t?t.replace(s=" ",""):s).toUpperCase().repeat(99):0;m=r.slice(n,n+=p&&i?6:4);p&&i?0:m=s+m+s;p=t;o+=(i>7?t?s+s+m:"":i?"TORTILL"[7-i]+s+m+s+"LITROTA"[7-i]:` A${m}L`)+`\n`}')+"  TORTIL"

```

## Explanation

```
x=>
  eval('                                          // use eval to save writin return and {}
    x=x.split`,`;                                 // convert ingredients to an array
    p=                                            // p = previous ingredient
      o="";                                       // o = output text
    for(i=10;i--;){                               // loop from top to bottom of taco
      t=x[1]?x[i/2|0]                             // t = ingredient text
        :x[i>2|0];                                // start a line early if 1 ingredient
      t!=p?r=                                     // r = repeated ingredient text
        (n=0,                                     // n = current index in repeated text
        t?t.replace(s=" ",""):s)                  // get the ingredient (or space)
        .toUpperCase().repeat(99):0;              // upper-case and repeat the ingredient
      m=r.slice(n,n+=p&&i?6:4);p&&i?0:m=s+m+s;    // m = text in the middle of the taco
      p=t;                                        // set p to current ingredient

      // Add the appropriate output
      o+=(i>7?t?s+s+m:"":i?"TORTILL"[7-i]+s+m+s+"LITROTA"[7-i]:` A${m}L`)+`\n`

    }                                             // implicit: eval returns o
  ')+"  TORTIL"                                   // return the output text

```

## Test

```
var solution = x=>eval('x=x.split`,`;p=o="";for(i=10;i--;){t=x[1]?x[i/2|0]:x[i>2|0];t!=p?r=(n=0,t?t.replace(s=" ",""):s).toUpperCase().repeat(99):0;m=r.slice(n,n+=p&&i?6:4);p&&i?0:m=s+m+s;p=t;o+=(i>7?t?s+s+m:"":i?"TORTILL"[7-i]+s+m+s+"LITROTA"[7-i]:` A${m}L`)+`\n`}')+"  TORTIL"
```

```
<input type="text" id="input" value="Beans,Veggies,Rice,Lettuce,Sour Cream" />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```
> 3 votes

# Answer
## Python 3, 475 bytes

```
n=range
s=input().upper().replace(" ","").split(",")[::-1]
s=sum(zip(s,s),tuple())
t=""
p=0
l=len(s)
if l==2:q=s[0];s=[q,q,q];l=3
r=[]
e=" "
f=e*4
d=[f," AL ","L  A","L  T","I  O","T  R","R  T","O  I","T  L",f,f]
for i in n(l):
 h=s[i]
 c=6
 a=""
 if i==0 or i==l-1:c=4
 if t!=h:
  p=0
  t=h
 for x in n(0,c):
  a+=h[p]
  p+=1
  if p==len(h):
   p=0
 if c==4:a=e+a+e
 r+=[a]
r=["TORTIL"]+r[::-1]
for i in n(0,11):
 y=10-i
 x=d[y]
 m=e*6
 if y<=l:m=r[y]
 print(x[:2]+m+x[2:])

```

It's probably way too long, but I may as well post something!
> 6 votes

# Answer
## Ruby, ~~376~~ ~~375~~ ~~368~~ ~~363~~ 362 bytes

```
->a{p='ALLITROT'.chars
s='LATORTIL'.chars
t=['  TORTIL']
c=[*a.split(?,).chunk(&:upcase)]
c.map.with_index{|x,i|n=x[1].size*2
w=x[0].tr(' ','')*9*n
[n+=i==0?1:0,w.sub!(/..../,' \0 ')]if i==c.size-1
w.chars.each_slice(6).take(n).reverse.map{|l|t=["#{p.shift||' '} #{l*''} #{s.shift||' '}"]+t}}
p.map{|x|t=[x+' '*8+s.shift]+t}
t[-2].sub! /(.{6})../,' \1'
t.join$/}

```

Still a work in progress.

(Bonus: Works with as many toppings as you want, not just 5. Mostly because I didn't see that rule at first \>\_\<)

Ungolfed version:

```
#!/usr/bin/env ruby

def make_taco ingredients
    # These three variables make up the tortilla.
    prefixes = 'ALLITROT'.chars
    suffixes = 'LATORTIL'.chars
    taco = ['  TORTIL']
    # .chunk is a Ruby builtin that's *incredibly* useful for this challenge.
    chunks = ingredients.split(',').chunk{|x| x}.to_a
    # Loop through every chunk of equal ingredients.
    chunks.each_with_index do |ingredient, idx|
        # Get the number of lines the group of ingredients should take up.
        count = ingredient[1].length * 2
        # *9 because that's guaranteed to be enough ingredient.
        wrapped = ingredient[0].upcase.sub(' ','') * 9 * count
        # If this is the last element...
        if idx == chunks.length - 1
            # Add spaces strategically to position the top "layer."
            wrapped.sub! /..../, ' \0 '
            # If this is also the first element...
            if idx == 0
                # We need to make one more row.
                count += 1
            end
        end
        # Arrange the ingredient like so, and then for each "layer"...
        wrapped.chars.each_slice(6).take(count).reverse.each do |line|
            # Add it to the taco, along with prefixes/suffixes if they exist.
            taco.push "#{prefixes.shift || ' '} #{line * ''} " +
                "#{suffixes.shift || ' '}"
        end
    end
    # Fill in the rest of the prefixes and suffixes we didn't use.
    prefixes.each do |prefix|
        taco.push prefix + ' ' * 8 + suffixes.shift
    end
    # Fix the "offset" on the second-to-last line.
    taco[1].sub! /(.{6})../, ' \1'
    # Since we've been building the taco bottom-up, reverse, join, and return.
    taco.reverse.join("\n")
end

puts make_taco 'Beans,Veggies,Rice,Lettuce,Sour Cream'
puts
puts make_taco 'Lettuce,Lettuce,Lettuce,Salsa'
puts
puts make_taco 'Guacamole'

```
> 3 votes

---
Tags: code-golf, ascii-art
---


# Question
Title: An executable script file that runs on POSIX and Windows
**Challenge**: write a single script file `foo.cmd` which can be invoked from the vanilla Windows `cmd.exe` prompt (not PowerShell, not in administrator mode), to execute arbitrary Windows-specific code...

```
> .\foo.cmd
Hello Windows!

```

...but also be invoked unaltered from a typical POSIX-compliant (Linux/OSX) shell prompt (`bash`, `tcsh`, or `zsh`), to execute arbitrary POSIX-specific code:

```
$ chmod a+x foo.cmd
$ ./foo.cmd
Hello POSIX!

```

...without requiring installation or creation of third-party interpreters/tools.

I know this is possible, but with cruft (i.e. on Windows, one or two lines of garbage/error-message are printed to stderr or stdout before "Hello Windows!").

The winning criterion is minimization of (first) the number of cruft lines, and (second) the number of cruft characters.

Cruft can be defined as any console output (stdout or stderr) that is not produced by the (arbitrary) payload code. Blank lines are counted in the line count. Newlines are not counted in the character count. Cruft scores should be summed across both platforms. Let's disregard mechanisms like `cls` that sweep away the cruft but at the cost of also blanking out previous terminal output. If Windows echos your commands because you haven't turned `@echo off` yet, let's exclude the characters it spends in printing the current directory and prompt.

A secondary criterion is the simplicity/elegance of the solution inside `foo.cmd`: if "infrastructure" is defined as any character not directly involved in the arbitrary payload code, then minimize first the number of lines that contain infrastructure characters, and second the total number of infrastructure characters.

Extra kudos if the POSIX part will work despite the file having CRLF line-endings! (Am not sure that last part is even possible.)

My existing solution, which I will post here once others have had a chance, uses 6 lines of infrastructure code (52 chars excluding newlines). It produces 5 lines of cruft, two of which are blank, all of which occur on Windows (30 chars excluding newlines and excluding the current directory/prompt string that appears on two of those lines).

# Answer
# 0 cruft lines, 0 cruft chars, 2 infra. lines, 21 infra. chars, CRLF ok

```
:<<@goto:eof
@echo Hello Windows!
@goto:eof
echo "Hello POSIX!" #

```

Removed the other solution.

17 characters using `exit /b` from Digital Trauma's answer:

```
:<<@exit/b
@echo Hello Windows!
@exit/b
echo "Hello POSIX!" #

```
> 15 votes

# Answer
# Score 0 cruft + 4 infra lines + 32 infra chars. LF & CRLF OK.

This is based off what I found at this blog, with the Amiga bits and other unnecessary lines taken out. I hid the DOS lines in commented quotes instead of using `\` line continues, so that this can work with both CRLF and LF.

```
@REM ()(:) #
@REM "
@ECHO Hello Windows!
@EXIT /B
@REM "
echo Hello POSIX!

```

With either DOS CRLF or \*nix LF line endings, it works on Ubuntu, OSX and wine:

```
ubuntu@ubuntu:~$ ./dosix.bat
Hello POSIX!
ubuntu@ubuntu:~$ wine cmd.exe
Wine CMD Version 5.1.2600 (1.6.2)

Z:\home\ubuntu>dosix.bat
Hello Windows!

Z:\home\ubuntu>exit
ubuntu@ubuntu:~$

```

To create this exactly (with CRLFs) on a \*nix machine (including OSX), paste the following to a terminal:

```
[ $(uname) = Darwin ] && decode=-D || decode=-d
ubuntu@ubuntu:~$ base64 $decode > dosix.bat << EOF
QFJFTSAoKSg6KSAjDQpAUkVNICINCkBFQ0hPIEhlbGxvIFdpbmRvd3MhDQpARVhJVCAvQg0KQFJF
TSAiDQplY2hvIEhlbGxvIFBPU0lYIQ0K
EOF

```
> 4 votes

# Answer
I'll already post the solution I had been using, since it has already been beaten. It's courtesy of a colleague of mine who I think must have read the same blog entry as Digital Trauma.

```
#!/bin/sh # >NUL 2>&1
echo \
@goto c \
>/dev/null
echo "Hello Posix!"
exit
:c
@echo Hello Windows!

```
* Windows cruft: 5 lines (of which two are blank) / 30 chars
* OSX cruft: 0
* Infrastucture: 6 lines / 52 chars
* CRLF compatibility: only if the interpreter named on the `#!` line doesn't care (so for standard interpreters like `sh` and friends, it fails)
> 3 votes

# Answer
# Summary/synthesis of answers and discussion

This was fun, and I learned a lot.

Some Windows-specific cruft is inevitable if, on your POSIX system, you need to start your script with a `#!` line. If you have no alternative but to do this, then this line:

```
#!/bin/sh # 2>NUL

```

is probably the best it can get. It causes one blank line and one line of cruft to be output on the Windows console. However, you *may* be able to get away without a `#!` line: on most systems, one of the usual shell interpreters will end up executing the script (the problem is that it's not universally predictable which interpreter that will be - it depends on, but will not necessarily be identical to, the shell you use to invoke the command).

Beyond that tricky first line, there were some really ingenious cruftless solutions. The winning submission by jimmy23013 consisted of only two short infrastructure lines, and made use of the dual role of the `:` character to implement a "silent" line on both platforms (as a *de-facto* no-op in `sh` and friends, and as a label marker in `cmd.exe`):

```
:<<@exit/b

:: Arbitrary Windows code goes here

@exit/b
#
# Arbitrary POSIX code goes here

```

It *is* possible to make such a script run on POSIX systems even despite CRLF line-endings, but to do this for most interpreters you have to end *every* line of your POSIX section (even blank lines) with a comment or comment character.

Finally, here are two variants on a solution I have developed based on everybody's input. They might be *almost* the best of all worlds, in that they minimize the damage from the lack of `#!` and make CRLF-compatibility even smoother. Two extra infrastructure lines are needed. Only one (standardized) line has to be interpreted by the unpredictable POSIX shell, and that line allows you to select the shell for the rest of the script (`bash` in the following example):

```
:<<@GOTO:Z

@echo Hello Windows!

@GOTO:Z
bash "$@"<<:Z
#
echo "Hello POSIX!" #
ps # let's throw this into the payload to keep track of which shell is being used
#
:Z

```

Part of the beauty of these heredoc solutions is that they are still CRLF-robust: as long as `<<:Z` comes at the *end* of the line, the heredoc processor will actually be looking for, and will find, the token `:Z\r`

As a final twist, you can get rid of those pesky end-of-line comments and still retain CRLF-robustness, by stripping the `\r` characters out before passing the lines to the shell. This places slightly more faith in the unpredictable shell (it would be nice to use `{ tr -d \\r|bash;}` instead of `(tr -d \\r|bash)` but curly brackets are bash-only syntax):

```
:<<@GOTO:Z

@echo Hello Windows!

@GOTO:Z
(tr -d \\r|bash "$@")<<:Z

echo "Hello POSIX!"
ps

:Z

```

Of course, this approach sacrifices the ability to pipe stdin input into the script.
> 3 votes

---
Tags: code-challenge, polyglot
---


title: The time after some time

text:
# Question
Title: The time after some time
For this challenge, we are writing the time in the following form: `hh:mm:ss`

Some examples:

> `12:34:08`
>
> `06:05:30`
>
> `23:59:00`

The challenge is to output the time after an amount of *hours*, *minutes* and *seconds* have elapsed, with as starting time `00:00:00`. You can compare this with a timer that started at `00:00:00`.

Here is an example of inputs (using **STDIN**) and outputs:

```
Input: 1h20m5s
Output: 01:20:05

Input: 0h100m0s
Output: 01:40:00

```

After 24 hours, the timer resets itself:

```
Input: 25h0m0s
Output: 01:00:00

```

The form of the input is always the same: `XhYmZs`, with `X` hours, `Y` minutes and `Z` seconds (assume that `X`, `Y` and `Z` are whole integers less than 100000 and never negative)

This is , so least amount of bytes wins this challenge

# Answer
> 4 votes
# CJam, 34 bytes

```
leu~]2%60b86400%60b3Te[{s2Te[}%':*

```

Try it here.

# Answer
> 4 votes
# Ruby - ~~131~~ ~~115~~ ~~107~~ ~~97~~ 84 bytes

I'm still golfing it.

```
h,m,s=gets.split(/\w/).map &:to_i;$><<"#{(h+m/60+s/3600)%24}:#{(m+s/60)%60}:#{s%60}"

```

Thanks for @Doorknob for /\w/ inshead of /h|m|s/

# Answer
> 2 votes
# Mathematica, ~~133~~ ~~116~~ ~~112~~ 111 bytes

```
IntegerString[(f=FromDigits)[f/@StringSplit[#,_?LetterQ],60]~Mod~86400~IntegerDigits~60,10,2]~StringRiffle~":"&

```

# Answer
> 2 votes
## C ~~149~~ 112 bytes

Test it here

```
main(h,m,s){scanf("%dh%dm%ds",&h,&m,&s);s+=h*3600+m*60;h=s/3600;m=s/60;printf("%02d:%02d:%02d",h%24,m%60,s%60);}

```

Credits to @Dennis for getting rid of a lot it.

# Answer
> 2 votes
# Python 2, ~~138~~ 126 Bytes

Now I'm using regex, still quite long though..

```
import re
a=input();b=map(int,re.split('h|m|s',a)[:-1])
s=b[0]*3600+b[1]*60+b[2]
print(':%02d'*3)[1:]%(s/3600%24,s/60%60,s%60)

```

Input should be in quotes.

# Answer
> 2 votes
# PHP, 80 ~~88~~ ~~93~~ Bytes

```
<?=!$s=split(~¤—’¢,fgets(STDIN)),date(~·Å–ÅŒ,$s[0]*3600+$s[1]*60+$s[2]-date(Z));

```

(saved as ISO-8859-1)

Works only on PHP 5 because of deprecated `split` function. Assumes that notices are not shown.

### How it works:

* `¤—’¢` is `"[hm]"` inverted and a valid constant name, PHP uses undefined constants as string (saves one character for the quotation marks)
* `·Å–ÅŒ` is the same for `"H:i:s"`
* Everything is a single short handed echo statement. `<?=x,y` outputs x and y. Using `!`, the result of the `$s` assignment gets converted to boolean and negated, then converted to string to output. `(string)false === ''`
* `split("[hm]", "XhYmZs")` splits the string to `[X,Y,Zs]`. Then, `3600*X+60*Y+Zs` is the number of seconds. PHP converts `Zs` to integer as `Z`
* We substract the timezone offset `date(Z)`, use this result as a timestamp and print its time part as "hours:minutes:seconds". In UTC (offset 0), the timestamp `0` is `1970/01/01 00:00:00`. Substracting the timezone offset normalizes the date as UTC without changing the actually used timezone (this saved 8 bytes for setting the timezone).
* Conveniently, 25 hours will result in 01:00:00 (on the next day).

# Answer
> 2 votes
## JavaScript 110 bytes

Where x is the input

```
x=x.split(/[hms]/).map(Number);for(z=2;z--;)x[z+1]-60&&(x[z]+=~~(x[z+1]/60));y=x[0]%24+":"+x[1]%60+":"+x[2]%60

```

I don't think this is the most efficient way

```
// How it works:
x=x.split(/[hms]/).map(Number);                // splitting the string into an array of numbers
for(z=2;z--;)x[z+1]-60&&(x[z]+=~~(x[z+1]/60)); // shifting excess of seconds to minutes, and then minutes to hours
y=x[0]%24+":"+x[1]%60+":"+x[2]%60              // putting them all together

```

# Answer
> 1 votes
# AutoIt, 208 bytes

```
Func _($0)
$1=StringRegExp($0,"[0-9]+",3)
For $2=2 To 1 Step -1
If $1[$2]>59 Then
$1[$2]=Mod($1[$2],59)-1
$1[$2-1]+=1
EndIf
Next
Return StringFormat("%02u:%02u:%02u",$1[0]-($1[0]>23?24:0),$1[1],$1[2])
EndFunc

```

Too long. Test:

```
ConsoleWrite(_("1h20m5s") & @LF)
ConsoleWrite(_("0h100m0s") & @LF)
ConsoleWrite(_("25h0m0s") & @LF)

```

# Answer
> 1 votes
# Pyth, 40 bytes

```
j\:%L"%02d">3j+%ivM:z"\d+"1K60 86400^KTK

```

I'm still learning. Try it here!

# Answer
> 1 votes
# Perl 5, 84 (83 Bytes + 1)

Uses the overflow of seconds or minutes.

```
($h,$m,$s)=split/\D/;$h+=($m+=$s/60)/60;printf"%0.2d:%0.2d:%0.2d",$h%24,$m%60,$s%60

```

### Test

```
$ echo 35:124:224s |perl -n 61736-time-after-some-time.pl
13:07:44

```

# Answer
> 1 votes
## VBA (150149 bytes)

```
Function t(s)
x = Split(Replace(Replace(Replace(s, "s", ""), "m", " "), "h", " "))
t = Format(TimeSerial(x(0), x(1), x(2)), "HH:MM:SS")
End Function

```

# Answer
> 1 votes
# JavaScript, 97 bytes

```
x=>([h,m,s]=x.match(/\d+/g),[(+h+m/60|0)%24,(+m+s/60|0)%60,s%=60].map(a=>(a>9?'':'0')+a).join`:`)

```

# Answer
> 1 votes
# PowerShell, 84 Bytes

```
$a=$args-split'[hms]';"{0:HH:mm:ss}"-f(date 0).AddSeconds(3600*$a[0]+60*$a[1]+$a[2])

```

Splits the command-line input into an array of strings based on the `[hms]` regex. Uses the verbose built-in function `.AddSeconds()` to add (hours\*3600, minutes\*60, and seconds) to `(date 0)` a/k/a `Monday, January 1, 0001, 12:00:00 AM`, then feeds that into `-f` with formatting `HH:mm:ss` which will automatically convert it to 24-hour clock format and output it.

### Example:

```
PS C:\Tools\Scripts\golfing> .\time-after-some-time.ps1 25h100m0s
02:40:00

```

# Answer
> 1 votes
# Lua, 104 bytes

```
h,m,s=io.read():match"(%d+)h(%d+)m(%d+)"m=m+s/60;print(("%02d:%02d:%02d"):format((h+m/60)%24,m%60,s%60))

```

# Answer
> 1 votes
## VB.NET (107 bytes)

First submission for code golf so I'm guessing character count =\> byte count?

```
MsgBox(TimeSpan.Zero.Add(TimeSpan.Parse(Regex.Replace(InputBox("XhYmZs"),"[hm]",":").Trim("s"))).ToString)

```

# Answer
> 1 votes
# Python 3, 158

```
import re
e=input()
b=[];p=0
for s in re.split('\D',e)[:3][::-1]:c,a=divmod(int(s),60);b+=[a+p];p=c
b[2]=(b[2]+p)%24;f=':%02d'*3;print(f[1:]%(b[2],b[1],b[0]))

```

Ungolfed version:

```
import re
def timer(elapsed):
    base=[]
    previous_carry=0
    for section in re.split('\D+',elapsed)[:3][::-1]:
        carry,amount=divmod(int(section),60)
        base+=[amount+previous_carry]
        previous_carry=carry
    base[2]=(base[2]+previous_carry)%24
    format_str = ':%02d'*3
    return format_str[1:]%(base[2],base[1],base[0])

```

# Answer
> 1 votes
# CJam, 50 bytes

```
0[l"hms"Ser~][24 60 60].{md}(;+2/::+{"%02d"e%}%':*

```

# Answer
> 1 votes
# GNU sed+date, 51 bytes

(including +1 byte for `-r` flag)

```
#!/bin/sed -rf
s/(.*h)(.*m)(.*s)/date -d"0:0 \1our\2in\3ec" +%T/e

```

This simply gets `date` to add the specified number of hours, minutes and seconds to `00:00:00` (today) and display the time part. Recommended to set `TZ=UTC` or avoid running the program around a local-time change (e.g. daylight savings).

---
Tags: code-golf
---


title: How many weeks?

text:
# Question
Title: How many weeks?
**Your task** is to output a single number; the number of ISO weeks that a given date range intersects. To quote Wikipedia: `An average year is exactly 52.1775 weeks long`, but this is not about the average.

**Input** consists of two space-separated ISO dates:

```
0047-12-24 2013-06-01

```

The end date is never before the start date. We'll use the extrapolated Gregorian calendar for simplicity.

**Test cases:**

```
Format: input -> output
2015-12-31 2016-01-01 -> 1    (both are within week 53 of 2015)
2016-01-03 2016-01-04 -> 2    (the 3rd is within week 53, and the 4th is in week 1)
2015-12-24 2015-12-24 -> 1    (this single day is of course within a single week)

```

Your solution should handle dates between `0001-01-01` and `9999-12-31`.

# Answer
> 2 votes
## Ruby, ~~89~~ ~~88~~ 86 bytes

```
->s{a,b=s.split.map{|x|Time.gm *x.split(?-)}
n=1
(a+=86400).wday==1&&n+=1until a==b
n}

```

A very primitive solution: given the first date `a` and the second date `b`, increment `a`, check if it's a Monday (if so, we've "rolled over" to a new week), and stop once `a` is `b`.

Takes input in the exact format specified in the question: a single space-separated string. (The way it parses the input is fancy-ish: it uses Ruby's "splat" operator, `*`. This operator "expands" an array or enumerable out, so `Time.gm *[2013, 06, 01]` becomes `Time.gm 2013, 06, 01`.)

Imported from a comment discussion:

> We don't care about "weeks in a year;" we only care about "weeks overall." So whether a year has 52 or 53 weeks doesn't make any difference.

Just to avoid future confusion with whether this handles year boundaries correctly—according to Wikipedia, all weeks always start on Monday and end on Sunday.

For some more fancy tricks, these are all equivalent:

```
until a==b;a+=86400;n+=a.wday==1?1:0;end
[a+=86400,n+=a.wday==1?1:0]until a==b
n+=(a+=86400).wday==1?1:0 until a==b
(a+=86400).wday==1&&n+=1 until a==b
(a+=86400).wday==1&&n+=1until a==b

```

# Answer
> 1 votes
# VBA , 125 Bytes

Expecting 2 function inputs as strings

```
Function u(k,j)
f=DateValue(k)
For i=0 To (DateValue(j)-f)
q=DatePart("ww",f+i,2,2)
If q<>j Then u=u+1
j=q
Next
End Function

```

Pretty sure This can be golfed. This is looping though everyday between the 2 dates and increments the counter every time the ISO date changes.

`DatePart("ww",f+i,2,2)` is the ISO week number in VBA the first 2 means `Monday (complies with ISO standard 8601, section 3.17)`. then second 2 means `Week that has at least four days in the new year (complies with ISO standard 8601, section 3.17)`

### 140 bytes w/single input

```
Function g(k)
y=Split(k)
f=DateValue(y(0))
For i=0 To (DateValue(y(1))-f)
q=DatePart("ww",f+i,2,2)
If q<>j Then g=g+1
j=q
Next
End Function

```

# Answer
> 1 votes
## R, 76 bytes

```
d=as.Date(scan("","raw"));sum(strftime(seq(d[1],d[2],"day")[-1],"%w")==1)+1

```

After the talk with @Doorknob, it's finally as easy as counting the Mondays.

`seq` allow to create a vector of dates (of each day between two dates) and strftime transform it to the 'number of the day in the week', now counts the times it's 1 to get the number of time you changed week and add 1 to take in account previous week.

Another approach looping:

## R, 85 bytes

```
n=1;d=as.Date(scan("","raw"));z=d[1];while(z<d[2]){n=n+(strftime(z<-z+1,"%w")==1)};n

```

# Answer
> 0 votes
# Mathematica ~~135 79 96 84~~ 74 bytes

Consistent with @Doorknob's suggestion, this

* generates all the dates in the range
* counts the number of Mondays (`ISOWeekDay` =="1") in the `DateRange`(excluding `d`), and
* adds `1` to the total.

---

```
Count[DateString[#,"ISOWeekDay"]&/@Rest@(DateRange@@StringSplit@#),"1"]+1&

```

---

```
Count[DateString[#,"ISOWeekDay"]&/@Rest@(DateRange@@StringSplit@#),"1"]+1&
/@ {"2015-12-31 2016-01-01", "2016-01-04 2016-01-05","2016-01-03 2016-01-04",
"2015-12-24 2015-12-24", "1876-12-24 2016-01-01"}

```

> {1, 1, 2, 1, 7255}

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


title: Condense these page numbers!

text:
# Question
Title: Condense these page numbers!
Disclaimer: while I have been on this site for entertainment purposes for a little while now, this is my first question, so please forgive any minor errors.

# Background

When assigning us homework, my teacher is really annoying and writes out *all* the problems we have to do individually. As such, it takes me *forever* to copy down which problems I have to do. I thought to make my life easier, I would send him a program that could make the list of problems take up less space.

While writing down a list of page or problem numbers, we use a dash to denote a range. For example, `19-21` becomes `19, 20, 21`. If there is a gap in between, two comma-separated ranges are used: `19-21, 27-31` becomes `19, 20, 21, 27, 28, 29, 30, 31`.
Right about now, you're probably thinking: "this seems pretty trivial". In fact, this has already been answered here and here.

However, there is a catch. If we have a range with equal consecutive digits, the repeated digits can be left out. For example: `15, 16, 17` becomes `15-7`, and `107, 108, 109` becomes `107-9`. For a bonus, if the last consecutive equal digit is 1 greater and the upper limit's last digit is less than or equal to that of the lower, the following can be omitted (sorry if that sounded confusing; perhaps some examples will clear it up). `109-113` becomes `109-3`, as a lower last digit implies increasing the 10s place.

# Challenge

Your program should take a list of integers via input (whatever is standard for your language, or a function). You can decide whether this list is comma-separated, space-separated, or as an actual list/array.

Output the **shortest way** (first sorted by number of ranges, then the sum of the characters included in the ranges) to represent that list using this notation. Each dashed range must be on the same line, but the ranges can be separated by commas or newlines (trailing newlines or commas are allowed). These ranges must be in order.

Since our school Wi-Fi is **terrible**, I have to make the file as small as possible in order to send it to him. The shortest code (in bytes) wins.

# Bonuses

My teacher is sloppy, so there are a few things that would help him out. Multiple bonuses stack through multiplication, e.g. a -10% bonus (x 90%) and a -25% (x 75%) bonus = 90% * 75% = x 67.5% (-32.5% bonus).

* Sometimes he puts them in the wrong order (he's not a math teacher). Take a -20% bonus if your program can accept integers that are not sorted least-to-greatest.
* Our book is weird, and each section starts counting the problems at -10. If your program can accept negative numbers, take a -25%.
* If it accepts the bonus of a lower last digit increasing 10's place, e.g. `25-32` reducing to `25-2`, take a -50% bonus.

# Test Cases

```
In:  1, 2, 3, 4, 5
Out: 1-5

In:  3, 4, 5, 9, 10, 11, 12
Out: 3-5, 9-12

In:  149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160
Out: 149-60

In: 1 2 3 4
Out: 1-4

For bonuses:

In: 109, 110, 111, 112, 113
Out: 109-3

In:  19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29
Out: 19-9

In: -3, -2, -1, 0, 1, 2
Out: -3-2

In: -3, -2, -1
Out: -3--1

```

An answer will be accepted on Saturday, 19 December 2015.

GLHF!

# Answer
> 5 votes
# LabVIEW, 97\*0.8\*0.75\*0.5 = 29.1 LabVIEW Primitives

this works by counting upwards if sucessive elemts are 1 apart and then creates a string from the the number and the number - count modulo 10 and some multiplication cause negatives are a bitch.

The gif showcases an input of `8,9,10,11` and outputs `8-1`. For input `-5,-4,-3,1,3,4,5` `-5--3,1,3-5`comes out.

# Answer
> 13 votes
## C++11, 451 * 80% * 75% * 50% = 135.3 bytes

Saved 9 bytes thanks to @kirbyfan64sos.

Saved 19 bytes thanks to @JosephMalle and @cat.

Saved 11 bytes thanks to @pinkfloydx33.

```
#include<vector>
#include<cmath>
#include<algorithm>
#include<string>
#define T string
#define P append
using namespace std;T f(vector<int>v){sort(v.begin(),v.end());T r=to_T(v[0]);int b=1;int m=v[0];for(int i=1;i<=v.size();i++){if(i!=v.size()&&v[i]==v[i-1]+1){if(!b){m=v[i-1];}b=1;}else{if(b){T s=to_T(v[i-1]);r.P("-").P(s.substr(s.size()-(v[i-1]-m==1?1:log10(v[i-1]-m)),s.size()));}if(i!=v.size()){r.P(", ").P(to_T(v[i]));}b=0;}}return r;}

```

This qualifies for all the bonuses.

Sample parameter test and result:

```
In:  [1, 2, 3, 4, 5]
Out: 1-5

In:  [3, 4, 5, 9, 10, 11, 12]
Out: 3-5, 9-12

In:  [149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160]
Out: 149-60

In:  [1, 2, 3, 4]
Out: 1-4

In:  [109, 110, 111, 112, 113]
Out: 109-3

In:  [19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
Out: 19-9

```

# Answer
> 8 votes
## Ruby, ~~120~~ 118 * 0.8 * 0.75 * 0.5 = 35.4 bytes

Takes command-line arguments as input (commas are okay); prints one range per line to standard output.

```
c=(b=(a=$*.map(&:to_i).sort).map &:succ)-a
puts (a-b).map{|m|(m<n=c.shift-1)?"#{m}-#{m<0?n:n%10**"#{n-m-1}".size}":m}

```

With whitespace/comments:

```
c=(
  b=(
    # a is the sorted input
    a=$*.map(&:to_i).sort
  # b is the set of successors of elements of a
  ).map &:succ
# c=b-a is the set of not-quite-least upper bounds of our ranges
)-a

# a-b is the set of greatest lower bounds of our ranges
puts (a-b).map {|m|
  # for each range [m,n], if there are multiple elements
  (m < n = c.shift-1) ?
    # yield the range, abbreviating n appropriately if positive
    "#{m}-#{m<0 ? n : n % 10 ** "#{n-m-1}".size}" :
    # in the one-element case, just yield that
    m
}

```

**Test cases**

```
$ ruby homework.rb 1, 2, 3, 4, 5
1-5

$ ruby homework.rb 3, 4, 5, 9, 10, 11, 12
3-5
9-2

$ ruby homework.rb 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160
149-60

$ ruby homework.rb 1 2 3 4
1-4

$ ruby homework.rb 109, 110, 111, 112, 113
109-3

$ ruby homework.rb 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29
19-9

```

**Features not covered by test cases**

Unordered input & single-element ranges:

```
$ ruby homework.rb 2 17 19 22 0 1 8 20 18
0-2
8
17-0
22

```

Negative ranges (not possible to abbreviate the larger number with these):

```
$ ruby homework.rb -17 -18 -19 -20 -21
-21--17

```

Abbreviation of arbitrary numbers of digits (ordinary bash expansion used for the input here):

```
$ ruby homework.rb {1234567..1235467} 2345999 2346000 2346001
1234567-467
2345999-1

```

# Answer
> 5 votes
# Javascript ES6, 229 * 80% * 75% * 50% = 68.7 bytes

## Test Input

I'm using the following test data:

```
var A1=[
  5,6,7,            // => 5-7     # (a) group pages
  2,3,              // => 2-3,5-7 # (b) must be properly sorted
  -9,-8,-7,         // => -10--8  # (c) allow negative numbers
  29,30,31,32,      // => 29-2    # (d) lower last digit implies increasing the 10s place
  9,10,11,12,       // => 9-11    # NOT 9-2
  36,37,38,39,40,41,42,43,44,45,46,47,
                    // => 36-47   # NOT 36-7
  99,100,101,102,   // => 99-102  # NOT 99-2
  109,110,111,112,  // => 109-2   # NOT 109-12
],
// more tests, not specified in the question
A2=[
  120,124,       // => 120,124 # (e) handle single pages
],
A3=[
  135,136,135    // => 135-6   # (f) handle duplicates
];

```

## Basic: 229 bytes

This version satisfies the requirements of the question (a) with all bonuses (c,d,e), but hangs on single pages. It can also handle duplicates(f). It handles negative pages down to -10,000, which can be easily increased with (large) loss of speed.

```
F=(a)=>{var R=[],i=NaN,l,u;a.map(x=>R[1e4+x]=x);R.concat('').map(x=>(i!=i&&(l=x,u=l-1),i=0,u=(x+="")-u-1?l=console.log(l+'-'+(u>0?(l.length-u.length||(z=>{for(;l[i]==u[i];i++);})(),u.length-i-2||u-l>9||i++,u.slice(i)):u))||x:x))}
F(A1.concat(A3)) --> -9--7 2-3 5-7 9-12 29-2 36-47 99-102 109-2 135-136

```

(The output above shows spaces instead of actual newlines for brevity)

## Single pages: 233 bytes

This slightly longer version additionally satisfies (e) and displays single pages as a range with equal lower and upper limits

```
G=(a)=>{var R=[],i=NaN,l,u;a.map(x=>R[1e4+x]=x);R.concat('').map(x=>(i!=i&&(l=x,u=l-1),i=0,u=(x+="")-u-1?l=console.log(l+'-'+(u-l&u>0?(l.length-u.length||(z=>{for(;l[i]==u[i];i++);})(),u.length-i-2||u-l>9||i++,u.slice(i)):u))||x:x))}
G(A1.concat(A2,A3)) --> -9--7 2-3 5-7 9-12 29-2 36-47 99-102 109-2 120-120 124-124

```

# Answer
> 3 votes
# Lua, 322\*80%\*75%\*50% = 96.6 Bytes

Finally done with the 3 challenges, Scores under 100 bytes :D

### Golfed

```
function f(l)table.sort(l)l[#l+1]=-13 a=l[1]t,s=a,"" for _,v in next,l do if v-t>1 or t-v>1 then s,p,r=s..a.."-",""..t,""..a r:gsub("%d",function(c)p=r:find(c)~=r:len()and p:gsub("^(-?)"..c,"%1")or p r=r:gsub("^"..c,"")end)p=t-a<10 and t%10<a%10 and p:gsub("^(%d)","")or p s,a,t=s..p..",",v,v else t=v end end return s end

```

### Ungolfed

```
function f(l)
    table.sort(l)
    l[#l+1]=-13
    a=l[1]
    t,s=a,""
    for _,v in next,l
    do
        if v-t>1 or t-v>1
        then
            s,p,r=s..a.."-",""..t,""..a
            r:gsub("%d",function(c)
                p=r:find(c)~=#r and p:gsub("^(-?)"..c,"%1")or p
                r=r:gsub("^"..c,"")
            end)
            p=t-a<10 and t%10<a%10 and p:gsub("^(%d)","")or p
            s=s..p..","
            a,t=v,v
        else
            t=v
        end
    end
return s
end

```

You can test lua online, to see how it perform against the test cases, copy paste the function, followed by this code :

```
a={1,2,3,4,5}
b={3,4,5,9,10,11,12,13,14,15,16,17,18,19,20,21}
c={149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160}
d={-7,8,5,-6,-5,6,7}
print(f(a))
print(f(b))
print(f(c))
print(f(d))

```

# Answer
> 3 votes
# GAP, 355 Bytes \*0.8\*0.75\*0.5 = 106.5

This satisfies all the bonuses. It cost me almost 100 extra bytes to make everything work nicely. This function only omits leading digits if the gap does not overflow the ones place once. For example `9 10 11` outputs `9-1` but `9 10 11 12 .. 20 21` outputs `9-21`.

If GAP was a little less verbose, I could have gotten this pretty short (also could have saved many bytes if I didn't follow the exact syntax.) I'll probably try golfing this a bit harder tomorrow. See below for test cases.

```
g:=function(l)local n;if not l=[] then Sort(l);n:=1;while not l=[] do;if not IsSubset(l,[l[1]..l[1]+n]) then if not n=1 then if n-1>10-l[1] mod 10 and n-1<11 then Print(l[1],"-",(l[1]+n-1) mod 10);else Print(l[1],"-",l[1]+n-1);fi;else Print(l[1]);fi;Print(", ");SubtractSet(l,[l[1]..l[1]+n-1]);g(l);fi;n:=n+1;od;fi;Print("\b\b  ");end;

```

ungolfed:

```
g:=function(l)
    local n;
    if not l=[] then
        Sort(l);
        n:=1;
        while not l=[] do;
            if not IsSubset(l,[l[1]..l[1]+n]) then
                if not n=1 then
                    if n-1>10-l[1] mod 10 and n-1<11 then
                        Print(l[1],"-",(l[1]+n-1) mod 10);
                    else
                        Print(l[1],"-",l[1]+n-1);
                    fi;
                else
                    Print(l[1]);
                fi;
                Print(", ");
                SubtractSet(l,[l[1]..l[1]+n-1]);
                g(l);
            fi;
            n:=n+1;
        od;
    fi;
    Print("\b\b  ");
end;

```

Note that in GAP syntax, `[a..b]` is equivalent to `[a,a+1,...,b]`. I believe that these test cases demonstrate that this program meets all the requirements. If something is wrong, let me know.

```
gap> h([1..5]);
1-5
gap> h([3,4,5,9,10,11,12]);
3-5, 9-2
gap> h([149..160]);
149-160
gap> h([109..113]);
109-3
gap> h([19..29]);
19-9

gap> h([-1,-2,-3,-7,-20000,9,10,110101,110102]);
-20000, -7, -3--1, 9-10, 110101-110102

gap> h([10101,10102,10103,10,11,12,13,14,15,16,234,999,1000,1001,1002]);
10-16, 234, 999-2, 10101-10103

```

# Answer
> 2 votes
# Java, 252 * 80% * 75% * 50% = 75.6 bytes

I've decided to go for a method (is much smaller in Java), here is the golfed version:

### Golfed

```
int p,c,s;String m(int[]a){p=s=c=0;c--;String o="";Arrays.sort(a);for(int n:a){if(s==0)o+=s=n;else if(n-p==1)c++;else{o+=t()+", "+(s=n);c=-1;}p=n;}return o+t();}String t(){return c>=0?"-"+(""+p).substring((""+Math.abs(p)).length()-(""+c).length()):"";}

```

And here is the readable version:

```
int p, c, s;

String m(int[] a) {
    p = s = c = 0;
    c--;
    String o = "";
    Arrays.sort(a);
    for (int n : a) {
        if (s == 0)
            o += s = n;
        else if (n - p == 1)
            c++;
        else {
            o += t() + ", " + (s = n);
            c = -1;
        }
        p = n;
    }
    return o + t();
}

String t() {
    return c >= 0 ? "-" + ("" + p).substring(("" + Math.abs(p)).length() - ("" + c).length()) : "";
}

```

When tested these are the results:

```
import java.util.Arrays;
public class A {
    public static void main(String...s) {
        A a = new A();
        System.out.println(a.m(new int[] {1, 2, 3, 4, 5}));
        System.out.println(a.m(new int[] {3, 4, 5, 9, 10, 11, 12}));
        System.out.println(a.m(new int[] {149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160}));
        System.out.println(a.m(new int[] {109, 110, 111, 112, 113}));
        System.out.println(a.m(new int[] {19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29}));
        System.out.println(a.m(new int[] {1,10,11,16}));
        System.out.println(a.m(new int[] {-3,-2,-1,0,1,2,3}));
        System.out.println(a.m(new int[] {-3,-2,-1}));
    }

    int p,c,s;String m(int[]a){p=s=c=0;c--;String o="";Arrays.sort(a);for(int n:a){if(s==0)o+=s=n;else if(n-p==1)c++;else{o+=t()+", "+(s=n);c=-1;}p=n;}return o+t();}String t(){return c>=0?"-"+(""+p).substring((""+Math.abs(p)).length()-(""+c).length()):"";}
}

```

Output:

```
1-5
3-5, 9-2
149-60
109-3
19-9
1, 10-1, 16
-3-3
-3--1

```

### Update:

It can now handle negative numbers as well, adding to the bonus.

# Answer
> 2 votes
# Japt, 127 bytes * 80% * 75% * 50% = 38.1

Wow, that was one heck of a challenge to include all the bonuses. It could probably be made shorter.

```
D=[]N=Nn-;DpNr@Y-1¥Xg1 ?[Xg Y]:DpX ©[YY]}D;Ds1 £[BC]=Xms;B¥C?B:B+'-+CsBg ¦'-©Cl ¥Bl ©C¬r@B¯Z ¥C¯Z ªC-B§ApCl -Z ©ÂBsX <ÂCsX ?Z:X

```

Try it online!

### How it works

The explanation is very rough; don't hesitate to ask any questions you might have.

```
/*    Setting up basic variables    */
                      // Implicit: A = 10, N = list of input numbers.
D=[],N=Nn-;           // D = empty array, N = N sorted by subtraction.

/*    Finding ranges of page numbers    */
Dp                    // Push into D the result of
NrXYZ{                // reducing each previous value X and item Y in N by this function,
}[];                  // starting with an empty array:
 Y-1==Xg1 ?           //  If Y is 1 more than the second item of X,
 [Xg Y]:              //   return [X[0], Y].
 DpX &&[YY]           //  Otherwise, push X into D and return [Y, Y].

/*    Formatting result    */
Ds1 mXYZ{             // Take the first item off of D and map each item X by this function:
 [BC]=Xms;            //  Set B and C to the first to items in X as strings.
 B==C?B               //  If B is the same as C, return B.
 :B+'-+Cs             //  Otherwise, return B + a hyphen + C.slice(
  Bg !='-&&           //   If B[0] is not a hyphen (B is not negative), AND
  Cl ==Bl &&          //   B and C are the same length,

  /*    Cutting off unnecessary digits    */
  Cq r                //    then C split into digits, reduced with
  rXYZ{               //    each previous value X, item Y, and index Z mapped by this function:
   Bs0,Z ==Cs0,Z ||   //     If B.slice(0,Z) equals C.slice(0,Z), OR
   C-B<=ApCl -Z       //     C - B <= 10 to the power of (C.length - Z);
   &&~~BsX <~~CsX     //     AND B.slice(X) is a smaller number than C.slice(X),
   ?Z:X               //     then Z; otherwise, X.
                      //   Otherwise, 0.

```

# Answer
> 1 votes
# R, 167 bytes x 80% x 75% x 50% -\> 50.1

```
s=sort(scan(se=","));r=c();while(length(s)){w=s==1:length(s)+s[1]-1;x=s[w];s=s[!w];z=tail(x,1);r=c(r,paste0(x[1],"-",ifelse(z-x[1]<=10,z%%10,z%%100)))};cat(r,sep=", ")

```

Indented, with new lines:

```
s=sort(scan(se=","))
r=c()
while(length(s)){
w=s==1:length(s)+s[1]-1
x=s[w]
s=s[!w]
z=tail(x,1)
r=c(r, paste0(x[1],"-", ifelse(z-x[1]<=10,
                               z%%10,
                               z%%100)))}
cat(r,sep=", ")

```

Test cases:

```
> s=sort(scan(se=","));r=c();while(length(s)){w=s==1:length(s)+s[1]-1;x=s[w];s=s[!w];r=c(r,paste0(x[1],"-",ifelse(tail(x,1)-x[1]<=10,tail(x,1)%%10,tail(x,1)%%100)))};cat(r,sep=", ")
1: 3, 4, 5, 9, 10, 11, 12
8:
Read 7 items
3-5, 9-2
> s=sort(scan(se=","));r=c();while(length(s)){w=s==1:length(s)+s[1]-1;x=s[w];s=s[!w];r=c(r,paste0(x[1],"-",ifelse(tail(x,1)-x[1]<=10,tail(x,1)%%10,tail(x,1)%%100)))};cat(r,sep=", ")
1: 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160
13:
Read 12 items
149-60

```

It works for the -50% bonus:

```
> s=sort(scan(se=","));r=c();while(length(s)){w=s==1:length(s)+s[1]-1;x=s[w];s=s[!w];r=c(r,paste0(x[1],"-",ifelse(tail(x,1)-x[1]<=10,tail(x,1)%%10,tail(x,1)%%100)))};cat(r,sep=", ")
1: 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29
12:
Read 11 items
19-9
> s=sort(scan(se=","));r=c();while(length(s)){w=s==1:length(s)+s[1]-1;x=s[w];s=s[!w];r=c(r,paste0(x[1],"-",ifelse(tail(x,1)-x[1]<=10,tail(x,1)%%10,tail(x,1)%%100)))};cat(r,sep=", ")
1: 109, 110, 111, 112, 113
6:
Read 5 items
109-3

```

It accepts unsorted input:

```
> s=sort(scan(se=","));r=c();while(length(s)){w=s==1:length(s)+s[1]-1;x=s[w];s=s[!w];r=c(r,paste0(x[1],"-",ifelse(tail(x,1)-x[1]<=10,tail(x,1)%%10,tail(x,1)%%100)))};cat(r,sep=", ")
1: 114, 109, 110, 111, 112, 113
7:
Read 6 items
109-4

```

It accepts negative numbers:

```
> s=sort(scan(se=","));r=c();while(length(s)){w=s==1:length(s)+s[1]-1;x=s[w];s=s[!w];r=c(r,paste0(x[1],"-",ifelse(tail(x,1)-x[1]<=10,tail(x,1)%%10,tail(x,1)%%100)))};cat(r,sep=", ")
1: -1,0,1,2
4:
Read 3 items
-1-2

```

# Answer
> 0 votes
# sh, 135 * .8 * .75 * .5 = 40.5

```
tr , \\n|sort -n|awk -vORS="" '$1-o>1||!c{print p c$1;s=$1}{o=$1;c=", ";p=""}o>s{p="-"substr(o,length(o)-length(o-s-1)+1)}END{print p}'

```

shell script

```
tr , \\n|           # comma separated -> newline separated
sort -n|            # sort
awk -vORS=""        # suppress automatic newlines in output

```

awk script

```
# on step > 1 or first run, end the current sequence and start a new one.
# on first run, p and c are empty strings.
$1-o>1||!c
    {print p c$1;s=$1}

# old = current, c = ", " except for first run, clear end string.
    {o=$1;c=", ";p=""}

# if the sequence is not a single number, its end is denoted by "-o".
# print only the last n digits of o.
o>s
    {p="-"substr(o,length(o)-length(o-s-1)+1)}

# end the current sequence without starting a new one.
END
    {print p}'

```

where `s` is the start of the current sequence and `o` is the previous input value.

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


title: King-Pen! (Dots and Boxes)

text:
# Question
Title: King-Pen! (Dots and Boxes)
This is a king of the hill challenge for Dots and Boxes (aka Pen the Pig). The game is simple, on your turn just draw a line on an empty fence. Every time you complete a square you get a point. Also, since we are playing by **championship rules**, if you complete at least one square on your turn you get an extra turn. This is a round robin tournament, where each bot plays each other bot ~~twice~~ 12 times on a 9x9 grid. Check out this match between two heavyweight titans, where ChainCollector makes mince meat of reigning co-champion Asdf:

# Rules

1. 0.5 second time limit per move.
2. No interfering with other bots.
3. Use PigPen.random() and PigPen.random(int) for randomness.
4. No writing to files.
5. Bot and all its persistent data will be reset every time opponent changes (every 12 rounds).

# Bots

Every bot extends Player.java:

```
package pigpen;

public abstract class Player {

public abstract int[] pick(Board board, int id, int round);

}

```

`Board` is the game board, which mainly serves to give you access to `Pen` classes, and `id` is your playerID (tells you if you're first or second), `round` tells you which round your playing against the same opponent (1 or 2). The return value is an `int[]`, where the first element is the penID (1-indexed), and the second element is the fenceID (0-indexed). See `Pen.pick(int)` for an easy way to generate this return value. See the Github page for example players and JavaDoc. Since we are only using a square grid ignore any functions and fields related to hexagons.

# How to Run

1. Download Source from Github.
2. Write your controller bot (make sure to include `package pigpen.players`) and put it in the `src/` folder;
3. Compile with `javac -cp src/* -d . src/*.java`. Run with `java pigpen.Tournament 4 9 9 false` (the last two numbers can be changed to adjust grid size. The last variable should only be set to `true` if you wish to use the pp\_record software.)

# Scores

1. ChainCollector: 72
2. Asdf: 57
3. Lazybones: 51
4. Finisher: 36
5. =LinearPlayer: 18
6. =BackwardPlayer: 18
7. RandomPlayer: 0

## See Also:

**Note**: this game is a competitive challenge and not easily solvable, due to giving players an extra turn for completing a box.

Thanks to Nathan Merrill and Darrel Hoffman for consulting on this challenge!

**Updates**:

* Added a `moves(int player)` method to the Board class to get a list of every move a player has made.

> ### Indefinite Bounty (100 Rep):
>
> First person to post a solution that wins every round, and uses **strategy** (adjusting play based on observing how the opponent plays).

# Answer
> 6 votes
# Lazybones

This bot is lazy. He picks a random spot and direction and continues to build in that direction without moving too much. There are only 2 cases where he does something different:

* "make money" by closing a peg with only 1 remaining fence
* choose a new spot and direction if placing the fence is not possible or would allow the other bot to "make money"

```
package pigpen.players;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import pigpen.Board;
import pigpen.Pen;
import pigpen.PigPen;
import pigpen.Player;

public class Lazybones extends Player {
    private static class Fence {
        private static boolean isOk(Board board, boolean vertical, int row, int col) {
            if (vertical) {
                Pen left = board.getPenAt(row, col - 1);
                Pen right = board.getPenAt(row, col);
                if (left.id() < 0 && right.id() < 0 ||
                        left.fences()[Pen.RIGHT] > 0 ||
                        right.fences()[Pen.LEFT] > 0 ||
                        left.remaining() == 2 ||
                        right.remaining() == 2) {
                    return false;
                }
            } else {
                Pen top = board.getPenAt(row - 1, col);
                Pen bottom = board.getPenAt(row, col);
                if (top.id() < 0 && bottom.id() < 0 ||
                        top.fences()[Pen.BOTTOM] > 0 ||
                        bottom.fences()[Pen.TOP] > 0 ||
                        top.remaining() == 2 ||
                        bottom.remaining() == 2) {
                    return false;
                }
            }
            return true;
        }

        private static Fence pickRandom(Board board) {
            List<Fence> ok = new ArrayList<>();
            List<Fence> notOk = new ArrayList<>();
            for (int row = 0; row < board.rows; row ++) {
                for (int col = 0; col < board.cols; col ++) {
                    (isOk(board, false, row, col) ? ok : notOk)
                            .add(new Fence(false, row, col));
                    (isOk(board, true, row, col) ? ok : notOk)
                            .add(new Fence(true, row, col));
                }
                (isOk(board, true, row, board.cols) ? ok : notOk)
                        .add(new Fence(true, row, board.cols));
            }
            for (int col = 0; col < board.cols; col ++) {
                (isOk(board, false, board.rows, col) ? ok : notOk)
                        .add(new Fence(false, board.rows, col));
            }
            if (ok.isEmpty()) {
                return notOk.get(PigPen.random(notOk.size()));
            } else {
                return ok.get(PigPen.random(ok.size()));
            }
        }

        private final boolean vertical;
        private final int row;
        private final int col;

        public Fence(boolean vertical, int row, int col) {
            super();
            this.vertical = vertical;
            this.row = row;
            this.col = col;
        }

        private Fence next(Board board, boolean negative) {
            int newRow = vertical ? (negative ? row - 1 : row + 1) : row;
            int newCol = vertical ? col : (negative ? col - 1 : col + 1);
            if (isOk(board, vertical, newRow, newCol)) {
                return new Fence(vertical, newRow, newCol);
            } else {
                return null;
            }
        }

        private int[] getResult(Board board) {
            if (vertical) {
                if (col < board.cols) {
                    return board.getPenAt(row, col).pick(Pen.LEFT);
                } else {
                    return board.getPenAt(row, col - 1).pick(Pen.RIGHT);
                }
            } else {
                if (row < board.rows) {
                    return board.getPenAt(row, col).pick(Pen.TOP);
                } else {
                    return board.getPenAt(row - 1, col).pick(Pen.BOTTOM);
                }
            }
        }
    }

    private Fence lastFence = null;
    private boolean negative = false;

    @Override
    public int[] pick(Board board, int id, int round) {
        List<Pen> money = board.getList().stream()
                .filter(p -> p.remaining() == 1).collect(Collectors.toList());
        if (!money.isEmpty()) {
            return money.get(PigPen.random(money.size())).pick(Pen.TOP);
        }
        if (lastFence != null) {
            lastFence = lastFence.next(board, negative);
        }
        if (lastFence == null) {
            lastFence = Fence.pickRandom(board);
            negative = PigPen.random(2) == 0;
        }
        return lastFence.getResult(board);
    }
}

```

# Answer
> 6 votes
# ChainCollector

This bot likes chains1. He wants as much of them as possible. Sometimes he even sacrifices a small part of a chain to win a bigger one.

\[1\] A chain consists of pens connected by open fences, where each pen has 1 or 2 open fences. If a single pen belonging to the chain can be finished, then because of the championship rule the whole chain can be finished as well.

```
package pigpen.players;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.TreeMap;

import pigpen.Board;
import pigpen.Pen;
import pigpen.Player;

public class ChainCollector extends Player {
    private enum Direction {
        TOP, RIGHT, BOTTOM, LEFT;

        public Direction opposite() {
            return values()[(ordinal() + 2) % 4];
        }
    }

    private enum ChainEndType {
        OPEN, CLOSED, LOOP
    }

    private static class PenEx {
        private final int id;
        private final List<Fence> openFences = new ArrayList<>();
        private boolean used = false;

        public PenEx(int id) {
            super();
            this.id = id;
        }

        public void addOpenFence(Direction direction, PenEx child) {
            openFences.add(new Fence(this, direction, child));
            if (child != null) {
                child.openFences.add(new Fence(child, direction.opposite(), this));
            }
        }
    }

    private static class Fence {
        public final PenEx parent;
        public final Direction direction;
        public final PenEx child;

        public Fence(PenEx parent, Direction direction, PenEx child) {
            super();
            this.parent = parent;
            this.direction = direction;
            this.child = child;
        }

        public int[] getMove() {
            if (parent == null) {
                return new int[] { child.id, direction.opposite().ordinal() };
            } else {
                return new int[] { parent.id, direction.ordinal() };
            }
        }
    }

    private static class Moves {
        private final TreeMap<Integer, List<Fence>> map = new TreeMap<>();

        public void add(int score, Fence move) {
            List<Fence> list = map.get(score);
            if (list == null) {
                list = new ArrayList<>();
                map.put(score, list);
            }
            list.add(move);
        }

        public boolean isEmpty() {
            return map.isEmpty();
        }

        public boolean hasExactlyOne() {
            return map.size() == 1 && map.firstEntry().getValue().size() == 1;
        }

        public int getLowestScore() {
            return map.firstKey();
        }

        public int[] getLowMove() {
            return map.firstEntry().getValue().get(0).getMove();
        }

        public int[] getHighMove() {
            return map.lastEntry().getValue().get(0).getMove();
        }
    }

    private static class BoardEx {
        private final List<PenEx> pens = new ArrayList<>();
        private final Moves neutralMoves = new Moves();
        private final Moves finisherMoves = new Moves();
        private final Moves safeFinisherMoves = new Moves();
        private final Moves sacrificeMoves = new Moves();
        private final Moves badMoves = new Moves();

        public BoardEx(Board board) {
            super();
            PenEx[][] tmp = new PenEx[board.rows][board.cols];
            for (int row = 0; row < board.rows; ++row) {
                for (int col = 0; col < board.cols; ++col) {
                    Pen pen = board.getPenAt(row, col);
                    int[] fences = pen.fences();
                    PenEx penEx = new PenEx(pen.id());
                    tmp[row][col] = penEx;
                    pens.add(penEx);
                    if (fences[Pen.TOP] == 0) {
                        penEx.addOpenFence(Direction.TOP, row == 0 ? null : tmp[row - 1][col]);
                    }
                    if (row == board.rows - 1 && fences[Pen.BOTTOM] == 0) {
                        penEx.addOpenFence(Direction.BOTTOM, null);
                    }
                    if (fences[Pen.LEFT] == 0) {
                        penEx.addOpenFence(Direction.LEFT, col == 0 ? null : tmp[row][col - 1]);
                    }
                    if (col == board.cols - 1 && fences[Pen.RIGHT] == 0) {
                        penEx.addOpenFence(Direction.RIGHT, null);
                    }
                }
            }
        }

        private ChainEndType followChain(Fence begin, List<Fence> result) {
            Fence current = begin;
            for (;;) {
                current.parent.used = true;
                result.add(current);
                if (current.child == null) {
                    return ChainEndType.OPEN;
                }
                List<Fence> childFences = current.child.openFences;
                switch (childFences.size()) {
                    case 1:
                        current.child.used = true;
                        return ChainEndType.CLOSED;
                    case 2:
                        if (current.child == begin.parent) {
                            return ChainEndType.LOOP;
                        } else {
                            current = current.direction.opposite() == childFences.get(0).direction ?
                                    childFences.get(1) : childFences.get(0);
                        }
                        break;
                    case 3:
                    case 4:
                        return ChainEndType.OPEN;
                    default:
                        throw new IllegalStateException();
                }
            }
        }

        public void findChains() {
            for (PenEx pen : pens) {
                if (!pen.used && pen.openFences.size() > 0) {
                    if (pen.openFences.size() < 3) {
                        List<Fence> fences = new ArrayList<>();
                        ChainEndType type1 = pen.openFences.size() == 1 ?
                                ChainEndType.CLOSED : followChain(pen.openFences.get(1), fences);
                        if (type1 == ChainEndType.LOOP) {
                            badMoves.add(fences.size(), fences.get(0));
                        } else {
                            Collections.reverse(fences);
                            ChainEndType type2 = followChain(pen.openFences.get(0), fences);
                            if (type1 == ChainEndType.OPEN && type2 == ChainEndType.CLOSED) {
                                type1 = ChainEndType.CLOSED;
                                type2 = ChainEndType.OPEN;
                                Collections.reverse(fences);
                            }
                            if (type1 == ChainEndType.OPEN) {
                                badMoves.add(fences.size() - 1, fences.get(fences.size() / 2));
                            } else if (type2 == ChainEndType.CLOSED) {
                                finisherMoves.add(fences.size() + 1, fences.get(0));
                                if (fences.size() == 3) {
                                    sacrificeMoves.add(fences.size() + 1, fences.get(1));
                                } else {
                                    safeFinisherMoves.add(fences.size() + 1, fences.get(0));
                                }

                            } else {
                                finisherMoves.add(fences.size(), fences.get(0));
                                if (fences.size() == 2) {
                                    sacrificeMoves.add(fences.size(), fences.get(1));
                                } else {
                                    safeFinisherMoves.add(fences.size(), fences.get(0));
                                }
                            }
                        }
                    } else {
                        pen.used = true;
                        for (Fence fence : pen.openFences) {
                            if (fence.child == null || fence.child.openFences.size() > 2) {
                                neutralMoves.add(fence.child == null ? 0 : fence.child.openFences.size(), fence);
                            }
                        }
                    }
                }
            }
        }

        public int[] bestMove() {
            if (!neutralMoves.isEmpty()) {
                if (!finisherMoves.isEmpty()) {
                    return finisherMoves.getHighMove();
                }
                return neutralMoves.getHighMove();
            }
            if (!safeFinisherMoves.isEmpty()) {
                return safeFinisherMoves.getHighMove();
            }
            if (badMoves.isEmpty() && !finisherMoves.isEmpty()) {
                return finisherMoves.getHighMove();
            }
            if (!sacrificeMoves.isEmpty()) {
                if (sacrificeMoves.hasExactlyOne()) {
                    if (badMoves.getLowestScore() - sacrificeMoves.getLowestScore() >= 2) {
                        return sacrificeMoves.getLowMove();
                    } else {
                        return finisherMoves.getHighMove();
                    }
                } else {
                    return finisherMoves.getHighMove();
                }
            }
            if (!badMoves.isEmpty()) {
                return badMoves.getLowMove();
            }
            return null;
        }
    }

    @Override
    public int[] pick(Board board, int id, int round) {
        BoardEx boardEx = new BoardEx(board);
        boardEx.findChains();
        return boardEx.bestMove();
    }
}

```

# Answer
> 3 votes
# Finisher

```
package pigpen.players;

import pigpen.*;

import java.util.*;

/**
 * Picks a Pen with only one fence remaining.
 * Otherwise picks one with the most fences remaining
 */
public class Finisher extends Player implements Comparator<Pen> {

  public int[] pick(Board board, int id) {
     return Collections.max(board.getList(),this).pick(Pen.TOP);

  }

  @Override
  public int compare(Pen p1, Pen p2) {
    //1 remaining is best, all remaining is second.
    int r1 = p1.remaining();
    int r2 = p2.remaining();
    if(r1 == 1) r1 = 7;
    if(r2 == 1) r2 = 7;
    return Integer.compare(r1,r2);
 }

}

```

Uses a Comparator to pick the Pen with the most available fences, but gives priority to Pen's with only 1 fence available. (7 is used rather than 5 to allow this code to work in hexagon mode as well)

# Answer
> 3 votes
# Asdf

Assigns a score to each fence and then picks the best out of them. For example: A pen with one open fence has a score of 10, while a pen with 2 open fences has a score of -8.

It seems like Lazybones uses a similar strategy, because it ties with this bot.

```
package pigpen.players;

import java.util.*;
import pigpen.*;

public class Asdf extends Player {
    private final List<Score> scores = new ArrayList<>();

    @Override
    public int[] pick(Board board, int id, int round) {
        scores.clear();
        List<Pen> pens = board.getList();

        pens.stream().filter(x -> !x.closed()).forEach((Pen p) -> evaluate(p));
        Optional<Score> best = scores.stream().max(Comparator.comparingInt(p -> p.points));

        if (best.isPresent()) {
            Score score = best.get();
            return score.pen.pick(score.fence);
        }
        return null;
    }

    private void evaluate(Pen pen) {
        int[] fences = pen.fences();
        for (int i = 0; i < fences.length; i++) {
            if (fences[i] == 0) {
                int points = getPoints(pen);
                Pen neighbour = pen.n(i);
                if (neighbour.id() != -1) {
                    points += getPoints(neighbour);
                }
                scores.add(new Score(pen, i, points));
            }
        }
    }

    private int getPoints(Pen pen) {
        switch (pen.remaining()) {
            case 1: return 10;
            case 2: return -1;
            case 3: return 1;
        }
        return 0;
    }

    class Score {
        private Pen pen;
        private int fence;
        private int points;

        Score(Pen pen, int fence, int points) {
            this.pen = pen;
            this.fence = fence;
            this.points = points;
        }
    }
}

```

# Answer
> 0 votes
# LinearPlayer

```
package pigpen.players;

import pigpen.*;

/**
 * Picks the first available fence in the first available Pen
 */
public class LinearPlayer extends Player {

@Override
public int[] pick(Board board, int id) {
    for(int p = 1;p<=board.size;p++) {
        Pen pen = board.get(p);
            if(!pen.closed()) {
                int[] fences = pen.fences();
                    for(int i =0;i<fences.length;i++) {
                        if(fences[i] == 0) {
                            return new int[]{pen.id(),i};
                        }
                    }
                }
        }
    return new int[]{1,0};
    }
}

```

The easiest way to write this bot is actually `return null`, because an invalid entry will automatically select the first available fence. This code does not use any shortcut methods and manually generates the return value.

# Answer
> 0 votes
# BackwardPlayer

```
package pigpen.players;

import pigpen.*;

/**
 * Picks the first available fence in the last available Pen
 */
 public class BackwardPlayer extends Player {

public int[] pick(Board board, int id) {
    for(int i = board.size;i>0;i--) {
        Pen p = board.get(i);
        if(!p.closed()) {
            return p.pick(Pen.TOP);
        }
    }
    return new int[] {1,0};
}
}

```

This code uses the shortcut method `Pen.pick(int)` to generate the return value. If the top fence is unavailable, it will pick the closest available fence going clockwise.

# Answer
> 0 votes
# RandomPlayer

```
package pigpen.players;

import pigpen.*;

/**
 * Picks the first available fence in a random Pen
 */
public class RandomPlayer extends Player {
    public int[] pick(Board board, int id) {
        int pen = PigPen.random(board.size)+1;
        return board.get(pen).pick(Pen.TOP);
    }
}

```

Same idea as BackwardPlayer, but randomly selects a pen. Note the `+1` because Pen's are 1-indexed.

---
Tags: king-of-the-hill, java
---


title: Playing Billiards

text:
# Question
Title: Playing Billiards
In this code golf, you will have to determine the direction of the shortest shot that hits exactly **n** cushions before falling into a pocket.

The billiard table is a 6 pocket pool table with the following characteristics:

* Dimensions are variable (**a** x **b**)
* No friction : the ball will roll forever until it falls into a pocket
* Pockets and ball sizes are almost zero. This means that the ball will fall in the pocket only if they have same position.
* The ball is placed at the bottom left hole at the beginning (but doesn't fall in it)

Create a full program or function that takes the dimensions (**a**,**b**) of the table and a the number of cushions to hit **n** as input and returns the angle in degrees of the shortest path hitting exactly **n** cushions before falling into a pocket.

* ***a*** \> 0
* ***b*** \> 0
* 0 \<= ***n*** \< 10000000
* 0 \< ***alpha*** \< 90 (in degrees) precision : at least 10^-6

## examples :

with **a** = 2, **b** = 1, **n** = 1 there are three possible paths : (1) (2) (3) on the following figure. the number (1) is the shortest so the output should be atan(2) = 63.43494882292201 degrees

The solution for **a** = 2, **b** = 1, **n** = 4 is atan(4/3) = 53.13010235415598 degrees

## test samples :

```
a = 2,    b = 1,    n = 1,       -> alpha = 63.43494882292201
a = 2,    b = 1,    n = 2,       -> alpha = 71.56505117707799
a = 2,    b = 1,    n = 3,       -> alpha = 75.96375653207353
a = 2,    b = 1,    n = 4,       -> alpha = 53.13010235415598
a = 2,    b = 1,    n = 5,       -> alpha = 59.03624346792648
a = 2,    b = 1,    n = 6,       -> alpha = 81.86989764584403
a = 4.76, b = 3.64, n = 27,      -> alpha = 48.503531644784466
a = 2,    b = 1,    n = 6,       -> alpha = 81.86989764584403
a = 8,    b = 3,    n = 33,      -> alpha = 73.24425107080101
a = 43,   b = 21,   n = 10005,   -> alpha = 63.97789961246943

```

This is code/billiard golf : shortest code wins!

# Answer
## Python 2.7, ~~352~~ ~~344~~ 281 bytes

```
from math import*
def l(a,b,n):
 a*=1.;b*=1.
 r=set()
 for i in range(1,n+3):
  t=[]
  for k in range(1,i):
   for h in[0,.5]:
    x=(i-k-h)
    if 1-(x/k in r):r.add(x/k);t+=(x*a,k*b),
 d=(a*n+1)**2+(b*n+1)**2
 for x,y in t:
  if x*x+y*y<d:d=x*x+y*y;o=degrees(atan(y/x))
 return o

```
* **-16 bytes** thanks to @Dschoni

Explanation: instead calculating the cushions hits, I'm adding n tables and taking the new holes as valid :  Black border/holes is the original, green border/holes is the valid for n=1, red border/holes is the valid for n=2 and so on. Then I remove the invalid holes (e.g. the blue arrow for n=1). I'll have a list of valid holes and their coordinates, then I calculate their distance from initial point, and then the angle of the smaller distance.
Notes:
~~a=4.76, b=3.64, n=27 - give 52.66286, trying to figure out why~~ fixed, and saved 8 bytes in the process =D
a=43, b=21, n=10005 - takes ~80 seconds (but gives the right angle)

readable version:

```
from math import *
def bill(a,b,n):
    a=float(a)
    b=float(b)
    ratios = set()
    for i in range(0,n+2): # Create the new boards
        outter = []
        j=i+1
        for k in range(1,j): # Calculate the new holes for each board
            #y=k
            for hole_offset in [0,0.5]:
                x=(j-k-hole_offset)
                if (x/k) not in ratios:
                    ratios.add(x/k)
                    outter.append((x*a,k*b))
    min_dist = (a*n+1)**2+(b*n+1)**2
    for x,y in outter:
        if x*x+y*y<min_dist:
            min_dist = x*x+y*y
            min_alpha=degrees(atan(y/x))
    return min_alpha

```
> 11 votes

# Answer
## Haskell, ~~133~~ 117 bytes

This is my implementation:

With a 2x1 table, a path will hit exactly n cushions before going into a pocket if: (x-1)/2 + (y-1) == n and x,y are mutually primes. where x,y are the distance of the ball over horizontal/vertical axes.

Paths are the same with arbitrary table size, so we just have to update lengths and angles with (a,b) and keep the shortest. Path length is sqrt((x\*a/2)^2+(y\*b)^2) and angle is atan((y\*b)/(x\*a/2))

```
z=toEnum
f a b n=minimum[[z x^2+r^2,180/pi*atan(r/z x)]|x<-[1..2*n+2],y<-[n+1-div(x-1)2],r<-[2*b/a*z y],gcd x y<2]!!1

```
> 3 votes

---
Tags: code-golf, geometry, optimization, path-finding
---


title: Rollover Calendar

text:
# Question
Title: Rollover Calendar
*This is inspired by one of Downgoat's questions in Sandbox, where I suggested that he include April 31 as Pi day for people who use day/month format, only for him to inform me that there is no April 31!*

Given a date string in *month/day* format that might be invalid, output the correct date using rollover. (First rollover the month, then rollover the day).

**Examples:**

**"15/43"** \- This reads as the 43rd day of the 15th month. First, we roll over the month to the next year, so we end up with 3 (March). Now, since March only has 31 days, we rollover the extra days to April, so we output the actual date as **"4/12"** (April 12th).

**"3/16"** \- This is a valid date (March 16th). Return it as is.

**"12/64"** \- Ah, so many fond memories from December 64th... December has 31 days, January has 31 days, so what I really mean is **"2/2"** (February 2nd).

**"19/99"** \- First, the 19 becomes a 7 (July). July has 31 days, August has 31 days, September has 30 days, so the output is **"10/7"** (October 7th).

**"1/99999"** \- A year has 365 days. 99999 (mod 365) = 354. The 354 day of the year is **"12/20"**.

**"9999999/10"** \- Apparently, 9999999 (mod 12) = 3, so this is **"3/10"** (March 10th).

**Criteria:**

Input month is an integer \> 0. Input day is an integer \> 0. Year never needs to be specified, as such there are no leap years to deal with.

**Update:**

As I think it would overly simplify the challenge, calendar functions, such as those in the Java Calendar class, are banned. Date parsing/formatting functions are still allowed though.

# Answer
> 11 votes
# LabVIEW, 32 LabVIEW Primitives

# Answer
> 4 votes
## C#, ~~269~~ 223

```
string v(string n){var x=new[]{31,28,31,30,31,30,31,31,30,31,30,31};var s=n.Split('/');Func<string,int> p=int.Parse;var m=p(s[0]);var d=p(s[1]);m=m>=12?m%12:m;while(d>x[m]){d-=x[m];m=++m>=12?m%12:m;}return(m==0?1:m)+"/"+d;}

```

**Edit**: Fixed to work for cases like 24/1, 36/1, etc. and golfed a little. Thanks for the comments, there are several places I saved a bit!

Ungolfed:

```
string v(string n)
{
    var x = new [] { 31 ,28, 31, 30, 31, 30,31, 31, 30, 31, 30, 31 };

    var s = n.Split('/');
    Func<string,int> p = int.Parse;
    var m = p(s[0]);
    var d = p(s[1]);
    m = m >= 12 ? m % 12 : m;
    while (d > x[m])
    {
        d -= x[m];
        m = ++m >= 12 ? m % 12 : m;
    }
    return (m==0?1:m) + "/" + d;
}

```

# Answer
> 4 votes
## R, ~~208~~ 182 bytes

```
m=c(31,28,31,30,31,30,31,31,30,31,30,31)
e=scan(sep="/");n=(e[1]/12-1)*12;if(!n%%12)n=12;if(n<0)n=e[1];j=e[2];while((j<-j-m[n])>0){n=n+1;if(n>12)n=1};j=m[n]+j;cat(n,j,sep="/")

```

Get the month by dividing by 12, then loop, removing the number of days of the current month until you get a negative number., inverse last step and print.

On multiple lines (need to use a file and source it):

```
m=c(31,28,31,30,31,30,31,31,30,31,30,31)
e=scan(sep="/")
n=(e[1]/12-1)*12
if(!n%%12)n=12
if(n<0)n=e[1]
j=e[2]
while((j<-j-m[n])>0){n=n+1;if(n>12)n=1}
j=m[n]+j;cat(n,j,sep="/")

```

# Answer
> 2 votes
# PHP \>= 5.5, 181 bytes

```
list($m,$d)=explode("/",$argv[1]);$m%=12;$d%=365;$i=0;while($d>100)$d-=[31,28,31,30,31,30,31,31,30,31,30,31][$i++];$m+=$i;echo date_create_from_format("m/d","$m/$d")->format("n/j");

```

PHP *almost* supports rollover with date parsing and formatting instructions alone. For example:

```
echo date_create_from_format("m/d","12/64")->format("n/j"); // Output: 2/2

```

However, once either number gets bigger than 100, PHP rejects parsing it and returns an error (probably for some arbitrary reason). So, the theory with this answer is to get it back down to where PHP will parse it, then submit it to `date_create_from_format()`.

Ungolfed:

```
list($month, $day) = explode("/", $argv[1]);
$month = $month % 12;
$day = $day % 365;
$i = 0;
$days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
while($day > 31) $day -= $days[$i++];
$month += $i;
echo DateTime::createFromFormat("m/d", $month . "/" . $day)->format("n/j");

```

Try it online

# Answer
> 2 votes
# JavaScript (ES6), 106 bytes

```
s=>eval('q="030101001010";p=s.split`/`;for(d=i=p[1],m=p[0]-1;i--;d>n&&(m++,d-=n))n=31-q[m%=12];m+1+"/"+d')

```

## Explanation

```
s=>
  eval(`              // use eval to enable for loop without needing to write {} or return
    q="030101001010"; // q = array of 31 - days in each month
    p=s.split\`/\`;   // p = array of [ month, day ]
    for(
      d=i=p[1],       // d = day
        m=p[0]-1;     // m = month - 1
      i--;            // loop for each day, this is more iterations than needed but extra
                      //     iterations do not affect the result and it's the shortest way
                      //     to guarantee all months have been subtracted from d, it also
                      //     ensures the loop runs at least once to get m % 12
      d>n&&(m++,d-=n) // if too many days, subtract the month's days and increment month
    )
      n=31-q[m%=12];  // n = number of days in month, get m % 12
    m+1+"/"+d         // return the result
  `)

```

## Test

```
var solution = s=>eval('q="030101001010";p=s.split`/`;for(d=i=p[1],m=p[0]-1;i--;d>n&&(m++,d-=n))n=31-q[m%=12];m+1+"/"+d')
```

```
<input type="text" id="input" value="19/99" />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```

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


title: Adjust your Chair

text:
# Question
Title: Adjust your Chair
## Challenge

You just bought a brand new chair! Problem is, you have no idea how to control it so you'll need to write a program to do it for you.

You can only sit in the unadjusted chair for so long. So your code will need to be as short as possible.

## Examples

```
5,3,2,2,1

O
|
|
| _
| |
|_|_
  |
  |
  O

```

```
3,5,2,3,5

O
|  _
|  |
|__|__
   |
   |
 __|__
 OOOOO

```

```
2,13,1,1,13

O
|      _
|______|______
 ______|______
 OOOOOOOOOOOOO

```

<sub>*Am I the only one who thinks this look like an airplane?*</sub>

## Chair parts

The chair has various components:

```
O
|
|  <- Backrest
|  _  <- Armrest
|  |
|__|__ <- Seat
   |
   |   <- Leg
  _|_
  OOO  <- Wheels

```

## Input

You will be outputting a chair given various variables.

The input will be in the following order, all inputs will be positive integers (always greater than 0) and will always be provided.

1. Backrest Height
2. Seat Width **always odd**
3. Armrest Height **Always less than backrest height**
4. Leg Height
5. Wheel count **Always less than or equal to seat width** and **Always odd**

## Detailed part Descriptions

The parts of the chair are:

---

**Backrest:** This amount of `|` is the **Backrest Height**

```
O
|
|

```

**Seat:** The amount of `_` is the **Seat Width**, insert a `|` in the middle for the armrest.

```
__|__

```

**Armrest:** The amount of `|` is the **Armrest Height**. This should be inserted in the middle of the seat.

```
_
|
|

```

**Leg:** The amount of `|` is determined by **Leg Height**

```
|
|

```

**Wheels:** The wheels are centered below the legs. If they are more than one, all but the center wheel should have `_` in the line above them.

```
_ _
OOO

```

## Output

The output may have a trailing newline. Each line may have trailing spaces. Leading whitespace is not allowed

# Answer
> 2 votes
# LabVIEW, 146 LabVIEW Primitives

This got a lot bigger than I imagined...

There won't be a GIF this time, on the one Hand because of the size on the other hand because there's no way anyone can follow all the data flowing.

It does work, unless you get LabVIEW and suggest a file hoster there will be no way to check though.

# Answer
> 8 votes
# JavaScript (ES6), 197 bytes

```
(b,s,a,l,w)=>eval('o="";for(i=0;i<b+l+2;i++)o+=(i?i>b?x[r](s/2-w/2+1)+(i>b+l?"O"[r](w):(p=(i<b+l?x:"_")[r](w/2))+"|"+p):"|"+(p=(i-b?x=" ":"_")[r="repeat"](s/2))+(i>b-a?"|":i<b-a?x:"-")+p:"O")+`\n`')

```

## Explanation

Well this got rather convoluted quite quickly. I'll just comment on what each line does at a high level. Hopefully with this formatting it's not too hard to follow all the ternary operators.

```
(b,s,a,l,w)=>
  eval(
    o="";
    for(i=0;i<b+l+2;i++)                        // for each line
      o+=(i?                                    // add to output

        // Leg lines
        i>b?
          x[r](s/2-w/2+1)                       // spaces before wheels
          +(
            i>b+l?
              "O"[r](w)                         // wheels
            :
              (p=(i<b+l?x:"_")[r](w/2))         // spaces or wheel cover before leg
              +"|"                              // leg
              +p                                // spaces or wheel cover after leg
          )

        // Backrest lines
        :
          "|"                                   // backrest
          +(p=(i-b?x=" ":"_")[r="repeat"](s/2)) // spaces or seat before armrest
          +(i>b-a?"|":i<b-a?x:"-")              // armrest
          +p                                    // spaces or seat after armrest

      // Headrest line
      :"O")
      +\`\n\`
  )

```

## Test

```
var solution = (b,s,a,l,w)=>eval('o="";for(i=0;i<b+l+2;i++)o+=(i?i>b?x[r](s/2-w/2+1)+(i>b+l?"O"[r](w):(p=(i<b+l?x:"_")[r](w/2))+"|"+p):"|"+(p=(i-b?x=" ":"_")[r="repeat"](s/2))+(i>b-a?"|":i<b-a?x:"-")+p:"O")+`\n`')
```

```
Input separated by commas (,) = <input type="text" id="input" value="5,3,2,3,5" />
<button onclick="result.textContent=solution(...input.value.split(',').map(x=>+x))">Go</button>
<pre id="result"></pre>
```

# Answer
> 3 votes
# Python 2, 157 bytes

```
b,s,a,l,w=input()
y,z,n,A='|_\n '
s/=2;W=w/2;x=A*s;X=n+A*(s-W+1);Y=n+y
print'O'+Y*(b-a-1)+Y+x+z+(Y+x+y)*(a-1)+n+(y+z*s)*2+(n+A+x+y)*(l-1)+X+z*W+y+z*W+X+'O'*w

```

---

**Example:**

`3,7,1,2,5`

```
O
|
|   _
|___|___
    |
  __|__
  OOOOO

```

# Answer
> 3 votes
# JavaScript (ES6), 182

An anonymous function. Using template strings, there are 3 newlines that are significant an included in the byte count.

```
(b,s,a,l,w,R=(x=s/2,c=' ')=>c.repeat(x),f=`
`+R(s/2+1-w/2),h=R(s/2,'_'),g=R(w/2,'_'),v='|')=>'O'+R(b+~a,u=`
`+v)+u+R()+'_'+R(a-1,u+R()+v)+u+h+v+h+R(l-1,`
 `+R()+v)+f+g+v+g+f+R(w,'O')

```

No loops, using repeat for the same purpose.

**Less golfed**

```
(b, s, a, l, w, // parameters
 // local variables as parameters with default values
 R = (x=s/2,c=' ')=>c.repeat(x), // shortcut for repeat
 f = `\n`+R(s/2+1-w/2), // filler before the wheels (used twice)
 h = R(s/2,'_'), // half seat (used twice)
 g = R(w/2,'_'), // last wheel support (used twice)
 v = '|', // vertical bar (used many times)
 u = `\n`+v // newline + bar (define below in the golfed version)
)=>
  'O'+R(b+~a, u)+  // backrest
  u+R()+'_'+       // backrest + armrest top
  R(a-1, u+R()+v)+ // backrest + armrest
  u+h+v+h+         // seat
  R(l-1, `\n`+R()+v)+ // leg
  f+g+v+g+         // wheels support
  f+R(w, 'O')      // wheels

```

**Test Snippet**

```
f=(b,s,a,l,w,R=(x=s/2,c=' ')=>c.repeat(x),f=`
`+R(s/2+1-w/2),h=R(s/2,'_'),g=R(w/2,'_'),v='|')=>'O'+R(b+~a,u=`
`+v)+u+R()+'_'+R(a-1,u+R()+v)+u+h+v+h+R(l-1,`
 `+R()+v)+f+g+v+g+f+R(w,'O')

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

function test()
{
  p=I.value.match(/\d+/g).map(x=>+x)
  console.log(p+'\n'+f(...p)+'\n')
}
```

```
Input <input type="text" id="I" value="5,5,3,2,3" />
<button onclick="test()">Go</button>
<pre id="O"></pre>
```

# Answer
> 1 votes
# SpecBAS - ~~185~~ 168 bytes

```
1 INPUT b's'a'l'w: sx=(s/2)+1,wx=sx-(w/2)
2  ?"o"'("|"#13)*b
3  ?AT b,1;"_"*s;AT b+l,wx;"_"*w;AT b-a,sx;"-"
4 FOR i=b+1-a TO b+l: ?AT i,sx;"|": NEXT i
5  ?AT b+l+1,wx;"0"*w

```

Now that SpecBAS allows `?` to be used instead of `PRINT` and doesn't need `LET` before variable assignment, it starts being a bit better at golfing.

Also helps that you can specify y,x print positions to avoid having to work out lots of spacing. This prints back, seat, arms and legs then wheels.

EDIT:

to print the back, replace a `FOR...NEXT` loop with pipe + return multiplied by the height (`("|"#13)*b`)

# Answer
> 1 votes
## Perl, 181 bytes

*includes +1 for `-n`. Put in a file and `echo 5,3,2,2,1 | perl -n file.pl`*

```
($b,$s,$a,$l,$w)=/\d+/g;$,=$/;print'O',('|')x($b-$a-1),($D='|'.$"x($s/=2)).'_',("$D|")x--$a,($q='|'.'_'x$s).$q,($"x$s.' |')x--$l,($x=$"x(1+$s-($W=$w/2))).'_'x$W.'|'.'_'x$W,$x.O x$w

```

With comments:

```
#!/usr/bin/perl -n              # -n: iterate stdin, put in $_

($b,$s,$a,$l,$w)=/\d+/g;        # get the parameters

$,=$/;                          # set $OUTPUT_FIELD_SEPARATOR to \n;
                                # this is printed between each of print's args

print                           # shorter than `-p` and @_=(...); $"=$/; $_="@_";
    'O',                        # the headrest

    ('|')x($b-$a-1),            # space between headrest and armrest.
                                # (...) x $n: produces $n lists.

    ($D='|' . $"x($s/=2))       # backrest and padding ($"=' ') up to armrest
    . '_',                      # armrest.

    ("$D|")x--$a,               # backrest, padding, armrest

    ($q='|' . '_'x$s) . $q,     # backrest bottom and 1/2 seat, armrest bottom and 1/2 seat

    ($" x $s . ' |' ) x --$l,   # padding before leg and leg, repeated leg-1 times

    ( $x =
      $" x (1+$s - ($W=$w/2) )  # padding before wheel top
    )
    . '_'x$W . '|'              # left side of wheel top, wheel top,
    . '_'x$W,                   # right side of wheel top

    $x . O x$w                  # padding before wheels, wheels

```

---
Tags: code-golf, ascii-art
---


title: Make a for loop repeat forever

text:
# Question
Title: Make a for loop repeat forever
`for` loops are useful in python in many ways, but one of the most common usages associated with a `for` loop is it's ability to repeat a certain amount of times. Like this:

```
for times in range(50):
    print "I'm repeating this 50 times..."

```

The challenge I propose to you is to make a `for` repeat **forever**. If you can find a way to do it without using a recursion, kudos to you. You can use **any** major version of Python. Just specify which one you are using. The goal is to do this in the smallest file size you can get, and a method that won't "break" after a while. Good luck!

# Answer
Because this was turned to a codegolf, have a **48 bytes** version as a one-liner. 3 bytes could be removed from both by replacing `print i` with `pass`.

```
for i in __import__('itertools').count():print i

```

Or a **47 bytes** version with two lines.

```
from itertools import*
for i in count():print i

```

---

Old message:

Easy it is.

```
def f(i = 0):
    while True:
        yield i
        i += 1
for i in f():
    print(i)

```
> 7 votes

# Answer
This can be done quite easily by abusing floating point addition.

```
def frange(start, stop, step):
    r = start
    while r < stop:
        yield r
        r += step

for x in frange(0, 1e16, 1):
    print (x)

```

IEEE754 64-bit floats have 53 bits of mantissa (including the implicit bit), so if `x > 1<<53` then `x + 1 == x`. `1 << 53` is approximately `9e15`.
> 11 votes

# Answer
This is an interesting way of doing it (32 chars for `class x`, 46 not counting the `print`):

```
class x:__iter__=next=lambda s:s
for i in x():print "Hello"

```

This defines an iterable whose `next` method never raises a `StopIteration`
> 6 votes

# Answer
I don't usually golf in Python, probably some reason people haven't already done posted this 23-character solution.

```
x=[1]
for i in x:
 x+=x

```

Much less memory-hungry if you do `x+=[i]` instead. Either one hangs my 2.7.5
> 3 votes

# Answer
```
for i in iter(lambda : 0, 1):
    print (i) # prints 0 forever

```

The `iter` function is normally used to create an iterator from an iterable.

The `iter` function can also take two arguments, a callable and a sentinel value. In that case it returns an iterator that yields the result of the callable until the callable returns the sentinel value.

In this case, the callable is a lambda that always returns 0. Since it never can return the sentinel value (1), this will loop forever.

Since this is code golf, this version is **28 characters and only one line**:

```
for i in iter(lambda:0,1):i

```
> 3 votes

# Answer
# 28 bytes, infinite, and no itertools

```
for x in iter(int,1):print 1

```

Shouldn't end without system program cutoffs (i.e. not my fault).

### 22 bytes without printing anything:

```
for x in iter(int,1):1

```
> 2 votes

# Answer
Itertools, to the rescue:

```
from itertools import count
for i in count():
    print i

```

or

```
from itertools import repeat
for i in repeat(42):
    print i

```
> 1 votes

# Answer
## 39 Characters, no itertools and no crashing

```
def f():
 while 1:yield
for i in f():1

```

Itertools is unnecessary, you can define your own generator.
> 1 votes

# Answer
# Python 2 & 3: 37 characters

```
class P:__getitem__=id
for t in P():1

```

¡No infinite memory required!
> 1 votes

# Answer
### Python 3.3: 2 lines, 29 characters

```
j=[1]
for i in j: j.append(1)

```

Does this break? I've run it for a short while, doesn't seem to hang.
> 0 votes

---
Tags: code-golf, python
---