title: Pandigital Doubling

text:
# Question
Title: Pandigital Doubling
*Inspired by this CMC*

Given a positive integer greater than 0, perform the following operation on it:

* If all ten single digits (`1234567890`) are in the number at least once, output the count and exit the program
* Otherwise, double the number and repeat, incrementing the count.

The count starts at 0 and is the number of times the input was doubled. For example, if the input were 617283945, it would need to be doubled once because 1234567890 has all 10 digits in it.

This is a so shortest code wins. Input may be taken as a string, if you want.

## Test cases

```
input => output

617283945 => 1
2 => 67
66833 => 44
1234567890 => 0
100 => 51
42 => 55

```

# Answer
# Python 3, 39 bytes

```
f=lambda n:len({*str(n)})<10and-~f(n*2)

```

Try it online!

Outputs `False` for `0`.
> 6 votes

# Answer
# 05AB1E, ~~11~~ 10 bytes

-1 byte thanks to scottinet

```
[D9ÝåË#·]N

```

Try it online! or as a Test Suite

```
[          // Start infinity loop
 D         // Duplicate current value (or input)
  9Ý       // Push [0,1,2,3,4,5,6,7,8,9]
    å      // Does each exist in the current value
     Ë#    // Break if all equal (if every digit exists)
       ·   // Else double the current value
        ]N // End loop and print the number of times through the loop

```
> 4 votes

# Answer
# , ~~24~~ 23 bytes

```
(]1&(+$:)2**)10>#@~.@":

```

Try it online!

## Explanation

```
(]1&(+$:)2**)10>#@~.@":  Input: integer n
                     ":  Format as string
                  ~.@    Unique
                #@       Length
             10>         Less than 10
           *             Multiply, gives n if previous was true, else 0
         2*              Multiply by 2
 ]                       Get the previous condition
  1&(   )                Execute this if true on 2n, else return 0
      $:                   Recurse
  1  +                     Add 1

```
> 4 votes

# Answer
# Perl 6, ~~31~~ 28 bytes (27 chars)

*-3 bytes thanks to @Joshua*

```
{($_,2×*...*.comb.Set>9)-1}

```

Try it online!

**Explanation:** Still the same construct to recursively generate lists. The first element is the given number (`$_`), each next element is 2 times the previous (`2×*` — we use ×, because, although 2 byte character, it's still 1 byte cheaper than `2 * *`), and we do this until the end condition of `*.comb.unique>9` is satisfied, i. e. when there is more than 9 unique characters in the number. (Technically, we break the string down to a list of characters with `.comb`, force it to a set with `.Set` (of course, Sets contain each element only once), and compare with 9, which forces the set into numerical context, which in turn gives its number of elements.)

Finally, we subtract 1 from this list. Again, the list is forced into numerical context, so what we return is 1 less than the length of that list.
> 3 votes

# Answer
# JavaScript (ES6) + big.js, ~~84~~ ~~74~~ ~~73~~ 70 bytes

*Thanks @ConorO'Brien for saving 10 bytes by suggesting big.js instead of bignumber.js*
*Thanks to @Rick Hitchcock for -1 byte*
*Thanks to @Shaggy for -3 bytes*

```
f=n=>[..."4"+2**29].every(d=>RegExp(d).test(c=Big(n)))?0:1+f(c.mul(2))

```

Takes input as string; supports up to around 269 due to automatic scientific notation conversion occurring beyond that point.

## Test Snippet

```
f=n=>[..."4"+2**29].every(d=>RegExp(d).test(c=Big(n)))?0:1+f(c.mul(2))

;[617283945, 2, 66833, 1234567890, 100, 42].forEach(t=>console.log(`f(${t}) = `+f(t)))
```

```
<script src="https://cdn.rawgit.com/MikeMcl/big.js/c6fadd08/big.min.js"></script>
```

## Infinite range, ~~106~~ ~~88~~ ~~87~~ 84 bytes

By using the config option to effectively disable scientific notation when converting numbers to strings, we can have nearly infinite range.

```
f=n=>[..."4"+2**29].every(d=>RegExp(d).test(c=Big(n)),Big.E_POS=1e9)?0:1+f(c.mul(2))

let num = `${Math.random()*1e6|0}`.repeat(100)
O.innerText=`f(\n${num}\n) = ${f(num)}`
```

```
<script src="https://cdn.rawgit.com/MikeMcl/big.js/c6fadd08/big.min.js"></script>
<pre id=O style="width:100%;white-space:normal;overflow-wrap:break-word"></pre>
```
> 3 votes

# Answer
# Jelly, ~~12~~, 11 bytes

```
QLn⁵
ḤÇÐ¿L’

```

Try it online!

> *Gotta go fast!*

Explanation:

```
        # Helper link, takes one argument 'z'
Q       # The unique digits of 'z'
 L      # Length
  n     # Does not equal
   ⁵    # 10
        #
        # Main link
  Ð¿    # While <condition> is true, run <body> and return all intermediate results
        # Condition:
 Ç      #   The helper link
        # Body:
Ḥ       #   Double the input
        # Now we have a list of all the 'z's that we passed to the helper link
    L   # Return it's length
     ’  # minus one

```
> 2 votes

# Answer
# , 43 bytes

```
f=:(,$:@+:@{.)`[@.(9<[:#@~.10&#.inv)
<:@#@f

```

Try it online!

Defines an anonymous function. Collects results quite suboptimally. Check out miles's superior answer here!
> 2 votes

# Answer
# Haskell, 46 bytes

```
f n|all(`elem`show n)['0'..'9']=0|1<3=1+f(2*n)

```

Try it online!
> 2 votes

# Answer
# Clojure, ~~115~~ ~~89~~ 82 bytes

-26 bytes by just using a string to represent the list of characters (duh, in retrospect), and changing from using recursion to `loop`, which allowed me to make a couple of optimizations.

-7 bytes by getting rid of the call to `bigint`. Apparently we only need to handle input that won't cause an overflow.

```
#(loop[n % c 0](if(empty?(remove(set(str n))"1234567890"))c(recur(* 2 n)(inc c))))

```

Pregolfed:

```
(defn pan [num]
  (loop [n num
         cnt 0]

    ; Remove all the characters from the stringified input
    ;  that are numeric. If the result is an empty list, all
    ;  the numbers were present.
    (if (empty? (remove (set (str n)) "1234567890"))
      cnt
      (recur (* 2 n) (inc cnt)))))

```
> 2 votes

# Answer
## Haskell, 44 bytes

```
until(\c->all(`elem`show(n*2^c))['0'..'9'])(+1)0

```
> 2 votes

# Answer
# Retina, 85 bytes

```
^\d*
$&¶$&
D`.(?=.*¶)
\d{10}¶\d+|\d*¶

[5-9]
#$&
T`d`EE
T`_d#`d_`\d#
#
1
}`\d\b
$&@
@

```

Try it online! Link includes test cases. Slightly optimised for run time. Explanation:

```
^\d*
$&¶$&

```

Duplicate the input number.

```
D`.(?=.*¶)

```

Deduplicate the digits in the first copy.

```
\d{10}¶\d+|\d*¶

```

If 10 digits remain, delete both numbers, otherwise just delete the first copy. Note that deleting both numbers causes the rest of the loop to no-op.

```
[5-9]
#$&

```

Place a `#` before large digits.

```
T`d`EE

```

Double each digit.

```
T`_d#`d_`\d#

```

Add in the carries.

```
#
1

```

Deal with a leading carry.

```
}`\d\b
$&@

```

Append an `@` and loop until all 10 digits are found.

```
@

```

Print the number of `@`s added.
> 2 votes

# Answer
# Java 8, ~~132~~ ~~110~~ ~~87~~ 74 bytes

```
n->{int c=0;for(;(n+"").chars().distinct().count()!=10;n*=2)c++;return c;}

```

-57 bytes thanks to *@OlivierGrégoire*.

**Explanation:**

Try it here. (Note: test case for `2` is disabled because it should stop at 268, but the size of `long` is limited to 263-1.)

```
n->          // Method with long parameter and integer return-type
  int c=0;   //  Count-integer, starting at 0
  for(;(n+"").chars().distinct().count()!=10;
             //  Loop (1) as long as the unique amount of digits in the number are not 10
    n*=2)    //    After every iteration: multiply the input by 2
   c++;      //   Increase the count by 1
             //  End of loop (1) (implicit / single-line body)
  return c;  //  Return the counter
}            // End of method

```

---

Old **132 bytes** answer using a `String` input and regex:

```
n->f(n,0)int f(String n,int c){String t="";for(int i=0;i<10;t+="(?=.*"+i+++")");return n.matches(t+".*")?c:f(new Long(n)*2+"",c+1);}

```

Try it here. (Note: test case for `2` is disabled because it causes a StackOverflowException due to slightly too much recursion.)

The total regex to check if the String contains all 9 digits becomes `^(?=.*0)(?=.*1)(?=.*2)(?=.*3)(?=.*4)(?=.*5)(?=.*6)(?=.*7)(?=.*8)(?=.*9).*$`, which uses a positive look-ahead for the entire String.
> 2 votes

# Answer
# APL (Dyalog Unicode), 19 + 2 = 21 bytes

```
0∘{∧/⎕D∊⍕⍵:⍺⋄⍺+1∇2×⍵}

```

Try it online!

This is a dyadic `Dfn` (**d**irect **f**unctio**n**), taking 0 as its left argument and the integer as the right. Since the input is supposed to be only the integer, I added 2 bytes for the argument `0∘` to the byte count.

`f←` is not included in the byte count, since it's not *necessary*. It just makes it easier to build the test cases.

### How it works:

**The headers:** I removed those from the byte count after some chatting in the APL room, since the function does what it's supposed to do and the results are only incorrect because of the default settings of APL's REPL.

`⎕FR←1287` Sets the **F**loat **R**epresentation to 128-bit decimal (7 is the code for decimal in APL's REPL). `⎕PP←34` Sets the **P**rint **P**recision to 34 digits. Both of these are needed, since APL's default representation for big numbers transforms them to scientific notation (e.g. 3.14159265359E15) which messes up the code big time.

```
0∘{∧/⎕D∊⍕⍵:⍺⋄⍺+1∇2×⍵} ⍝ Dyadic Dfn
0∘                     ⍝ Fixes 0 as the left argument
          :            ⍝ If
     ⎕D                ⍝ String representation of all digits [0, 9]
       ∊               ⍝ "is in"
        ⍕⍵             ⍝ String representation of the input
   ∧/                  ⍝ AND-reduction. Yields 1 (true) iff all digits are in the right argument.
           ⍺           ⍝ return the left argument
            ⋄          ⍝ Else
                 2×⍵   ⍝ Double the right arg
             ⍺+1       ⍝ increment the left arg
                ∇      ⍝ Recursively call this function with the new arguments.

```
> 2 votes

# Answer
# Husk, 10 bytes

```
←Vö>9Lud¡D

```

Try it online!

### Explanation

```
        ¡D    Repeatedly double the input, collecting results in a list
 V            Return the first index where the following is true
     L          The length of
       d        the digits
      u         with duplicates removed
  ö>9           is greater than 9
←             Decrement (as Husk uses 1-indexing)

```
> 1 votes

# Answer
# Mathematica, ~~59~~ ~~48~~ ~~47~~ ~~46~~ 38 bytes

*-9 bytes thanks to Jenny\_mathy.*

```
If[!FreeQ[DigitCount@#,0],#0[2#]+1,0]&

```

Try it online using Mathics!
> 1 votes

# Answer
# PowerShell, ~~70~~ 69 bytes

```
for($n=[bigint]$args[0];([char[]]"$n"|group).count-le9;$n*=2){$i++}$i

```

Try it online!

*(Nearly twice as long as the Python answer :-\ )*

Takes input `$args[0]`, casts it as a `[bigint]`, saves it to `$n`. Enters a `for` loop. Each iteration we check against whether the `$n`umber converted to a string then to a `char`-array, when `Group-Object`'d together, has a `.count` `-l`ess than or `e`qual to `9`. Meaning, the only way that it equals 10 is if at least one digit of every number `1234567890` is present. If yes, we exit the loop. If not, we `$n*=2` and continue. Each iteration inside the loop, we're simply incrementing `$i`. When we exit the loop, we simply output `$i`.

Note that for input like `1234567890` where every digit is already accounted for, this will output nothing, which is a falsey value in PowerShell, and equivalent to `0` when cast as an `[int]`. If that's not OK, we can simply put a `+` in front of the output `$i` to explicitly cast it as an integer.

*Saved a byte thanks to Roland Heath.*
> 1 votes

# Answer
# , 74 bytes

```
function(x){while(!all(0:9%in%el(strsplit(c(x,""),"")))){F=F+1;x=2*x};F*1}

```

Try it online! Note that R will give the wrong answer to `f(2)` due to limitations of how the language stores large integers.

Explanation: For the test of pandigitality, the input is coerced to a character vector by joining with an empty string and then split into individual digits. We then check whether all of 0:9 are present in the resulting vector; if not, we increment the counter, double the input and repeat.

The counter uses F which initialises as FALSE. To make sure it is coerced to numeric, we multiply by one before returning.
> 1 votes

# Answer
# Ruby, ~~46~~ ~~45~~ ~~39~~ 38 bytes

```
def f n;n.digits.uniq[9]?0:1+f(n*2)end

```

Try it online!

Updates:

1. -1 by using `def f n;` instead of `def f(n);`.
2. -6 by using `…[9]` instead of `….size==10`
3. -1 by removing a semicolon
> 1 votes

# Answer
# q/kdb+, 33 bytes

**Solution:**

```
(#)1_{x*2 1 min!:[10]in 10 vs x}\

```

**Examples:**

```
q)(#)1_{x*2 1 min!:[10]in 10 vs x}\[100]
51
q)(#)1_{x*2 1 min!:[10]in 10 vs x}\[1234567890]
0
q)(#)1_{x*2 1 min!:[10]in 10 vs x}\[42]
55

```

**Explanation:**

All the bytes are in the equality, might be able to golf this one down a little further. Utilises q's `scan` adverb:

```
count 1_{x*2 1 min til[10] in 10 vs x}\ / ungolfed solution
        {                            }\ / scan over this lambda until it yields same result
                              10 vs x   / convert to base 10
                           in           / left list in right list, returns boolean list
                   til[10]              / range 0..9
               min                      / return the minimum of the list, 0 or 1
           2 1                          / list (2;1) indexed into with 0 or 1
         x*                             / return x multiplied by either 2 or 1
      1_                                / 1 drop, drop one element from front of list
count                                   / count the length of the list

```

**Notes:**

If we drop to the `k` prompt then we can have a 25 byte solution. Converts the number to a list of characters:

```
q)\
  #1_{x*2 1@&/($!10)in$$x}\[100]
51

```
> 1 votes

# Answer
# Pyth, 11 bytes

```
f>l{`.<QT9Z

```

Test suite.

First natural number `T` where `input << T` meets the requirement.
> 0 votes

# Answer
# Perl 5, 52 + 1 (-p) = 53 bytes

```
$/=10;for$i(0..9){$/-=/$i/}$_*=2;++$\;$/&&redo}{$\--

```

Try it online!
> 0 votes

# Answer
# Perl, 43 + 1 bytes

```
for$x(0..9){$_*=2,++$\,redo LINE if!/$x/}}{

```

Using the `-p` flag. This builds on the solution provided by Xcali above.
> 0 votes

# Answer
# **Swift 4**, 111 bytes

```
func p(_ x:Int,_ c:Int=0)->Int{if !(String(Set(String(x)).sorted())=="0123456789"){return p(x*2,c+1)};return c}

```

Note: Won't work for x = 2, because of overflow.

Explanation - Input x is first typecasted to string. Then Set() removes the repeating characters. Then it is sorted to match the result. If it doesn't match, x is doubles and counter is incremented.
> 0 votes

# Answer
# Japt, 15 bytes

```
LÆ*2pXÃbì_â Ê¥A

```

Try it

---

## Explanation

Implicit input of integer `U`.

```
LÆ    Ã

```

Create an array of integers from `0` to `99` and pass each through a function where `X` is the current element.

```
*2pX

```

`U` multiplied by 2 raised to the power of `X`.

```
b

```

Get the index of the first element thay returns true when passed through the following function.

```
ì_â

```

Split to an array of digits and remove the duplicates.

```
Ê¥A

```

Get the length of the array and check for equality with `10`.

---

## Alternative, 15 bytes

```
@*2pX)ìâ sÊ¥A}a

```

Try it

---

### Explanation

Implicit input of integer `U`.

```
@            }a

