title: Hitting 495 (Kaprekar)

text:
# Question
Title: Hitting 495 (Kaprekar)
**Input**:

A three digit number

* from stdin or as an argument
* not all digits are the same
* may start with one or two zero's

**Process**

Order the input-digits ascending and descending to form two new numbers. Subtract the smallest from the largest. Use the difference as new input. NB: This process needs 3 digits, so 10 has to be returned, or taken care of, as 010.

Repeat this process (Kaprekar transformation) until you hit 495.

**Output**:
The number of steps it took to reach 495.

Example:

Input: 211

```
211 – 112 = 099
990 – 099 = 891 (rather than 99 - 99 = 0)
981 – 189 = 792
972 – 279 = 693
963 – 369 = 594
954 − 459 = 495

```

Output: 6

# Answer
> 9 votes
## Golfscript, ~~29~~ 26 characters

```
.$)\0=-.5<{7\}4if-\~495=!*

```

Basically a mix of Joey's PS- and my Ruby-solution.

Edit: Thanks Nabb for a suggestion on how to shorten this by 3 characters.

# Answer
> 21 votes
## Windows PowerShell, 61 ~~65~~ ~~70~~ ~~72~~ ~~73~~ ~~82~~

Evil alternative approach. It becomes apparent if you desperately search for patterns in the input.

Be sure to also check out Ventero's Ruby and Golfscript solutions which use the same technique which was sort of a joined work :-)

```
(7..3+1..5)[($x=($a="$args")[0..2]|sort)[2]-$x[0]]*($a-ne495)

```

A little explanation might be in order for this, I guess. Suppose you have a number consisting of three digits. For convenience they are labeled *a*, *b* and *c* here with *c* being the largest. You then are going to subtract *abc* from *cba*.

If we picture that, we are going to get (*c**a* − 1), 9 and (10 + *a* \- *c*) as the individual digits. This will *always* hold, no matter the input digits. This also means that the middle digit get no say in how long the sequence will be, simply because it always is `9`.

So basically the first and last digit of the *sorted* digits suffice in determining the length of the sequence. One can easily make a list with every conceivable combination of first and last digit (there are only 45) to search for patterns there.

As it turns out, there are at least two. Both play with the first few results of the different digits: `[6 5 4 3 1 2 3 4 5]`. First, taking the *difference* between the largest and the smallest digit and subtracting one gives the appropriate index in the aforementioned list of results. Second, interpreting the smallest and largest digit as a single number and doing modulo 11 yields the same, except that one has to prepend another `6` to the list.

# Answer
> 11 votes
## J, ~~43~~ 37

```
<:$".@(\:,'-',/:)~@":@((3$10)&#:)^:a:

```

Sample run (note how stripping the 3 leading chars displays a trace):

```
   <:$".@(\:,'-',/:)~@":@((3$10)&#:)^:a:211
6
   ".@(\:,'-',/:)~@":@((3$10)&#:)^:a:211
211 99 891 792 693 594 495
   <:$".@(\:,'-',/:)~@":@((3$10)&#:)^:a:494
1
   <:$".@(\:,'-',/:)~@":@((3$10)&#:)^:a:495
0

```

This version repeatedly (`^:`) converts to decimal (`(3$10)&#:`), concatenates the descending list (`\:`), a minus sign `'-'` and the ascending list (`/:`), and evaluates (`".`). Until the result is stable (`a:`). Then it counts the number of returned elements (`<:$`).

I'm as surprised as you it needs fewer characters than the table lookup variant.

# Answer
> 4 votes
## Python, 89 characters

```
n=input()
c=0
while n-495:s=''.join(sorted('%03d'%n));n=int(s[::-1])-int(s);c+=1
print c

```

# Answer
> 4 votes
## J, 40

Using the Joey/Ventero approach. (go upvote them first)

```
(-&4`(7&-)@.(<&5)".'-'1}\:~y)-'495'-:y=.

```

This doesn't beat Golfscript, but I liked the idea of sorting the number, replacing the middle digit with a `-` and evaluating that.

# Answer
> 3 votes
## Windows PowerShell, ~~80~~ 79

```
for($a="$args";$a-495;++$i){$a=-join($x="00$a"[-1..-3]|sort)[2..0]-+-join$x}+$i

```

History:

* 2011-03-05 00:27 **(113)** Initial attempt.
* 2011-03-05 00:33 **(107)** One `sort` has to suffice.
* 2011-03-05 00:36 **(92)** Inlined the `filter`.
* 2011-03-05 00:41 **(87)** No format string anymore. There are other ways.
* 2011-03-05 00:43 **(85)** Unnecessary parentheses.
* 2011-03-05 01:01 **(83)** `-eq``-`.
* 2011-03-05 15:42 **(80)** I no longer need to cast the initial input to `int`. Removed unneeded parentheses.
* 2015-09-11 08:20 **(79)** I can move a `+` and save a space by abusing that `-` can only mean arithmetic and thus always converts both operands to a number.

Side note: My test cases.

# Answer
> 3 votes
## Ruby 1.8, ~~64 55 52~~ 48 characters

```
l=gets.bytes;i=l.max-l.min;p /495/?0:i<5?7-i:i-4

```

Note that the input shouldn't contain a line break.

For Ruby 1.9, the solution needs an additional space before the last colon.

* (64 -\> 55) Thanks to Joey for pointing out that the input already consists of 3 digits.
* (55 -\> 53) Thanks to steenslag for pointing out `Array#minmax`
* (53 -\> 52) Actually just using `Array#max` and `Array#min` directly is shorter.
* (52 -\> 48) Implicitly match a regexp against `$_` to test for 495.

# Answer
> 2 votes
## C - 133

*newline added for appearance*

```
c;main(n,l,h,t,i){scanf("%d",&n);for(;n!=495;c++,n=(h-l)*99)
for(l=n%10,h=l,i=2;i--;)t=(n/=10)%10,t<l?l=t:t>h?h=t:0;printf("%d\n",c);}

```

# Answer
> 2 votes
# APL, 42 chars/bytes\*

```
{⍵=495:⍺+0⋄L←⍵⊤⍨3⍴10⋄(⍺+1)∇10⊥L[⍒L]-L[⍋L]}

```

APL entry was missing from historic golf! Had to rectify. Trivial implementation, nothing fancy. Tested on ngn/apl.

**Explanation**

The function is initially called with a single number . It will recursively call itself  with the number of steps already taken  and the new number .

```
⍵=495: ⍺+0

```

Terminating condition: if  is 495, return the number of steps already taken (0 if  is yet undefined—this may differ in other dialects.)

```
L←(3⍴10)⊤⍵

```

Decode  into a list of 3 digits base 10. Above  is reflected to save 1 char.

```
(⍺+1) ∇ 10⊥L[⍒L]-L[⍋L]

```

Sort the list both ways, subtract one from the other member-wise, encode the result in base 10 (this works for negative digits too; may differ in other dialects) and recurse, adding 1 to  (or just 1 if undefined, see above.)

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
<sup>\*: APL can be written in its own (legacy) single-byte charset that maps APL symbols to the upper 128 byte values. Therefore, for the purpose of scoring, a program of N chars *that only uses ASCII characters and APL symbols* can be considered to be N bytes long.</sup>

# Answer
> 1 votes
**Lua 173 bytes**

Going for the longest one:

```
T=table c=T.concat i=1 n=tonumber p=io.read()while l~="495"do l={p:match"(%d)(%d)(%d)"}T.sort(l)k={}k[1]=l[3]k[2]=l[2]k[3]=l[1]p=('%03i'):format(c(k)-c(l))i=i+1 end print(i)

```

# Answer
> 1 votes
## Python, 63

```
f=lambda n:n-495and-~f(99*(int(max(`n`))-int(min(`n`))*(n>99)))

```

A recursive function. Gives `0` for `n==495` and otherwise transforms `n` and increments the counter by `1` with `-~`.

The transformation uses the fact that for three-digit numbers `abc-cba` equals `99*(a-c)`. To account for two-digit numbers, we set the `min` digit to `0` unless `n>99`.

# Answer
> 0 votes
# JavaScript 145

This was the best I could do on such short notice:

`for(n=prompt(i=o=e='');!i--|n-495;o+=n+' - '+a+' = '+(n=(p=n-a+e)[2]?p:0+p)+'\n')b=n.split(e).sort(),n=b.reverse(a=b.join(e)).join(e);alert(o+~i)`

---
Tags: code-golf, repeated-transformation
---


# Question
Title: Shortest script that gives the time passed since a Unix timestamp
What you need to do to win this challenge is to write the shortest "timeago" script that outputs the number of decades, years, weeks, days, hours, minutes, and seconds between a given Unix timestamp and the time the script is run.

You must give the time difference in "lowest terms", e.g. `1 week` not `7 days`, `9 years` not `0 decades 9 years`. You also must use plural forms correctly, e.g. `1 day` not `1 days`.

Your script must be accurate to within plus or minus 1 second (so the exact second rounding method is unimportant).

```
Time Equivalency Table
1 decade = 10 years
1 year = 31536000 seconds (not technically correct but close enough)
1 week = 7 days
1 day = 24 hours
1 hour = 60 minutes
1 minute = 60 seconds

```

The output should be of the form

```
A decade(s) B year(s) C week(s) D day(s) E hour(s) F minute(s) G second(s)

```

where `A...G` are all non-negative integers and the `s` is only there for plurals.

# Notes

* The timestamp will always be a time from the past. **It may be negative.**
* Input and output may be anything reasonable: stdin/stdout, function input and return value, etc.
* You may not use any tools that already do this. i.e. if your language has a `timesince(timestamp)` function built in you may not use that function.

*I have vastly edited this to make it clearer in hopes to assuage the somewhat silly battle between new users with unclear questions and old users who require perfection. It was not a terrible question (though now it may be too similar to this).*

Given that enough time is passed since the last answer, I declare **Three If By Whiskey** with its *177 bytes* Ruby implementation the winner of this context!

# Answer
## Ruby, ~~184~~ 177

```
->n{x=Time.now.to_i-n;d=[3650*y=86400,365*y,7*y,y,3600,60,1];(0..6).map{|i|c=x/d[i];(x%=d[i]*c;"#{c} #{%w[decade year week day hour minute second][i]}#{c<2?'':'s'}")if c>0}*' '}

```

There's nothing particularly clever here, but I suspect it's still very close to optimal.

**Example run**

```
p ->n{x=Time.now.to_i-n;d=[3650*y=86400,365*y,7*y,y,3600,60,1];(0..6).map{|i|c=x/d[i];(x%=d[i]*c;"#{c} #{%w[decade year week day hour minute second][i]}#{c<2?'':'s'}")if c>0}*' '}[0]
"4 decades 4 years 41 weeks 3 days 14 hours 20 minutes 48 seconds"

```
> 2 votes

# Answer
## J , 165

```
;' '&,@":&.>@((#~([:*&>{."1))@((;:' decades years weeks days hours minutes seconds')(],.([}.~[:-1=])&.>)<"0@(_ 10 52 7 24 60 60&#:)@(-~([:".@}:[:2!:0'date +%s'"_))))

```

Can probably be golfed more. Uses a shell call to date for getting the current unix epoch time, since Unix epoch is unavailable in J.

Example run:

```
;' '&,@":&.>@((#~([:*&>{."1))@((;:' decades years weeks days hours minutes seconds')(],.([}.~[:-1=])&.>)<"0@(_ 10 52 7 24 60 60&#:)@(-~([:".@}:[:2!:0'date +%s'"_)))) 0
4 decades 4 years 41 weeks 3 days 12 hours 54 minutes 1 second

```
> 2 votes

# Answer
# Python - 183

```
import time;t=int(time.time()-input());d=86400
for f,u in zip((3650*d,365*d,7*d,d,3600,60,1),'decade year week day hour minute second'.split()):
 if t/f:print`t/f`,u+'s'*(t/f>1),;t%=f

```

Output for a timestamp 999996400 seconds in the past:

```
3 decades 1 year 37 weeks 46 minutes 39 seconds

```
> 2 votes

# Answer
# Javascript, 287

```
function p(e,n){return e>2?e+" "+n+"s ":e+" "+n+" "}function t(e){n=new Date/1e3,l=e-n,c=1,m=60,h=60*m,d=24*h,w=7*d,y=365*d,a=10*y,s="",v={a:"Decade",y:"Year",w:"Week",d:"Day",h:"Hour",m:"Minute",c:"Second"};for(i in v)k=v[i],i=window[i],(r=Math.floor(l/i))>0&&(s+=p(r,k)),l%=i;alert(s)}

```

to run use `t(secondsInFuture)`;
> 1 votes

# Answer
# JavaScript, 392

```
t=function(c){i=function(){var a=+new Date/1e3-c,b=document;29>a?b.write("just now"):60>a?b.write((a|0)+" seconds ago"):60<a&&120>a?b.write("1 minute ago"):60>a/60?b.write((a/60|0)+" minutes ago"):60<a/60&&120>a/60?b.write("1 hour ago"):24>a/3600?b.write((a/3600|0)+" hours ago"):24<a/3600&&48>a/3600?b.write("1 day ago"):1<=a/86400&&b.write((a/86400|0)+" days ago")};i();setInterval(i,3e4)};

```