```

Starting with `0`, return the first number that returns true when passed through the following function, with `X` being the current number.

```
*2pX)

```

As above, multiply `U` by 2 to the power of `X`.

```
ìâ

```

Split to an array of digits, remove duplicates and rejoin to an integer.

Convert to a string, get the length and convert back to an integer.

```
¥A

```

Check for equality with `10`.
> 0 votes

# Answer
# GNU dc, 61 bytes

Input is copied from top of stack (which must be otherwise empty); output is pushed to top of stack.

```
[I~1r:ad0<s]ss[d1+r;a1=p]sp[d2*lfx]sh[0Sadlsxlpx11!=h]dsfxz1-

```

## Explanation

We use the array variable `a`, storing a 1 in `a[d]` if digit `d` is present, otherwise falling back to 0 there. We use the GNU extension `~` to obtain quotient and remainder in a single command.

```
# populate a[0-9] from the digits
[I~1r:ad0<s]ss

# check pandigit
# return 1 more than lowest unset element of a[]
# start with stack=0
[d1+r;a1=p]sp

# Test for pandigit; double and repeat if needed
[dd+lfx]sh
[0Sadlsxlpx11!=h]dsfx

# We left one value on the stack for each doubling, plus the original
z1-

```

As a bonus, this will work in arbitrary number bases (not only decimal): simply set the input radix as required (the constant `11` in the definition of `f` will be read using that number base, so is automatically correct).

## Test

```
for i in 617283945 2 66833 1234567890 100 42
do
    printf '%s => ' $i
    dc -e $i \
       -e '[I~1r:ad0<s]ss[d1+r;a1=p]sp[dd+lfx]sh[0Sadlsxlpx11!=h]dsfxz1-' \
       -e p
done

```

```
617283945 => 1
2 => 67
66833 => 44
1234567890 => 0
100 => 51
42 => 55

```
> 0 votes

# Answer
## REXX, 57 bytes

```
arg n
do b=0 while verify(0123456789,n)>0
  n=n*2
  end
say b

```
> 0 votes

---
Tags: code-golf, math, number, integer
---


title: It's a rainy day

text:
# Question
Title: It's a rainy day
# Context

> It's Valentines Day. The only one you ever loved left you yesterday for this guy she always found *"stupid and uninteresting"*. On your way home, you've been stuck in traffic, listening to old songs on the radio, the rain hitting the windscreen is rocking you. After a while in your car, you find yourself alone in your small apartment being unable to think of something else but her. There is no light and you stare trough the window, letting darkness surrounds you. There is no one to talk to, your friends are now gone a long time ago after warning you about this new girl haunting your mind. You start up your computer, as it's the only thing you can do, open your browser and post a new programming puzzle to stackexchange, in an attempt to change your mind.

# Challenge

Write a program in the language of your choice simulating the rain which falls on the ground. The output can be composed of ASCII characters or 2D/3D rendered. The camera is fixed : you are above looking straight to the ground. Your program must includes some kind of animation like refreshing the console or the page each time you generate a new "frame". It has to be realistic, I know it's a bit subjective but let's say you can't just fill all the ground in only one big drop.

The output don't have to be an image but if you're using cryptic language it's better to provide a .gif to illustrate how it looks in action (but of course, it will not affect your score if you don't).

# Rules

* Your score is the total of bytes used
* -20 points if you use colours
* -50 if you achieve to render some kind of wind
* Lowest score wins

# Example

A very basic example of what should be rendered:

I hope you'll do better and enjoy this challenge.

*Sorry for my english, feel free to edit my post if you want to correct some errors*

# Leader board

If your name is not listed it's because your attempt has been considered not fitting the rules.

```
Tobia - APL - 35
j6m8 - Processing.js - 38
The Guy with The Hat - Processing - 42
ace - Processing - 74
kelunik - JS/CSS - 89
Riot - Bash - 91
Michael - JS/jQuery - 105
Florent - HTML/JS - 123
David Carraher - Mathematica - 134
Doorknob - HTML/JS - 150
undergroundmonorail - Python - 175

```

Congratulations to Tobia !

# Answer
> 26 votes
# APL, 105 chars/bytes\* – 20 – 50 = 35 score

```
e←{⍞←∊'␛['⍵}
e¨'36m' '?25l' '2J'
{⍵←3⌊⍵+3×0=?t⍴50
⍵{(⍵c)←⍕¨⍵+1
e⍵';'c'H',' .∘⍟'[⍺]}¨⍳t
∇0⌈⍵-1}0⍴⍨t←24 80