*Also the unminified code for the curious ones*

```
t = function(timestamp){

i = function() {
var diff = (+new Date/1e3)-(timestamp),
d = document;

    if( (diff) < 29) {

        d.write( 'just now' )
    }
    else if( diff < 60) {

        d.write( ( (diff) |0 ) + ' seconds ago' )
    }
    else if( diff > 60 && diff < 120) {
        d.write(  '1 minute ago' )
    }
    else if( (diff)/60 < 60) {
        d.write( ( (diff)/60 |0 ) + ' minutes ago' )
    }
    else if( (diff)/60 > 60 && (diff)/60 < 120) {
        d.write( '1 hour ago' )
    }
    else if( (diff)/3600 < 24) {
        d.write( ( (diff)/3600 |0 ) + ' hours ago' )
    }
    else if( (diff)/3600 > 24 && (diff)/3600 < 48) {
        d.write( '1 day ago' )
    }
    else if( (diff)/86400 >= 1) {
        d.write( ( (diff)/86400 |0 ) + ' days ago' )
    }
  }

i()

setInterval(i, 3e4)

}

```

It updates every 30 seconds and calculates both singular and plural.

To run it use `t(unix_timestamp)`
> 1 votes

# Answer
# Javascript, 263

```
i=[315360000,31536000,604800,86400,3600,60,1];s=['decade','year','week','day','hour','minute','second'];function g(d){return p(parseInt((new Date().getTime()-d)/1000), 0);}function p(d,n){k=d-d%i[n];r=k/i[n];return (r>0?r+' '+s[n]+'(s) ':'')+(n<6?p(d-k,n+1):'');}

```

to run from the Javascript console, call

```
g(unixTimestamp);

```
> 0 votes

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


# Question
Title: Generate ordered binary combinations without repetitions
# Challenge

Write the shortest program that receives two signed integers `n` and `i` and for each `i` between 1 and `2^n - 1` returns the next ordered permutation based on the binary representation of the number. There is no specific order of the combinations but the number of 1s in the binary representation must always stay the same or grow and numbers each output may happen only once

# Clarification

The goal of this program is to generate all the combinations without repetitions of a set. To do so you may consider that each item is represented by a bit in a bit mask, that way if you have three items, A, B and C represented by 001, 010 and 100 respectively the combinations ABC, ACB, BCA, BAC, CAB and CBA are all represented as 111.

For increasing values of `i` your program should output a new combinations always with the same number of elements or more.

# Input

You may read the input in the format

> `n i`

or just use `n` and `i` variables, whichever suits you best.

# Output

You may output a single number `k`

# Sample cases

Each test case is two lines, input followed by output with a binary representation here for demonstration purposes:

```
3 1
1 (001)

3 2
4 (100)

3 3
2 (010)

3 4
6 (110)

3 7
7 (111)

```

# Rules

* Shortest code wins (bytes)
* The result can be returned by a function or printed by your program.
* You may assume `n` and `i` variables already exist, there's no need to handle input if you don't want to.
* The answers with the same number of `1` bits can be output in any order
* The input is guaranteed to be well formed and `1 <= i <= 2^n - 1`.

Happy Golfing!

# Answer
# Pyth, 13 bytes

```
i@o/N1^U2vzQ2

```

Just constructs a cartesian power of `[0, 1]`, sorts it by number of `1`s, and indexes before converting to base10.
> 1 votes

# Answer
## Ruby, 72 bytes

```
p [0,1].repeated_permutation(n).sort_by{|x|x.count 1}[i].join('').to_i 2

```

How it works:

```
irb(main):001:0> [0, 1].repeated_permutation(3).to_a  # generate permutations
=> [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1],
    [1, 1, 0], [1, 1, 1]]

irb(main):002:0> _.sort_by {|x| x.count 1 }           # sort by number of 1's
=> [[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [0, 1, 1], [1, 0, 1],
    [1, 1, 0], [1, 1, 1]]

irb(main):003:0> _[2].join ''  # convert array of binary digits to string
=> "010"
irb(main):004:0> _.to_i 2      # interpret string as binary number
=> 2

```
> 3 votes

---
Tags: code-golf, math, combinatorics, binary
---


title: The Lazy Programmer's XML Parser

text:
# Question
Title: The Lazy Programmer's XML Parser
# Background

You are working as a programmer for a car sales company. Your task for this week is to program an XML parser that takes in data about available models from different car manufacturers, and pretty-prints information about the newest models. Luckily for you, the testing department has provided only one test case! The faster you can write code that passes it, the more time you have for procrastination during the rest of the week.

# Input

Your input is *exactly* this piece of XML data, supplied by the testing department. It contains data about some car manufacturers, their series of cars, and the models in these series. You may assume a trailing newline.

```
<?xml version="1.0" ?>
<products>
  <manufacturer name="Test Manufacturer 1">
    <series title="Supercar" code="S1">
      <model>
        <name>Road Czar</name>
        <code>C</code>
        <year>2011</year>
      </model>
      <model>
        <name>Ubervehicle</name>
        <code>U</code>
        <year>2013</year>
      </model>
      <model>
        <name>Incredibulus</name>
        <code>I</code>
        <year>2015</year>
      </model>
      <model>
        <name>Model 1</name>
        <code>01</code>
        <year>2010</year>
      </model>
    </series>
    <series title="Test series 22" code="Test">
      <model>
        <name>Test model asdafds</name>
        <code>TT</code>
        <year>2014</year>
      </model>
    </series>
  </manufacturer>
  <manufacturer name="Car Corporation">
    <series title="Corporation Car" code="CC">
      <model>
        <name>First and Only Model</name>
        <code>FOM</code>
        <year>2012</year>
      </model>
    </series>
  </manufacturer>
  <manufacturer name="Second Test Manufacturer">
    <series title="AAAAAAAAAAAAAA" code="D">
      <model>
        <name>Some older model</name>
        <code>O</code>
        <year>2011</year>
      </model>
      <model>
        <name>The newest model</name>
        <code>N</code>
        <year>2014</year>
      </model>
    </series>
    <series title="BBBBBBBBBBBBBBB" code="asdf">
      <model>
        <name>Another newest model here</name>
        <code>TT</code>
        <year>2015</year>
      </model>
    </series>
  </manufacturer>
</products>

```

# Output

Your output is this string. It lists the car manufacturers in alphabetical order, followed by a colon and the number of series they make. Under each manufacturer, it lists the series name, model name, and code of each of their models, starting from the newest and going backward by year. Trailing whitespace and line breaks are acceptable, as long as your output looks similar to this when printed.

```
Car Corporation: 1 series
  Corporation Car, First and Only Model (CC-FOM)
Second Test Manufacturer: 2 series
  BBBBBBBBBBBBBBB, Another newest model here (asdf-TT)
  AAAAAAAAAAAAAA, The newest model (D-N)
  AAAAAAAAAAAAAA, Some older model (D-O)
Test Manufacturer 1: 2 series
  Supercar, Incredibulus (S1-I)
  Test series 22, Test model asdafds (Test-TT)
  Supercar, Ubervehicle (S1-U)
  Supercar, Road Czar (S1-C)
  Supercar, Model 1 (S1-01)

```

# Rules and Scoring

You may write either a function or full program. The lowest byte count wins, and standard loopholes are disallowed.

Note that the input is fixed: you don't need to support any other inputs than the one given here. Your program is allowed to return nonsense or even crash if the input is modified in any way. You may also ignore the input and hard-code the output, if desired. However, you may *not* use XML or HTML parser libraries or built-ins.

# Answer
> 8 votes
# CJam, ~~109~~ 107 bytes

```
"rzn ¸À¨ 4T\$D"S/q"<>"'"er'"/
f{\:i2/_E5bf.+.+\ff=)1<_s,9/+":  series
"2/.+\"  ,  ()
-"2/Z4e\f.\}

```

Note that four of the characters in the string at the beginning are unprintable.

Try it online in the CJam interpreter.

### Idea

This is basically a hardcode that splits the input at all occurrences of **\<**, **\>** and **"**, selects specific chunks and interleaves them with the remaining parts of the output.

After splitting the input, the chunks at indexes **110**, **114** and **122** are **Car Corporation**, **Corporation Car** and **First and Only Model**. The codes for series and name can be found at indexes 116 and 126, which can be calculated by adding 2 and 4 to the indexes of the names. Finally, the number of series is the length of the string **Car Corporation** divided by **9** (obviously).

Thus, we encode the part of the output that corresponds to this manufacturer as `[114 122 110]` or rather the string `"rzn"`.

### Code

```
e# Split the string at spaces.

"rzn ¸À¨ 4T\$D"S/

e# After replacing characters with their code points, this will be the result:
e# [[114 122 110] [184 192 144 168 144 152 140] [12 52 84 92 12 36 12 20 12 68 8]]

e# Read from STDIN, replace < and > with " and split at double quotes.

q"<>"'"er'"/

f{       e# For each chunk of the split string, push the split input; then:
\:i2/    e# Replace characters with character codes and split into chunks of
         e# length 2.
_E5b     e# Copy the result and push [2 4].
f.+      e# Replace each pair [I J] in the copy with [I+2 J+4].
.+       e# Vectorized concatenation.
         e# For the first chunk, we've achieved
         e# [114 122 110] -> [[114 122] [110]]
         e#               -> [[114 122] [110]] [[116 126] [110 112 4]]
         e#               -> [[114 122 116 126] [110 112 4]]
\ff=     e# Replace each integer with the chunk of the split input at that index.
)1<      e# Pop the first chunk and reduce it to the first string.
_s,9/    e# Divide that strings length by 9 and append the integer to the array.
":  series
"2/      e# Push [": " " s" "er" "ie" "s\n"].
.+       e# Vectorized concatenation; pushes the manufacturer line.
\        e# Swap the remaining strings on top of the stack.
"  ,  ()
-"2/     e# Push ["  " ", " " (" ")\n" "-"].
Z4e\     e# Swap the chunks at indexes 3 and 4.
\f.\     e# Interleave both arrays of strings.
}

```

# Answer
> 10 votes
# Bubblegum, ~~227~~ 225 bytes

```
0000000: 6d 50 45 b6 02 31 10 dc cf 29 6a 87 eb 92 1d ee 0e 07  mPE..1...)j.......
0000012: 08 93 1e 3c e1 45 be 9d fe 37 ae bd 2b 7d 95 54 85 41  ...<.E...7..+}.T.A
0000024: 55 9b 83 36 c2 ad b5 2a a1 00 4b 66 4d 36 c0 23 0f f6  U..6...*..KfM6.#..
0000036: a5 d1 58 1b eb 20 94 c4 50 ed 7e d1 d7 92 76 88 57 ab  ..X.. ..P.~...v.W.
0000048: 99 c6 b0 9f 08 a6 14 6a 96 66 c4 9e be 50 3e 12 a1 f3  .......j.f...P>...
000005a: 86 4c 09 c5 7b 67 e5 f9 d2 28 2b ed 56 64 a0 e8 9b 83  .L..{g...(+.Vd....
000006c: d8 9f 3a 99 20 c4 85 95 51 66 36 4b 70 ac fc 74 69 cc  ..:. ...Qf6Kp..ti.
000007e: 56 f4 9c 88 d7 32 83 4f c6 a9 de 13 f4 4e 92 b9 1b 87  V....2.O.....N....
0000090: 89 e0 6d 24 0a 4f 33 a7 fe 40 26 e4 37 a3 ad 42 43 72  ..m$.O3..@&.7..BCr
00000a2: bd f0 3b 6f 11 9f 16 32 ed 04 eb a7 fc d9 8d 62 91 f7  ..;o...2.......b..
00000b4: dc 97 f0 6a 11 49 f6 1e b9 cb fc 7b dd 7c 41 e6 8b 56  ...j.I.....{.|A..V
00000c6: eb 70 47 a7 b6 f9 b3 3c d1 42 a2 fa 27 cc 49 ac 3e 89  .pG....<.B..'.I.>.
00000d8: 97 ff 2e 9c a4 7c 21 f1 0f                             .....|!..

```

This isn't very competitive, but I just couldn't resist to post my first Bubblegum answer to an actual challenge.

The hexdump can be reversed with `xxd -r -c 18 > xml.bg`.

The code completely ignores the input. Compression has been done with zopfli, which uses the DEFLATE format but obtains a better ratio than (g)zip.

*Thanks to @Sp3000 for -2 bytes!*

# Answer
> 9 votes
# sed, 449 bytes

Assumes sed to be run with the `-nr` options.

```
/\?|<p/d;:M
/<ma/{s/.*"(.*)".*/Q\1: X series/;/C/ s/X/1/;s/X/2/;H;d}
/<se/{s/.*"([^"]*)".*"([^"]*)".*/@\1!\2/;H;d}
/<mo/{
G;s/.*@(.*)*$/\1/;x;s/@(.*)*$//;x;:A N
/<\/m/!bA
s/\n/!/g;s/  +//g;s|<[/a-z]*>||g;s/(.*)!(.*)!(.*)!(.*)!(.*)!/%\1, \3 (\2-\4)@\1!\2/;H}
/<\/se/{x;s/\n*@.*$//;x}
$!{n;bM}
x;s/\n//g;s/Q(.*)Q(.*)%(.*)Q(.*)/\2\n  \3\n\4\n\1/
s/%(.*)%(.*)%(.*)\n(.*)%(.*)%(.*)%(.*)%(.*)%(.*)/\n  \3\n  \2\n  \1\n\4\n  \7\n  \9\n  \6\n  \5\n  \8/;p

```

Ungolfed version:

```
# Remove first 2 lines
/\?|<p/ d

:M
#manufacturer
/<ma/ {
    s/.*"(.*)".*/Q\1: X series/
    #Car corp
    /C/ s/X/1/
    #other
    s/X/2/
    H
    d
}

#series: store in hold buffer. (treating the hold buffer as a list, with @ as a delimeter)
/<se/{
    s/.*"([^"]*)".*"([^"]*)".*/@\1!\2/
    H
    d
}
/<mo/ {
    # pull series from hold buffer
    G
    s/.*@(.*)*$/\1/

    # remove series from hold buffer
    x
    s/@(.*)*$//
    x

    # Concatenate model into one line
    :A N
    /<\/m/ !{
        bA
    }
    s/\n/!/g

    # Remove junk
    s/  +//g
    s|<[/a-z]*>||g

    # Append formatted line to hold buffer, replace series at the end
    s/(.*)!(.*)!(.*)!(.*)!(.*)!/%\1, \3 (\2-\4)@\1!\2/
    H
}
/<\/se/ {
    #pop series name
    x
    s/\n*@.*$//
    x
}

$ ! {
    n
    b M
}
# end of loop

x
s/\n//g

# "sort"
s/Q(.*)Q(.*)%(.*)Q(.*)/\2\n  \3\n\4\n\1/
s/%(.*)%(.*)%(.*)\n(.*)%(.*)%(.*)%(.*)%(.*)%(.*)/\n  \3\n  \2\n  \1\n\4\n  \7\n  \9\n  \6\n  \5\n  \8/
p

```

# Answer
> 2 votes
# Bash, ~~388~~ ~~368~~ 365

```
base64 -d<<<H4sICKVS9FUCA2hlcmUAbVFBasMwELwH8oc92mBD5GNuqUogB9dQOw9QpDUWKFJYWS3t6yvJtI3T7k07szOzKy4IuKObIzFrZ/fAwCNp9NsN3APABVVw1ORnEFZBZ80HtE6hgYLz+ti15XbTo3QRGzCSWmHDKOQcCGkPzZ3q07oqOFg3T0hg8T1NXrNqbCAUwquxHoYyzR1WVcEw4XqkeK5f/mX27orgjIoeP8wuMv8EBbaO2ocbkkybn6wkVPoSTPBQ9Kw+ZaessPChaarlvXjE6GJUkZx63zv8Cp4vSG84aWkw650f8FcnFPDP+D0J5Q/ocnmWsR0rvwC2OTuexgEAAA==|zcat

```

### Small test because:

```
$ bash ./go_procrastination.sh cars.xml
Car Corporation: 1 series
  Corporation Car, First and Only Model (CC-FOM)
Second Test Manufacturer: 2 series
  BBBBBBBBBBBBBBB, Another newest model here (asdf-TT)
  AAAAAAAAAAAAAA, The newest model (D-N)
  AAAAAAAAAAAAAA, Some older model (D-O)
Test Manufacturer 1: 2 series
  Supercar, Incredibulus (S1-I)
  Test series 22, Test model asdafds (Test-TT)
  Supercar, Ubervehicle (S1-U)
  Supercar, Road Czar (S1-C)
  Supercar, Model 1 (S1-01)

```

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


title: Benfords Law of Words

text:
# Question
Title: Benfords Law of Words
**Background**

Benford's Law is freaky!

Of all the numbers in the world, roughly 30% of them start with a 1! 17.6% start with a 2, 12.5% start with a 3, and so on, and so on.

For example, take a look at the following graph. Take the largest 120000 towns in the world, take their altitude, and voila - they obey Benford's law. Divide these numbers by ~3 to convert them into meters, and amazingly, they still obey this law!

In fact, it can be generalized past the first digit:

Source

---

**Challenge**

So I wondered, how does this apply to letters and words?

Your challenge is to parse the big list of words below and formulate the table above (printing a matrix will suffice). Unlike this work, you will not only need to find the occurrence of the first letter, but also the second, third, fourth, and fifth. If a word does not have the nth digit, you can ignore that word (i.e. if you are compiling the 5th column (looking at the fifth digit), you should ignore all words less than 5 characters long)

Big List of Words: https://raw.githubusercontent.com/kevina/wordlist/master/alt12dicts/2of4brif.txt

Due to suggestion in the comments, **this contest is now a code golf competiton**, so shortest code in bytes wins. The entry must be a complete program and must output the table specified above. Built-ins are allowed.

Good luck!

# Answer
## R: 88, 95, or 126 bytes

```
z=sapply(readr::read_lines("http://tinyurl.com/pshoqyo"),Vectorize(substr),1:5,1:5)
y=apply(z,1,table,exclude="")
y/colSums(y)

```

That's **126 bytes** where that the data is downloaded from the provided URL (a tinyurl equivalent to be exact).

I can shorten the code to **88 bytes** if you allow to read the input from stdin:

```
z=sapply(scan(,""),Vectorize(substr),1:5,1:5)
y=apply(z,1,table,exclude="")
y/colSums(y)

```

or **95 bytes** if the data is provided via a `t.txt` file:

```
z=sapply(scan("t.txt",""),Vectorize(substr),1:5,1:5)
y=apply(z,1,table,exclude="")
y/colSums(y)

```

The output:

```
          aah         <NA>        <NA>        <NA>         <NA>
a 0.054250087 0.1366519284 0.091410860 0.062576399 0.0656915218
b 0.057777336 0.0070112047 0.023141714 0.020833697 0.0171560104
c 0.099582311 0.0178502654 0.053853798 0.046119198 0.0308013314
d 0.065925417 0.0080894018 0.032457317 0.040240449 0.0279619439
e 0.044177897 0.1499494924 0.068491563 0.115709739 0.1336258142
f 0.045208406 0.0035603690 0.019392694 0.018553559 0.0122387071
g 0.033566827 0.0028011669 0.026038614 0.031346432 0.0212462947
h 0.035818471 0.0396356269 0.009065709 0.021577492 0.0288307086
i 0.042716723 0.1027737583 0.061586103 0.079272029 0.1020188291
j 0.009065709 0.0002815175 0.002997334 0.001872970 0.0003181567
k 0.006557703 0.0032954113 0.004342637 0.025971634 0.0180791157
l 0.030602613 0.0469071140 0.057569618 0.058683031 0.0625465746
m 0.050139230 0.0185368141 0.045014732 0.032771954 0.0237633928
n 0.017230697 0.0724559354 0.080629937 0.054978721 0.0516144003
o 0.026307990 0.1417192442 0.067001176 0.058609030 0.0616554195
p 0.082236243 0.0202858231 0.041453955 0.040891509 0.0257849684
q 0.004835478 0.0032155407 0.002880155 0.002475636 0.0009935913
r 0.056736060 0.0873758770 0.099060304 0.069567953 0.0749333466
s 0.124834642 0.0096061647 0.069021478 0.057992614 0.0674600544
t 0.053731760 0.0237137132 0.066835577 0.085112378 0.0682529848
u 0.022802921 0.0768211701 0.043144600 0.036018688 0.0333164804
v 0.014224916 0.0093814228 0.018101442 0.014540002 0.0068392204
w 0.026536498 0.0070329376 0.010477867 0.009521917 0.0073194562
x 0.000184196 0.0124653498 0.004669879 0.001490387 0.0012265464
y 0.003312471 0.0105155083 0.009124480 0.006613406 0.0145012475
z 0.001506947 0.0003146373 0.003828814 0.004336978 0.0029114873

```
> 1 votes

# Answer
# Mathematica 246 bytes

The probabilities are based on all the words in the file.

```
p=Prepend;t=Transpose;d="Digit";
p[t[p[N[#/Total@#,5]&/@ t[Sort[Cases[Tally[Position[Characters
@Import["t.txt","List"],#][[All,2]]],{n_,_} /;n<6]]/.{_,k_}->k&/@
(c=CharacterRange["a","z"])],c]],{d,"1st "<> d,"2nd "<>d,"3rd "<>d,"4th "<>d,"5th "<>d}]
//Grid

```

---

---

In the given list of 60387 words, the occurrences are distributed as follows. Letters "s" and "c" are the most likely to appear at the beginning of a word (7455 and 6008, respectively). Only 11 words begin with the letter "x".

---

**Without headers in table** 162 bytes

```
t=Transpose;t[N[#/Total@#]&/@t[Sort[Cases[Tally[Position[Characters@Import["t.txt", "List"], #][[All,2]]],{n_,_} /;n<6]]/.{_,k_}->k&/@CharacterRange["a","z"]]]//Grid

```
> 5 votes

# Answer
# MATLAB, ~~113~~ 117 bytes

I made this a script that loads our text file, conveniently called *t.txt*, and prints the table without headers to the screen.

Old version (113 bytes) contained an error:

```
D=max(1,strvcat(importdata('t.txt'))-95);F=[];for n=1:5,F=[F,accumarray(D(:,n),1)/length(D)];end;disp(F(2:end,:))

```

New corrected version is slightly longer unfortunately.

```
D=max(1,strvcat(importdata('t.txt'))-95);F=[];for n=1:5,E=D(:,n);F=[F,accumarray(E,1)/sum(E~=1)];end;disp(F(2:end,:))

```

Giving the output:

```
0.0543    0.1367    0.0914    0.0626    0.0657
0.0578    0.0070    0.0229    0.0200    0.0181
0.0995    0.0177    0.0512    0.0466    0.0324
0.0652    0.0077    0.0325    0.0407    0.0294
0.0420    0.1499    0.0686    0.1169    0.1391
0.0452    0.0036    0.0194    0.0186    0.0122
0.0336    0.0028    0.0258    0.0301    0.0224
0.0358    0.0392    0.0086    0.0218    0.0304
0.0422    0.0976    0.0616    0.0802    0.1073
0.0086    0.0003    0.0030    0.0019    0.0003
0.0066    0.0033    0.0043    0.0260    0.0181
0.0306    0.0469    0.0570    0.0564    0.0658
0.0501    0.0183    0.0428    0.0331    0.0250
0.0170    0.0688    0.0807    0.0556    0.0543
0.0250    0.1417    0.0671    0.0592    0.0642
0.0822    0.0203    0.0415    0.0409    0.0258
0.0048    0.0032    0.0029    0.0024    0.0010
0.0567    0.0864    0.0942    0.0703    0.0789
0.1235    0.0091    0.0691    0.0586    0.0710
0.0510    0.0237    0.0669    0.0860    0.0711
0.0228    0.0768    0.0431    0.0360    0.0333
0.0142    0.0094    0.0179    0.0140    0.0072
0.0265    0.0070    0.0100    0.0096    0.0077
0.0002    0.0118    0.0047    0.0015    0.0013
0.0031    0.0105    0.0091    0.0067    0.0151
0.0015    0.0003    0.0038    0.0043    0.0029

```
> 3 votes

# Answer
# Python 3, ~~143~~ 129 bytes

~~This is taking a long time to run on the provided data. I have no idea if it will finish any time soon.~~

I think the interpreter I'm using is refusing to run the program because of the input size. My program did the first 1000 words in 1 second.

**Edit**: Now stops at 5 letters/columns.

```
s=input().split()
l=96
while l<122:l+=1;print([sum(i<len(w)and w[i]==chr(l)for w in s)/sum(i<len(w)for w in s)for i in range(5)])

```

With the letters on the left (136):

```
s=input().split()
l=96
while l<122:l+=1;print(chr(l),[sum(i<len(w)and w[i]==chr(l)for w in s)/sum(i<len(w)for w in s)for i in range(5)])

```

### Example Output

This is the output for input of `hello\nworld`:

```
[0.0, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.5]
[0.0, 0.5, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.0]
[0.5, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.5, 1.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.5, 0.0, 0.0, 0.5]
[0.0, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.5, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.0]
[0.5, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.0]

```

Output for the first 2000 words (not so nice to look at :/):