```

\*: Most APL implementations support some form of (legacy) single-byte charset, that maps APL symbols to the upper 128 byte values. Therefore, for the purpose of golfing, a program **that only uses ASCII characters and APL symbols** can be scored as chars = bytes.

I tested it on Nick's latest apl.js on Node.js in an OS X terminal. But I haven't used anything specific to his dialect, so it should work on any modern APL that can be run on an ANSI terminal and supports d-funs `{...}`, strand assignment `(a b)←...`, and commute , such as Dyalog for Linux or for Raspberry PI (with `⎕IO←0`)

The  in line 1 is a literal escape character (which is 1 byte). You can input it using `Ctrl-V` `Esc` in a Linux terminal or in Vim, or supposedly something like `Alt-027` in Windows. Also, I couldn't find a reliable way to discover the terminal size, so you might want to edit the number of rows and columns at the end of the last line.

I defend the 50 bonus by the fact that each raindrop goes through the following shapes: `⍟∘.` which give the impression of a slight downwards wind, given that the scene is being looked at from above. In fact, looking at the gif below, you should get the impression that each drop is gently moving downwards and to the left, before disappearing on the ground.

**Ungolfed version:**

```
e←{⍞←∊"␛["⍵}                  # utility to print escape sequence
e¨'36m' '?25l' '2J'            # set cyan, hide the cursor and clear screen
{                              # repeat (⍵=current board of raindrops)
  ⍵←3⌊⍵+3×0=?t⍴50              #   add some new drops (=3) in random places
  ⍵{                           #   print the drops (⍺=drop value, ⍵=coords)
    (r c)←⍕¨⍵+1                #     convert the coordinates to string
    e r';'c'H',' .∘⍟'[⍺]       #     print or clear the drop
  }¨⍳t                         #   ..
  ∇0⌈⍵-1                       #   remove 1 from every drop and repeat
}0⍴⍨t←24 80                    # ..starting with an empty board

```

**Output:**

---

# APL, different style

Out of competition.

```
m←×/t←1+(ζη)←2×(βγ)←24 80
e←{⍞←∊(⎕UCS 27)'['⍵}
s←{⍵[β-1-⍳β;1+⍳γ]}
p←{⍺{e'H'⍺,⍨{⍺,';',⍵}/⍕¨⍵}¨(,s⍵)/,1+⍳βγ}
e¨'2J' '36m' '?25l'
{'/'p⍵←(200<m÷?t⍴m)∨0⍪⍵[⍳ζ;1+⍳η],0
' 'p(~⍵)∧0,⍵[1+⍳ζ;⍳η]⍪0
'.∘°'[?(+/,sδ)/3]pδ←⍵∧~d←.2<m÷⍨?t⍴m
∇⍵∧d}t⍴0