```
[1.0, 0.0015, 0.082164328657314628, 0.045523520485584217, 0.067875647668393782]
[0.0, 0.11899999999999999, 0.027555110220440882, 0.0096105209914011131, 0.017616580310880828]
[0.0, 0.1565, 0.096192384769539077, 0.015680323722812341, 0.046632124352331605]
[0.0, 0.14499999999999999, 0.03406813627254509, 0.019221041982802226, 0.042487046632124353]
[0.0, 0.019, 0.04458917835671343, 0.17653009610520992, 0.098963730569948186]
[0.0, 0.050000000000000003, 0.033066132264529056, 0.0030349013657056147, 0.0020725388601036268]
[0.0, 0.049000000000000002, 0.037575150300601205, 0.0096105209914011131, 0.03367875647668394]
[0.0, 0.0030000000000000001, 0.016533066132264528, 0.032372281234193223, 0.021243523316062177]
[0.0, 0.052499999999999998, 0.045591182364729456, 0.13606474456246839, 0.09689119170984456]
[0.0, 0.00050000000000000001, 0.025050100200400802, 0.0, 0.0]
[0.0, 0.00050000000000000001, 0.0075150300601202402, 0.00050581689428426911, 0.00051813471502590671]
[0.0, 0.123, 0.050601202404809621, 0.084977238239757211, 0.034715025906735753]
[0.0, 0.094, 0.036072144288577156, 0.027314112291350532, 0.030569948186528497]
[0.0, 0.1865, 0.03406813627254509, 0.030349013657056147, 0.080310880829015538]
[0.0, 0.0, 0.077655310621242479, 0.11987860394537178, 0.053886010362694303]
[0.0, 0.0, 0.027555110220440882, 0.018715225088517955, 0.013471502590673576]
[0.0, 0.0, 0.014529058116232466, 0.0015174506828528073, 0.0041450777202072537]
[0.0, 0.0, 0.095190380761523044, 0.076884167931208905, 0.11968911917098446]
[0.0, 0.0, 0.039579158316633264, 0.036418816388467376, 0.078238341968911912]
[0.0, 0.0, 0.10671342685370741, 0.039453717754172987, 0.077720207253886009]
[0.0, 0.0, 0.030561122244488977, 0.098128477491148211, 0.029015544041450778]
[0.0, 0.0, 0.033567134268537073, 0.0015174506828528073, 0.013989637305699482]
[0.0, 0.0, 0.00050100200400801599, 0.0075872534142640367, 0.0041450777202072537]
[0.0, 0.0, 0.0, 0.0, 0.0067357512953367879]
[0.0, 0.0, 0.002004008016032064, 0.0040465351542741529, 0.024352331606217616]
[0.0, 0.0, 0.0015030060120240481, 0.0050581689428426911, 0.0010362694300518134]

```

### Ungolfed

```
s=input().split()
m=[]
l=96
while l<122:
    l+=1;r=[]
    for i in range(max(map(len,s))):                # Max length of words in list
        L=sum(i<len(w)for w in s)                   # How many words of this length
        f=sum(i<len(w)and w[i]==chr(l)for w in s)   # Number of char in that pos
        r+=[f/L]
    m+=[r]
for r in m:print(r)

```
> 2 votes

# Answer
# bash with gawk 4 and sort, 125

Pretty much what awk was made for

```
awk '{for(;NF;c[NF--]++)a[$NF][NF]++}END{for(i in a){printf i;for(j=0;j++<5;)printf" %.9f",a[i][j]/c[j];print""}}' FS= wordlist.txt|sort

```

"wordlist.txt" needs to be replaced by the name of your file containing the list of words, and I counted the whole filename as one character, because it could be ;)

Be sure to leave the space between `FS=` and the filename.

It takes into account, that not all words have five letters. So for the average of the second to fifth position it divides only by the number of words with at least that much letters.

## awk part readable

```
{
    for(;NF;c[NF--]++)    # count number of words with at least that length
        a[$NF][NF]++      # count occurences of character at that position
}

END{
    for(i in a)
    {
        printf i;
        for(j=0;j++<5;)
            printf" %.5f",a[i][j]/c[j];    # print averages
        print""
    }
}

```

You can easily utilize the `sort` to gather some information. For instance the option `-rk2` sorts by the most common letter in the first position, `-rk3` sorts by the most common letter in the second position and so on.

## Output without sort options

```
a 0.054250087 0.136651928 0.091410860 0.062576399 0.065691522
b 0.057777336 0.007004819 0.022906584 0.020010382 0.018061682
c 0.099491612 0.017652806 0.051200027 0.046635074 0.032427344
d 0.065196151 0.007683773 0.032486906 0.040690567 0.029411252
e 0.041962674 0.149949492 0.068554001 0.116897470 0.139123764
f 0.045208406 0.003560369 0.019392694 0.018553559 0.012238707
g 0.033566827 0.002798616 0.025774050 0.030107671 0.022367893
h 0.035785848 0.039197178 0.008618975 0.021818852 0.030352691
i 0.042244192 0.097620349 0.061642246 0.080158743 0.107306613
j 0.008611125 0.000281518 0.003000066 0.001892195 0.000331247
k 0.006557703 0.003295411 0.004342637 0.025971634 0.018079116
l 0.030602613 0.046864391 0.056984685 0.056363971 0.065848428
m 0.050093563 0.018331760 0.042796526 0.033138532 0.025017870
n 0.017040091 0.068822760 0.080703441 0.055593697 0.054289649
o 0.024988822 0.141719244 0.067062256 0.059210636 0.064192193
p 0.082236243 0.020285823 0.041453955 0.040891509 0.025784968
q 0.004835478 0.003212612 0.002850892 0.002377803 0.001046043
r 0.056684386 0.086409327 0.094178877 0.070346121 0.078889102
s 0.123453723 0.009124480 0.069084400 0.058641303 0.070956607
t 0.051037475 0.023713713 0.066896506 0.085986035 0.071061211
u 0.022802921 0.076821170 0.043144600 0.036018688 0.033316480
v 0.014224916 0.009372878 0.017917523 0.013965405 0.007200265
w 0.026512329 0.006955139 0.009961546 0.009628426 0.007705853
x 0.000182158 0.011840297 0.004674136 0.001507058 0.001290120
y 0.003146373 0.010515508 0.009132799 0.006681291 0.015097892
z 0.001506947 0.000314637 0.003828814 0.004336978 0.002911487

```

## Output sorted after occurrence as first letter

```
s 0.123453723 0.009124480 0.069084400 0.058641303 0.070956607
c 0.099491612 0.017652806 0.051200027 0.046635074 0.032427344
p 0.082236243 0.020285823 0.041453955 0.040891509 0.025784968
d 0.065196151 0.007683773 0.032486906 0.040690567 0.029411252
b 0.057777336 0.007004819 0.022906584 0.020010382 0.018061682
r 0.056684386 0.086409327 0.094178877 0.070346121 0.078889102
a 0.054250087 0.136651928 0.091410860 0.062576399 0.065691522
t 0.051037475 0.023713713 0.066896506 0.085986035 0.071061211
m 0.050093563 0.018331760 0.042796526 0.033138532 0.025017870
f 0.045208406 0.003560369 0.019392694 0.018553559 0.012238707
i 0.042244192 0.097620349 0.061642246 0.080158743 0.107306613
e 0.041962674 0.149949492 0.068554001 0.116897470 0.139123764
h 0.035785848 0.039197178 0.008618975 0.021818852 0.030352691
g 0.033566827 0.002798616 0.025774050 0.030107671 0.022367893
l 0.030602613 0.046864391 0.056984685 0.056363971 0.065848428
w 0.026512329 0.006955139 0.009961546 0.009628426 0.007705853
o 0.024988822 0.141719244 0.067062256 0.059210636 0.064192193
u 0.022802921 0.076821170 0.043144600 0.036018688 0.033316480
n 0.017040091 0.068822760 0.080703441 0.055593697 0.054289649
v 0.014224916 0.009372878 0.017917523 0.013965405 0.007200265
j 0.008611125 0.000281518 0.003000066 0.001892195 0.000331247
k 0.006557703 0.003295411 0.004342637 0.025971634 0.018079116
q 0.004835478 0.003212612 0.002850892 0.002377803 0.001046043
y 0.003146373 0.010515508 0.009132799 0.006681291 0.015097892
z 0.001506947 0.000314637 0.003828814 0.004336978 0.002911487
x 0.000182158 0.011840297 0.004674136 0.001507058 0.001290120

```

## Second letter

```
e 0.041962674 0.149949492 0.068554001 0.116897470 0.139123764
o 0.024988822 0.141719244 0.067062256 0.059210636 0.064192193
a 0.054250087 0.136651928 0.091410860 0.062576399 0.065691522
i 0.042244192 0.097620349 0.061642246 0.080158743 0.107306613
r 0.056684386 0.086409327 0.094178877 0.070346121 0.078889102

```

## Third letter

```
r 0.056684386 0.086409327 0.094178877 0.070346121 0.078889102
a 0.054250087 0.136651928 0.091410860 0.062576399 0.065691522
n 0.017040091 0.068822760 0.080703441 0.055593697 0.054289649
s 0.123453723 0.009124480 0.069084400 0.058641303 0.070956607
e 0.041962674 0.149949492 0.068554001 0.116897470 0.139123764

```

## Fourth letter

```
e 0.041962674 0.149949492 0.068554001 0.116897470 0.139123764
t 0.051037475 0.023713713 0.066896506 0.085986035 0.071061211
i 0.042244192 0.097620349 0.061642246 0.080158743 0.107306613
r 0.056684386 0.086409327 0.094178877 0.070346121 0.078889102
a 0.054250087 0.136651928 0.091410860 0.062576399 0.065691522

```

## Fifth letter

```
e 0.041962674 0.149949492 0.068554001 0.116897470 0.139123764
i 0.042244192 0.097620349 0.061642246 0.080158743 0.107306613
r 0.056684386 0.086409327 0.094178877 0.070346121 0.078889102
t 0.051037475 0.023713713 0.066896506 0.085986035 0.071061211
s 0.123453723 0.009124480 0.069084400 0.058641303 0.070956607

```

So it looks like there is no Benfords Law of Words ;)
> 2 votes

# Answer
# Dyalog APL (76)

```
⎕ML←3⋄L{R÷+⌿R←0 1↓K[⍋⊃K←,∘≢⌸⍺⌷¨⍵;]}¨(↓(L←⍳5)∘.≤≢¨G)/¨⊂G←W⊂⍨10≠W←83 ¯1⎕MAP'w'

```

This assumes the input is in a file called `w` in the working directory.

Output:

```
      ⎕ML←3⋄L{R÷+⌿R←0 1↓K[⍋⊃K←,∘≢⌸⍺⌷¨⍵;]}¨(↓(L←⍳5)∘.≤≢¨G)/¨⊂G←W⊂⍨10≠W←83 ¯1⎕MAP'w'
 0.05425008694    0.1366519284     0.09141085991   0.06257639947   0.06569152182
 0.05777733618    0.007004818918   0.02290658357   0.02001038196   0.01806168169
 0.09949161243    0.01765280607    0.05120002652   0.04663507426   0.03242734357
 0.06519615149    0.007683772997   0.03248690579   0.04069056749   0.02941125194
 0.04196267409    0.1499494924     0.06855400119   0.1168974698    0.1391237644
 0.04520840578    0.003560368954   0.01939269376   0.01855355917   0.01223870709
 0.0335668273     0.002798615596   0.02577405026   0.03010767093   0.02236789344
 0.03578584795    0.0391971782     0.008618975005  0.02181885162   0.03035269095
 0.04224419163    0.09762034875    0.06164224624   0.08015874345   0.1073066127
 0.008611124911   0.0002815175452  0.0030000663    0.001892195114  0.000331247058
 0.006557702817   0.003295411264   0.004342637406  0.02597163382   0.01807911574
 0.03060261315    0.04686439134    0.05698468474   0.05636397127   0.06584842832
 0.05009356318    0.01833176015    0.04279652589   0.03313853213   0.02501786991
 0.01704009141    0.06882275987    0.08070344096   0.05559369715   0.0542896494
 0.0249888221     0.1417192442     0.06706225552   0.05921063648   0.06419219303
 0.0822362429     0.02028582311    0.04145395478   0.04089150857   0.02578496836
 0.004835477835   0.003212611986   0.002850891732  0.002377802709  0.001046043341
 0.05668438571    0.08640932651    0.09417887688   0.070346121     0.07888910197
 0.1234537235     0.009124480435   0.06908439966   0.05864130344   0.07095660664
 0.05103747495    0.02371371322    0.066896506     0.0859860346    0.07106121097
 0.02280292116    0.07682117012    0.04314459988   0.03601868752   0.03331648041
 0.01422491596    0.009372878269   0.01791752304   0.01396540465   0.007200264998
 0.02651232881    0.006955139351   0.009961546112  0.009628426464  0.007705852612
 0.0001821584116  0.01184029675    0.004674136445  0.001507058055  0.001290120121
 0.003146372564   0.0105155083     0.009132798515  0.006681290711  0.01509789222
 0.001506946859   0.0003146372564  0.003828813896  0.004336978181  0.002911487299

```

Explanation:

* `⎕ML←3`: set migration level to 3. (Among other things, this changes the behaviour of  from 'split' into 'partition', so we don't have to get rid of the linefeeds.)
* `W←83 ¯1⎕MAP'w'`: read the file `w` as a string of ASCII values, store it in `W`.
* `G←W⊂⍨10≠W`: partition `W` on linefeeds (character 10) and store the words in `G`.
* `(↓(L←⍳5)∘.≤≢¨G)/¨⊂G`: store the numbers 1 to 5 in `L`, and for each number, select those words from G which have at least that many letters.
* `L{`...: for each of the numbers 1 to 5, and the matching list of words,:
    + `⍺⌷¨⍵`: for each word, select the ⍺-th letter
    + `K←,∘≢⌸`: for each letter, find out how many times it occurs, store this in `K`.
    + `K[⍋⊃K`...`;]`: sort `K` by the value of the letter (so `a` is at the top, and `z` at the bottom).
    + `R←0 1↓`: drop the first column (the letter), leaving only the amount of times it occurred. Store this in R.
    + `R÷+⌿R`: divide the value for each letter by the total amount.
> 1 votes

---
Tags: code-golf
---


title: Interrupt handler call serializator

text:
# Question
Title: Interrupt handler call serializator
*The question uses C to formulate the problem, but solutions in any language can be accepted. At the end of the question you can find a pythonic version.*

As part of a bigger software, we have a C function:

```
void wrapper(void* p);

```

Which is a wrapper function around the C function:

```
void handler(void* p);

```

`wrapper()` is triggered by an external effect (hardware interrupt, unix signal, it doesn't matter), which also provides a `p` as its argument. The triggering can happen after the execution of any CPU instruction, *even if `wrapper()` or `handler()` is being executed*. The triggering happens similarly to the interrupt requests in a cpu, or to the signal handlers in unix: after `wrapper()` returns, the execution continues from exactly the same CPU state as the triggering found it.

We don't know what does `handler()`, but we know that it doesn't interact with the triggering mechanism.

As a help, we have

```
void swap(void **a, void **b);

```

which swaps the contents of two `void*` pointers in a single cpu instruction.

The solution of the problem is a `wrapper()` function, which "serializes" `handler()`: it makes sure, that `handler()` never is called in multiple times: every new `handler()` will be called only after the previous returned.

Trigger can't be lost: for every `wrapper()`, exactly one `handler()` must be called. It shouldn't be called from the same `wrapper()` which was actually triggered, but `p` can't be lost.

Similar solutions in practical situations often block the triggering for a short period, here it is impossible.

If needed, `malloc()`, `free()` and `NULL` (`==(void*)0`) can be used, but out of it, no library calls. These functions are considered reentrant (if triggering happens in them, they will work correctly). Especially any direct or indirect usage of any multithreading isn't allowed.

There is no speed criteria for `wrapper()`, but it must be ready in a finite time. We know, that the triggering won't happen so fast to cause some hardware/stack/etc. overflow. `wrapper()` must handle any deep of reentrancy.

Any language can be used for the task (incl. asm or interpreted languages), but no language construction or api calls which would make the task essentially easier, as in C.

*The `handler()` calls don't need to happen in the same order as their corresponding `wrapper()` was triggered.*

The solution is an implementation of `wrapper()`.

**Analogous problem in Python:**

Look for the signal handlers module in python (here). This what this problem is about. Essentially, we have a

```
def wrapper(p):
  ..the solution...

```

What is a wrapper around

```
def handler(p):
  ...we don't know what is here...

```

The execution of `wrapper` is triggered by an external event. It means, that it can happen *any time*, *even while we are in `wrapper` or in `handler`*. If the triggering event happens, `wrapper` will be called. After it returns, the normal program execution will continue. The task is to implement `wrapper` in a such way, that `handler` won't run multiple times in the same moment. I.e. the next `handler` will be called only after the previous returned, even if the triggering happens while the `wrapper`(s) of previous trigger(s) run.

No python API call or external module can be used, with the single exeception of a

```
def swap(a, b):

```

...which exchanges the values of `a` and `b` in a single instruction (equivalent of a `tmp = a; a = b; b = tmp`, but it does in a single moment, without a triggering would be happened).

*Bonus Python problem:* the internal Python functions which handles the lists, dicts, etc, *they all aren't reentrant*. This means, if you call `mylist.append()`, it is possible that the trigger will happen during the execution of the `append()` method. If another `wrapper()` or `handler()` try to do *anything* with a such list, your program will segfault and solution won't be accepted. The case is the same for every higher-level language. In short: *if you use \_any\_ higher level language construct, i.e. list/dict/object/etc, you need to make sure that it won't be used by any other `wrapper` which is triggered meanwhile.*

**The objective win criterion:**

Afaik, this is a hard problem. If anybody can find a solution, is already a big success (to me was it around a week to find one), and on my opinion, there won't be a big difference between the different results. But it is required here to have an "objective winning" criterion, and so, lets say "the shortest solution in bytes" is the winner.

# Answer
# C, 149 bytes

*Note:* *This seems to be a pretty controversial challenge, so I might be treading on thin ice here :)* *To make things clear, as far as I understand, the OP meant for the problem to be strictly single-threaded, which simplifies matters, since invocations of `wrapper()` can only interleave in an all-or-nothing fashion; if that's not the case, then this solution is wrong.* *The so called "interrupts" that trigger `wrapper()` are assumed to have the same semantics as C signals, as defined by the C standard, except that, as part of the hypothesis of the challenge, `malloc()` and `free()` can be called, and `swap()` can be used to access objects of type `void* volatile` with static storage duration, during the execution of their handler.* *(notwithstanding, the golfed version invokes all kinds of UB that aren't directly relevant to this challenge.)*

```
P B;wrapper(p){P c=malloc(8);P b=c,n=c;*c=0;c[1]=p;while(c=n){S;if(b)return*b=c;handler(c[1]);S;n=*c;free(c);}}

```

Compile with: `gcc -c -w -m32 "-DV=volatile" "-DP=int*V*V" "-DS=swap(&b,&B)" wrapper.c`.

Look below for a test program to link against.

(The calculated code size is the size of the snippet, and of the three `-D...` arguments, not including the quotes.)

## Ungolfed

We use a queue to store pending `handler()` invocations. Several queues may exist simultaneously, but at most one may be active at any given time. When `wrapper()` is invoked, if a queue is already active, we add an item at the back of the queue and return immediately. Otherwise, we start a new queue, and handle all of its items, until it empties; during the handling of a queue item (i.e., during an invocation of `handler()`), we make the queue active, so that nested invocations of `wrapper()` don't call `handler()` themselves; however, while fetching the next item, we deactivate the queue, so that nested invocations of `wrapper()` start their own queue, instead of modifying the one we're currently inspecting.

```
#include <stddef.h> /* NULL */
#include <stdlib.h> /* malloc(), free() */

void swap(void* volatile*, void* volatile*);
void handler(void* p);

/* Each queue item contains an argument, `p`, for the invocation of `handler()`,
 * and a pointer to the next item. The last item in the queue has a NULL `next`
 * pointer.
 */
struct queue_item {
    struct queue_item* volatile next;
    void* p;
};

/* Points to the last item in the currently active queue, or NULL if there is no
 * active queue.
 */
static void* volatile active_queue_back;

void wrapper(void* p) {
    struct queue_item* current;
    void* back;

    /* We allocate a new queue item for the current invocation of `handler()`.
     */
    current = malloc(sizeof(struct queue_item));
    current->next = NULL;
    current->p = p;

    /* We make the new item the back of the active queue, by assigning it to
     * `active_queue_back`, while at the same time fetching the previous value
     * of `active_queue_back`.
     */
    back = current;
    swap(&back, &active_queue_back);

    /* `back` now holds the previous value of `active_queue_back`. Since the
     * swap is atomic, no two interleaving invocations of `wrapper()` see the
     * same previous value, and no item is lost.
     */

    /* We check if there was an active queue prior to the current invocation of
     * `wrapper()`, that is, if the previous value of `active_queue_back` is not
     * NULL.
     */
    if (back != NULL) {
        /* If there was an active queue, we pass ownership over the new item
         * to the previously active queue (essentially making it active again,)
         * by linking it after the previous back of the queue. The owner of the
         * active queue is now responsible for handling, and disposing of, the
         * item, or, alternatively, for handing it over to someone further down
         * the line.
         */
        ((struct queue_item*) back)->next = current;

        /* Note that any reinvocation of `wrapper()`, following the preceeding
         * swap, will have added a queue item at the back of our newly allocated
         * one, directly or indirectly. Ownership over these items is
         * transitively passed to the owner of the active queue as well.
         */
    } else {
        /* If there was no active queue prior to this invocation, we take over
         * the queue, processing its items until it empties.
         */

        while (1) {
            struct queue_item* next;

            /* At the beginning of each iteration of the loop, we own the active
             * queue, `current` points to the current queue item (which is
             * initially the item created at the beginning of the function), and
             * `back` is NULL.
             */

            /* We can now call `handler()` for the value of `p` associated with
             * the current item. Note that any reinvocation of `wrapper()`,
             * from this point until the following swap, sees an active queue,
             * and therefore will not call `handler()` itself, but will rather
             * add an item at, ultimately, the back of our queue.
             */
            handler(current->p);

            /* In order to safely fetch the next item of the queue, we need to
             * make sure that no one else modifies the queue while we're at it.
             * To do that, we assign NULL to `active_queue_back` (recall that
             * `back` holds NULL at this point,) while fetching its current
             * value into `back`.
             *
             * Any reinvocation of `wrapper()`, from this point until the
             * following swap, will see no active queue, and hence will start
             * its own independent queue, process it until it empties, and leave
             * `active_queue_back` NULL again, before control returns to the
             * current invocation.
             */
            swap(&back, &active_queue_back);

            /* We free the current item and move on to the next one. If the next
             * item is NULL, we terminate the loop.
             */
            next = current->next;
            free(current);
            if (next == NULL) break;
            else current = next;

            /* We restore the previous value of `active_queue_back`, so that our
             * queue is active again. Recall that `active_queue_back` is NULL at
             * this point, so `back` becomes NULL after the swap.
             */
            swap(&back, &active_queue_back);
        }
    }
}

```

This program can be compiled with `gcc -c -m32 wrapper.c`, instead of the golfed version. (Since this version doesn't rely on any shenanigans, unlike the golfed one, it can be compiled without `-m32`; in this case, don't use `-m32` for the test program either.)

## Test Program

The following program is a very rudimentary test for `wrapper()`. It's not meant to be thorough, nor does it rely on completely defined behavior; rather, its main purpose to show `wrapper()` in action.

Compile with: `gcc -m32 -otest wrapper.o test.c`, in a POSIX environment.

Run with: `./test`.

The program triggers `wrapper()` upon receipt of SIGINT (usually, Ctrl + C), and has `handler()` print a message, and sleep for one second (during which SIGINT may be sent again). You can terminate the program by sending it SIGQUIT (usually, Ctrl + \\).

```
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <time.h>
#include <signal.h>
#include <unistd.h>

void wrapper(void* p);

void swap(void* volatile* a, void* volatile* b) {
    void* t = *a; *a = *b; *b = t;
}

void handler(void* p) {
    struct timespec tp;

    printf("handler(p = %tu) entered. Sleeping for 1 second...", (uintptr_t) p);
    fflush(stdout);

    tp.tv_sec = 1; tp.tv_nsec = 0;
    while (nanosleep(&tp, &tp));

    printf(" handler(p = %tu) returned.\n", (uintptr_t) p);
    fflush(stdout);
}

static void signal_handler(int signum) {
    static volatile sig_atomic_t n = 0;
    wrapper((void*) ++n);
}

int main() {
    struct sigaction sa = {};
    sa.sa_handler = signal_handler;
    sa.sa_flags = SA_NODEFER;
    sigaction(SIGINT, &sa, NULL);

    while (pause());
}

```
> 3 votes

---
Tags: code-golf
---


title: Lookup without conditional statements

text:
# Question
Title: Lookup without conditional statements
This challenge was inspired by programming an Arduino microcontroller. I have 6 LEDs and 6 buttons connected to various pins on the board. In the code, each button and LED is assigned an ID number (1-6). Pin numbers (ranging from 0-13) corresponding to the ID numbers are looked up using a `switch` statement. Purely for amusement, I was wondering if these `switch`es could be circumvented with an arithmetic/other function just to horrify future code maintainers.

## The challenge

Provide the function/functions that take the ID number (integer) as a parameter and return the pin number (integer) for the 6 LEDs and/or the 6 buttons, without using conditional statements (no `if`, no `switch` and no ternary).

Return values for LEDs:

```
ID    Pin
1      3
2      5
3      6
4      9
5     10
6     11

```

Return values for buttons:

```
ID    Pin
1      2
2      4
3      7
4      8
5     12
6     13

```

## Bonus challenge

Provide a single function that takes an ID number (integer) and second parameter (any type) indicating whether LED or button pins are requested, and returns the corresponding pin (integer).