```

Here my aim was to give the impression of raindrops falling with a slant and accumulating on the ground, while trying to keep the number of visible drops (either falling or splattered) constant on average. The trick was to create a number of new falling drops `/` at every cycle and having the falling drops "wipe out" any splattered ones they travel across.

The result is strangely reminiscent of the Matrix code.

**Output**
(the jerk every 5s is the gif looping)

# Answer
> 42 votes
# Bash: 111 bytes - 20 = 91 points!

A contemplative gentle drizzle in your terminal. Adjust the numbers 819 and 41 for different height and width respectively.

```
e='printf \e';while :;do for i in {0..819};do((RANDOM<9))&&$e[1\;36m.||$e[1C;((i%41<1))&&$e'
';done;$e[20A;done

```

A pleasant bonus is the way the cursor pitter-patters across the rain area.

Edit: shortening from 140 bytes to 129 bytes thanks to @manatwork's suggestions. 2nd edit: shortening from 129 bytes to 111 bytes thanks to @manatwork's and @Tobia's suggestions, plus additional inspiration - see comments.

(Note: screenshot shows previous less-golfed version of the code, which is functionally identical)

# Answer
> 39 votes
## Python, 312 bytes - 50 (wind) = 262

```
from pygame import*
R=__import__('random').randint
t,u=640,480;init();d=display;s=d.set_mode((t,u))
w=[255]*3;r=range(t)
a=[[R(0,t),R(0,u),R(3,6)]for i in r]
while time.wait(9):
 d.flip();event.get();s.fill(R(0,99)<1and w)
 for i in r:x,y,z=a[i];draw.line(s,w,(x,y),(x+z,y+2*z));a[i][0]=(x+z)%t;a[i][1]=(y+z*2)%u

```

Sample output (a 50-frame loop):

Actual playpack is significantly faster than gifs allow.

# Answer
> 35 votes
# HTML / JS, 170 chars - 20 = 150 points

```
<canvas id=c></canvas><script>d=400;with(c)width=height=d,t=getContext('2d');t.fillStyle='blue';setInterval("t.fillRect(Math.random()*d,Math.random()*d,5,5)",50)</script>
```

(sidenote: golfed further by passing a string to `setInterval`, `with`, automatic ID variable names... it feels so wrong! *shudders*)

It just draws random blue rectangles.

# HTML / JS, 309 chars - 20 - 50 = 239 points

Now with wind!

```
<canvas id=c></canvas><script>s=400;r=Math.random;with(c)width=height=s,t=getContext('2d');t.fillStyle='blue';o=[];setInterval("t.clearRect(0,0,s,s);for(i=0;++i<o.length;)d=o[i],t.fillRect(d[0],d[1],d[2],d[2]),d[0]+=1,d[1]+=2,d[2]-=1,d[2]<0?o.splice(i,1):0;if(r()<.6)o.push([r()*400,r()*400,20])",50)</script>
```

# Answer
> 33 votes
## JS + jQuery (172-20-50 = 102)

Copy/Paste that line in the browser console (generally press F12 key) :

```
r=Math.random;w=$(window);setInterval("$('<b>♥</b>').css({color:'red',position:'fixed',top:r()*w.height(),left:r()*w.width()}).appendTo('body').animate({fontSize:0},3e3)",9)

```

Animated red hearts rain for Valentine's day !

# Answer
> 26 votes
# Mathematica

134 - 20 = 114

## 2D

```
n = 99; m = Array[0 &, {n, n}]; r := RandomInteger[{1, n}, {2}]
Table[ArrayPlot[m = ReplacePart[m, r ->  1], ColorRules -> {1 -> Blue}], {k, 250}];
Export["d.gif", d]

```

---

## 3D

The raindrop shape is made via a revolution plot around the z axis.

Initially, rain is generated for a region that extends well above the display region. The appearance of falling rain is achieved by shifting the Viewpoint upwards along the z-axis. (It is more efficient than recalculating the position of each raindrop.)

```
r = RandomInteger; z = Table[{r@30, r@30, r@160}, {100}];
w = RevolutionPlot3D[{.7 Sin[x] Cos[x], 0,   1.4 Sin[x] }, {x, 0, -Pi/2},
PerformanceGoal -> "Speed"][[1]];
c = Map[Translate[w, #] &, z];
p = Table[Graphics3D[c, PlotRange -> {k, k + 50}], {k, 1, 100}]
Export["p.gif", p]

```

---

## With Wind

There is considerable overhead to making the rain fall with wind. But I'm including here anyway.

The blue floor pretty much keeps {x,y} view region confined to the area of interest. There are some glitches, but, oh well,

```
r = RandomInteger;
z = Table[{r@120, r@30, r@180}, {800}];
w = RevolutionPlot3D[{.7 Sin[x] Cos[x], 0,   1.4 Sin[x] }, {x,
     0, -Pi/2}, PerformanceGoal -> "Speed"][[1]];
c = Map[Translate[w, #] &, z];
g[k_, z1_, w_, c1_] :=
 Module[{z2},
  z2 = Cases[z, {x_, _, _} /; 0 + k < x < 30 + k];
  c = Map[Translate[w, #] &, z2];
  Graphics3D[{Polygon[{{0 + k, 0, 1 + k}, {30 + k, 0, 1 + k}, {30 + k,
        30, 1 + k}, {0 + k, 30, 1 + k}}], c},
   PlotRange -> {k, k + 50}]]

p = Table[g[k, z, w, c], {k, 1, 100, 1}];
Export["p.gif", p]

```

---

## From Directly Above

The closest raindrops are clipped but I'll overlook that.

```
m=40;
r=RandomInteger;
positions=Table[{r@m,r@m,r@1000},{800}];
g[lowZ_,pos_]:=
Module[{hiZ=lowZ+103},
Graphics3D[{PointSize[Small],White,Point[{{0,0,lowZ},{0,m,lowZ},{m,0,lowZ},{m,m,lowZ},{0,0,hiZ},{0,m,hiZ},{m,0,hiZ},{m,m,hiZ}}],
ImageSize-> 350,Sphere/@Cases[pos,{_,_,z1_}/;lowZ<z1<hiZ-2]},PlotRange->{lowZ,hiZ},
ViewPoint-> {0,0,1},ImagePadding->5]]

```

# Answer
> 10 votes
# HTML / JavaScript, 156 123 (143 - 20)

```
<body bgcolor=0 onload="t=c.getContext('2d');t.fillStyle='#07d';setInterval('n=Math.random()*4e4;t.fillRect(n%270,n/150,1,1)',1)"><canvas id=c>
```

Annotated version:

```
<body bgcolor="#000">
<canvas id="c"></canvas>
<script>
  onload = function() {
    // Retrieve the rendering context
    t=c.getContext('2d');
    // Set rain color
    t.fillStyle='#07d';
    // Render whenever it is possible
    setInterval(function() {
      // Generate a number between 0 and 40,000
      // 40,000 ~= 270 * 150
      n=Math.random()*4e4;
      // Draw a raindrop.
      // Since x and y are not rounded, the raindrop looks blurry!
      t.fillRect(n%270,n/150,1,1)
    }, 1);
  };
</script>
</body>

```

# Answer
> 7 votes
# Smalltalk (Smalltalk/X)

with random wind ;-)

```
|BG CLR N1 H W v WIND drops gen newDrops draw remove move buffer|

BG := Color black.
CLR := Color blue lightened.
H := 100.
W := 100.
N1 := 10.
WIND := 0.
drops := OrderedCollection new.

gen := [:n | ((1 to:n) collect:[:i | Random nextIntegerBetween:1 and:W] as:Set) collect:[:x | x@0]].
newDrops := [drops addAll:(gen value:N1)].
draw := [buffer fill:BG; paint:CLR. drops do:[:d | buffer displayPoint:d]].
remove := [drops := drops reject:[:d | d y > H]].
move := [:wind | drops := drops collect:[:d| (d x + wind)\\W @ (d y + 1)]].
v := View new openAndWait.
buffer := Form extent:(v extent) depth:24 onDevice:v device.

[
    [v shown] whileTrue:[
        draw value.
        v displayForm:buffer.
        move value:WIND.
        remove value.
        newDrops value.
        WIND := (WIND+(Random nextBetween:-1 and:1)) clampBetween:-5 and:5.
        Delay waitForSeconds:0.1.
    ]
] fork.

```

output in view:

# Answer
> 6 votes
## Processing, 94 - 20 = 74

```
void setup(){background(0);fill(0,0,255);}
void draw(){ellipse(random(0,99),random(0,99),3,3);}

```

(New line added for readability.)

Click here for an online demo.

# Answer
> 5 votes
# Bash

```
while true;do echo " / / / / /";echo "/ / / / / ";done

```

I'm not sure this should be a code golf because there isn't a strict requirement on what the "rain" must look like.

EDIT: If you want it to look like the camera is pointing straight down use this:

```
while true;do echo " . . . . .";echo ". . . . . ";done

```

# Answer
> 3 votes
## Python 2.7: 195 - 20 = 175

I'm sure there's more that can be done here, but this is what I've got for now:

```
import os,time
from random import*
l=[i[:]for i in[[' ']*100]*50]
while 1:
 os.system('clear')
 l[randint(0,49)][randint(0,99)]='.'
 print'\033[94m\n'.join(''.join(r)for r in l)
 time.sleep(.05)

```

I'll post a gif of the output when I remember how to do that.

This works on linux. Replacing `'clear'` with `'cls'` makes it work on windows, but then ANSI colours don't work and I lose the bonus.

I have a 2D array of one-character strings, initialized to . Every 0.05 seconds, one of them is chosen at random set to `.`, and the screen is redrawn.

`from random import*` saves two characters over `import os,time,random` and using `random.randint()` twice, though I'm not convinced that's the best way to choose a cell anyway. I wanted to use `random.choice()` but I couldn't think of a way around immutable strings that wouldn't waste more characters than it saved.

# Answer
> 2 votes
# 132 + 27 - 20 - 50 = 89

# Javascript (132)

```
r=Math.random;setInterval("$('body').append($('<i>∘</i>').css({left:r()*2e3,top:r()*2e3}).animate({left:'+=70',fontSize:0},500))",1)

```

# CSS (27)

```
i{color:blue;position:fixed

```

Demo: http://jsfiddle.net/kelunik/5WC87/4/embedded/result/

# Answer
> 1 votes
# Processing, 62 - 20 = 42

```
void draw(){stroke(0,0,214);point(random(0,99),random(0,99));}

```

Generates blue pixels on a white background. Demonstration in a very similar language here: https://www.khanacademy.org/cs/rain2/6172053633761280

# Answer
> 1 votes
# Processing.js, 86 - 20 = 66

...but it also slowly fades out (the ground absorbs the rain, naturally). Points for that?

```
g=99;r=random;void draw(){fill(0,9);rect(0,0,g,g);fill(0,g,r(g));rect(r(g),r(g),2,2);}

```

Bonus features include varying between greenish and blueish (it's clearly dirty 'city' rain).

Also, I was very pleased that I got to use a JavaScript hack in here; Note that, because this is processing.*js*, you can throw in things like the typeless declaration of g=99, or the alias of `r` for `random` (cross-language alias!).

Any other ideas to minify?

## Readable version:

```
g = 99;
r = random;                  // Javascript trickery
void draw() {
    fill(0, 9);
    rect(0, 0, g, g);        // Fade the background
    fill(0, r(g), r);
    rect(r(g), r(g), 2, 2);  // Add a new drop
}

```

The whole thing can be viewed here.

## ...plus another version without fade: 58 - 20 = 38

If you don't like fading and don't mind grey dirt:

```
r=random;void draw(){fill(0,0,255);rect(r(99),r(99),2,2);}

```

# Answer
> 1 votes
# Tcl/Tk, 139 - 20 = 119

Reusing my own answer http://codegolf.stackexchange.com/a/143018/29325

***Must be run in the interactive shell***

```
gri [can .c -w 40 -he 40]
set x 0
wh 1 {.c cr o $x [set y [exp int(rand()*40)]] $x [set x $y] -f #[form %06x [exp int(rand()*255**3)]]
upd}

```

Unfortunately, converting `expr int(rand()*` into a `proc` makes the script have one byte more!

To stop, one just needs to click the ineffable "X" button.

---
Tags: code-golf
---


title: Bitwise XOR of rational numbers

text:
# Question
Title: Bitwise XOR of rational numbers
## Introduction

Every rational number between 0 and 1 can be represented as an eventually periodic sequence of bits. For example, the binary representation of 11/40 is

```
0.010 0011 0011 0011 ...

```

where the `0011` part repeats indefinitely. One way of finding this representation is the following. Start with **r = 11/40**, then repeatedly double it and take the fractional part, recording when it goes above 1. When the value of **r** repeats, you know you have entered a loop.

```
1. r = 11/40
2. 2*r = 11/20 < 1   ->  next bit is 0, r = 11/20
3. 2*r = 11/10 >= 1  ->  next bit is 1, r = 2*r - 1 = 1/10
4. 2*r = 1/5 < 1     ->  next bit is 0, r = 1/5
5. 2*r = 2/5 < 1     ->  next bit is 0, r = 2/5
6. 2*r = 4/5 < 1     ->  next bit is 0, r = 4/5
7. 2*r = 8/5 >= 1    ->  next bit is 1, r = 2*r - 1 = 3/5
8. 2*r = 6/5 >= 1    ->  next bit is 1, r = 2*r - 1 = 1/5, same as in 4.
   The loop 5. -> 6. -> 7. -> 8. now repeats.

```

To get from the binary string back to 11/40, you can use the formula

```
(int(prefix) + int(suffix)/(2^len(suffix) - 1)) / 2^len(prefix)

```

where `prefix` is the initial part `010`, `suffix` is the repeating part `0011`, and `int` converts a binary string to integer.

Given two such representations, we can perform the bitwise XOR operation on them. The resulting sequence will also be periodic, so it represents a rational number.

For some rational numbers, there are two binary representations.

```
1/4 = 0.010000000...
    = 0.001111111...

```

The choice between them can affect the result of the bitwise XOR. In these cases, we use the former representation, which has infinitely many 0s.

## The task

Your inputs are two rational numbers in the half-open interval \[0,1). Your output shall be the result of the bitwise XOR operation applied to the inputs, expressed as a rational number. Note that the output can be 1, even though neither of the inputs are.

The exact formats of input and output are flexible, but each rational number should be represented by two integers, the numerator and denominator (with the exception of 0 and 1, which can be represented as `0` and `1` if desired). You can assume that the inputs are expressed in lowest terms. The output **must** be expressed in lowest terms. A built-in rational number type is an acceptable format, as long as it satisfies these restrictions. You can ignore any bounds on integers imposed by your language, but your algorithm should theoretically work for all rational numbers.

The lowest byte count wins. Standard rules apply.

## Example

Consider the inputs 11/40 and 3/7. We write their representations one above the other, delimiting the repeating parts by pipes `|`. Then we extract repeating parts of equal lengths, and apply bitwise XOR to them and the parts before them.

```
11/40 = 0. 0 1 0|0 0 1 1|0 0 1 1|0 0 1 1|0 0 1 1|0 0 1 1|0 0 1 1|0 0 1 ...
3/7   = 0.|0 1 1|0 1 1|0 1 1|0 1 1|0 1 1|0 1 1|0 1 1|0 1 1|0 1 1|0 1 1|...
     -> 0. 0 0 1|0 1 0 1 1 1 1 0 1 0 0 0|0 1 0 1 1 1 1 0 1 0 0 0|0 1 0 ...

```

The resulting rational number is 89/520.

## Test cases

```
0 0 -> 0
1/2 1/2 -> 0
1/2 1/4 -> 3/4
1/3 2/3 -> 1
1/2 3/4 -> 1/4
5/8 1/3 -> 23/24
1/3 1/5 -> 2/5
15/16 3/19 -> 257/304
15/16 257/304 -> 3/19
3/7 11/40 -> 89/520
5/32 17/24 -> 59/96
16/29 16/39 -> 621001733121535520/696556744961512799

```

# Answer
# Python 3, 193 164 bytes

```
def x(a,b,z=0):
 l=[]
 while(a,b)not in l:l+=[(a,b)];z=2*z|(a<.5)^(b<.5);a=a*2%1;b=b*2%1
 p=l.index((a,b));P=len(l)-p
 return((z>>P)+z%2**P*a**0/~-2**(P or 1))/2**p

```

Takes input as Python 3's `fractions.Fraction` type, and outputs it as well.

Fun fact (you can easily show this using generating functions), if you change `(a<.5)^(b<.5)` to `((a>=.5)and(b>=.5))` above you get the binary AND between two rational numbers. Call this `nd(a, b)`. Then we have `a + b - 2*nd(a, b) = x(a, b)`!
> 4 votes

# Answer
# JavaScript, 141 bytes

```
(p,q,r,s)=>(h=(v,u)=>v%u?h(u,v%u):[a/u,b/u])(b=(g=x=>x%q||x%s?g((x|x/2)+x%2):x)(1),a=(o=b/(b-(b&~-b)),x=p*b/q,y=r*b/s,(x%o^y%o)+(x/o^y/o)*o))

```

Wont work for last test case (integer overflow). Input 4 numbers for `p/q xor r/s`, output an array with two numbers. For testcase `0, 0`, you should input `0, 1, 0, 1`.

**How:**

(All numbers described here is in binary form.)

1. find the smallest number `b`, which `b = 10 ^ p - 10 ^ q (p, q are integers, p > q); and b = 0 (mod q); and b = 0 (mod s)`;
2. Let `x = p * b / q`, `y = r * b / q`; Convert `p / q`, `r / s` to `x / b` and `y / b`;
3. Let `o = 10 ^ (p - q) - 1`; split `x`, `y` to `[x % o, x / o]`, `[y % o, y / o]`; get xor for each part `[x % o xor y % o, x / o xor y / o]`, and join back to `(x % o xor y % o) + (x / o xor y / o) * o`; Donate it as `a`;
4. If `a = 0`, the answer is `0` (or `0 / 1`); Otherwise let `u = gcd(a, b)`; the answer is `(a/u)` and `(b/u)`.

```
f=

(p,q,r,s)=>(h=(v,u)=>u%v?h(u%v,v):[a/v,b/v])(b=(g=x=>x%q||x%s?g((x|x/2)+x%2):x)(1),a=(o=b/(b-(b&~-b)),x=p*b/q,y=r*b/s,(x%o^y%o)+(x/o^y/o)*o))
```

```
<div oninput="[v5.value,v6.value]=['?','?'];[v5.value,v6.value]=f(+v1.value,+v2.value,+v3.value,+v4.value)">
<input id=v1 />/<input id=v2 /> xor <input id=v3 />/<input id=v4 /> = <output id=v5></output> / <output id=v6></output>
<style>input{width:40px}</style>
</div>
```
> 2 votes

---
Tags: code-golf, rational-numbers, bitwise
---


title: Levenshtein distance & OEIS (Robbers)

text:
# Question
Title: Levenshtein distance & OEIS (Robbers)
This is the Robber post. The Cop post is here.

---

Your task is to take an integer input **N** and output the **Nth** digit in the sequence OEIS A002942.

The sequence consists of the square numbers written backwards:

```
1, 4, 9, 61, 52, 63, 94, 46, 18, 1, 121, 441, ...

```

Note that leading zeros are trimmed away (**100** becomes **1**, not **001**). Concatenating this into a string (or one long number gives):

```
1496152639446181121441

```

You shall output the **Nth** digit in this string/number. You may choose to take **N** as 0-indexed or 1-indexed (please state which one you choose).

### Test cases (1-indexed):

```
N = 5,      ==> 1
N = 17,     ==> 1   <- Important test case! It's not zero.
N = 20,     ==> 4
N = 78,     ==> 0
N = 100,    ==> 4
N = 274164, ==> 1

```

Your code should work for numbers up to **N = 2^15** (unless your language can't handles 32 bit integers by default, in which case **N** can be lower).

---

## Robbers:

You should try to crack the Cops' posts.

Your code must be in the same language as the Cop post, and have a Levenshtein distance exactly equal to the distance given by the cop. Your code cannot be longer than the original solution (but it can be the same size).

You may check the Levenshtein distance here!

The winner will be the robber that cracked the most posts.

# Answer
> 4 votes
# Haskell, Laikoni

```
((show.(*1).read.reverse.show.(^2)=<<[1..])!!)

```

Try it online!

The `(*1)` was necessary for type checking.

# Answer
> 3 votes
# JavaScript, Arnauld

```
/*ZZ*/m=>[...Array(m+1).keys()].map(eval(atob("eD0+K1suLi4iIit4KnhdLnJldmVyc2VgYC5qb2luYGA="))).join``[m]

```

# Answer
> 2 votes
# cQuents 0, Stephen

```
":\r$$

```

Try it online! I have no idea how this code works, but it still worked after removing the `*`.

# Answer
> 2 votes
# Wolfram Language (Mathematica), Jenny\_mathy

```
(Join@@Table[k@FromDigits@Reverse@(k=IntegerDigits)[i*i],{i,10^4}])[[#]]&

```

Try it online!

Alternative version also at distance 43:

```
(Join@@IntegerDigits@IntegerReverse[Range@#^2])[[1#]]&

```

Try it online!

# Answer
> 2 votes
# 6502 Machine Code (C64), Felix Palmen

I tested this with all the questions test cases and quite a few extras (like 2^15... that took awhile), and it appears to work the same as the original with LD = 1.

```
00 C0 20 FD AE A0 00 99 5B 00 C8 20 73 00 90 F7 99 5B 00 A2 0B CA 88 30 09 B9
5B 00 29 0F 95 5B 10 F3 A9 00 95 5B CA 10 F9 A9 01 A0 03 99 69 00 88 10 FA A0
20 A2 76 18 B5 E6 90 02 09 10 4A 95 E6 E8 10 F4 A2 03 76 69 CA 10 FB 88 F0 11
A2 09 B5 5C C9 08 30 04 E9 03 95 5C CA 10 F3 30 D6 A2 03 B5 69 95 57 CA 10 F9
A9 01 85 FB A2 03 A9 00 95 FB CA D0 FB A2 03 B5 FB 95 22 95 26 CA 10 F7 A9 00
A2 03 95 69 CA 10 FB A0 20 A2 02 46 25 76 22 CA 10 FB 90 0C A2 7C 18 B5 AA 75
ED 95 ED E8 10 F7 A2 7D 06 26 36 AA E8 10 FB 88 10 DD A0 0B A9 00 99 5A 00 88
D0 FA A0 20 A2 09 B5 5C C9 05 30 04 69 02 95 5C CA 10 F3 06 69 A2 FD 36 6D E8
D0 FB A2 09 B5 5C 2A C9 10 29 0F 95 5C CA 10 F4 88 D0 D7 E0 0A F0 05 E8 B5 5B
F0 F7 09 30 99 5B 00 C8 E8 E0 0B F0 04 B5 5B 90 F1 88 B9 5B 00 C9 30 F0 F8 A2
7C 18 B5 DB E9 00 95 DB E8 10 F7 90 14 88 30 05 B9 5B 00 D0 EA A2 7C F6 7F D0
03 E8 10 F9 4C 73 C0 B9 5B 00 4C D2 FF

```

**Online demo**, usage: sys49152,n where n is the 0-indexed input.

# Answer
> 1 votes
# Python 3, HyperNeutrino

```
lambda o:"".join(str(p*p+2*p+1)[::~0].lstrip("0")for p in range(o+1))[o]

```

Try it online!

# Answer
> 1 votes
# Lua, Katenkyo

```
i=1s=""while(#s<...+0)do s=s..((i*i)..""):reverse():gsub("(0+)(%d+)$","%2")i=i+1 end
print(s:sub(...,...))

```

Try it online!

I don't know Lua, but this was a simple one, just replaced a space with a newline.

# Answer
> 1 votes
# Python 2, dylnan

```
d=lambda y:y if y%10>0 else d(y/10)
lambda n:''.join([str(d(x*x))[::-1]for x in range(1,n+1)])[n-1]#fix

```

Try it online!

Note: this cop submission was bugged and didn't work for inputs lower than 5. While I was at it I built this solution which has the correct Levenshtein distance AND fixes the bug.

# Answer
> 1 votes
# Perl 5, (-p) Xcali

Updated after comment, Levenshtein Distance between

```
a$j.=int reverse$_**2for 1..$_;$_--;say$j=~s/.{$_}(.).*/$1/r

```

and

```
p$_=substr w.(join"",map{whyddwzz;0|reverse$_**2}1..$_),$_,1

```

is 55

Try it online

# Answer
> 1 votes
# Java 8, Kevin Cruijssen

```
/*!FooBarFooBarFoo!*/N->{String R="",T=R;for(int I=1,J;N+2>R.length();I++){for(T="",J=(I*I+"").length();0<J;T+=(I*I+"").charAt(--J));R+=new Long(T)+"";}return R.charAt(N);}

```

Try it online!

### Change log

* Replaced `.replaceAll()` with `new Long()`.
* Removed the test for perfect squares. Now using perfect squares directly.
* Updated all variable names to upper-case.
* Rewritten the inequalities.
* And finally added a 21-byte leading comment to reach the correct LD.

# Answer
> 1 votes
# Octave, Stewie Griffin

```
@(n)regexprep(fliplr(num2str((1:n)'.^2))'(:)',' +0*','')(n)%abcdefghijk

```

Try it online!

I was actually attempting my own Octave answer and spotted the existing one. Mine was already significantly shorter so adding a comment at the end was sufficient to get to the required distance of 63.

# Answer
> 1 votes
# PHP, Jo.

```
<?for($j++;strlen($p)<$argv[1];$j++)$p.=(int)strrev($j**2);echo($p[$argv[1]+2-3]);

```

Try it online!

(I was planning to switch the inequality in order to get even larger LD...)

# Answer
> 0 votes
# 6502 Machine Code (C64), Felix Palmen

May also be a "simple" crack, but it *appears* to work as the original.
Having the LD = 1 is just so tempting to try to crack it (sorry, Felix). :)

```
00 C0 20 FD AE A0 00 99 5B 00 C8 20 73 00 90 F7 99 5B 00 A2 0B CA 98 88 30 09
B9 5B 00 29 0F 95 5B 10 F2 95 5B CA 10 FB A0 20 A2 76 18 B5 E6 90 02 09 10 4A
95 E6 E8 10 F4 A2 03 76 69 CA 10 FB 88 F0 11 A2 09 B5 5C C9 08 30 04 EB 03 95
5C CA 10 F3 30 D6 A2 03 B5 69 95 57 CA 10 F9 A9 01 85 FB A2 03 A9 00 95 FB CA
D0 FB A2 03 B5 FB 95 22 95 26 CA 10 F7 A9 00 A2 03 95 69 CA 10 FB A0 20 A2 02
46 25 76 22 CA 10 FB 90 0C A2 7C 18 B5 AA 75 ED 95 ED E8 10 F7 A2 7D 06 26 36
AA E8 10 FB 88 10 DD A2 0B A9 00 95 5A CA D0 FB A0 20 A2 09 B5 5C C9 05 30 04
69 02 95 5C CA 10 F3 06 69 A2 FD 36 6D E8 D0 FB A2 09 B5 5C 2A C9 10 29 0F 95
5C CA 10 F4 88 D0 D7 E8 B5 5B F0 FB 09 30 99 5B 00 C8 E8 E0 0B F0 04 B5 5B 90
F1 88 B9 5B 00 C9 30 F0 F8 A2 7C 18 B5 DB E9 00 95 DB E8 10 F7 90 14 88 30 05
B9 5B 00 D0 EA A2 7C F6 7F D0 03 E8 10 F9 4C 68 C0 B9 5B 00 4C D2 FF

```

**Online demo**, usage: sys49152,n where n is the 0-indexed input.

---
Tags: number, sequence, cops-and-robbers, edit-distance
---


title: Bobby's Booby-Trapped Safe

text:
# Question
Title: Bobby's Booby-Trapped Safe
Bobby's booby-trapped safe requires an n-digit code to unlock it. Alex has a probe which can test combinations without typing them onto the safe. The probe responds *Fail* if no individual digit is the same as that in its corresponding position in Bobby's code. Otherwise it responds *Close*, including when all digits are correct. For example, when n=3, if the correct code is 014, then the responses to 099 and 014 are both Close, but the response to 140 is Fail.

Your task is to create a program/function that takes n (a positive integer) as input and returns the answer to the following question:

*If Alex is following an optimal strategy, in the worst-case scenario, what is the smallest number of attempts needed to guarantee that he knows the correct code, whatever it is?*

This is a codegolf challenge, so make your code short.

### Test Cases

```
> 1
9

> 2
11

> 3
13

> 4
16

> 5
19

> 6
21

```

This is a modified version of a problem from BMO2 2017.

# Explanation of the Test Cases

Where n=1, in the worst case, Alex will try eight numbers that all fail. The ninth number he tries will determine what the code is. Therefore, the answer is nine.

Where n=2, there are a hundred possible codes. In the worst case, he will fail the first test and narrow it down to eighty-one possible codes. Failing will be the worst case (and so he'll keep failing) until Alex has narrowed it down to nine possible codes (after seven tries). If he fails the next one (on his eighth try), he'll have narrowed it down to four possible codes, so if he gets 'Close', then he'll have five possible codes. We can then deduce that Alex will need at least three more tries to guess the code because five distinct numbers cannot be represented with distinct two-digit binary codes. Thus, Alex needs at least eleven guesses. Now, observe that Alex can find the code in eleven guesses. He can try 00, 11, ..., 99. If he failed nine of those tests, the one he didn't fail is the answer. If he failed eight of them (suppose he didn't fail xx and yy), he can try xy. If xy fails, the code is yx. Otherwise, the code is xy. Therefore, the answer is eleven.

Where n=3, Alex will fail every try (like in the n=2 case). He will start with a thousand possible codes, then after his seventh guess he will have narrowed it down to sixty-four possibilities (in the worst case, when Alex has failed all the tests). Then, if Alex doesn't fail the next test, he will have narrowed it down to thirty-seven possibilities. Alex will then need at least six more guesses to find the code. Therefore, Alex needs at least thirteen guesses. In fact, finding the code within thirteen guesses is possible. A possible strategy is to try 000, 111, ..., 999. If nine of these fail, then the code that didn't fail is right. If eight of them failed, then (if xxx and yyy worked and zzz failed) Alex can do xzz, zxz and zzx to check if each digit is x or y. If seven codes failed, then (if xxx, yyy and zzz worked and www failed) Alex can do xww and yww (to find the first digit) and then there is just one more code (could be xyz, xzy, yxz, yzx, zxy or zyx) Alex can try to see what order the last two digits are in (since the code has to be made of three different digits).

A similar argument is used for n=4, n=5 and n=6. Note that a different strategy would have to be found for n\>10.

# Answer
> 1 votes
# Mathematica, 125 bytes (121 chars)

```
(f@{_}=0;f@l_:=1+Min[Max[{g=GatherBy[l,vFreeQ[#-v,0]]}~With~If[Length@g<2,∞,f/@g]]&/@R~T~#];f@(T=Tuples)[R=Range@10,#])&

```

Try it online!

(it actually does not run the code, just the function pasted into TIO. So because the function is not invoked, it does nothing)

This cannot be run even with input `n=1` because it has no memoization or whatever optimization. The ungolfed code below, however, does return `9` for `n=1`.

Ungolfed code:

```
n = Input[];

base = 10;

Clear@f;
f@{_} = 0;
f@l_ := f@l =
  1 + Min[
    Max[
       With[{groups = GatherBy[l, v \[Function] FreeQ[# - v, 0]]},
        If[Length@groups == 1, Infinity, f /@ groups]
        ]
       ] & /@ Tuples[Range@base, n]
    ]

f@Tuples[Range@base, n]

```

This code run in upper bound time `O(2^(10^n poly(n)))`, which is impractical for all `n ≥ 2`.

Explanation:

Let a number be represented as a list of `n` numbers from 1 to 10. There are `10^n` numbers.
Then, the function `f` receive a list of "numbers" `l` (so a 2D list of digits), and return the information "assuming all the possible candidate numbers are in the list `l`, at least how many question are necessary to reduce it to `1` candidate in the worst case?"
So the function `f` is defined as:

```
f@{_} = 0;

```

When there is only 1 candidate, we only need to ask 0 more questions.

```
f@l_ := f@l =

```

Memoization (in ungolfed code) to slightly improve performance.

```
1 +

```

Ask one question.

```
/@ Tuples[Range@base, n]

```

For each possible number (numbers are represent as `n`-tuple of digits, each digit is in the range from `1` to `base` (10)) to be asked,

```
Min[]

```

find the minimum (best strategy)

```
groups = GatherBy[l, v \[Function] FreeQ[# - v, 0]]

```

partition the candidates to 2 groups: one gives the value "Close" when ask this number, and the other gives the value "Fail" when ask this number.

```
If[Length@groups == 1,

```

If all the numbers in the list `l` get to the same answer when test,

```
Infinity

```

return `Infinity` (avoid asking this question, avoid loop forever)

```
, f /@ groups

```

otherwise recursively apply the function `f` to the resulting group

```
Max[]

```

and get the maximum (worst case).

---
Tags: code-golf, combinatorics, optimization
---


# Question
Title: Shortest code to dump a file into workable memory
This is a slightly different code golf from the usual problems. I'm forced to work with Java at my workplace and I'm increasingly annoyed at what I must do to read a file into memory to a String so I can operate on it in a normal way.

The golf is this: What is the shortest possible function to dump a file into your language's smallest data structure of characters?

Java would be char\[\], C++ would be char\*, Haskell would be a \[Char\], etc. I don't care about complete programs or main() functions, but you do have to open and close the file.

> inb4 Unix's `>`

# Answer
> 3 votes
# C#

```
var a = System.IO.File.ReadAllText("filename.txt");

```

`a` is a string that will contain the contents of `filename.txt`

# Answer
> 3 votes
# PHP

```
$a=file('foo.txt');

```

`$a` now contains an array of strings of the lines of `foo.txt`.

Similarly:

```
$a=file_get_contents('foo.txt');

```

`$a` now contains a single string of the contents of `foo.txt`.

# Answer
> 2 votes
## Python

```
a=open('filename.txt').read()

```

The garbage collector will close the file.

# Answer
> 2 votes
## C (for unixoid systems)

```
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>

/* inside a function */
struct stat fd_stat;
int fd;
void *buffer;

int fd = open("my.file",O_RDONLY);
if (fd<0) exit(EXIT_FAILURE);
fstat(fd,fd_stat);
buffer = mmap(NULL,fd_stat->st_size,PROT_READ,MAP_SHARED,fd,0);
if (buffer==NULL) exit(EXIT_FAILURE);

```

This ridiculously long piece of code creates a buffer `buffer` of length `fd_stat->st_size` that contains the file. You probably won't use C for code-golfing anyway..

# Answer
> 2 votes
### Scala

In Scala, you can get a iterator easily:

```
scala> io.Source.fromFile("Cg6367.scala").getLines
res274: Iterator[String] = non-empty iterator

```

then you can iterate over a collection of lines with a for loop, or use one of the other 200 methods, usable on iterators, like map, forall, filter, first, head, last, drop, groupBy, sortBy, ... - you name it. Simply outputting the content would be:

```
val ls = io.Source.fromFile("Cg6367.scala").getLines
println (ls.mkString ("\n"))

```

# Answer
> 1 votes
## J

```
a=.1!:1<'filename.txt'

```

`a` now contains a string representing the contents of `filename.txt`.

# Answer
> 1 votes
## C, 135 chars

Though 40 of those 135 chars are just because there are some `#include`s that you just can't skip:

```
#include<sys/mman.h>
#include<sys/stat.h>

```

(Add `fcntl.h` and `unistd.h` for non-golfing completeness.) Then in the place where the file contents are desired, it's as simple as:

```
struct stat s;char*p;int f=open("filename.txt",0);fstat(f,&s);
p=mmap(0,s.st_size,1,2,f,0);close(f);

```

The file is closed and `p` contains a pointer to the file contents. (Don't forget to call `munmap()` when you're done.)

# Answer
> 1 votes
# C

There's already a C answer, but this one uses nothing more than the absolute basics. It's also rather odd, and doesn't handle errors, because if users are going to give bad inputs really they deserve to have the program crash on them.

```
#include <stdlib.h>
#include <stdio.h>

**b,**m;main(l){
  FILE*f=fopen("foo.txt","r");
  for(m=b=malloc(64);~(l=fgetc(f));){
    *b++=&l;
    b=malloc(64);
  }
  return fclose(f);
}

```

Dumps the file into a linked list of chars, which if it's good enough for Haskell, it's good enough for C. Assumes a pointer is 32 bits and EOF is -1. Clearly a linked list of ints is the most

# Answer
> 0 votes
# Ruby

* `a=File.open('foo.txt', 'r') { |f| f.read }`
* `a=IO.read('foo.txt')`

# Answer
> 0 votes
Clojure's slurp overload that doesn't take the encoding is deprecated (for good reason):

```
(slurp "a.txt")

```

Here's the way to specify the encoding

```
(slurp "a.txt" :encoding "UTF-8")

```

# Answer
> 0 votes
# Tcl

```
set t [read [open file.txt]]

```

# Answer
> 0 votes
# Groovy, 9 bytes, or 19

Closure expecting a File object:

```
{it.text}

```

Closure expecting a String filepath:

```
{new File(it).text}

```

# Answer
> 0 votes
# F#

```
let a = System.IO.File.ReadAllText("filename.txt")

```

`a` is a System.String that will contain the contents of `filename.txt`

.NET family \<3

# Answer
> 0 votes
# Java 7, 108 bytes (Method, Byte\[\])

```
public byte[] r(String p)throws Exception{return java.nio.file.Files.readAllBytes(new java.io.File(p).toPath());}

```

---

# Java 7, 125 Bytes (Method, String)

```
public String r(String p)throws Exception{return new String(java.nio.file.Files.readAllBytes(new java.io.File(p).toPath()));}

```

---

# Java, 193 bytes (Method, Lines)

Here's a java method that reads an entire file as a List of strings, one line means 1 string. Linebreaks are detected as defined here.

Boiler-plate:

```
public class A {
    public static void main(String[] args) throws Exception {
        List<String> lines = readLines(args[0]);
    }
}

```

Method:

```
import java.util.*;public List readLines(String path)throws Exception{List l=new ArrayList();Scanner s=new Scanner(new java.io.File(path));while(l.add(s.nextLine())&&s.hasNextLine());return l;}

```

Ungolfed:

```
public List readLines(String path)throws Exception{
    List l = new ArrayList();
    Scanner s = new Scanner(new java.io.File(path));
    while(l.add(s.nextLine())&&s.hasNextLine());
    return l;
}

```

Ungolfed (With Best-Practices):

```
public static List<String> readLines(String path) throws FileNotFoundException {
    List<String> l = new ArrayList<String>();
    Scanner s = new Scanner(new java.io.File(path));
    while(l.add(s.nextLine())&&s.hasNextLine());
    s.close();
    return l;
}

```

# Answer
> 0 votes
## Swift

```
import Foundation

let contents = try! String(contentsOfFile: "filename.txt")

```

# Answer
> 0 votes
# Perl 5, 26 bytes

```
sub{local(@ARGV,$/)=@_;<>}

```

Try it online!

# Answer
> 0 votes
# C, 110 bytes without filename

Another C answer. This one is very inefficient, but at least it is short. First is the header:

```
#import<stdio.h>

```

And then the code (`N` is the filename):

```
char*r,c;FILE*F=fopen(N,"r");for(int i=r=0;~(c=fgetc(F));r[i-1]=c)r=realloc(r,++i);fclose(F);

```

Assumes EOF is -1. `r` will be a pointer to the result block. (If `N` is empty file, then it will be a null pointer)

# Answer
> 0 votes
# q/kdb+, 9 bytes + filename

**Solution:**

```
a:read0`:filename.txt

```

`a` is now a list of lists; a list of chars for each line in `filename.txt`.

**Explanation:**

```
a:read0`:filename.txt / solution
       `:filename.txt / path to the file, in this case filename.txt
  read0               / read file as characters
a:                    / assign to variable a

```

Or we could drop to the `k` prompt we can do if we wanted to conserve some bytes:

```
\
  a:0:`:filename.txt

```

# Answer
> 0 votes
# AutoHotkey

```
FileRead,a,foo.txt

```

`a` is a variable that now contains all the contents of the file `foo.txt` so long as that file is less than 1 GB. If file size or available memory is a problem, then you can loop through each line of a file instead using `Loop,Read,foo.txt`.

It has some options available such as limiting the read to the first `n` bytes or reading the file using a different file encoding so long as it's from a standard list.

---
Tags: code-golf
---


title: Paper and Envelope Sizes

text:
# Question
Title: Paper and Envelope Sizes
**Task**

Given a letter (A, B, C), and a number (0-10), output the size of the matching standard paper size (Series A and B) or the matching standard envelope size (C series) in millimetres in the format `aaaa x bbbb` where `aaaa` and `bbbb` are the width and height measurements in millimetres as per ISO216 (Series A & B) or ISO296 (Series C)

To make things easier I will quote from Wikipedia's table of Paper Sizes

```
ISO paper sizes in portrait view
Format  A series    B series    C series
Size     mm × mm      mm × mm    mm × mm
0       841 × 1189  1000 × 1414 917 × 1297
1       594 × 841    707 × 1000 648 × 917
2       420 × 594    500 × 707  458 × 648
3       297 × 420    353 × 500  324 × 458
4       210 × 297    250 × 353  229 × 324
5       148 × 210    176 × 250  162 × 229
6       105 × 148    125 × 176  114 × 162
7        74 × 105     88 × 125   81 × 114
8        52 × 74      62 × 88    57 × 81
9        37 × 52      44 × 62    40 × 57
10       26 × 37      31 × 44    28 × 40

```

So examples of input and output:

```
**Test case 1**
Input: A4
Output: 210 x 297

**Test Case 2**
Input: B6
Output: 125 x 176

**Test Case 3**
Input: C2
Output: 458 x 648

```

**Things to note:**

1. The format "210 x 297" or "1000 x 1414" etc. While this is the preferable format, You can choose to omit the " x " from your output, i.e. in the form of an array or two numbers or whatever tickles your fancy as long as the width measurement is outputted before the height.
2. The ratio between the height and the width is roughly equivalent to the square root of 2, so in the calculation of the heights, the width is multiplied by sqrt(2), and then rounded up or down to the nearest millimetre, thus resulting in the measurements in the table above. This may help golf down your code.
3. In successive sizes for a series as you go down the table, the width for one size becomes the height for the next. This may also help you golf down your code.

**Rules:**

1. This is code-golf. Standard rules apply as a result. The score will be based on byte count. Lowest count will win.
2. No silly loopholes, we've been there before... We shan't go through this again.
3. If you can code it, then please also consider attaching a link to a working instance of your code so that other programmers and golfers can learn how your code works. This is not mandatory, but I'd like to encourage others to do this so we can all learn off one another. I certainly would love to learn more about other golfer's languages where possible.

Best of luck.

# Answer
> 9 votes
## JavaScript (ES7), 57 bytes

*Saved 1 byte thanks to @WallyWest*

```
s=>n=>[n,n-1].map(x=>.707**x*{A:841,B:1e3,C:917}[s]+.2|0)

```

# Answer
> 6 votes
# C (gcc), ~~113~~ ~~111~~ ~~90~~ ~~78~~ 70 bytes

It needs `-lm` to run on TIO, but works well on my computer without the option.

*Saved 20 bytes thanks to pizzapants184.*

Return values by pointer.

```
f(a,b,c,d)int*c,*d;{float x=1e3*pow(.707,b+a%3/4.)+.2;*c=x,*d=x/.707;}

```

Explanation:

```
f(a,b,c,d)int*c,*d;{          // calling by char, but receive as int
    float x = 1e3 * pow(.707, // float gives enough precision
            a % 3 / 4.        // series: a%3/4.=.5,0,.25 when a=65,66,67
            + b) - .2;        // magic number to get correct roundings
    *c = x, *d = x / .707;
}

```

# Answer
> 3 votes
# JavaScript, 53 bytes

```
L=>N=>[N+1,N].map(p=>1091/2**(p/2+~{B:2,C:1}[L]/8)|0)

```

```
f=

L=>N=>[N+1,N].map(p=>1091/2**(p/2+~{B:2,C:1}[L]/8)|0)

document.write('<table><tr><th><th>A<th>B<th>C',[...Array(11)].map((_,i)=>'<tr><th>'+i+['A','B','C'].map(j=>'<td>'+f(j)(i)).join``).join``);
```

Save many bytes by using alternative output format, thanks to Neil.

# Answer
> 3 votes
# Java (OpenJDK 8), 59 bytes

```
f->s->new double[]{s=1e3*Math.pow(.707,s+f%3/4d)-.2,s/.707}

```

Try it online!

Inspired by @Colera Su's C entry, then improved by myself.

* 14 bytes saved thanks to Kevin Cruijssen

# Answer
> 3 votes
# Python 2, ~~103~~ ~~97~~ ~~93~~ ~~84~~ ~~83~~ 81 bytes

```
def f(l,n):w=[841,1000,917][ord(l)-65];h=int(w/.707);exec"w,h=h/2,w;"*n;print w,h

```

Try it online!

# Answer
> 3 votes
# APL (Dyalog), ~~31~~ 28 bytes

-2 thanks to ngn.

Full program body. Assumes `⎕IO` (**I**ndex **O**rigin) to be `0`, which is default on many systems. Prompts for number, then letter, both from STDIN. Prints to STDOUT.

```
⌊.2+1E3÷2*8÷⍨('BC'⍳⍞)+4×⎕-⍳2

```

Try it online!

A slightly modified version lets us test all possibilities at once: Try it online!

`⍳2` first two **ɩ**ndices, i.e. 0 and 1

`⎕-` subtract that from numeric input

multiply four with that

`(``)+` add the following

character input…

`'BC'⍳` …'s **ɩ**ndex in this string ("A" will give 2, as the index beyond the last)

`8÷⍨` divide that by 8

`2*` raise 2 to the power of that

`1E3÷` 1000 divided by that

`.2+` add ⅕ to that

floor (round down)

# Answer
> 3 votes
## Batch, 105 bytes

```
@set/aA=1189,B=1414,C=1297,h=%1,w=h*29/41
@for /l %%i in (1,1,%2)do @set/at=w,w=h/2,h=t
@echo %w% x %h%

```

41/29 ≅ √2

# Answer
> 3 votes
# MATL, ~~34~~ ~~33~~ 30 bytes

```
917 841 1000.5vjo)t2X^*hi2/W/k

```

Try it online! or Verify all test cases

Saved 4 byte thanks to Luis Mendo

# Answer
> 2 votes
# Befunge, ~~69~~ ~~56~~ 55 bytes

```
"}"8*~3%:"L"*7vv\p00-1_$..@
")"*":":-*!!\+<>2/00g:^:&\/

```

Try it online!

**Explanation**

We don't have the luxury of floating point or anything like a power function in Befunge, so we calculate the base size for the given format character, *f*, as follow:

```
fn = f % 3
width = 1000 - (n * 76 + 7) * !!n
height = width * 58 / 41

```

We then repeatedly rotate and divide these dimensions to get to the appropriate subdivision for the given size number.

```
"}"8*                         Push 1000 for later use in the width calculation.
     ~                        Read the format character from stdin.
      3%                      Convert into a number in the range 0 to 2.
        :"L"*7v               Calculate width = 1000 - (fn * 76 + 7) * !!fn
        -*!!\+<                  where fn is the format number derived above.
")"*":":                  /   Calculate height = width * 58 / 41.
                         \    Swap so the width is above the height on the stack.
                      v:&     Read the numeric size from stdin and duplicate for testing.
                      _       While not zero, go left.
                 p00-1        Decrement the size and move it from the stack into memory.
               v/             Swap the width and height.
               >2/            Divide the new width by 2.
                  00g:        Restore the size from memory and duplicate for testing.
                      _       While not zero, repeat this loop.
                       $      When zero, continue to the right and drop the size.
                        ..@   Output the width and height, then exit.

```

---
Tags: code-golf
---


title: Make a Robo-Reviewer: Close Votes

text:
# Question
Title: Make a Robo-Reviewer: Close Votes
Write a program that reviews posts for the Close Votes queue on Stack Overflow.

Since it's near-impossible to write a bot that can accurately review posts in the actual queue, **we're instead going to use a grossly oversimplified version of the queue and its rules.**

Your program should take in the body of a question as a string, and output an array of `option_id`s for the applicable close reasons. For Leave Open, you can output an empty array OR a falsey value. **Note: this is a significant change from the sandbox version of this challenge so make sure to update stashed solutions.**

Here is a list of the close reasons, their fresh-off-the-API `option_id`s, and the gross oversimplifications that should be used to flag them. All keywords and key phrases are case-insensitive and should have word boundaries on both sides.

* `28509` \- **duplicate**
* **off-topic because…**

+ `46431` \- Questions about **general computing hardware and software** are off-topic for Stack Overflow unless they directly involve tools used primarily for programming. You may be able to get help on Super User.
        - *Contains the keyword `install`, or its various conjugations: `installs`, `installing`, `installation`, `installed`.*
    + `36074` \- Questions on **professional server- or networking-related infrastructure administration** are off-topic for Stack Overflow unless they directly involve programming or programming tools. You may be able to get help on Server Fault.
        - *Contains the keyword `server`, but NOT `php` or `cgi`.*
    + `54583` \- Questions asking us to **recommend or find a book, tool, software library, tutorial or other off-site resource** are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.

    - *Contains one of the mentioned words (`book`, `tool`, `software library`, `tutorial`, `API`) or their plurals.*
    + `77` \- Questions seeking debugging help ("**why isn't this code working?**") must include the desired behavior, a *specific problem or error* and *the shortest code necessary* to reproduce it **in the question itself**. Questions without **a clear problem statement** are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable example.

    - *The question has no code markdown. You may assume that code markdown will not be inside any other syntax.*
    + `44435` \- This question was caused by **a problem that can no longer be reproduced** or **a simple typographical error**. While similar questions may be on-topic here, this one was resolved in a manner unlikely to help future readers. This can often be avoided by identifying and closely inspecting the shortest program necessary to reproduce the problem before posting.

    - *There are unpaired or incorrectly paired parentheses, brackets, or braces.*
* `16055` \- **unclear what you're asking**
    + *The question does not contain a question mark character.*
    + *The question has no latin characters.*
    + If *either* of the above apply, then it should appear in the output array, but it shouldn't appear twice.
* `29650` **too broad**
    + *The question contains a question starter (`who`, `what`, `when`, `where`, `why`, `how`) followed by `should I`.*
* `62000` **primarily opinion-based**
    + *The question contains the phrases `best/good/bad practice(s)`, or `good/bad idea(s)`.*

As usual for a challenge, the winner is the shortest answer in bytes.

# Test Cases

# Answer
# Python 2.7, ~~644~~ ~~639~~ ~~593~~ ~~560~~ 549 bytes

```
from re import*
s,g,t,w=input(),"([{)]}",[],"NullPointerException"
l=g.index
print[[29650,46431,54583,62000,16055,77,36074,28509,218384][i]for i,r in enumerate(["(wh([oy]|at|en|ere)|how) should I","install(ing|s|ation|ed)","(book|tool|software librar(ies|y)|tutorial|API)s?","(best|good|bad) (practice|idea)s?","^[^a-z]*$|^[^?]*$","^((?![#*[(~>`=]|\d\.|\-{3}).)*$","(?=^.*server)(?!^.*(php|cgi))",w,w])if search(i<5and r or"(^|\W)"+r+"($|\W)",s,flags=I|S)]+[44435]*(any(t.append(g[l(c)+3])if l(c)<3else t==[]or c!=t.pop()for c in s if c in g)or[]<t)

```

Try it online!

The basic concept is to use a series of regex's to do most of the heavy lifting. I do rebuild regex's to reduce bytes; if you wish to see the full regexes, refer to the ungolfed section below. Then, I go through and check stuff that regex isn't good at (like matching parenthesis correctly).

# Important note regarding testing

The examples as given in OP's post are wrong. If you look through the links, you should be able to notice where my program is finding the correct solution. For instance, the OP's didn't seem to recognize `>` and other markdown as markdown. That is where most of the variance comes from.

# Pseudo-ungolfed version

I decided that it may be beneficial for understanding to post a precursor to my code-golf.

```
import re

def doesMatch(string):
    openClosed = "([{)]}"
    current = []
    for char in string:
        if char in openClosed:
            if openClosed.index(char) < 3:
                current.append(openClosed[openClosed.index(char)+3])
            elif len(current) == 0 or current.pop() != char:
                return False
    return not len(current)

def take(post):
    regexes = [
        "(^|\W)(who|what|when|why|how|where) should I($|\W)",
        "(^|\W)install(ing|s|ation|ed)($|\W)",
        "(^|\W)(book|tool|software library|software libraries|tutorial|API)s?($|\W)",
        "(?=^[^a-z]*$)|(?=^[^?]*$)",
        "(^|\W)(best|good|bad) (practice|idea)s?($|\W)",
        "^((?![#*[(~>`=]|\d\.|\-{3}).)*$",
        "(?=^.*server)(?!^.*(php|cgi))"
        ]
    errors = [[29650,46431,54583,16055,62000,77,36074][i] for i,regex in enumerate(regexes) if re.search(regex,post,flags=re.I|re.S)]
    if not doesMatch(post):
        errors.append(44435)
    if post.find("NullPointerException") != -1:
        errors += [28509,218384]
    return errors

with open("test.txt","r") as fi:
    print(take(fi.read()))

```

Thanks to the following for helping reduce bytes:

* LyricLy
* notjagan
* ovs
* Mr. Xcoder
> 4 votes

---
Tags: code-golf
---


title: Random Pixel Poking

text:
# Question
Title: Random Pixel Poking
Your task is simple: write a program that will replace random pixels in a black 16px * 8px rectangle (width by height) with a white pixel.

The holes must be uniformly random, and you should output the 16px by 8 px image with the white pixels inserted.

Replace only 1 pixel per column (16 total replaced pixels)

You don't take any input, and you can't rely on the image being stored elsewhere on the computer.

This is so the program with the shortest bytecount wins!

# Answer
> 7 votes
# MATL, ~~15~~ ~~14~~ 13 bytes

```
8tE2$r&S1=3YG

```

Example (with MATL compiler running on MATLAB):

Or try it at **MATL Online!** (If it doesn't run the first time, press "Run" again or refresh the page). Note that the image is scaled by the online interpreter for better visualization.

This is a port of my Octave / MATLAB answer (see explanation there). Here are the equivalent statements:

```
MATL        Octave / MATLAB
----        ---------------
8tE         8,16
2$r         rand(...)
&S          [~,out]=sort(...)
1=          ...==1
3YG         imshow(...)

```

# Answer
> 6 votes
# Pyth - ~~16~~ 15 bytes

Outputs image to `o.png`.

```
.wCm.S+255mZ7y8

```

Example image:

# Answer
> 4 votes
# C, ~~85~~ 100 bytes

```
main(c){char a[138]="P5 16 8 1 ";for(srand(time(0)),c=17;--c;a[9+c+(rand()&112)]=1);write(1,a,138);}

```

Writes a PGM image file to stdout (call it with `prog >out.pgm`).

**Ungolfed and explained:**

```
main(c) {
    // A buffer large enough to contain the whole image,
    // pre-filled with the PGM header.
    // This is a binary greyscale (P5) image with only two levels (1),
    // Because a binary bitmap would require pixel packing.
    char a[138] = "P5 16 8 1 ";

    // c iterates from 16 to 1 over the columns
    for(
        srand(time(0)), c = 17;
        --c;

        // (rand() % 8) * 16 is equivalent to (rand() & 7) << 4
        // Since all bits are equally random, this is equivalent
        // to rand() & (7 << 4), that is rand() & 112.
        // This picks a pixel from the first column, which is then
        // offset to the correct column by c - 1 + 10
        // (10 is the length of the header).
        a[9 + c + (rand() & 112)] = 1
    )
        ; // Empty for body

    // Write the whole buffer to stdout
    write(1,a,138);
}

```

**Updates:**

* OP has clarified that the output should change with each execution, lost 15 bytes to `srand(time(0))` (`:(`)

# Answer
> 3 votes
# Processing, ~~74~~ 73 bytes

```
fill(0);rect(0,0,15,7);stroke(-1);for(int i=0;i<16;)point(i++,random(8));

```

Sample output:

### Explanation

```
fill(0);               //sets the fill colour to black
rect(0,0,15,7);        //draws a 16*8 black rectangle
stroke(-1);            //set stroke colour to white
for(int i=0;i<16;)     // for-loop with 16 iterations
 point(i++,random(8)); //  draw a point at x-coordinate i and a random y coordinate
                       //  the colour of the point is white since that is the stroke colour

```

# Answer
> 3 votes
## Ruby, 61 bytes

```
puts'P116 8';puts Array.new(16){[*[1]*7,0].shuffle}.transpose

```

This is a full program that outputs the image in netpbm format to stdout.

Sample output:

```
puts'P116 8';   # output the netpbm header (P1 for black and white, 16x8)
puts            # then output the data as follows:
Array.new(16){  # make a 16-element array and for each element,
[*[1]*7,0]      # generate the array [1,1,1,1,1,1,1,0] (1=black 0=white)
.shuffle}       # shuffle the array
.transpose      # transpose the rows/columns of the 2d array (so that each column
                # has one white pixel)

```

# Answer
> 3 votes
# Octave / MATLAB, ~~48~~ ~~37~~ 35 bytes

```
[~,z]=sort(rand(8,16));imshow(z==1)

```

Example (on Octave):

### Explanation

```
           rand(8,16)                  % 8×16 matrix of random values with uniform
                                       % distribution in (0,1)
[~,z]=sort(          );                % Sort each column, and for each output the
                                       % indices of the sorting. This gives an 8×16
                                       % matrix where each column contains a random
                                       % permutation of the values 1,2,...,8
                              z==1     % Test equality with 1. This makes all values
                                       % except 1 equal to 0
                       imshow(    )    % Show image, with grey colormap

```

# Answer
> 2 votes
# HTML+JavaScript, 148 bytes

```
c=O.getContext`2d`;for(x=16;x--;){r=Math.random()*8|0;for(y=8;y--;)c.fillStyle=y-r?'#000':'#fff',c.fillRect(x,y,1,1)}
```

```
<canvas id=O width=16 height=8>
```

# Answer
> 2 votes
# Befunge, 90 bytes

This generates a PBM file written to stdout.

```
>030#v_\2*>>?1v
:v9\$<^!:-1\<+<
|>p1+:78+`!
>"P",1..8.28*8*v
.1-\88+%9p:!#@_>1-::88+%9g:!!

```

Try it online!

**Explanation**

The top three lines make up the random number generator, storing 16 random 3-bit numbers (i.e. in the range 0-7) on the tenth line of the playfield. Line four writes out the PBM header, and the last line then generates the pixels of the image. This is done by counting down the 16 random numbers as the pixels are output - when the number corresponding to a particular column reaches zero we output a 1 rather than a 0.

Sample output (zoomed):

# Answer
> 1 votes
# Mathematica, ~~77~~ 60 bytes

```
Image[{RandomInteger@7+1,#}->1&~Array~16~SparseArray~{8,16}]

```

**Sample Output**

**Explanation**

```
{RandomInteger@7+1,#}->1&~Array~16

```

Make replacement rules for each column; replace a randomly selected position with 1.

```
... ~SparseArray~{8,16}

```

Create a `SparseArray` with size 8x16 from the replacement rules. The background is `0` by default. (8x16 because Mathematica counts rows first)

```
Image[ ... ]

```

Convert the `SparseArray` into an `Image` object.

**77 byte version**

```
ReplacePixelValue[Image@(a=Array)[0&~a~16&,8],{#,RandomInteger@7+1}->1&~a~16]

```

# Answer
> 0 votes
# R, 76 bytes

```
a=matrix(0,8,16);for(i in 1:16)a[sample(1:8,1),i]=1;png::writePNG(a,'a.png')

```

Uses package `png` to output to a file.
Example output:

# Answer
> 0 votes
# QBasic, 59 bytes

```
RANDOMIZE TIMER
SCREEN 9
FOR x=0TO 15
PSET(x,RND*8-.5)
NEXT

```

Pretty straightforward. The `-.5` is needed because `PSET` with non-integer arguments uses round-to-nearest instead of floor or truncate (and `-.5` is shorter than `INT()`).

The image in question is displayed at the top left corner of the output window. A (cropped) example:

# Answer
> 0 votes
# Java, (*Does it even matter* Bytes, AKA 244 + 18 import = 262)

```
import java.awt.*;static void l(){new Frame(){public void paint(Graphics g){int x=50;int i=16;g.setColor(Color.BLACK);g.fillRect(x,x,16,8);g.setColor(Color.WHITE);for(;i>0;i--){int y=(int)(Math.random()*8);g.drawLine(x+i,x+y,x+i,x+y);setVisible(1>0);}}}.show();}

```

Was wonky because the coordinate system includes the frame window pane... So you need to buffer by at least 26 bytes or nothing shows up, hence the `x=50` bit.

# Answer
> 0 votes
# Postscript (65 bytes)

```
0 0íkà0ícà8íc0 8ícííB1à1íù16{0 randàíj0.5í©ík1 0íÖíß1 0í≠}íÉ

```

Ungolfed version:

```
0 0 moveto
16 0 lineto
16 8 lineto
0 8 lineto
closepath
fill
1 1 1 setrgbcolor
16{0 rand 16 mod 0.5 sub moveto 1 0 rlineto stroke 1 0 translate}repeat

```

# Answer
> 0 votes
# SmileBASIC, 30 bytes

```
FOR I=0TO 15GPSET I,RND(8)NEXT

```

# Answer
> 0 votes
# Chip-8, 12 bytes

```
0xA201 'Load sprite at address 201 (which is the second byte of this instruction)
0xC007 'Set register 0 to a random number from 0 to 7 (rnd & 0x7)
0xD101 'Draw sprite. x = register 1, y = register 0, height = 1
0x7101 'Add 1 to register 1
0x3110 'If register 1 is not 16...
0x1202 'Jump to second instruction

```

Draws the image on the screen.

# Answer
> 0 votes
# Tcl/Tk, 163

Two different approaches render to the same byte extent:

```
grid [canvas .c -w 16 -he 8 -bg #000 -highlightt 0]
.c cr i 8 4 -i [set p [image c photo -w 16 -h 8]]
set x 0
time {$p p #FFF -t $x [expr int(rand()*8)];incr x} 16

```

---

```
grid [canvas .c -w 16 -he 8 -bg #000 -highlightt 0]
.c cr i 8 4 -i [set p [image c photo -w 16 -h 8]]
time {$p p #FFF -t [expr [incr x]-1] [expr int(rand()*8)]} 16

```

# Answer
> 0 votes
**VBA Excel, ~~86~~ 105 bytes**

using immediate window

```
Cells.RowHeight=42:[a1:p8].interior.color=0:for x=0to 15:[a1].offset(rnd*7,x).interior.color=vbwhite:next

```

---
Tags: code-golf, graphical-output, random
---