## Rules

This is **not** an Arduino-specific challenge. Use **any language**, do **whatever** you want.

Edit: at the suggestion of *steveverril*, this is now a **code golf** challenge.

Good luck!

(If you're still reading: although patently absurd and arbitrary by programming standards, the mappings are based on the Arduino Micro's pinout. Pins 0 and 1 are reserved for serial communication, LEDs are assigned to the 6 lowest-numbered PWM-capable pins, buttons are assigned to remaining pins)

# Answer
# C, 28 bytes each

```
p(i){return"@cefijk"[i]&15;}
b(i){return"@bdghlm"[i]&15;}

```

This is basically the same as the answer by kirbyfan64sos, but uses a char array instead of integers, and has a dummy first byte so there is no need to subtract 1 from the function parameter.
> 10 votes

# Answer
# Haskell, 24 bytes each

```
l 1=3
l n=n+l(div(n+2)3)

```

to check:

```
> map l [1..6]
[3,5,6,9,10,11]

```

.

```
b 1=2
b n=n+b(div(n+1)2)

```

to check:

```
> map b [1..6]
[2,4,7,8,12,13]

```

## bonus, Haskell, 36 bytes

```
a f 1=f+2
a f n=n+a f(n+f+1`div`f+2)

```

to check:

```
> map (a 0) [1..6]
[2,4,7,8,12,13]
> map (a 1) [1..6]
[3,5,6,9,10,11]

```

0 for buttons, 1 for LEDs.
> 9 votes

# Answer
# C (math), 32 / ~~27~~ 26 bytes (45 for bonus challenge)

Several people have posted various table-lookup solutions, but that seemed to me like taking the easy way out.. I wanted to see how well I could do with purely mathematical operations:

```
p(i){return~i&1|i*2^i*!(i%5-1);}
b(i){return i/5*5+1^p(i);}

```

It wasn't clear whether one function calling the other was acceptable or not; if not, one can use this alternate definition of `b(i)` (33 bytes) instead:

```
b(i){return(i&1|i*2)+i/5-!(i/2);}

```

### Bonus Challenge (45 bytes):

```
f(i,t){return(i&1|i*2)+i/5-!(i/2)^t+i/5*5*t;}

```

(pass `t=0` for buttons, `t=1` for LEDs)
> 7 votes

# Answer
# C, 36 bytes each (49 bytes for the bonus challenge)

```
p(i){return 3500459>>(4*(7+~i))&15;}
b(i){return 2390221>>(4*(7+~i))&15;}

```

~~I'm sorry...I just couldn't help it...~~ Ok, I put a real solution now.

## Bonus challenge, 49 bytes

```
f(i,t){return(2390221+t*1110238)>>(4*(7+~i))&15;}

```

Use `f(button,0)` and `f(pin,1)`.

Live demo at Ideone.

## Originals:

```
p(i){int a[]={3,5,6,9,10,11};return a[i-1];}
b(i){int a[]={2,4,7,8,12,13};return a[i-1];}

```
> 5 votes

# Answer
# Pyth - 12 bytes each

Base encodes the array.

```
@jC"Ý"14tQ (buttons)
@jC"\r'"12tQ (leds)

```

The last one is actually twelve bytes except I can't write a carriage return so i escaped it.

Test Suite for Buttons.

Test Suite for LEDS.
> 4 votes

# Answer
# Pyth, Bonus only: 20 bytes

```
M@jC"5i«$xÍ"16+*6HtG

```

param#2 is 0 for LEDs, 1 for Buttons. To get Pin# for LED4,`g4 0`

I would have posted this as a comment to Maltysen's entry, but I just started, so lack the required reputation. I've just started using PYTH tonight, and admit that I shamelessly adapted his method of efficiently encoding a list.

If this was inappropriate, my deepest apologies, and I'll remove my entry.
> 3 votes

# Answer
# MIPS, 16 bytes

Bit shifting and bitmask. Input in `$a0`, output in `$v0`.

```
sll     $t0, $a0, 2
li      $t1, 0xba96530
srlv    $t0, $t1, $t0
andi    $v0, $t0, 0xf

```

For bonus, use immediate `0xdc87420`
> 2 votes

# Answer
# F#, 28+28 bytes

I wanted to try this without a lookup table.

```
let L x=1+x*2-x%4/3-x/5-x/6
let B x=x*2+x/3-x/4+x%6/5*2

```
> 2 votes

# Answer
# SWI-Prolog, 34 bytes each

```
l(I,P):-nth1(I,[3,5,6,9,10,11],P).
b(I,P):-nth1(I,[2,4,7,8,12,13],P).

```

`l/2` is for LEDs, `b/2` is for buttons.

### Bonus, 66 bytes

```
a(I,S,P):-nth1(I,[3:2,5:4,6:7,9:8,10:12,11:13],A:B),(S=0,P=A;P=B).

```

`S = 0` for LEDs, anything else for Buttons.
> 1 votes

# Answer
# q/k (18 bytes each)

Simply a case of indexing:

```
L:0N 3 5 6 9 10 11
B:0N 2 4 1 8 12 13

```

Example:

```
q) L[2]
5
q) B[6]
13

```

## Bonus (1 byte, given L & B defined)

```
@

```

Example:

```
q) @[`L;2]
5
q) @[`B;6]
13

```
> 1 votes

# Answer
# CJam, 10 bytes each

These are anonymous functions. The links to the online interpreter show then within a small test harness that executes the function for all input values.

Function 1 (LEDs):

```
{5*3|4+3/}

```

Try it online

Function 2 (buttons):

```
{_6|5+*5/}

```

Try it online

I wrote a small program that generates and evaluates these expressions. For both of them, it found a number of solutions with 8 characters (counting the expression only without the braces), but none with less.
> 1 votes

# Answer
# Javascript (ES6), 26/27 bytes

LEDs:

```
a=>`0
`.charCodeAt(a)

```

Buttons:

```
a=>`0\r`.charCodeAt(a)

```

If the above doesn't run (which is likely), here's a hexdump:

```
00000000: 6C 3D 61 3D 3E 60 30 03 - 05 06 09 0A 0B 60 2E 63 |l=a=>`0      `.c|
00000010: 68 61 72 43 6F 64 65 41 - 74 28 61 29 0A 62 3D 61 |harCodeAt(a) b=a|
00000020: 3D 3E 60 30 02 04 07 08 - 0C 5C 72 60 2E 63 68 61 |=>`0     \r`.cha|
00000030: 72 43 6F 64 65 41 74 28 - 61 29                   |rCodeAt(a)|

```

I couldn't get the second one to work with a raw CR so I had to use `\r`

### Bonus, 41 bytes

```
(a,b)=>`0
\r`.charCodeAt(a+b*6)

```

Hexdump

```
00000000: 28 61 2C 62 29 3D 3E 60 - 30 03 05 06 09 0A 0B 02 |(a,b)=>`0       |
00000010: 04 07 08 0C 5C 72 60 2E - 63 68 61 72 43 6F 64 65 |    \r`.charCode|
00000020: 41 74 28 61 2B 62 2A 36 - 29                      |At(a+b*6)|

```

Second parameter is 0 for LEDs, and 1 for buttons.
> 0 votes

# Answer
# JavaScript ~~113~~ ~~74~~ ~~66~~ ~~59~~ ~~52~~ 33 (one function)

Using bit shift to get 4bit values. Must be called with p(n, 195650864 or 231240736).

```
/*
  11   10    9    6    5    3
1011 1010 1001 0110 0101 0011 0000 = 195650864

  13   12    8    7    4    2
1101 1100 1000 0111 0100 0010 0000 = 231240736

                   b >> i * 4 xxxx
                         & 15 1111
                              yyyy (matching 1s)
*/
// Where b = 195650864 for pins and 231240736 for buttons.
function p(i,b){return b>>i*4&15}

```

Alternate.

```
/*
Using bitwise * 4 for bitwise only.
function p(i,b){return b>>(i<<2)&15}
*/

```
> 0 votes

# Answer
# Brainf\**k, 107 bytes

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

```

This being my first hand-coded BF program, I don't doubt that there are several optimizations to be made. But it's still awesome. :)

I'm not sure if `[]` counts as a conditional, though... :/
> 0 votes

# Answer
### POWERSHELL - 27-27-72

**LED use 1..6 as args**

```
:\>wc -c LED.PS1 & cat LED.PS1 & echo.& powershell -nologo -f LED.PS1 1
27 LED.PS1
(0,3,5,6,9,10,11)[$args[0]]
3

```

**button use 1..6 as args**

```
:\>wc -c button.PS1 & cat button.PS1 & echo.& powershell -nologo -f button.PS1 6
27 button.PS1
(0,2,4,7,8,12,13)[$args[0]]
13

```

**LED or BUTTON use b 1 ; l 2 ; b 6 ; l 5 etc as args**

```
:\>wc -c ledbutt.PS1 & cat ledbutt.PS1 & echo.& powershell -nologo -f ledbutt.PS1 b 5
72 ledbutt.PS1
$a=@{"b"=(0,3,5,6,9,10,11);"l"=(0,2,4,7,8,12,13)};$a[$args[0]][$args[1]]
10
:\>powershell -nologo -f ledbutt.PS1 l 5
12
:\>powershell -nologo -f ledbutt.PS1 b 3
6
:\>powershell -nologo -f ledbutt.PS1 l 2
4

```
> 0 votes

# Answer
# Octave, 40 bytes (bonus challenge)

Using an anonuymous function:

```
@(x,y)[3 2;5 4;6 7;9 8;10 12;11 13](x,y)

```

After defining this function, call this function as `ans(x,y)`, where `x` is the pin/button number and `y` indicates pin or button with values `1` and `2` respectively.

Try it online
> 0 votes

# Answer
# JavaScript(ES6) 18,22,44

**Edit** Shorter but boring

```
// LED
l=i=>1-~' 134789'[i]
// Buttons
b=i=>[,2,4,7,8,12,13][i]

// bonus
f=(i,t)=>1-~[' 134789',[,0,2,5,6,10,11]][t][i]

//Test

out=x=>O.innerHTML+=x+'\n'

for(i=1;i<=6;i++) out(i +' -> '+l(i) + ' '+b(i) +' '+f(i,0)+' '+f(i,1))
```

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

# Answer
# Perl 4 (37 and 31 bytes)

LEDs (37 bytes):

```
$c=pop;$c*2+($c~~[1,2,4,6]&&5.5<=>$c)

```

... but it uses a lookup table.

Buttons (31 bytes, no lookup):

```
$c=pop;2*($c+($c==5))+($c%3==0)

```
> 0 votes

# Answer
# Python, 31 Bytes Each

Not exactly creative or anything, but it works!

```
l=lambda x:int(" 3569AB"[x],16)
b=lambda x:int(" 2478CD"[x],16)

```

# Bonus, 44 Bytes

```
k=lambda x,y:int("3569AB2478CD"[x-1+6*y],16)

```

`y` should be 0 for LEDs, and 1 for buttons.
> 0 votes

# Answer
# Python, 60 + 58 = 118 bytes

```
p=lambda i:(2**i)*(i<3)+1+(i>2)*(5+3*(i-3))-(i>4)*(i-3+~i%2)
b=lambda i:2**i-(i>2)-(i>3)*(2**(i-1)-1)-4*(i>4)-15*(i==6)

```

These are awful. i don't even know what I'm doing here...

But they're pretty interesting nonetheless! :D
> 0 votes

# Answer
# Ruby, 45 Bytes

```
->i,t{[3,5,6,9,10,11,2,4,7,8,12,13][t*6+i-1]}

```

# Test Inputs:

```
->i,t{[3,5,6,9,10,11,2,4,7,8,12,13][t*6+i-1]}.call 1,0
=> 3

->i,t{[3,5,6,9,10,11,2,4,7,8,12,13][t*6+i-1]}.call 3,1
=> 7

```
> 0 votes

# Answer
# Forth, 26 bytes each, 34 for bonus

Similar to the C version by squeamish.

```
: P " CEFIJK" + C@ F AND ;
: B " BDGHLM" + C@ F AND ;

```

Bonus:

```
: A " CEFIJKBDGHLM" + + C@ F AND ;

```

Use 0 for LEDs and 6 for buttons. And the parameter order doesn't matter
> 0 votes

# Answer
# Pyth, 19 bytes each

```
L.&.>3500459*4-6b15
L.&.>2390221*4-6b15

```

For pins and buttons, respectively.
> -1 votes

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


# Question
Title: All possible orders of items of unknown type
This is code golf. Fewest bytes wins, only standard libraries, etc.

Write code, in any language, to output all possible same-length permutations of all items of an array / list / object in the input format and any order, grouped in whatever way you like. The items can be of ANY type, as allowed by the programming language.

Example input and output (inputting array, outputting array of arrays).
Inputs:

```
[1, 2, 3]

```

and outputs:

```
[
    [1, 2, 3],
    [1, 3, 2],
    [2, 1, 3],
    [2, 3, 1],
    [3, 1, 2],
    [3, 2, 1]
]

```

Code-Golf: Permutations reposts not allowed!

# Answer
> 5 votes
# Pyth, 3 bytes

```
.pQ

```

:D

Live demo.

---
Tags: code-golf
---


title: Draw an SQL Output Table

text:
# Question
Title: Draw an SQL Output Table
I'm sure most of us have seen SQL results in a terminal, all neatly formatted into rows and columns. If you haven't, here's an example:

```
+----------+-----------+----------------+
| column 1 | column 2  | column 3       |
+----------+-----------+----------------+
| data     | more data | even more data |
| etc      | just goes | on and on      |
+----------+-----------+----------------+

```

Your goal for this challenge is, given the columns and row data for a table, draw the table in this style. There should be a horizontal line at the top and bottom of the table, and one right below the header row. There should be vertical lines between every column, and one on both sides of the table. You should use pipes for vertical lines, hyphens for horizontal lines, and plusses for where they intersect.

## Specifics:

* The data can be entered via stdin, or as the argument to a function, but it must be in some form of string
* The data should be split by the string delimiter `;`
* The data will consist of only ASCII characters, is not quoted, and will not contain the delimiter.
* The first row of the data will be used for column headers
* The data will always have the same number of columns
* The input will always contain at least two rows (one header, one data). You do not have to handle empty sets.
* A trailing or preceding newline is permitted
* Each column should be as wide as the widest element, padding shorter elements on the right *(bonus -5% if you pad numbers on the left)*
* There should be 1 space of padding before and after the headers and data, except when the column is wider
* You are not allowed to use the actual `mysql` program to generate the table
* Standard loopholes apply

## Sample Input:

```
column 1;column 2;column 3
hello;world;test
longer data;foo;bar

```

## Output

```
+-------------+----------+----------+
| column 1    | column 2 | column 3 |
+-------------+----------+----------+
| hello       | world    | test     |
| longer data | foo      | bar      |
+-------------+----------+----------+

```

## Scoring:

Lowest number of bytes wins, of course. -5% bonus for padding numbers on the left (see specifics).

# Answer
# CJam, ~~67~~ 58 bytes

```
' qN/';f/ff+z_.{[z,):TS*'|+f.e|T'-*'++:T\(T@~T]}z{s_W=\N}/

```

Try it online in the CJam interpreter.
> 2 votes

# Answer
## JavaScript (ES6), 262 bytes

```
f=x=>{w=[],o=z=>y(`| ${z[m]((c,i)=>(c+' '.repeat(w[i]-c.length))).join` | `} |`),(d=x.split`
`[m='map'](r=>r.split`;`))[m](r=>r[m]((c,i)=>w[i]=Math.max(c.length,w[i]||0)));(y=console.log)(s=`+${w[m](c=>'-'.repeat(c+2)).join`+`}+`);o(d.shift());y(s);d[m](o);y(s)}

```

### Demo

Since it is ES6, this demo works in Firefox and Edge at this time. For some reason it does not work in Chrome/Opera even with experimental JavaScript features enabled.

```
// Snippet stuff
console.log = x => document.getElementsByTagName('output')[0].innerHTML += x + '\n';
document.getElementsByTagName('button')[0].addEventListener('click', () => {
  f(document.getElementById('I').value);
});

// Actual code
f = x => {
  w = [], o = z => y(`| ${z[m]((c,i)=>(c+' '.repeat(w[i]-c.length))).join` | `} |`), (d = x.split `
` [m = 'map'](r => r.split `;`))[m](r => r[m]((c, i) => w[i] = Math.max(c.length, w[i] || 0)));
  (y = console.log)(s = `+${w[m](c=>'-'.repeat(c+2)).join`+`}+`);
  o(d.shift());
  y(s);
  d[m](o);
  y(s)
}
```

```
<p>
  <textarea id=I cols=80 rows=15>column 1;column 2;column 3
hello;world;test
longer data;foo;bar</textarea>
</p>
<button type=button>Go</button>
<pre><output></output></pre>
```
> 2 votes

---
Tags: code-golf
---


title: Exchange the Stacks!

text:
# Question
Title: Exchange the Stacks!
# Exchange the Stacks!

Write a program that can exchange any character from two stacks. In this challenge, a stack is a tower of characters. An example stack is below:

```
1
a
4
d
*
c
3

```

There are two stacks involved in the challenge and both are inputted when the program runs. The program will also be given an argument of which position in Stack 1 to exchange with stack 2. So if the stacks look like this:

**STACK 1**

```
a
$
5
D
0
)
_

```

**STACK 2**

```
^
p
0
-
@
L
m

```

and the program is told to exchange position 2, the resulting stacks will look like this:

**STACK 1**

```
a
p
5
D
0
)
_

```

**STACK 2**

```
^
$
0
-
@
L
m

```

and the program should output them. The program should run with any stack size, not just 7, and should work with all standard characters (characters that are easily types at the keyboard, without using fancy stuff like Alt codes). Space is not required to work. Your program should accept three inputs: The contents of stack 1, the contents of stack 2 and the character to swap. Inside the program, I don't mind what form the stacks take, but when they are outputted, it must be in the form of each character separated by a newline. Input can be in any form.

## Scoring

This is and so the least bytes wins!

## Leaderboard

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

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

```
# Language Name, N bytes

```

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

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

```

```
var QUESTION_ID=57831;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),e.has_more?getAnswers():process()}})}function shouldHaveHeading(e){var a=!1,r=e.body_markdown.split("\n");try{a|=/^#/.test(e.body_markdown),a|=["-","="].indexOf(r[1][0])>-1,a&=LANGUAGE_REG.test(e.body_markdown)}catch(n){}return a}function shouldHaveScore(e){var a=!1;try{a|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(r){}return a}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading),answers.sort(function(e,a){var r=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0],n=+(a.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0];return r-n});var e={},a=1,r=null,n=1;answers.forEach(function(s){var t=s.body_markdown.split("\n")[0],o=jQuery("#answer-template").html(),l=(t.match(NUMBER_REG)[0],(t.match(SIZE_REG)||[0])[0]),c=t.match(LANGUAGE_REG)[1],i=getAuthorName(s);l!=r&&(n=a),r=l,++a,o=o.replace("{{PLACE}}",n+".").replace("{{NAME}}",i).replace("{{LANGUAGE}}",c).replace("{{SIZE}}",l).replace("{{LINK}}",s.share_link),o=jQuery(o),jQuery("#answers").append(o),e[c]=e[c]||{lang:c,user:i,size:l,link:s.share_link}});var s=[];for(var t in e)e.hasOwnProperty(t)&&s.push(e[t]);s.sort(function(e,a){return e.lang>a.lang?1:e.lang<a.lang?-1:0});for(var o=0;o<s.length;++o){var l=jQuery("#language-template").html(),t=s[o];l=l.replace("{{LANGUAGE}}",t.lang).replace("{{NAME}}",t.user).replace("{{SIZE}}",t.size).replace("{{LINK}}",t.link),l=jQuery(l),jQuery("#languages").append(l)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/,NUMBER_REG=/\d+/,LANGUAGE_REG=/^#*\s*([^,]+)/;
```

```
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>
```

# Answer
> 5 votes
# Python 3, 107 bytes

This account's first golf ;)

```
x,y,p=input(),input(),int(input())-1
print('\n'.join(x[:p]+y[p]+x[p+1:])+'\n'+'\n'.join(y[:p]+x[p]+y[p+1:]))

```

Takes input as three lines, the first being the first stack, the second line, the second stack and the third, the position.

Outputs the stack as separated by newlines.

# Answer
> 2 votes
# CJam, ~~16~~ 17 bytes

Didn't notice the position was 1-based. Fixed now, at the cost of 1 byte.

```
ll+_,2/li(_@+e\N*

```

Takes the input on three lines:

```
Stack 1
Stack 2
Position (1-based)

```

Also supports spaces in the stacks. Outputs the swapped stacks, one character per line.

Try it online.

# Explanation

```
ll+               e# Concatenate first two lines
   _,2/           e# Push half length (size of one stack)
       li(        e# Read third line as integer, subtract 1
          _@+     e# Sum a copy of the position with the stack size
             e\   e# Swap (position) <-> (position + stack size)
               N* e# Join with newline

```

# Answer
> 1 votes
# AutoIt, ~~135~~ ~~132~~ 129

```
$l=$CmdLine
$d=StringLen($l[1])
$b=$l[2]
$c=$d/2+$b
For $n=1 To $d
ConsoleWrite(StringMid($l[1],$n=$b?$c:$n=$c?$b:$n,1)&@LF)
Next

```

Run like this:

```
compiled.exe abccba 1

```

where `abccba` are both stacks concatenated and `1` is the switch position (1-based). Supports spaces and all unicode characters. Output:

```
c
b
c
a
b
a

```

# Answer
> 1 votes
# C#, ~~238~~ ~~222~~ 213 bytes

```
namespace System.Linq{class A{static void Main(string[]a){int n=int.Parse(a[2])-1;Console.Write(string.Join("\n",a[0].Select((x,i)=>i==n?a[1][n]:x))+"\n\n"+string.Join("\n",a[1].Select((x,i)=>i==n?a[0][n]:x)));}}}

```

To execute:

```
compiled.exe <stack 1> <stack 2> <index to exchange>

```

The stacks have to be inputted without separator between the stack items, e.g. `compiled.exe abcdef 123456 2`.

Thanks to Andrea Biondo for saving 25 bytes!

Ungolfed code:

```
using System;
using System.Linq;

namespace ExchangingStacks
{
    class Program
    {
        static void Main(string[] args)
        {
            string stack1 = args[0];
            string stack2 = args[1];
            int exchangeIndex = int.Parse(args[2]) - 1;
            var newStack1 = stack1.Select((x, index) => index == exchangeIndex ? stack2[exchangeIndex] : x);
            var newStack2 = stack2.Select((x, index) => index == exchangeIndex ? stack1[exchangeIndex] : x);
            Console.Write(string.Join("\n", newStack1) + "\n\n" + string.Join("\n", newStack2));
        }
    }
}

```

# Answer
> 1 votes
# PowerShell, 81 Bytes

```
param([char[]]$a,[char[]]$b,$n);$n--;$t=$b[$n];$b[$n]=$a[$n];$a[$n]=$t;$a;"`n";$b

```

Holy Dollar Signs, Batman! 16 of the 81 characters (~20%) are `$`.

The input is expected to be literal-string delimited and space-separated, thanks to the very liberal input requirements. If one of the input stacks includes the `'` character, it will need to be escaped with a backtick. Example of the input from the question:

```
.\exchange-the-stacks.ps1 'a$5D0)_' '^p0-@Lm' 2

```

Pretty simple char-array manipulation. PowerShell, by default, when "executing" an array, will print each item on its own line, so simply `$a` will output each element newline-separated, hence why this is so competitive with other non-golfing languages, as we don't need to specially format the output.

---
Tags: code-golf
---


title: Find the nearest clock hands

text:
# Question
Title: Find the nearest clock hands
**Challenge**

Given a number of seconds past midnight, output the smallest angle between any two hands on a clock face, using as few bytes as possible.

You may assume that the number of seconds is always less than 86400. Angles may be represented in degrees or radians.

A reference solution is at: http://ideone.com/eVdgC0

**Test Cases** (results in degrees)

```
0 -> 0
60 -> 0.5
600 -> 5
3600 -> 0
5400 -> 45
6930 -> 84.75
50000 -> 63.333

```

**Clarificarions**

* The clock has 3 hands: hours, minutes and seconds.
* All hands move continuously, thus hour and minute hands can be found between graduations on the clock face.

# Answer
# CJam, ~~36~~ ~~35~~ ~~34~~ ~~32~~ 30 bytes

```
riP*30/_60/_C/]2m*::-:mc:mC$3=

```

The output is in radians. I've verified the solutions for all 86400 possible inputs.

Try it online in the CJam interpreter.

### Idea

Since  radians is a full lap, each minute/second interval on the clock is **2π/60 = π/30** radians wide.

Thus, dividing the number of seconds by **π/30** yields the position of the second hand.

The minute hand moves at one sixtieth of the pace of the second hand, so dividing the result from above by **60** yields the position of the minute hand.

Likewise, dividing the last result by **12** yields the position of the hour hand.

Note that our three quotient from above are not necessarily in the range **\[0,2π).**

By calculating all nine possible differences of the hands' angles, we obtain three **0**'s (angular distance between a hand and itself) and the six distances between the different hands.

If the closest hands are on a half that does not include **12**, one of the differences from above will be the desired output (mod ).

However, at **01:55:30** (for example), the hour hand is at an angle of 1.008 rad (57.75 deg) and the minute hand at an angle of 5.812 rad (333.00 deg) from **12**, giving a difference of 4.804 rad (275.25 deg). By subtracting this result from a full lap, we obtain the angle measured "in the other direction", which equals 1.479 rad (84.75 rad).

Now, rather than mapping each angle **θ** in **\[0,2π)** and conditionally subtracting the result from **π**, we can simply calculate **arccos(cos(θ))**, since **cos** is both periodic and even, and **arccos** always yields a value in **\[0,π)**.

Skipping over the three smallest results (all zero), the fourth smallest will be the desired output.

### Code

```
ri                             e# Read an integer from STDIN.
  P*30/                        e# Multiply by π and divide by 30.
       _60/                    e# Divide a copy by 60.
           _C/                 e# Divide a copy by 12.
              ]2m*             e# Push the array of all pairs of quotients.
                  ::-          e# Replace each pair by its difference.
                     :mc       e# Apply cosine to each difference.
                        :mC    e# Apply arccosine to each cosine.
                           $3= e# Sort and select the fourth smallest element.

```

## Alternate version (34 bytes)

```
rd6*_60/_C/]360f%2m*::m360X$f-+$6=

```

The output is in degrees and no trigonometric functions are used.

Try it online in the CJam interpreter.
> 10 votes

# Answer
# Mathematica, 40 bytes

```
Min@Abs@Mod[#{11,708,719}/120,360,-180]&

```

Explanation: Let `t` be number of seconds since midnight. The position of each hand is

```
hour: t/120 (mod 360)
min:  t/10 (mod 360)
sec:  6t (mod 360)

```

To calculate the absolute angular distance between `x` degrees and `y` degrees, we can mod `y - x` by 360 into the range `[-180, 180]` and then take the absolute value. (Note that there is no restriction on `x` and `y`.) So this function just calculates the pairwise differences `t/10-t/120`, `6t-t/10`, and `6t-t/120` and does that.
> 9 votes

# Answer
## Python, 65

```
lambda n,l={720,60,1}:6*min((n/x-n/y)%60for x in l for y in{x}^l)

```

The distance traveled by the hour, minute, and second hand, in units of 1/60 of the circle are `h,m,s = n/720, n/60, n/1`. We can take these mod 60 to get their position on the circle from `0` to `60`.

If we take their difference mod 60, we get the number of units that one is in front of the other. We take all six possible differences, find the min, then multiply by `6` to rescale to `360` degrees.

The two-layer list comprehension first chooses the first hand as represented by `720`, `60`, or `1`, then chooses the other hand out of that set with the first choice removed via set xor.

I tested this exhaustively against the reference code.
> 7 votes

# Answer
# C#, 163 152 bytes

This creates every hand twice to count for wrap-around, then loops through every combination and finds the minimum angle between hands. Calculations are performed in 60 divisions, then multiplied by 6 to get degrees.

Indented for clarity:

```
float F(int s){
    float b=60,c;
    float[]a={c=s/b/b%12*5,c+b,c=s/b%b,c+b,s%=60,s+b};
    for(s=36;s-->0;)
        b=s%6!=s/6&(c=(c=a[s%6]-a[s/6])<0?-c:c)<b?c:b;
    return b*6;
}

```

Example output:

```
    0 seconds, 00:00:00, smallest angle is 0°
43200 seconds, 12:00:00, smallest angle is 0°
86399 seconds, 23:59:59, smallest angle is 0.09164429°
 3330 seconds, 00:55:30, smallest angle is 54.75°
39930 seconds, 11:05:30, smallest angle is 60.25001°
21955 seconds, 06:05:55, smallest angle is 65.49998°
21305 seconds, 05:55:05, smallest angle is 59.50001°
 5455 seconds, 01:30:55, smallest angle is 75.45831°
41405 seconds, 11:30:05, smallest angle is 44.95834°

```
> 6 votes

# Answer
# TI-BASIC, 17 bytes

```
min(cos⁻¹(cos(ΔList(Ans{6,.1,5!⁻¹,6

```

Uses Dennis's `arccos(cos(` to normalize distances; however, rather than calculating all pairwise distances, it only calculates the three needed using `ΔList([seconds],[minutes],[hours],[seconds]`.

This program expects `Degree` mode and returns the answer in degrees.

EDIT: `5!` is one byte shorter than `120`.
> 2 votes

---
Tags: code-golf, arithmetic, geometry
---


title: Is this a candidate Calvin Number?

text:
# Question
Title: Is this a candidate Calvin Number?
This challenge is a tribute to our Legendary Challenge Writer™, Calvin's Hobbies — now renamed to Helka Homba —, in the same spirit as Generate Dennis Numbers.

Calvin is a pretty impressive contributor to PPCG, with the 6th most reputation overall and probably indisputibly the best challenge writing skills out of all of us. However, of course, for this challenge, we will focus on his user ID.

26997 might not look very interesting at first. In fact, it's *almost* interesting in a few ways. For example, here's a chart of `26997 mod <n>` for certain values of `n`:

```
n   |  26997 % n
----+-----------
3   |  0
4   |  1
5   |  2
6   |  3
7   |  5 :(
8   |  5
9   |  6
10  |  7

```

However, 26997 is one of the few numbers that can be represented by `(n * 10)<sup>n</sup> - n`, where `n` is an integer \> 0.

Here are the first few numbers which can be expressed in this way, which we will henceforth call *Calvin Numbers*:

```
9
398
26997
2559996
312499995
46655999994
8235429999993
1677721599999992
387420488999999991
99999999999999999990
28531167061099999999989
8916100448255999999999988
3028751065922529999999999987
1111200682555801599999999999986
437893890380859374999999999999985
184467440737095516159999999999999984
82724026188633676417699999999999999983
39346408075296537575423999999999999999982
19784196556603135891239789999999999999999981
10485759999999999999999999999999999999999999980

```

These *Calvin Numbers* have some interesting properties. More patterns emerge when we right-align them and highlight all the `9`s:

The ones that we're interested in for this challenge are:

* Regardless of `n`, every *Calvin Number* ends with `10<sup>n</sup> - n`.

So, Calvin(1) ends with `9`, Calvin(2) ends with `98`, and the pattern continues `997`, `9996`, `99995`, etc., with each successive *Calvin Number* counting down and adding an extra `9` to the beginning.
* For values of `n` where `n % 10 == 0` (i.e. `n` is divisble by 10), Calvin(n) ends with `10<sup>2n</sup> - n`.

That is, the pattern extends for twice as many digits as normal, with an extra number of `9`s at the beginning equal to `n`.
* When `n` is a power of `10` (`10`, `100`, `1000`, etc.), the pattern extends even further—every single digit is either a `9` or a `0`.

This pattern is the following: `(n + 1) * 10<sup>n</sup> - n` nines, and `n` zeroes. This is easier to understand in a chart (your solution will only have to handle numbers up to 10000 anyway, so this is all you need):

```
n      |  Calvin(n)
-------+-----------------------
10     |  19 nines, 1 zero
100    |  298 nines, 2 zeroes
1000   |  3997 nines, 3 zeroes
10000  |  49998 nines, 4 zeroes

```

The number of nines even exhibits several properties of *Calvin Numbers* itself, but that's too much detail for this challenge.

## Challenge

*Calvin Numbers* get far too big, far too quickly, for a "get the nth *Calvin Number* challenge to be feasible in languages without arbitrary-precision integers. Therefore, the challenge is to determine whether a number fits the above patterns—that is, whether a number is a "candidate Calvin Number" or not.

Here are the criteria for a number to be considered a *candidate Calvin Number* (hereafter referred to as a CCN for short):

* It ends with a number that fits the pattern `10<sup>n</sup> - n` for an integer `n`.

So, to be a CCN, a number must end with 9, or 98, or 997, 9996, 99995, etc.
* If the last digit is `0`, it must also end with `10<sup>2n</sup> - n`, for the same `n` as in the previous point.

This means that `12312312399999999999999999999999999999999999980` is not a CCN, but `10485759999999999999999999999999999999999999980` is (it's the correct one, in fact).
* If the value of `n` in the previous two steps is a power of 10, the entire number must fit the third pattern described above.

## Input / Output

The input will be provided as a string, and it will always represent a number that is less than `Calvin(10000) + 10000` (which can also be expressed as `10<sup>50000</sup>`). (To clarify, the greatest possible input is 50000 nines, and the least possible input is `1`.)

The output should be a truthy value if the input represents a number which is a CCN, and a falsy value otherwise. For the definitions of these terms, see meta.

## Test cases

Inputs that should result in a truthy value:

```
9
26997
99999999999999999990
437893890380859374999999999999985
10485759999999999999999999999999999999999999980
[encoded data, 4654 characters]

```

Inputs that should result in a falsy value:

```
1
26897
79999999999999999990
437893890380859374299999999999985
12312312399999999999999999999999999999999999980
[encoded data, 4660 characters]

```

## Rules

* You may *not*, at any point in your program, handle integers larger than `18446744073709551615` (`2<sup>64</sup>`), if your language has support for arbitrary-precision integers (or number types with a high enough precision to allow storing numbers greater than this).

This is simply to prevent solutions that loop through all possible *Calvin Numbers* (or all possible values of `10<sup>n</sup> - n`).
* This is , so the shortest code in bytes will win.

# Answer
# Racket, 353

```
(require srfi/13)(let([s(~a(read))])(for/or([n(range 1 999)])(and(let*([y(string-length(~a n))])(string-suffix?(string-append(make-string(-(if(=(modulo n 10)0)(* 2 n)n)y)#\9)(~r #:min-width y #:pad-string"0"(-(expt 10 y)n)))s))(let([n(inexact->exact(/(log n)(log 10)))])(or(not(integer? n))(string-prefix?(make-string(-(*(+ 1 n)(expt 10 n))n)#\9)s))))))

```

Accepts a number from stdin, outputs `#t` or `#f`.

**Ungolfed version:**

```
(require srfi/13)

(define (calvin? str)
  (for/or ([n (in-range 1 10001)])
    (and (10^n-n$? n str)
         (or (not (integer? (/ (log n) (log 10))))
             (expt-of-ten-check? n str)))))

(define (10^n-n$? n str)
  (let* ([div-by-ten? (zero? (modulo n 10))]
         [digits (string-length (~a n))]
         [nines (- (if div-by-ten? (* 2 n) n) digits)]
         [suffix (string-append (make-string nines #\9)
                                (~r #:min-width digits #:pad-string "0" (- (expt 10 digits) n)))])
    (string-suffix? suffix str)))

(define (expt-of-ten-check? n str)
  (let* ([n (inexact->exact (/ (log n) (log 10)))]
         [nines (- (* (add1 n) (expt 10 n)) n)]
         [prefix (make-string nines #\9)])
    (string-prefix? prefix str)))

```

I normally don't do code golf, and Racket certainly isn't the most suitable language for it, but nobody had answered yet, so I figured I'd give it a shot. ;)
> 9 votes

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


title: Extended Domino Dots

text:
# Question
Title: Extended Domino Dots
## Introduction

Classes have started! And so does the boredom. I decided to doodle in my notebook and started to draw some dots in (IMO) an aesthetically pleasing way. I came up with these numbers:

based on these conditions:
Given (n, m)
1) There must be *n* dots
2) All dots must lie on an *m* by *m* lattice
3) The position of the dots must minimize the spread\* from the top left corner
4) The configuration of the dots must be diagonally symmetric as pictured:

\*Spread (in this context) is defined as the sum of the distances from the top left dot position (whether or not there is a dot there). For example, the spread of the example above is 0 + 1 + 2 + 1 + √2 + 2 + 2√2 = 6 + 3√2

## The Challenge

Come up with an algorithm using that uses *natural numbers* n and m (where it will always be that n \<= m^2) to *generate* a configuration of dots that follow all the rules above.

**Input** can be received via STDIN, command-line argument, or function parameter.

**Output** the pattern to STDOUT or return a string with newlines. Any two different characters may be used in the output. (e.g.

```
110
100
000

```

is the same as

```
**-
*--
---

```

**Shortest Code in Bytes Wins**

## Example

STDIN: `6 3`
STDOUT:

```
***
**_
*__

```

# The Challenge has Ended!!!

After seven days I decided to declare the winner, but first some special awards!
Fastest code goes to... orlp with his submission in Pyth !
Slowest code goes to... orlp with his submission in Pyth !
Most straightforward code goes to... orlp with his submission in Pyth !
Most confusing code goes to... orlp with his submission in Pyth !
Longest Code goes to... orlp with his submission in Pyth !

## And last but not least

**Shortest code goes to......... orlp with his submission in Pyth !**

Congratulations!

# Answer
# Pyth, 37 bytes

```
jc:*d*QQiRQhos.aMNf.Am}_dTT.c^UQ2vzNQ

```

Slow solution. Generates all possible pairs of \[0, m), generate all possible n-combinations of those pairs (without repetition). Filter each combination of pairs such that if P is in the combination, so is `reverse(P)`. This guarantees diagonal symmetry. Sort by the sum of distances to the origin. Decode the pairs of numbers as base-m numbers, giving a list of indices. Create a string of spaces except for those indices, putting quotation marks instead. Finally chop into m pieces and join by newlines. Creates outputs like such:

```
""""
"""
""
"

```
> 3 votes

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