title: Roll Dungeons and Dragons dice

text:
# Question
Title: Roll Dungeons and Dragons dice
I want to play Dungeons and Dragons, but I don't have any dice! Your challenge is to roll some D&D dice.

The input format specification in Backus-Naur form is:

```
<valid-input>  ::= <opt-integer> "d" <integer> <opt-modifier>
<opt-integer>  ::= | <integer>
<opt-modifier> ::= | "+" <integer>
<integer>      ::= "0" | "1" | "2" | "3" | "4" | "5" |
                   "6" | "7" | "8" | "9" | <integer> <integer>

```

The optional integer before the `d` is the number of dice to roll; it must be at least `1`, and defaults to `1` if not supplied.

The required integer immediately after the `d` is the number of sides each die has; it must be at least `1`. The sides of each die are distinct consecutive positive integers starting at `1`.

The optional modifier may be `+0`, and it defaults to `+0` if not specified.

For example, for the input `2d10+5`, you generate two random numbers from 1 to 10 inclusive, add them together, and add 5. Then you will output the result.

If you receive invalid input, such as `2d`, `d20+`, `0d4`, `2d5+1+2`, `2+2`, or anything else that doesn't fit this format, you must output "`Invalid input`". Otherwise, you must output only a single random integer, weighted according to the input. For example, `3d6` should produce more `10`s than `4`s.

### Test cases

```
Input      Minimum possible output    Maximum possible output
d1         1                          1
d6         1                          6
d1+3       4                          4
d20+3      4                          23
2d1        2                          2
2d6+2      4                          14
d01        1                          1
d01+0      1                          1
01d01+01   2                          2
3d20+10    13                         70

d          Invalid input
d0         Invalid input
d+0        Invalid input
d0+0       Invalid input
0d1        Invalid input
0d1+1      Invalid input
d1+        Invalid input
1d         Invalid input
1d1+       Invalid input
1d+1       Invalid input
2d+2d      Invalid input
d2+d2      Invalid input
d2+2+2     Invalid input
d2-1       Invalid input
-d2        Invalid input
-2d2       Invalid input
4*3        Invalid input
4*d2       Invalid input

```

This is , so the shortest code in bytes will win!

# Answer
> 12 votes
# Perl, ~~109~~ ~~95~~ ~~93~~ ~~96~~ 89 bytes

```
s/^d/1d/;/^(\d+)d(\d+)(\+\d+)?$/;$d+=1+rand$2|0for
1..$1;$_=$1*$2?$d+$3:'Invalid input'

```

Requires the `-p` switch, which accounts for two of the bytes. Try it online on Ideone.

### How it works

* Because of the `-p` switch, a line is read from STDIN and stored in `$_`.
* The command `s/^d/1d/` prepends a *1* to `$_` if it begins with a *d*, i. e., if the number of dice has not been specified.
* The regular expression `/^(\d+)d(\d+)(\+\d+)?/` checks if the line consists of a number, a literal *d*, another number and, optionally, a third number preceded by a *+* sign.

If there is a match, the numbers will be saved in `$1`, `$2` and `$3`.

In this case, the input will be valid if and only if `$1` and `$2` are both positive.
* `$d += 1 + rand $2 | 0` adds a pseudo-randomly chosen integer from 1 to the specified number of sides to `$d` (initially treated as zero).
* `for 1 .. $1` does the above once for every integer between 1 and the number of dice.
* The command `$_ = $1 * $2 ? $d + $3 : 'Invalid input'` does the following:

+ If `$1 * $2` is zero, it sets `$_` to *Invalid input*.
    + Otherwise, the input is valid and it sets `$_` to the sum of the dice rolls and the modifier.
* Because of the `-p` switch, Perl prints the contents of `$_`.
* Since there a no further input lines, the script exits.

# Answer
> 6 votes
# Fortran: 145

```
character(1)a;read(*,*)s,a,j,a,k;n=0;if(k<0.or.a=="-")then;print*,"error k<0";stop;endif;do l=1,int(s);n=n+int(s*rand(0)+1);enddo;print*,n+k;end;

```

Abuses implicit typing (`i-n` are all integers, everything else a real). Minor caveat: input must be space separated, so `2d10+5` must be entered as `2 d 10 + 5`, otherwise you'll get an `input conversion error`.

# Answer
> 4 votes
## Ruby, 116

Alternative Ruby version. I was trying to find a way to do it without the regular expressions, but the validation you have to do is a lot harder without them.

```
gets=~/^(\d+)?d(\d+)(\+\d+)?$/
a=$1||?1
puts$~&&a>?0?eval("r=#{$3||0};#{a}.times{r+=rand(#$2)+1};r"):'Invalid input'

```

This one is 112, using Dennis' clever Perl algorithm:

```
$p='(\d*[1-9]\d*)'
puts~/^#$p?d#$p(\+\d+)?$/?eval("r=#{$3||0};#{$1||1}.times{r+=rand(#$2)+1};r"):'Invalid input'

```

# Answer
> 3 votes
## GolfScript (120 106 bytes)

```
.100?!1`*\+.43?)!'+0'*+.10,'d+':^*-!*.10,''*-^=*^1/{/n*}/~].,3=*3,or:x~;*{x~\{rand)+}+@*}'Invalid input'if

```

This is not only shorter than the first version, but also more elegant. The part which actually does the die rolling is

```
\{rand)+}+@*

```

The rest is mainly input validation, and a few characters for parsing.

```
# Start by converting valid inputs into valid inputs with all optional bits.
# Prepend a '1' if the string starts with 'd'.
.100?!1`*\+
# Append '+0' if there's no '+' in the string.
.43?)!'+0'*+
# Now we start knocking out the invalid inputs.
# If it contains a character other than [0-9d+], replace the string with ''.
.10,'d+':^*-!*
# If it doesn't contain exactly one 'd', exactly one '+', and the 'd' before the '+',
# replace the string with ''.
.10,''*-^=*
# Now we either have a valid string, an empty string, or a string which is almost valid
# but has some empty substrings which should be integers, or a forbidden 0 integer value.
# Replace the 'd' and '+' with newlines, eval the result, and gather into an array.
^1/{/n*}/~]
# If we had any empty parts, we'll have fewer than 3 items on the stack.
# In that case, replace with integer values which will fail the final validation step.
.,3=*3,or
# Final validation: number of dice * number of sides per die != 0.
:x~;*
# If we pass, do the actual die rolling. Otherwise give the error message.
{x~\{rand)+}+@*}'Invalid input'if

```

Online demo with test framework

# Answer
> 2 votes
# J - 130 (45?) char

This challenge seems to be a little biased towards regular expressions, especially with having to differentiate invalid input. J has a POSIX regex library, so it's not that bad, but it's not integrated as it is with Perl, so J fares no better than other languages.

```
+/@,`(1+?@#~)/`('Invalid input'"_)@.(0 e.$)0 1 1>.".>|.}.((,'?d','(\+[0-9]+)?$',~}.)'^([0-9]*[1-9][0-9]*)')(rxmatch rxfrom])1!:1]1

```

If you're just implementing the logic for valid expressions, like the Python/PHP solutions appear to, it's the more reasonable 45 chars:

```
+/,(1+[:?@#/1>.".;._2@,&'d')`".;._1'+',1!:1]1

```

Notable bits:

* `1!:1]1` is the input, and `(rxmatch rxfrom])` is the logic that returns the subexpression matches.
* Whether or not the input was legal is handled by the regex matching, so we can set the defaults for n and p with `0 1 1>.`. It looks backwards (n is 1 by default and p is 0) because we had to reverse (`|.`) the list earlier, so that the logic at the end executes in the right order.
* `@.` is the *Agenda* conjunction, essentially a J-ish switch statement. If the matches are empty (if 0 is an e.lement of the $hape: `0 e.$`), we emit the error message, else we go through with rolling the dice: `#~` to set out the dice, `1+?` to roll, and `+/@,` to add the modifier p and sum.

# Answer
> 2 votes
# Java, 378

Just wanted to try a solution with Java far from the best solution. But hey: Java isn't a golfing language in any case!

It gets the input from command line. First parameter `args[0]` is the input value.

```
class A{public static void main(String[]s){System.out.print(s[0].matches(
"(0+\\d+|[1-9]\\d*|)d(0+\\d+|[1-9]\\d*)(\\+\\d+)?")?z(s[0]):"Invalid input");}static int
z(String s){String[]a=s.split("d");String[]b=a[1].split("\\+");int c=a[0].isEmpty()?1:Byte.
decode(a[0]);int d=b.length<2?0:Byte.decode(b[1]);while(c-->0)d+=new java.util.Random().
nextInt(Byte.decode(b[0]))+1;return d;}}

```

Did you know, that `decode` is shorter than `valueOf`?

# Answer
> 2 votes
## TinyMUSH, 239

```
@dig/t +
@op d=+
@lo d=d
@fail d=Invalid input
@cr .
@set .=com
&d .=$*:\ifelse(regmatch(%0,^(\\\\d+)?d(\\\\d+)(\\\\+\\\\d+)?$,0 1 2 3),ifzero(and(or(not(strlen(%q1)),%q1),%q2),Invalid input,add(die(usetrue(%q1,1),%q2),%q3)),Invalid input)

```

The first four lines deal with the fact that "d" is an alias for the universal "down" exit with a built-in failure message when it doesn't exist; exits are scanned before user-defined commands. The remaining lines create an object with a user-defined command making use of the built-in die() function.

# Answer
> 2 votes
# PHP, 129

```
<?eval(preg_filter(~Ð¡×£›ÔÖÀ›×£›Ö×£Ô£›ÔÖÀÛÐ,~ÛžÂÝÛÎÝÀÅÎÄ™×ÄÛ–ÔÔÃÛžÄÛŒÔÂž‘›×ÎÓÛÍÖÖÄšœ—ÛŒÛÌÄ,$_GET[0])?:~šœ—Ý¶‘‰ž“–›ß–‘Š‹ÝÄ);

```

Uses a regex to create a expression which PHP then evaluates. Input is fed in via url: ?0=*argument*. Make sure you urlencode the + to %2b. Here's what it looks like in a more readable form:

```
eval(preg_filter('/^(\\d)?d(\\d)(\\+\\d)?$/','$a="$1"?:1;for(;$i++<$a;$s+=rand(1,$2));echo$s$3;',$_GET[0])?:'echo"Invalid input";');

```

Bitwise inverting the strings using `~` not only saves a character because you don't need quotes (PHP assumes they are strings) but also saves characters because you don't have to escape the backslashes in the regular expression.

The `?:` operator is a special form of the ternary operator. `$foo = $a ? $a : $b` is the same as `$foo = $a ?: $b`.

# Answer
> 1 votes
# Ruby, ~~167~~ 147

```
/^(\d+)?d(\d+)(\+\d+)?$/.match gets
abort'Invalid input'if !$~||$1==?0||!$2||$2==?0
p eval(([0]*($1||1).to_i).map{rand($2.to_i)+1}*?+)+($3||0).to_i

```

Uses a regexp to do all the work. Since I'm using `\d+`, the only things I need to check for invalid input are that there was a match, that neither `n` nor `m` were `0`, and that there was an `m`. If any of those are found, it aborts with a message (`'Invalid input'`). Then it just prints the result, since it would have aborted by now if the input was invalid.

The result-printing isn't that interesting, but...

```
([0]*($1||1).to_i)    # create an array of n elements (1 if there is no n)
.map{rand($2.to_i)+1} # fill it up with random numbers, where the number x is 1 < x < m+1
.inject(:+)           # add them all up
+($3||0).to_i         # and finally add the modifier (0 if there is none)

```

I later changed `.inject(:+)` to `eval(...*?+)`, but the idea is the same.

# Answer
> 1 votes
# Python 3, 184 bytes

```
import random,re
try:a,b,c=re.findall("^(\d*)d(\d+)(\+\d+)?$",input())[0];t=int(c or 0)+(sum(random.randint(1,int(b))for i in range(int(a or 1)))or q)
except:t="Invalid input"
print(t)

```

Passes all tests. If zero dice were allowed, it would be 6 bytes shorter by leaving out `(or q)`.

# Answer
> 1 votes
# Vyxal `V`, 89 bytes

```
h\d=[1p|]⁽±Ḋ→a⟨←aL5=|←a⌊±T⟨0|2|4⟩=|←a1i\d=|←a3i\+=⟩A[←a0i⌊ʁ(←a2i⌊℅⅛)¾∑←a4i⌊+,|«¢q⁰∷Ṗ-←¥«,

```

Try it Online!

Ties Perl

h\d=[1p|]         # Checks if the first character is a d, and prepends a 1
        ⁽±Ḋ→a     # Splits the string on non-numeric values, so consecutive digits stay grouped, then casts the list to variable "a"

     ⟨←aL5=|           # is it Length 5 (3 numbers, the "+" and the "d")
       ←a⌊±T⟨0|2|4⟩=|  # convert the numbers-as-strings to numbers and check if the numbers are in positions 1 3 and 5 (0 indexed)
         ←a1i\d=|     # is the second item in the list  "d"
           ←a3i\+=⟩    # is the fourth item "+"
                A     # are all of these checks true?

  [←a0i⌊ʁ               # If all the checks are true, create a range from 0-a[0]
        (←a2i⌊℅⅛)       #  for i in said range, generate a random number 0-a[2] and push to global array
             ¾∑←a4i⌊+,  # push global array, sum the values, and add a[4]

            |«¢q⁰∷Ṗ-←¥«, # If any of the checks are false, print "invalid input"
```
</code></pre>

# Answer
> 1 votes
# Zsh, 205 ~~223~~ bytes

```
set -e;e=Invalid\ input;trap '<<<$e' ERR
echo "^0d\n+$\nd+\n+d\n+.+\n[-|*]">p;[[ `grep -cfp<<<$1`>0 ]]&&<<<$e&&exit
q=(${(s: :)${1//(#s)d/1d}//[^0-9]/ });for i ({1..$q[1]})((s+=RANDOM%q[2]+1))
<<<$[s+q[3]]

```

Try it Online (with all test cases)

Writing the validation code was a chore. Without this guff, the solution would be a svelte 89 bytes:

```
q=(${(s: :)${1//(#s)d/1d}//[^0-9]/ });for i ({1..$q[1]})((s+=RANDOM%q[2]+1))
<<<$[s+q[3]]

```

# Answer
> 0 votes
# Python3, 204B

Mine beats the existing Python answer by adding in the required error handling and reading `d20` as `1d20` rather than `0d20` :)

```
import random,re
try:a,b,c=re.findall('^([1-9]\d*)?d(\d+)(\+\d+)?$',input())[0];I=int;R=sum(random.randrange(I(b))+1for x in[0]*(1if a==''else I(a)))+(0if c==''else I(c))
except:R='Invalid input'
print(R)

```

edited to fix 2 typos: `I(x) => I(c)`, `Invalid Input => Invalid input`

edited to fix regex: `\+?(\d*) => (\+\d+)?`

# Answer
> 0 votes
# Go, unseeded, 366 bytes

```
import(."regexp";."strconv";."math/rand")
func f(s string)int{k:=MustCompile(`^(\d*)d(\d+)(\+\d+)?$`).FindAllStringSubmatch(s,-1)
if len(k)<1||k[0][2]==""{return-1}
r:=k[0]
var n,l,f,m,t int
l=len(r)
n,_=Atoi(r[1])
if n<1&&r[1]==""{n=1}else if n<1{return-1}
if l>2{f,_=Atoi(r[2])}
if f<1{return-1}
if l>3{m,_=Atoi(r[3])}
for i:=0;i<n;i++{t+=Intn(f)+1}
t+=m
return t}

```

Attempt This Online!

# Go, seeded, 393 bytes

```
import(."regexp";."strconv";."math/rand";."time")
func f(s string)int{k:=MustCompile(`^(\d*)d(\d+)(\+\d+)?$`).FindAllStringSubmatch(s,-1)
if len(k)<1||k[0][2]==""{return-1}
r:=k[0]
var n,l,f,m,t int
l=len(r)
n,_=Atoi(r[1])
if n<1&&r[1]==""{n=1}else if n<1{return-1}
if l>2{f,_=Atoi(r[2])}
if f<1{return-1}
if l>3{m,_=Atoi(r[3])}
Seed(Now().Unix())
for i:=0;i<n;i++{t+=Intn(f)+1}
t+=m
return t}

```

Attempt This Online!

---
Tags: code-golf, random
---


# Question
Title: Dutch Burgerservicenummer (BSN) eleven-test
### Introduction:

A Dutch BSN (BurgerServiceNummer) is valid when it complies to the following rules:

* It only contains digits.
* The length should be either 8 or 9 in length.
* When the digits are indexed as `A` through `I`, the result of the following sum: `9xA + 8xB + 7xC + 6xD + 5xE + 4xF + 3xG + 2xH + -1xI` (NOTE the -1 instead of 1!) should be divisible by 11, and should not be 0.

### Challenge:

**Input:** A string or char-array representing the BSN.

**Output:** A truthy or falsey result whether the input is a valid BSN.

### Challenge Rules:

* The input format should be a string or char-array. You are not allowed to use an int-array of digits, or a (possibly octal) number. (You are allowed to convert it to an int-array of digits yourself, though, but not directly as argument.)
* Despite the restriction on the input above, you can assume all test cases will contain one or more digits (`[0-9]+`)
* Regarding the BSN with length 8 instead of 9, the Dutch Wikipedia states the following: "*For the eleven-test and for other practical uses, a leading zero is added to make the number of length 9.*" (source)

### General rules:

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation if necessary.

### Test cases:

```
// Truthy test cases:
111222333
123456782
232262536
010464554
10464554
44016773

// Falsey test cases:
000000000
192837465
247594057
88888888
73
3112223342
000000012

```

# Answer
> 9 votes
# 05AB1E, ~~23~~ 21 bytes

```
`()DgLR*OD11Ö89¹gåP0Ê

```

Try it online! or as a Test suite

**Explanation**

```
`                        # push input as individual chars onto stack
 (                       # negate top value
  )                      # wrap in list
   DgLR                  # range [len(input) ... 1]
       *O                # multiply with list of digits and sum
         D11Ö            # is evenly divisible by 11
             89¹gå       # len(input) is 8 or 9
                  P      # product of sum/divisible by 11/len in (8,9)
                   0Ê    # not equal to 0

```

# Answer
> 12 votes
# JavaScript (ES6) 57

Input as an array of chars. `reduceRight` saves the day!

```
s=>!(i=1,t=s.reduceRight((t,v)=>t-v*++i),!t|t%11|(i|1)-9)

```

**Test**

```
F=
s=>!(i=1,t=s.reduceRight((t,v)=>t-v*++i),!t|t%11|(i|1)-9)

;['111222333','123456782','232262536','010464554','10464554','44016773']
.forEach(t=>{
  var r=F([...t]);console.log(t,r)
})

;['000000000','192837465','247594057','88888888','73','3112223342','3112223342']
.forEach(t=>{
  var r=F([...t]);console.log(t,r)
})
```

# Answer
> 8 votes
## R, 86 67 bytes

Edit: Thanks to Jarko Dubbeldam for suggesting the dot product!

```
l=length(x<-scan(,""));s=as.double(x)%*%c(l:2,-1);!s%%11&s&l>7&l<10

```

Reads input from stdin and store as an array/vector of characters. Subsequently convert to numeric,multiply with the vector `9...2,-1` and check all conditions.

# Answer
> 7 votes
## JavaScript (ES6), ~~61~~ ~~60~~ ~~59~~ 58 bytes

Takes an array of chars as input. Returns `false` / `true`.

```
a=>!(a.map(c=>s-=--k?-c*k-c:c,k=a.length&9,s=0)|!s|k|s%11)

```

### Test cases

```
let f =

a=>!(a.map(c=>s-=--k?-c*k-c:c,k=a.length&9,s=0)|!s|k|s%11)

// truthy
console.log(f([..."111222333"]));
console.log(f([..."123456782"]));
console.log(f([..."232262536"]));
console.log(f([..."010464554"]));
console.log(f([..."10464554"]));
console.log(f([..."44016773"]));

// falsy
console.log(f([..."000000000"]));
console.log(f([..."192837465"]));
console.log(f([..."247594057"]));
console.log(f([..."88888888"]));
console.log(f([..."73"]));
console.log(f([..."3112223342"]));
```

# Answer
> 6 votes
## C, ~~112~~ ~~101~~ ~~96~~ ~~98~~ 104 bytes

*Thanks to @MartinEnder for saving ~~5~~ 3 bytes ~~while fixing my code~~!*

```
j,i,k,l;f(char*s){l=strlen(s);for(i=l,j=k=0;j<l;)k+=(s[j++]-48)*(i>1?i--:-1);return!(k%11)&&k&&(l^8)<2;}

```

Returns 0 if invalid, 1 if valid. Try it online!

# Answer
> 5 votes
# R, ~~95~~ ~~79~~ 93 bytes

```
function(x){y=as.double(el(strsplit(x,"")));z=y%*%c((q<-length(y)):2,-1);(z&!z%%11&q>7&q<10)}

```

Unnamed function that takes a string as argument. At first I overread the requirement of having a string as input instead of a number, but that's good, because it saves some bytes on conversion.

I am not sure how to interpret the array of characters, but if that means that you can use a vector of stringed digits `"1" "2" "3" "4" etc` as input, it becomes a bit shorter even:

```
function(x){y=as.double(x);z=y%*%c((q<-length(y)):2,-1);(z&!z%%11&q>7&q<10)}

```

Splits x into a numeric vector, then appends a 0 if length is 8, then calculates the dotproduct of vector y and `c(9,8,7,6,5,4,3,2,-1)`. Tests if the result is both nonzero and divisible by 11.

Saved 16 bytes thanks to the logic by @Emigna, implicitly appending the 0 in the creation of the vector `c(length(x):2,-1)`.

Forgot to add check for length 8/9, so +14 bytes :(

# Answer
> 4 votes
## Perl, 58 bytes (52 + 6)

```
@N=(-1,2..9);$r+=$_*shift@N for reverse@F;$_=$r&&/^\d{8,9}$/&&!($r%11)

```

Run with

```
perl -F// -lapE

```

Input passed through `STDIN`:

***Usage***

```
echo 232262536 | perl -F// -lapE '@N=(-1,2..9);$r+=$_*shift@N for reverse@F;$_=$r&&/^\d{8,9}$/&&!($r%11)'

```

---

Outputs `1` for as the truthy value, `0` or nothing for falsey values.

# Answer
> 3 votes
# C++14, ~~107~~ 106 bytes

-1 byte for `int` instead of `auto` in for loop.

As unnamed lambda returning via reference parameter. Requires input to be `std::string` or a container of char, like `vector<char>`.

```
[](auto c,int&r){int i=c.size();r=7<i&&i<10?-2*c.back()+96:~1<<9;for(int x:c)r+=(x-48)*i--;r=r%11<1&&r>0;}

```

Ungolfed and usage:

```
#include<iostream>
#include<string>

auto f=
[](auto c, int& r){
 int i = c.size();
 //if the size is correct, init r to -2*I so we can add I safely later
 //otherwise such a big negative number, that the final test fails
 r = 7<i && i<10 ? -2*c.back()+96 : ~1<<9;
 for (auto x:c)
  r += (x-48)*i--;
 r = r%11<1 && r>0;
}
;

using namespace std;
using namespace std::literals;

int main(){
 int r;
 f("111222333"s,r); std::cout << r << std::endl;
 f("123456782"s,r); std::cout << r << std::endl;
 f("010464554"s,r); std::cout << r << std::endl;
 f("10464554"s,r); std::cout << r << std::endl;
 f("44016773"s,r); std::cout << r << std::endl;
 std::cout << std::endl;
 f("000000000"s,r); std::cout << r << std::endl;
 f("192837465"s,r); std::cout << r << std::endl;
 f("73"s,r); std::cout << r << std::endl;
 f("88888888"s,r); std::cout << r << std::endl;
 f("3112222342"s,r); std::cout << r << std::endl;
 std::cout << std::endl;
 f("99999999"s,r); std::cout << r << std::endl;
 f("999999999"s,r); std::cout << r << std::endl;
}

```

# Answer
> 3 votes
# Jelly, 21 bytes

```
V€U×JN1¦µL:2=4×Sµ11ḍa

```

**TryItOnline!** or run all test cases

Truthy return values are non-zero (and are, in fact, the multiple of 11 sum).

### How?

```
V€U×JN1¦µL:2=4×Sµ11ḍa - Main link: string of digits  e.g. "111222333"
V€                    - eval each - effectively cast each to an integer (keeps leading zeros)
  U                   - upend                        e.g. [ 3, 3, 3, 2, 2, 2, 1, 1, 1]
    J                 - range(length)                e.g. [ 1, 2, 3, 4, 5, 6, 7, 8, 9]
   ×                  - multiply                     e.g. [ 3, 6, 9, 8,10,12, 7, 8, 9]
      1¦              - apply to index 1 (first element)
     N                -     negate                   e.g. [-3, 6, 9, 8,10,12, 7, 8, 9]
        µ             - monadic chain separation   e.g. z=[-3, 6, 9, 8,10,12, 7, 8, 9]
         L            - length(z)                    e.g. 9
          :2          - integer divide by 2          e.g. 4
            =4        - equals 4?                    e.g. 1
               S      - sum(z)                       e.g. 66
              ×       - multiply                     e.g. 66
                µ     - monadic chain separation   e.g. z=66
                 11ḍ  - divides(11, z)               e.g. 1
                    a - and z (for z=0 case)         e.g. 66 (truthy)

```

# Answer
> 3 votes
# Haskell, ~~116~~ ~~112~~ 102 bytes

```
f x=div(length x)2==4&&g x>0&&h x
h=((==0).(`mod`11)).g
g=sum.zipWith(*)(-1:[2..]).map(read.(:[])).reverse

```

`g` counts the sum used in the eleven-proef of `h`, while `f` also checks for the correct length and that the eleven-proef is not 0. Especially the checks of `f` take a lot of bytes.

EDIT: saved 10 bytes thanks to Lynn and `div` rounding down.

# Answer
> 3 votes
# Befunge, 72 bytes

```
>+~>:0`v
^1\-*68_\2/4-!00p*8>1-10p\910gv
@.!+!\%+56:*g00$  _^#!:g01+*-<<

```

Try it online!

**Explanation**

```
>+~>:0`v            Read characters from stdin until EOF, converting each digit into
^1\-*68_              a number on the stack, and keeping a count of the characters read.

      \2/4-!00p     Save !(count/2-4), which is only true for valid lengths (8 and 9).
               *    Multiply the EOF (-1) with the final digit; this is the initial total.

8>1-10p\910gv       Loop over the remaining 8 digits, multiplying each of them by 9-i and
 ^#!:g01+*-<<         add to the total; i goes from 7 down to 0, so 9-i goes from 2 to 9.

               $    Drop the loop counter.
           *g00     Multiply total by the length calculation (invalid lengths become 0).
      %+65:         Make a copy of the total, and calculate modulo 11.
    !\              Boolean not the other copy to check for zero.
  !+                !(total%11 + !(total)) is only true for non-zero multiples of 11.
@.                  Output the result and exit.

```

# Answer
> 3 votes
# MATL, 36 bytes

Not the longest MATL program I've ever written, but I like how `if`/`else` statements get very lengthy very quickly in golfing languages. I feel that this solution may not be optimal in MATL, but as of yet I can't optimize it any further. I'm thinking of using the double 0 somewhere, and maybe cut down on the `t`'s everywhere.

```
48-tn8=?0wh]tn9=?P[a2:9]*st11\~Y&}x0

```

Try it online! Explanation:

```
48-                                  % Subtract 48 (ASCII '0')
   tn                                % Duplicate. Get length.
     8=?                             % If length equals 8
        0wh                          %     Prepend 0 to the duplicate
           ]                         % End if.
            t                        % Duplicate again.
             n9=?                    % If length equals 9.
                 P                   %     Reverse the duplicate
                  [a2:9]*            %     Element-wise product with [-1 2 ... 9]
                         s           %     Sum
                          t11\       %     Duplicate sum, modulus 11
                              ~Y&    %     Result on stack: modulus==0 AND sum!=0
                                 }   % Else
                                  x0 %     Remove the duplicate. Put 0 on stack.
                                     % Display implicitly.

```

# Answer
> 3 votes
# MATL, 26 bytes

```
!UGg*R!s0&)s-t11\~Gn8-tg=v

```

The result is a non-empty column vector, which is truthy iff all its entries are nonzero.

Try it online!

Or verify all test cases with each result on a different line.

### Explanation

This tests the three conditions in the following order:

1. Weighted sum is nonzero;
2. Weighted sum is dividible by 11;
3. Length is 8 or 9.

Consider input `'8925'` for the explanation. `;` is the row separator for matrices.

```
!     % Implicit input. Transpose into a column vecvtor
      % STACK: ['8'; '9'; '2'; '5']
U     % Convert each digit to number
      % STACK: [8; 9; 2; 5]
Gg    % Push a row array of ones as long as the input
      % STACK: [8; 9; 2; 5], [1 1 1 1]
*     % Multiply, element-wise with broadcast
      % STACK: [8 8 8 8; 9 9 9 9; 2 2 2 2; 5 5 5 5]
R     % Upper triangular part
      % STACK: [8 8 8 8; 0 9 9 9; 0 0 2 2; 0 0 0 5]
!     % Transpose
      % STACK: [8 0 0 0;8 9 0 0;8 9 2 0;8 9 2 5]
s     % Sum of each column. This multiplies last element by 1, second-last by 2 etc
      % STACK: [32 27 4 5]
0&)   % Split into last element and remaining elements
      % STACK: 5, [32 27 4]
s     % Sum of array
      % STACK: 5, 63
-     % Subtract
      % STACK: -58. This is the result of condition 1
t11\  % Duplicate. Modulo 11
      % STACK: -58, 8
~     % Logical negation
      % STACK: -58, 0. This gives condition 2
Gn    % Push numnber of entries in the input
      % STACK: -58, 0, 4
8-    % Subtract 8. For valid lengths (8 or 9) this gives 0 or 1
      % STACK: -58, 0, -4
tg    % Duplicate. Convert to logical: set nonzero values to 1
      % STACK: -58, 0, -4, 1
=     % 1 if equal, 0 otherwise. Lenghts 8 or 9 will give 1. This is condition 3
      % STACK: -58, 0, 0
v     % Vertically concatenate the entire stack. This is truthy iff all values
      % are non-zero. Implicitly display
      % STACK: [-58; 0; 0]

```

# Answer
> 3 votes
## PHP ~~139~~ 128 bytes

```
 $u=-1;$i=$argv[1];while($u<=strlen($i)){$c+=($u*(substr($i,-(abs($u)),1)));$u +=$u<0?3:1;}echo($c>0&&!($c%11)&&$u>8&&$u<11?1:0);

```

Could not get the CLI to just echo the true of false. Had to make do it this way. Any ideas?

128 bytes: Turned "true" and "false" to 1 and 0.

# Answer
> 3 votes
## PowerShell v2+, 96 bytes

```
param($n)$i=8-($n.count-eq8);!(($b=($n|%{(-"$_",(($i+1)*+"$_"))[!!$i--]})-join'+'|iex)%11)-and$b

```

OK, I'll admit, this looks like a complete mess. And it kinda is. But, bear with me and we'll get through it.

We take input `$n` (as a `char`-array) and set `$i` equal to `8` minus a Boolean value for whether there are 8 items in `$n`. Meaning, if there are 8 items, then `$i` would be `7`.

The next section combines the calculation with our output. Working from the inside, we loop through `$n` with `$n|%{...}`. Each iteration, we use a pseudo-ternary to come up with one of two results -- either `-"$_"` or `(($i+1)*+"$_")`. The index is based on whether `$i` is `0` or not (i.e., we've hit the `-1xI` case from the challenge equation), which gets post-decremented for the next go-round. Those are all gathered up in parens and `-join`ed together with `+`. For example, with input `111222333` at this point we'd have `9+8+7+12+10+8+9+6+-3`. That is piped to `iex` (short for `Invoke-Expression` and similar to `eval`) before being stored into `$b`. We then take that `%11` and perform a Boolean-not `!(...)` on that (i.e., so if it is divisible by 11, this portion is `$true`). That's coupled with `-and$b` to ensure that `$b` is non-zero. That Boolean result is left on the pipeline and output is implicit.

### Examples

```
PS C:\Tools\Scripts\golfing> 111222333,123456782,232262536,010464554,10464554,44016773|%{"$_ -> "+(.\dutch-burgerservicenummer.ps1 ([char[]]"$_"))}
111222333 -> True
123456782 -> True
232262536 -> True
10464554 -> True
10464554 -> True
44016773 -> True

PS C:\Tools\Scripts\golfing> 000000000,192837465,247594057,88888888,73,3112223342,000000012|%{"$_ -> "+(.\dutch-burgerservicenummer.ps1 ([char[]]"$_"))}
0 -> False
192837465 -> False
247594057 -> False
88888888 -> False
73 -> False
3112223342 -> False
12 -> False

```

# Answer
> 3 votes
# Python 3.8 (pre-release), ~~111~~ ~~110~~ 104 bytes

*-1 byte thanks to @Kevin-cruijssen*

*-6 bytes by reading the rules (yay)*

```
lambda s:len(s)in(8,9)and not(x:=sum(a:=[*map(lambda n,m:int(n)*m,s[::-1],range(1,10))])-2*a[0])%11and x

```

Try it online!

There's probably more golfing to do, but this is what I have for now.

# Answer
> 2 votes
## Python 2, 102 bytes

```
def f(i):S=sum(a*b for a,b in zip([-1]+range(2,10),map(int,i)[::-1]));return(7<len(i)<10)*(S%11<1)*S>0

```

# Answer
> 2 votes
# Python 2, 96 bytes

```
def g(s):u=7<len(s)<10and sum(x*int(('0'+s)[-x])for x in range(2,10))-int(s[-1]);print(u%11<1)*u

```

Takes a string as input. The function adds a `'0'` to the front of the string whether it needs it or not, and uses Python's negative indices to add elements, starting from the end of the string and working back-to-front.

The `-1xI` is handled separately, using a second call to `int()`. I couldn't figure out how to avoid this without costing more bytes than I saved.

`def g(s):u=7<len(s)<10and sum(x*int(('0'+s)[-x])for x in range(10))-2*int(s[-1]);print(u%11<1)*u` would work just as well, since it would add `1` times `s[-1]` but then subtract it twice, and it would also add `0` times (something) which of course wouldn't affect the sum.

# Answer
> 2 votes
# Brain-Flak, 345 Bytes

Includes +3 for `-a`

```
([]){{}({}[((((()()()){}){}){}){}]<>)<>([])}{}<>([][(()()()()){}]){({}[()]){([]){{}{}([])}}}{}([{}])({}({}){})({}({})({}){})({}(({}){}){})({}(({})({})){}{})({}(({})({}){}){})({}((({}))({}){}){}{})({}((({}){}){}){})(({}(((({})){}){}){}{}{}<(((()()())()){}{})>)){{}({}(<>))<>{(({})){({}[()])<>}{}}{}<>([{}()]{}[{}]<(())>){((<{}{}>))}{}(<()>)}{}

```

Truthy is 1, Falsy has a 0 on the top of the stack.

Try it Online!

I'm pretty sure there is a shorter way to do the multiplication in a loop, but I haven't found it yet.

```
#reverse and subtract 48 from all numbers (ASCII -> decimal)
([]){{}({}[((((()()()){}){}){}){}]<>)<>([])}{}<>

([][(()()()()){}])       #height - 8
{({}[()]){               #if not 0 subtract 1
   ([]){{}{}([])}        #if still not 0 pop everything
}}{}                     #this loop pops everything unless there are 8 or 9 digits

([{}])                   # -I
({}({}){})               # H*2
({}({})({}){})           # G*3
({}(({}){}){})           # F*4
({}(({})({})){}{})       # E*5
({}(({})({}){}){})       # D*6
({}((({}))({}){}){}{})   # C*7
({}((({}){}){}){})       # B*8
(({}(((({})){}){}){}{}{} # A*9 pushed twice with:
<(((()()())()){}{})>))   # 11 under it

{{} #if not 0
({}(<>))<>{(({})){({}[()])<>}{}}{}<>([{}()]{}   # mod 11
[{}]<(())>){((<{}{}>))}{}                       # logical not
(<()>)                                          # push 0 to exit loop
}{}
                                                # implicit print

```

# Answer
> 2 votes
## C#, ~~120~~ 115 bytes

This loops through the `char[]` it receives as input and returns true or false:

```
bool b(char[]n){int r=0,k,i=0,l=n.Length;for(;i<l;i++){k=i==l-1?-1:l-i;r+=k*(n[i]-48);}return r>0&r%11<1&l<10&l>7;}

```

Fiddle: https://dotnetfiddle.net/3Kaxrt

I'm sure I can scrape out a few bytes, especially in the messy `return`. Any ideas welcome!

Edit: Saved 5 bytes thanks to Kevin. I had no idea I could use `&` instead of `&&`!

# Answer
> 2 votes
# Java 8, ~~115~~ ~~98~~ 94 bytes

```
b->{int l=b.length,i=l,r=0;for(;l>7&l<10&i-->0;)r-=(b[i]-48)*(l-i<2?1:i-l);return r>0&r%11<1;}

```

I'm surprised no one has posted a Java answer yet, so here is one.

-4 bytes thanks to *@ceilingcat*.

**Explanation:**

Try it here.

```
b->{                // Method with character-array as parameter and boolean return-type
  int l=b.length,   //  Length of the array
      i=l,          //  Index-integer, starting at this length
      r=0;          //  The result-sum, starting at 0
  for(;l>7&l<10     //  Start looping if the length is either 8 or 9
       &i-->0;)     //  And continue looping downwards while the index is larger than 0
      r-=           //   Decrease the result-sum by:
         (b[i]-48)  //    The current digit
         *(         //    Multiplied by:
           l-i<2?   //     If `l-i` is 1:
            1       //      Simply multiply by 1
           :        //     Else:
            i-l);   //      Multiply by `i-l`
  return r>0        //  Return if the result-sum is larger than 0,
    &r%11<1;}       //   and if the result-sum is divisible by 11

```

# Answer
> 2 votes
# PHP, ~~86~~ ~~85~~ ~~84~~ ~~83~~ ~~82~~ 79 bytes

Note: uses PHP 7.1 for negative string indices.

```
for($l=log10($a=$argn);~$c=$a[-++$x];)$s+=$x>1?$x*$c:-$c;echo$s%11<1&$l>7&$l<9;

```

Run like this:

```
echo 010464554 | php -nR 'for($l=log10($a=$argn);~$c=$a[-++$x];)$s+=$x>1?$x*$c:-$c;echo$s%11<1&$l>7&$l<9;';echo
> 1

```

# Version for PHP \< 7.1 (+10 bytes)

```
echo 010464554 | php -nR 'for($l=log10($a=$argn);~$c=$a[strlen($a)-++$x];)$s+=$x>1?$x*$c:-$c;echo$s%11<1&$l>7&$l<9;';echo

```

# Explanation

```
for(
  $l=log10(         # Take the log of the input number.
    $a=$argn        # Set input to $a
  );
  ~$c=$a[-++$x];    # Iterate over digits of input (reverse). Negate to
                    # change every char to extended ASCII (all truthy),
                    # without changing empty sting (still falsy, ending
                    # the loop).
)
  $s+=$x>1?         # Add current char to the sum...
     ?$x*$c:-$c;    # multiplied by $x, unless $x is 1; subtract it.
echo
  $s%11<1 &         # Check if sum is divisible by 11, and
  $l>7   &          # log of the input is greater than 7, and
  $l<9;             # log of the input is less than 9. Outputs 0 or 1.

```

# Tweaks

* Shorter way to distinguish between empty string and `"0"`, saved a byte
* Since `10000000` is invalid, no need to compare with `greater than or equals`, `greater than` suffices, saving a byte
* Shorter way to subtract least significant digit
* Negate char instead of XOR, saving a byte
* Saved 3 bytes by using `-R` to make `$argn` available

# Answer
> 2 votes
# Ly, 58 bytes

```
iy9L[r'0r!]ppry9=[pp8[f'0-srlrpsrl`*r,]p'0-N&+[92+%!u;]]u;

```

Try it online!

I thought this would be shorter... There's probably room for improvement?

First part, input digits, pad with leading `0` if necessary

```
i              - input all digits (as codepoints)
 y             - push the stack size onto the stack
  9L[    !]p   - if/then block, true if <9 digits
     r'0r      - reverse stack, push 0, reverse again
            p  - pop the stack size entry off the stack

```

Second part, only process digits if we end up with 9 digits

```
r              - reverse the stack
 y             - push the stack size info the stack
  9=[pp ... ]  - if/then block, true if stack size is 9

```

Third part, process the first 8 digits

```
8[               ,]p - loop 8 times
  f                  - bring digit forward
   '0-               - convert from char to int
      s              - save digit value
       rl            - copy digit to bottom of stack
         rp          - delete from top of stack
           s         - save current loop var
            rl       - copy to bottom of stack
              `      - increment by one
               *     - multiple with current digit
                r    - reverse stack

```

Fourth part, process last digit, sum results

```
'0-     - convert digit from char to int
   N    - negate
    &+  - sum all entries on the stack

```

Fifth part, "is it zero?" and "is divisible by 11?" checks

```
[       ]   - if/then block, true is sum is non-zero
 92+        - push 11 onto the stack
    %!      - modulo math to get remainder, invert the result
      u;    - print top of stack as int, then exit

```

Last part, prints "falsey" if some success criteria wasn't met

```
u;  - print top of stack (which will be 0) and exit

```

# AWK, 88 bytes

```
$0="0"$0,n=gsub(a," ")-1{b=n-9;c=9}!b||b==1{for(d-=$n;++b<n;e=d%11)d+=$b*c--}1,$0=!e*!!d

```

Try it online!

And one I had fun golfing, just to abuse the flexibility of AWK.

```
$0="0"$0                             - append "0" to the input
           gsub(a," ')-1             - re-parse the input, one char per arg
        ,n=           -1             - set "n", decr RC to get number of chars
                        {         }  - code block...
                         b=n-9;      - set "b" to first char to use
                               c=9   - set "c" to initial multiplier val

!b||b==l                                   - true is we got 8 or 9 chars
        {                                } - code block...
         for(                  )           - loop over initial 8 chars
             d-=$n;                        - init: "d" set to neg of last digit
                   ++b<n;                  - test: ends after 8 chars processed
                         e=d%11            - loop-end: "e" is remainder of "%11"
                                d+=$b*c--  - loop-code: multiply and add next digit

1,           - unconditionally run implicit "print $0" code block
  $0=!e*!!d  - "$0" is 1 if accum value is non-zero and divisible by 11

```

# Answer
> 2 votes
# K (ngn/k), ~~42~~ 41 bytes

-1 byte from @ngn's improvements

```
{(4=-2!#x)&t&~11!t:+/(|-1,2+!8)*-9#0,.'x}

```

Try it online!

Takes the input as a list of characters.

* `.'x` convert each digit to its integer (e.g. convert `"123"` to `1 2 3`)
* `-9#0,` prepend a `0`, then take the last nine values (handles padding 8-digit codes, and avoids errors on input that is not 9 digits long)
* `(|-1,2+!8)*` generate `9 8 7 6 5 4 3 2 -1`, and multiply the parsed digits by this
* `t:+/` take the sum, storing in variable `t`
* `t&~11!t` check that 11 evenly divides t, and that t is non-zero
* `(4=-2!#x)&` also check that the input is 8 or 9 characters long (literally: the length of the input (integer) divided by 2 is equal to 4)

# Answer
> 2 votes
# Ruby, 65 bytes

-1 byte thanks to Kevin Cruijssen

```
->n{a,*b=n.to_i.digits
i=1
b[6]&&(b[..7].sum{_1*i+=1}-a)%11<1||p}

```

Attempt This Online!

# Answer
> 1 votes
## Clojure, 114 bytes

Well this is something, `-` substracts the rest of the arguments from the first one so that handles the special case of weight `-1`. This function returns `nil` for inputs of invalid length, but on `if` clauses they operate the same as `false`. `(#{8 9}(count v))` returns `nil` if length of `v` is not 8 or 9.

```
(fn[v](if(#{8 9}(count v))(#(and(< % 0)(=(mod % 11)0))(apply -(map *(range 1 10)(reverse(map #(-(int %)48)v)))))))

```

Test cases:

```
(pprint (group-by f (map str [123456782 232262536 "010464554" 10464554 44016773 "000000000" 192837465 247594057 88888888 73 3112223342 "000000012"])))
{true  ["123456782" "232262536" "010464554" "10464554" "44016773"],
 false ["000000000" "192837465" "247594057" "88888888" "000000012"],
 nil   ["73" "3112223342"]}

```

# Answer
> 1 votes
# Perl 5, 63 + 2 (`-F`) = 65 bytes

```
$F[-1]*=-1;map$s+=++$i*$_,reverse@F;say/^.{8,9}$/&&$s&&!($s%11)

```

Try it online!

# Answer
> 1 votes
# Stax, 23 bytes

```
╪╦µΘç}<╔▼◘╞i∟~¿≥←║▐√ 4u

```

Run and debug online!

## Explanation

Uses the unpacked version to explain.

```
i%8A:byr{]ei^*mBN+|+c11%!L|A
i                               Suppress implicit eval
 %8A:b                          Length is 8 or 9 (Element #1 on the final stack)
      yr                        Reverse input
        {     m                 Map each element with
         ]e                         Its numerical value
           i^*                      Multiplied current 1-based loop index
               BN+              Negate the first element
                  |+            Sum (Element #2 on the final stack)
                    c11%!       Sum is multiple of 11 (Element #3 on the final stack)
                         L|A    Collect all the three elements and `and` them.

```

# Answer
> 1 votes
# Python 3.8, 96 bytes

```
lambda i:7<len(i)<10*((S:=sum(a*b for a,b in zip([-1,*range(2,10)],map(int,i[::-1]))))%11<1)*S>0

```

Try it online!

Similar to @TFeld's Python 2 answer, but uses Python 3.8 assignment expressions and a few other tricks to get it down to 96 bytes.

# Answer
> 1 votes
# TI-Basic, 60 bytes

```
max(length(Ans)={8,9})sum(seq(int(10fPart(expr(Ans)/₁₀^(I)))(I-2(I=1)),I,1,9
not(fPart((Ans+not(Ans))/11

```

Takes input in `Ans` as a string. Output is stored in `Ans` and is displayed.

# Answer
> 1 votes
# Python 3.8 (pre-release), 87 bytes

```
lambda s:s[7:][:(q:=eval('-'+'+'.join(map('*'.join,zip('123456789',s[::-1])))))>q%11<1]

```

Try it online!

Returns a non-empty string if the number is valid, and an empty string otherwise.

# Answer
> 0 votes
# MathGolf, ~~23~~ 20 bytes

```
~b*]h╒xm*Σ_A÷l£½4=ß╓

```

Outputs `1`/`0` for truthy/falsey respectively.

Try it online.

**Explanation:**

```
~          # Dump the digits of the (implicit) input-string to the stack
 b*        # Multiply the top one by -1
   ]       # Wrap all values on the stack into a list
    h      # Push the length (without popping the list)
     ╒     # Pop and push a list in the range [1,length)
      x    # Reverse it to (length,1]
       m*  # Multiply the values in the two lists at the same positions
         Σ # Sum it together
_          # Duplicate this sum
 A÷        # Pop and check if it's divisible by 11
l£         # Push the input-length
  ½        # Integer-divide it by 2
   4=      # Check if it's equal to 4
ß          # Wrap all three values on the stack into a list
 ╓         # Pop and push the minimum
           # (after which the entire stack is output implicitly as result)

```

---
Tags: code-golf, string, arithmetic, decision-problem
---


title: Period 2 Reversed Quine

text:
# Question
Title: Period 2 Reversed Quine
Your task is to write a program that outputs its own source code in reverse. However, when the reversed code is run, it should output the source code, facing the correct direction.

## Example

Say your program is `abc`. When run, it should output `cba`. `cba`, when run, should output `abc`.

## Rules

Your program should follow all the rules of a proper quine (except for outputting the source code). Palindromes are disallowed.

Random note: I am aware of this but I believe that this challenge is different because the transformed code must have the same properties.

# Answer
> 9 votes
# RProgN, 3 bytes

```
1
2

```

*Thanks to @MartinEnder for reminding me about this answer.*

Try it online!

### How it works

This exploits a potential flaw in our definition of proper quine:

> It must be possible to identify a section of the program which encodes a different part of the program. ("Different" meaning that the two parts appear in different positions.)
>
> Furthermore, a quine must not access its own source, directly or indirectly.

That's obviously the case here, as the output is the reverse of the code and the code is not a palindrome.

RProgN – *reverse* programmer notation – uses a LIFO stack and prints the items on it in the order they are popped. The two tokens **1** and **2**, separated by spaces and/or newlines, get popped in reverse order and are printed separated by a newline.

This prints the reversed program

```
2
1

```

which, in turn, prints the original one.

!enilno ti yrT

# Answer
> 10 votes
# Befunge-98, 33 bytes

```
b3*>1#;-:0g,:#;_@_;#:,g0:-;#1>*b3

```

Try it online!

# Answer
> 7 votes
## Fission 2, 10 bytes

```
"L;L'!+!'_

```

Try it online!

This prints:

```
_'!+!'L;L"

```

Try it online!

And vice versa.

### Explanation

This is a modification of the reverse quine. It's working to our advantage here that `!` is used for printing and is also only one code point away from the the quote `"`. That makes it easier to make the quote printing section palindromic (the `'!+!'`). Let's start with the first code:

```
"L;L'!+!'_

```

This program has two entry points at the `L`s, which each creates a left-going atom. However, the right one immediately hits the `;` which destroys it. The left one enters string mode and wraps around to the end, so that it prints the entire code (except the `"`) from back to front. That already gives us `_'!+!'L;L`. All that's left is to print the `"`. `_` can be ignored, `'!` sets the atom's mass to 33 (the code point of `!`), `+` increments it to `"`, and `!` prints it. That's all the output done. The `'L` sets the atoms mass to the code point of `L` but that's irrelevant. `;` destroys this atom as well and since no atoms are left, the program terminates.

Now the other way round:

```
_'!+!'L;L"

```

Again, we have two entry points but one atom is immediately destroyed. This time we move through the `!+!'` section first, so we start by printing a quote. The `'_` is again irrelevant, but we need the `_` (or some other useless character) here to avoid `'` escaping the `"`. The atom wraps to the end, traverses the source code once in string mode to print the rest of the program in reverse, the `L` is then ignored and `;` destroys the atom and terminates the program.

# Answer
> 0 votes
# \<\>\<, 19 bytes

```
"rf2+2*rol?!;70.05;!?lor*d3r'

```

Try it

**Reversed**

```
'r3d*rol?!;50.07;!?lor*2+2fr"

```

it yrT

So I'm not super sure if this is a proper quine. Let me know what your opinion is, I'll delete the post if people think it's invalid.

I use the `'` to switch into quoting mode that will push the code raw into the stack. Then when the pointer wraps around it will exit the quote again. However, I do need to manually add the `'` quote character at the end as `d3*`, and `"` as `rf2+2`. These would count as "code that encodes a different part of the program".

---
Tags: code-golf, quine
---


title: The Art of Word Shaping

text:
# Question
Title: The Art of Word Shaping
# The Art of Word Shaping

Given a binary matrix and a string of letters, replace all 1's in the matrix, moving from top to bottom and from left to right within each row, with the letters of the string. Once the letters have been formed into the shape of the matrix, print the matrix, replacing 0's with spaces. It's probably easier to just give an example or two.

---

Case: *Base case...*

**Input One:**

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

"PPCGPPCG"

```

**Output One:**

```
  P
 P C
G   P
 P C
  G

```

---

Case: *If the input string is longer than the number of ones...*

**Input Two:**

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

lambda

```

**Output Two:**

```
l
 a
m b

```

---

Case: *If the input string is shorter than the number of ones...*

**Input Three:**

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

PPCG

```

**Output Three:**

```
PPC
G P
PCG

```

---

# Available Assumptions

* You may assume the input string is never empty.
* You may assume the matrix will never be empty.
* You may not assume that the binary matrix will never be all zeros.

# Rules

* If the string is shorter than the number of ones, repeat the string; all ones must be replaced.
* If the string is longer than the number of ones, only use what is needed.
* You may use True/False in place of integers/bits for the input.
* Trailing spaces ARE REQUIRED, all zeros must be **replaced** with spaces.
* A single trailing newline is acceptable.
* This is code-golf, lowest byte count wins.

# Answer
> 3 votes
# MATL, 11 bytes

```
yz:)1Gg!(c!

```

Inputs are a numeric matrix (with `;` as row separator) and a string.

**Try it online!** Or verify test cases: **1**, **2**, **3**.

```
y       % Take the two inputs implicitly. Duplicate the first
        % STACK: [1,0,0; 0,1,0; 1,0,1], 'lambda', [1,0,0; 0,1,0; 1,0,1]
z       % Number of nonzeros
        % STACK: [1,0,0; 0,1,0; 1,0,1], 'lambda', 4
:       % Range
        % STACK: [1,0,0; 0,1,0; 1,0,1], 'lambda', [1 2 3 4]
)       % Reference indexing (select values)
        % STACK: [1,0,0; 0,1,0; 1,0,1], 'lamb'
1Gg     % Push first input as a logical matrix; will be used as index
        % STACK: [1,0,0; 0,1,0; 1,0,1], 'lamb', [1,0,0; 0,1,0; 1,0,1]
!       % Transpose. This is necessary because MATL uses column-major order
        % (down, then accross)
(       % Assignment indexing (fill with values). Since the original matrix
        % is numeric, the new values are introduced as their ASCII codes
        % STACK: [108, 0, 109; 0, 97, 0; 1, 0, 98]
c       % Convert to char
        % STACK: ['l m'; ' a '; '  b']
!       % Transpose back. Implicitly display
        % STACK: ['l  '; ' a '; 'm b']

```

# Answer
> 8 votes
# Vim, ~~44~~ 42 bytes

```
qqy$P0xjf1"_xP{@qq@q:s/0/ /g^M:s/,/^V^M/g^M{D

```

Saved 2 bytes thanks to @DjMcMoylex!

Here, the `^M` is a literal newline, and the `^V` is `CTRL-V`

Takes the input in this format:

```
PPCG
00100,01010,10001,01010,00100

```

**Disclaimer:** If the string is longer than ~40 chars long, your computer might run out of ram.

Explanation:

```
qq             @qq@q                            # Start recording a recursive macro.
  y$P0x                                         # Duplicate the string and cut out the first character
       jf1"_xP{                                 # Find the first 1, and replace it with the cut character from the string.
                                                # Now we have replaced all the 1's with their respective character, but we still have the array in the original format, and we have the string massivly duplicated at the first line, so we need to clean it up:
                    :s/0/ /g^M                  # Replace all 0's with a space
                              :s/,/^V^M/g^M     # Replace all ,'s with a newline. The ^V acts like a backslash, it escapes the newline so that the command isn't run too soon
                                           {D   # Delete the first line

```

Here's a gif of me "running" the "program":

# Answer
> 6 votes
# JavaScript ES6, ~~67~~ ~~53~~ ~~50~~ 49 bytes

Saved 3 bytes thanks to @ETHproductions Saved 1 more thanks to @Neil

```
(a,b,i)=>a.replace(/./g,c=>+c?b[++i]||b[i=0]:' ')

```

```
f=
(a,b,i)=>a.replace(/./g,c=>+c?b[++i]||b[i=0]:' ')

G=_=>h.innerHTML = f(`00100
01010
10001
01010
00100`,z.value)
h.innerHTML = G()
```

```
<input id=z oninput="G()" value="PPCG"></input>
<pre id=h>
```

Old code before I knew that string matrices are a valid input format:

```
(a,b)=>a.map(c=>c.map(d=>d?b[i++%b.length]:' ').join``,i=0).join`
`

```

```
f=
(a,b)=>a.map(c=>c.map(d=>d?b[i++%b.length]:' ').join``,i=0).join`
`

G=_=>h.innerHTML = f([[0,0,1,0,0],[0,1,0,1,0],[1,0,0,0,1],[0,1,0,1,0],[0,0,1,0,0]],z.value)
h.innerHTML = G()
```

```
<input id=z oninput="G()" value="PPCG"></input>
<pre id=h>
```

# Answer
> 6 votes
## Retina, ~~41~~ 33 bytes

```
0

+1`(.)(.*)(\D+)1
$2$1$3$1
A1`

```

Try it online!

The input string is given on the first row of the input, followed by the matrix. Since Retina has no concept of lists (or really anything except strings), there are no separators in the binary matrix except for linefeeds to separate rows.

### Explanation

```
0

```

Turns zeros into spaces.

```
+1`(.)(.*)(\D+)1
$2$1$3$1

```

Repeatedly replace the first `1` with the first character of the input string while also rotating that character to the end of the input string. This takes care cases where there are more `1`s than characters in the input string.

```
A1`

```

Discard the first line, i.e. the input string.

# Answer
> 5 votes
## Perl, 40 bytes

36 bytes of code + `-i -p` flags.

```
@F=$^I=~/./g;s/1/$F[$i++%@F]/g;y;0;

```

(note the final space and the lack of final newline).

To run it, write the input string after `-i` flag, and supply the matrix in the input :

```
perl -iPPCGPPCG -pe '@F=$^I=~/./g;s/1/$F[$i++%@F]/g;y;0; ' <<< "00100
01010
10001
01010
00100"

```

If your Perl is a bit old, you might need to add a final semicolon (after the space).

# Answer
> 5 votes
# Python 2, ~~114~~ 71 bytes

Turns out I was re-inventing the wheel, a simple double replace on a multiline string works quite well. The string has the additional benefit of being able to count zeros directly rather than having to do the really ugly `s*len(L)*len(L[0])` for a nested list

```
lambda S,s:S.replace("0"," ").replace("1","{}").format(*s*S.count('0'))

```

Old solution:

```
lambda s,L:"\n".join(["".join(map(lambda n:chr(n+32),l)).replace("!","{}")for l in L]).format(*s*len(L)*len(L[0]))

```

First we convert everything + 32 with `chr` (all zeros become spaces), then we replace all of the `!` with `{}` to allow using the `format` function.

~~If `NULL` can be counted as a space~~ If I decide to cheat and use `NULL` instead of space, I can skip the addition of 32 to save 12 bytes. (`print` displays `'\x00'` as a space)

```
lambda s,L:"\n".join(["".join(map(chr,l)).replace('\x01','{}')for l in L]).format(*s*len(L)*len(L[0]))

```

# Answer
> 3 votes
# PHP, ~~110~~ ~~91~~ ~~97~~ ~~88~~ ~~82~~ ~~81~~ ~~80~~ 75 bytes

saved 6 bytes thanks to @user59178

```
while(""<$c=$argv[1][$i++])echo$c<1?$c?:" ":($s=$argv[2])[$k++%strlen($s)];

```

Run with `-r`. Expects matrix as multiline string in first argument, string in second argument.

# Answer
> 3 votes
# APL, 18 bytes

```
{(⍴⍺)⍴X\⍵⍴⍨+/X←,⍺}

```

This is a function that takes a boolean matrix as its left argument and a string as its right argument.

```
      (↑(1 0 0)(0 1 0)(1 0 1)) {(⍴⍺)⍴X\⍵⍴⍨+/X←,⍺}'lambda'
l
 a
m b

```

Explanation:

APL has a built-in that does something like this, `\` (expand). However, it only works on vectors, and it requires each character to be actually used.

* `X←,⍺`: flatten the matrix and store the result in X.
* `⍵⍴⍨+/X`: reshape the character vector so that it has the required amount of elements (this also takes care of lengthening the string by repeating characters if necessary).
* `X\`: take one of the characters for each `1` and a space for each `0` in `X`.
* `(⍴⍺)⍴`: reshape the result so that it has the shape of the original matrix.

# Answer
> 3 votes
## PowerShell v2+, 70 bytes

```
param($a,$b)$b|%{-join($_|%{if($_){$a[$n++];$n%=$a.length}else{' '}})}

```

Takes input word as `$a` and the matrix as an array-of-arrays as `$b` (see examples below). Loops through `$b`, then loops through the elements of each row `$_|%{...}`. Inner loop is an `if`/`else` condition, where we either output `$a[$n++]` and take mod-equal to the length of the string, or output a space `' '`. Those are `-join`ed together back into a string. Each of the strings is left on the pipeline, and implicit output with newlines between happens via `Write-Output` at program completion.

```
PS C:\Tools\Scripts\golfing> .\the-art-of-word-shaping.ps1 'PPCGPPCG' @(@(0,0,1,0,0),@(0,1,0,1,0),@(1,0,0,0,1),@(0,1,0,1,0),@(0,0,1,0,0))
  P
 P C
G   P
 P C
  G

PS C:\Tools\Scripts\golfing> .\the-art-of-word-shaping.ps1 'lambda' @(@(1,0,0),@(0,1,0),@(1,0,1))
l
 a
m b

PS C:\Tools\Scripts\golfing> .\the-art-of-word-shaping.ps1 'PPCG' @(@(1,1,1),@(1,0,1),@(1,1,1))
PPC
G P
PCG

```

# Answer
> 3 votes
## Python 3, 104 (or 83) Bytes

```
import itertools as i
def f(s,L):s=i.cycle(s);return'\n'.join(' '.join(next(s)*e for e in l)for l in L)

```

There is shorter option (83 Bytes), but it will fail if string is more than 999 times shorter than needed:

```
def f(s,L):s=list(s)*999;return'\n'.join(' '.join(s.pop(0)*e for e in l)for l in L)

```

# Answer
> 2 votes
# Groovy, 63

```
{a,b->i=0;a.replaceAll("1",{b[i++%b.size()]}).replace("0"," ")}

```

# Answer
> 2 votes
# Japt `-R`, ~~10~~ 11 bytes

+1 byte to work around a weird bug with Japt's `-m`ap flag that I've never come across before.

```
®®?VgT°:SÃq

```

Try it

```
®®?VgT°:SÃq     :Implicit input of 2D boolean array U & string V
®               :Map
 ®              :  Map
  ?             :    If truthy (i.e., 1)
   Vg           :      Get the character in V at index
     T°         :      T (initially 0) postfix incremented
       :        :    Else
        S       :      Space
         Ã      :  End map
          q     :  Join
                :Implicit output joined with newlines

```

# Answer
> 1 votes
# Pyth, 12 bytes

```
jms?R@z~hZ\

```

Try it online: Demonstration

### Explanation:

```
jms?R@z~hZ\ dQ   implicit d and Q at the end
                 I use the variable Z, which is initialized with 0 by default
 m           Q   map each line d of the Q (input matrix) to:
   ?R       d       map each number d of the line either to
     @z~hZ             input[Z++] (increase Z, but lookup in input string with old value)
          \            or space
  s                 join chars to a string
j                print each string on a separate line

```

# Answer
> 1 votes
# Common Lisp, 152 bytes

```
(defun m(g w)(let((a 0))(loop for r in g do(loop for e in r do(format t"~[ ~;~c~]"e(char w a))(if(= e 1)(setf a(mod(1+ a)(length w)))))(format t"~%"))))

```

Usage:

```
* (m (list (list 1 0 1)
           (list 0 1 0)
           (list 1 0 1)) "ppcg")
p p
 c
g p

```

This function loops through each element of each row of the grid. The `format` control string either prints a space if the element is a 0 or consumes the character argument if the element is 1. A newline gets printed after every row of the grid. If the string is too short, it repeats from the beginning; if it's too long, only the appropriate part gets outputted.

# Answer
> 1 votes
## ES6, 78 bytes

```
  (a,b,x=0)=>(b.map(r=>r.map(i=>i?a[x++%a.length]:' ')+'\n')+'').replace(/,/g,'')

```

I tried

# Answer
> 1 votes
# Java, 237 233 Bytes

*Edit: saved 4 Bytes thanks to Mukul Kumar*

Golfed:

```
String T(int[][]m,String b){int l=m.length,a=0;String o="";for(int i=0;i<l;i++){for(int j=0;j<l;j++){if(m[i][j]==1&&a<b.length()){o+=Character.toString(b.toCharArray()[a]);a++;if(a== b.length()-1)a=0;}else o+=" ";}o+="\n";}return o;}

```

Ungolfed:

```
public String T(int[][] m, String b) {
    int l = m.length,a=0;
    String o = "";
    for(int i = 0; i < l; i++)
    {
        for(int j = 0; j < l; j++)
        {
            if(m[i][j] == 1 && a < b.length())
            {
                o += Character.toString(b.toCharArray()[a]);
                a++;

                if(a == b.length() - 1)
                    a = 0;
            }
            else
             o += " ";
        }
        o += "\n";
    }
    return o;
}

```

Testing:

```
  int[][] matrix = new int[][]
  {{ 0, 0, 1, 0, 0 }, { 0, 1, 0, 1, 0 },
  { 1, 0, 0, 0, 1 },{ 0, 1, 0, 1, 0 },
  { 0, 0, 1, 0, 0 },};
  TheArtOfWordShaping taows = new TheArtOfWordShaping();
  System.out.println(taows.T(matrix, "PPCGPPCG"));

  matrix = new int[][] {{1,0,0}, {0,1,0}, {1,0, 1}};
  taows = new TheArtOfWordShaping();
  System.out.println(taows.T(matrix, "lamda"));

  matrix = new int[][] {{1,1,1},{1,0,1},{1,1, 1}};
  taows = new TheArtOfWordShaping();
  System.out.println(taows.T(matrix, "PPCG"));

  P
 P C
G   P
 P C
  P

l
 a
m d

PPC
P P
CPP

```

# Answer
> 1 votes
## Pip, 18 bytes

17 bytes of code, +1 for `-l` flag.

```
Yb{a?y@++vs}MMa^s

```

Takes the array as the first command-line argument like this: `100 010 101` (needs to be quoted in shells) and the string as the second command-line argument. Try it online!

### Explanation

```
                   a and b are cmdline args, s is space, v is -1
Yb                 Yank b into global variable y
              a^s  Split a on space into list of rows
  {        }MM     Map this function to the items of the items of a (i.e. each character):
   a               Function argument
    ?              Ternary operator (truthy if 1, falsey if 0)
       ++v         If truthy, increment v...
     y@            ... and use it to index into y (cyclically)
                   I.e.: each time we hit a 1, replace it with the next character of y
          s        If falsey, space
                   The result is a list of lists of characters; -l concats sublists and
                   newline-separates the main list

```

# Answer
> 1 votes
## Pyke, 12 bytes

```
.FdRIKQoQl%@

```

Try it here!

Outputs a matrix of characters

Or 9 bytes, noncompetitive.

```
.FdRIKQo@

```

Try it here!

* Add wrapping on indexables where the index asked for is bigger than the length of the indexable.  .F - deep\_for(input) I - if ^: Qo@ - Q\[o++\] dR - else " "

Even more noncompetitive, 8 bytes

```
.FIQo@(P

```

Try it here!

* `print_grid` now aligns empty strings properly
* `deep_for` now does type-guessing on falsies of a different type to the truthies

```
.F    (  -  deep_for(input)
 I       -   if ^:
  Qo@    -    input[o++]
       P - pretty_print(^)

```

# Answer
> 1 votes
# Java,122 bytes

```
String g(int[][]a,char[]b){String r="";int e=0;for(int[]c:a){for(int d:c){r+=d==0?' ':b[e++%b.length];}r+='\n';}return r;}

```

# Answer
> 1 votes
# , 18 bytes

```
({' '&,)~$$,*+/\@,

```

Try it online!

* `,*+/\@,` Flatten the matrix, then multiply the flatten by the scan sum of the flatten.
* `({' '&,)~` Prepend a space to the replacement chars, and the index into that using the result of the previous step.

# Answer
> 1 votes
# 05AB1E, 10 bytes

```
SƶDêþIÞðš‡

```

Inputs in the order \\$matrix, string\\$, where the \\$matrix\\$ is a multi-line string. Outputs the result as a list of characters.

Try it online or verify all test cases.

**Explanation:**

```
S          # Split the first (implicit) multi-line string to a list of characters
 ƶ         # Multiply each by its 1-based index (the 0s and "\n" remain unchanged, only
           # the 1s are changed to their 1-based index)
  D        # Duplicate this list
   ê       # Remove all 0s except for a leading one, by using a sorted-uniquify
    þ      # Remove the newline, by only keeping numbers
     I     # Push the second input-string
      Þ    # Cycle its characters indefintely
       ðš  # Prepend a leading space " "
         ‡ # Transliterate the 0s and 1-based indices with these characters
           # (after which the resulting list of characters is output implicitly)

```

With an actual matrix as I/O, it would have been 13 bytes instead by adding a trailing `¹gä`: try it online or verify all test cases (note that the `S` also implicitly flattens, although an actual flatten `˜` could be used here as well).

# Answer
> 1 votes
# Vyxal `j`, 10 bytes

```
$¨Svv¨i?ðṠ

```

Try it Online!

First time I've used `¨S` in an answer I think. Takes matrix then string

## Explained

```
$¨Svv¨i?ðṠ
$          # Push matrix then string to the stack
 ¨S        # and set the input source to the characters of the string. This quite literally overrides argv.
   vv      # to each item in the matrix:
     ¨i    #   if the item is 1:
       ?   #     take input (which will be next character of string)
        ð  #   else: space
         Ṡ # sums of items
           # j flag joins on newlines

```

# Answer
> 1 votes
# Vyxal, 8 bytes

```
‛ %İṠ⁋$%

```

Try it Online!

```
   İ     # Index into...
‛ %      # " %"
    Ṡ⁋   # Join each into a string, join by newlines
      $% # Replace %s with corresponding elements of the input

```

# Answer
> 0 votes
# Mathematica, 76 bytes

```
""<>(s=#2;f:=(s=RotateLeft[s];Last[s]);Map[If[#1,f," "]&,#,{2}]~Riffle~"\n")&

```

Unnamed function of two arguments, the first of which (`#`) is an array of `True`s and `False`s, and the second of which (`s`) is a list of characters. The helper function

```
f:=(s=RotateLeft[s];Last[s])

```

is defined, which puts the moves the first character of `s` to the end and then returns that just-moved character. Calling `f` several times will cyclically return the characters of `s` in order.

The core function is

```
Map[If[#1,f," "]&,#,{2}]

```

which calls `f` on every `True` value in the input array and returns a space on every false input. (The `{2}` tells `Map` to work on elements of the array's component lists, rather than those lists themselves.)

Those 60 bytes return an array of characters-of-`s` and spaces. The wrapper

```
    ""<>(...~Riffle~"\n")&

```

puts newlines between each of that array's lists and then concatenates everything.

# Answer
> 0 votes
# C++, 61 bytes

```
for(auto&i:m){for(int&j:i)cout<<(j?s[k++%l]:' ');cout<<'\n';}

```

# Answer
> 0 votes
# Ruby, 52 bytes

```
->a,s{i=-1
a.gsub(/(0)|1/){$1?" ":s[(i+=1)%s.size]}}

```

Attempt This Online!

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


title: Generate any random integer

text:
# Question
Title: Generate any random integer
Your program/function should

* output exactly one integer
* output **any** integer with positive probability
* output an integer greater than 1.000.000 or less than -1.000.000 with at least with 50% probability.

Example outputs (all must be possible):

```
59875669123
12
-42
-4640055890
0
2014
12
24
-7190464664658648640055894646646586486400558904644646646586486400558904646649001

```

Clarifications:

* A trailing line break is permitted.
* Leading zeros aren't allowed.
* `-0` is permitted.

Shortest code wins.

# Answer
> 11 votes
# CJam, ~~16~~ ~~14~~ 13 bytes

```
0{Kmr(+esmr}g

```

This will run for a *very* long time, because it uses the current timestamp (on the order of 1012) to determine if the loop should terminate. I'm using this as the submission, as it is the shortest, but there are two 14-byte alternatives, which have their own merits:

```
0{esmr(+esmr}g

```

This one is *not* limited by the period of the PRNG, since the range of *all* random numbers depends on the current timestamp. Therefore, this should be able to produce any number whatsoever, although the probability for negative, or even small positive numbers vanishingly small.

Below is an equivalent version that uses `3e5` instead of the timestamp. And `20` for the first range (as the 13-byte submission). It's much faster and also complies with all the rules. It is sort of the limiting case to get the 50% probability for numbers beyond 1,000,000 while keeping a reasonable runtime and small code-size. The explanation and mathematical justification refer to this version:

```
0{Kmr(+3e5mr}g

```

This usually takes a few seconds to run. You can replace the `5` with a `2` to make it run even faster. But then the requirement on the 50% probability will only be met for 1,000 instead of 1,000,000.

I'm starting at 0. Then I've got a loop, which I break out of with probability 1/(3\*105). Within that loop I add a random integer between -1 and 18 (inclusive) to my running total. There is a finite (albeit small) probability that each integer will be output, with positive integers being much more likely than negative ones (I don't think you'll see a negative one in your lifetime). Breaking out with such a small probability, and incrementing most of the time (and adding much more than subtracting) ensures that we'll usually go beyond 1,000,000.

```
0              "Push a 0.";
 {          }g "Do while...";
  Kmr          "Get a random integer in 0..19.";
     (         "Decrement to give -1..18.";
      +        "Add.";
       3e5mr   "Get a random integer in 0..299,999. Aborts if this is 0.";

```

Some mathematical justification:

* In each step we add 8.5 on average.
* To get to 1,000,000 we need 117,647 of these steps.
* The probability that we'll do *less* than this number of steps is

```
sum(n=0..117,646) (299,999/300,000)^n * 1/300,000

```

which evaluates to `0.324402`. Hence, in about two thirds of the cases, we'll take more 117,647 steps, and easily each 1,000,000.
* (Note that this is not the exact probability, because there will be some fluctuation about those average 8.5, but to get to 50%, we need to go well beyond 117,646 to about 210,000 steps.)
* If in doubt, we can easily blow up the denominator of the termination probability, up to `9e9` without adding any bytes (but years of runtime).

# ...or 11 bytes?

Finally, there's an 11 byte version, which is also not limited by the period of the PRNG, but which will run out of memory pretty much every time. It only generates one random number (based on the timestamp) each iteration, and uses it both for incrementing and terminating. The results from each iteration remain on the stack and are only summed up at the end. Thanks to Dennis for this idea:

```
{esmr(}h]:+

```

# Answer
> 11 votes
# Java, ~~133~~ 149

```
void f(){String s=x(2)<1?"-":"";for(s+=x(9)+1;x(50)>0;s+=x(10));System.out.print(x(9)<1?0:s);}int x(int i){return new java.util.Random().nextInt(i);}

```

## Example outputs

```
-8288612864831065123773
0
660850844164689214
-92190983694570102879284616600593698307556468079819964903404819
3264

```

## Ungolfed

```
void f() {
    String s = x(2)<1 ? "-" : "";       // start with optional negative sign
    s+=x(9)+1;                          // add a random non-zero digit
    for(; x(50)>0; )                    // with a 98% probability...
        s+=x(10)                        // append a random digit
    System.out.print(x(9)<1 ? 0 : s);   // 10% chance of printing 0 instead
}

int x(int i) {
    return new java.util.Random().nextInt(i);
}

```

## Old answer (before rule change)

```
void f(){if(Math.random()<.5)System.out.print('-');do System.out.print(new java.util.Random().nextInt(10));while(Math.random()>.02);}

```

# Answer
> 4 votes
# Mathematica - 47

```
Round@RandomVariate@NormalDistribution[0,15*^5]

```

Basically just generate random number using normal distribution with variance equal to 1500000. This will produce an integer between -10^6 and 10^6 with probability 49.5015%.

# Answer
> 4 votes
# Python 2, ~~75~~ 69 bytes

```
from random import*;s=0;j=randrange
while j(12):s=s*9+j(-8,9)
print s

```

It is trivial to check that the while loop in the middle can generate all integers (albeit biased towards zero). "12" is chosen such that there are roughly half of numbers exceeding ±106.

---

Older solution:

# ~~Python 2, 44 bytes~~

~~Based on the Mathematica solution.~~

```
from random import*;print int(gauss(0,8**7))

```

**Doesn't really work because Python's `float` has only finite precision.**

# Answer
> 3 votes
# Ruby, 70

```
f=->{m=10**6
r=rand -m..m
r<1?(r>-5e5??-:'')+r.to_s+f[][/\d+/]:r.to_s}

```

To make generating very large numbers possible, I'm returning the number as a `String` from a lambda. If that's not allowed, count 8 characters extra (for `puts f[]`) to make it a program instead of a function.

### Explanation

Generate a number between `-1,000,000` and `1,000,000`. If the number is `1` or higher, the number is returned as a `String`.

If the number is lower than `1`, the function is called recursively to return number outside the number range. To make sure negative numbers can also be generated, a `-` is prefixed to the resulting `String` if the initial number is greater than `-500,000`.

I hope I understood the challenge correctly!

# Answer
> 3 votes
## R, 38

```
library(Rmpfr)
round(rnorm(1,2e6,1e6))

```

Draws from the Gaussian distribution with mean 2,000,000, chosen randomly, and standard deviation 1,000,000, so that about 2/3 of the draws will lie within 1,000,000 and 3,000,000. The distribution is unbounded so in theory this can generate any integer. The Rmpfr package replaces R's built in double floats with arbitrary precision.

# Answer
> 2 votes
# Perl, 114 Chars

```
use Math::BigInt;sub r{$x=Math::BigInt->new(0);while(rand(99)!=0){$x->badd(rand(2**99)-2**98);}print($x->bstr());}

```

## Breakdown:

```
use Math::BigInt;               -- include BigIntegers
  sub r{                        -- Define subroutine "r"
    $x=Math::BigInt->new(0);    -- Create BigInteger $x with initial value "0"
      while(rand(99)!=0){       -- Loop around until rand(99) equals "0" (may be a long time)
        $x->badd(               -- Add a value to that BigInt
          rand(2**99)-2**98);   -- Generate a random number between -2^98 and +2^98-1
        }print($x->bstr());}    -- print the value of the BigInt

```

The probability of getting a value between -1.000.000 and 1.000.000 are tending towards zero *BUT* it is possible.

> Note: This subroutine may run for a long time and error out with an "Out of Memory!" error but it's technically generating *any* integer as stated in the question.

# Perl, 25

```
sub r{rand(2**99)-2**98;}

```

Generates a random integer within the range of +/-2^99.

## Breakdown

```
sub r{                    -- Define subroutine "r"
     rand(2**99)          -- Generate a random integer between 0 and 2^99
                -2**98;}  -- Subtract 2^98 to get negative values as well

```

Tested with 1 million samples:

```
~5 are inside the range of +/-1.000.000
~999.995 are outside that range
= a probability of ~99,99% of generating an integer outside that range.
Compare that number to the probability of 2.000.000 in 2^99: It is approx. the same.

```

This meets all rules:

* 1 integer
* any integer is possible
* at least 50% (in my case 99,99%) of all generated integers are outside the range of +/-1.000.000.

> This works because the underlying random number generator defines equal probability to every bit that is generated, thus doing that on generated integers as well.
> Every integer has a probability of 1/2^99 to be generated.

## Edit:

I had to increase the exponent so that larger integers are being generated. I have chosen 99 because it keeps the code as short as possible.

# Answer
> 2 votes
# C#, ~~126~~ 107 bytes

```
string F(){var a=new System.Random();var b=a.Next(-1E6,1E6+1)+"";while(a.Next(1)>0)b+=a.Next(10);return b;}

```

Ungolfed:

```
string F()
{
    System.Random rand = new System.Random();
    string rtn = rand.Next(-1E6, 1E6 + 1) + "";
    while (rand.Next(1) > 0)
         rtn += a.Next(10);
    return rtn;
}

```

Chance to generate a number of *n* digits is 1/2^(n-10), which is greater than 0 for all positive n, and 1/2 for n=11. ~~Also creates leading zeros, which do not seem to be disallowed in the original question or any of its comments.~~

# Answer
> 2 votes
# Perl, 53 characters

```
print"-"if rand>.5;do{print int rand 10}while rand>.1

```

I certainly don't see any reason to *work* with integers when printing one :)

Has equal probability of printing a number with or without a leading "-".

Prints a 1-digit number 10% of the time, a 2-digit number 9% of the time, a 3-digit number 8.1% of the time, a 4-digit number 7.29% of the time, a 5-digit number 6.56% of the time, a 6-digit number 5.9% of the time, etc. Any length is possible, with decreasing probability. The one-through-five digit numbers account for about 41.5% of output cases, and the number 1,000,000 (or -1,000,000) only 6-millionths of a percent, so the output number will be outside of the range -1,000,000 through 1,000,000 about 54.6% of the time.

Both "0" and "-0" are possible outputs, which I hope is not a problem.

# Answer
> 2 votes
# Perl, 62 bytes

`print $n=int rand(20)-10;while($n&&rand>.1){print int rand 10}`

I had the same idea as @Hobbs, of generating a digit at a time, but his code didn't satisfy the added no-leading-zeros requirement. Generating the first digit instead of just the sign solved that. And unless there's a shorter way to exit if we printed a zero, or a shorter way to generate the leading -9 to 9, this should do it for size.

In a shell loop: `while perl -e '...'; do echo;done |less`

I think this is one of the shortest that doesn't require infinite RAM to satisfy the problem. As a bonus, the output is isn't strongly biased towards anything, and runtime is very fast.

I tried using bitwise and to save a character in the while condition, but I think this ends up being true more often, so the loop ends sooner. Would need more chars to adjust other things to counter that, to maintain the probability of generating abs(output) \> 1M.

# Answer
> 2 votes
# Bash, 42 bytes

`printf "%d\n" 0x$(xxd -p -l5 /dev/random)`
/dev/random on OSX is just random bytes, and `xxd -p -l5` converts 5 of the ascii characters to hex, and `printf` turns it into decimal format.

# Answer
> 1 votes
# Javascript (73)

This solution uses that you can construct a number with base *n* by multiplying the previous number with *n* and adding a digit in base *n*. We have an additional `..?..:..` in there to be able to create all negative integers. The following code should be tested in a browser console.

```
b=Math.round;c=Math.random;x=0;while(b(c()*99)){x*=b(c())?2:-2;x+=b(c())}

```

The probability to get an integer \>= `2^1` (or \<= `-(2^1)`) is equal to the chance that the loop is ran 2 times. The chance of that happening is `(98/99)^2`. The chance of getting a number that is greater than `2^20` (or \<= `-(2^20)`) is therefore `(98/99)^21 = 0.808` or 81%. This is all in theory though, and assuming that Math.random is truely random. It obviously isn't.

---

Snippet testing this code. Also in a more readable fashion.

```
var interval = 0;
var epic_unicorns = 0;
var unicorns = 0;

function gimmerandom() {
  var b = Math.round;
  var c = Math.random;
  var x = 0;
  while( b(c()*99) ) {
    x *= b(c()) ? 2 : -2;
    x += b(c());
  }
  return x;
}

function randomcount() {
  var a = gimmerandom();
  if( a <= -1000000 || a >= 1000000 ) {
    epic_unicorns++;
  }
  unicorns++;
  updatedisplay();
}

function updatedisplay() {
  $('#num_of_epicunicorns').text( epic_unicorns );
  $('#num_of_unicorns').text( unicorns );
  var perc = unicorns > 0 ? Math.round( (epic_unicorns / unicorns) * 1000 ) / 10 : 0;
  $('#perc_of_unicorns').text( perc );
}

$('#a').on( 'click', function() {
  clearInterval( interval );
  interval = setInterval( randomcount, 10 );
} );

$('#b').on( 'click', function() {
  clearInterval( interval );
} );

$('#c').on( 'click', function() {
  epic_unicorns = 0;
  unicorns = 0;
  updatedisplay();
} );

updatedisplay();

```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="num_of_epicunicorns"></span> / <span id="num_of_unicorns"></span> (<span id="perc_of_unicorns"></span>%) were larger than 1.000.000 or less than 1.000.000.

<br><br>
<input type="button" id="a" value="Start">
<input type="button" id="b" value="Stop">
<input type="button" id="c" value="Reset">
```

# Answer
> 1 votes
# GolfScript, 20 bytes

```
0{)8.?rand}do.2&(*4/

```

Yeah, this one is also kind of slow.

Compared to languages like CJam and Pyth, GolfScript suffers from a verbose random number generation keyword (`rand`). To overcome this handicap, I needed to find a way to use it only once.

This code works by repeatedly picking a random number between 0 and 88−1 = 16,777,215 inclusive, and incrementing a counter until the random number happens to be 0. The resulting counter value has a geometric distribution with a median approximately -1 / log2(1 − 1/88) ≈ 11,629,080, so it meets the "over 1,000,000 at least 50% of the time" test.

Alas, the random number thus generated is always strictly positive. Thus, the extra `.2&(*4/` part is needed to let it become negative or zero. It works by extracting the second-lowest bit of the number (which is thus either 0 or 2), decrementing it to make it -1 or 1, multiplying it with the original number, and dividing the result by 4 (to get rid of the lowest two bits, which are now correlated with the sign, and also to allow the result to become zero). Even after the division by 4, the absolute value of the random number still has a median of -1 / log2(1 − 1/88) / 4 ≈ 2,907,270, so it still passes the 50% test.

# Answer
> 1 votes
# JavaScript, 81 bytes

This code fulfills all the rules:

* Output any integer with positive probability
* Output integers outside the range of +/-1000000 with at least 50% probability
* No leading `0` in the output

As a bonus, the algorithm runs with a time complexity of **O(log10n)** so it returns the integer almost instantly.

```
for(s="",r=Math.random;r()>.1;s+=10*r()|0);r(s=s.replace(/^0*/,"")||0)<.5?"-"+s:s

```

This assumes an REPL environment. Try running the above code in your browser's console, or use the stack snippet below:

```
D.onclick = function() {
  for(s="", r=Math.random;r()>.1; s+=10*r()|0);
  P.innerHTML += (r(s=s.replace(/^0*/,"") || 0) <.5 ?"-" + s : s) + "<br>"
}
```

```
<button id=D>Generate a random number</button><pre id=P></pre>
```

**Algorithm**:

* Keep appending random digits to string `s` until a `Math.random() > 0.1`.
* Based on `Math.random() > 0.5`, make the number negative (by prepending the string `s` with `-`).

This algorithm does not have a uniform distribution across all integers. Integers with higher digit count are less probable than the lower ones. In each for loop iteration, there is a 10% chance that I will stop at the current digit. I just have to make sure that I stop after 6 digits more than 50% of the time.

This equation by @nutki explains the maximum value of stopping chance percentage based on the above condition:

```
1 - 50%^(1/6) ≈ 0.11

```

Thus 0.1 is well within range to satisfy all the three rules of the question.

# Answer
> 1 votes
# TI-BASIC, 14 bytes

```
1-2int(2rand:randNorm(AnsE6,9

```

Similar to @ssdecontrol's R answer, this draws from the Gaussian distribution with mean -1,000,000 or 1,000,000, chosen randomly, and standard deviation 9. The distribution is unbounded so in theory this can generate any integer.

**Explanation**:

```
1-2int(2rand     - get a random integer 0 or 1, then multiply by 2 and subtract 1
:                - this gives the number 1 or -1 (with equal probability) to Ans
randNorm(AnsE6,9 - displays Gaussian distribution with mean (Ans * 1,000,000) and std. dev. 9

```

# Answer
> 1 votes
# Bash, 66

```
LANG=C sed -r '/^-?(0|[1-9][0-9]*)$/q;s/.*/5000000/;q'</dev/random

```

It almost always prints 5000000. But if it found a valid number in `/dev/random`, it will print that number instead.

And this one is faster:

```
LANG=C sed -r '/^-?(0|[1-9][0-9]*)$/q;s/.*/5000000/;q'</dev/urandom

```

# Answer
> 1 votes
# C++, 95 bytes

```
void f(){int d=-18,s=-1;while(s<9){d=(rand()%19+d+9)%10;cout<<d;s=9-rand()%10*min(d*d+s+1,1);}}

```

## Expanded:

```
void f() {
    int d=-18,s=-1;
    while(s<9) {
        d=(rand()%19+d+9)%10;
        cout<<d;
        s=9-rand()%10*min(d*d+s+1,1);
    }
}

```

## Explanation:

The function keeps on printing consecutive random digits until a random valued switch takes the required value to stop the function. d is the variable that keeps the value of the next digit to be printed. s is the switch variable that takes random integer values in the interval \[0, 9\], if s == 9 then no more digits are printed and the funtion ends.

The variables d and s are initialized in order to give special treatment to the first digit (taking it from the interval \[-9, 9\] and if the first digit is zero then the function must end to avoid leading zeroes). The value of d could be assigned as d=rand()%10 but then the first digit couldn't be negative. d is assigned instead as d=(rand()%19+d+9)%10 and initialized at -18 so the first value of d will range from \[-9, 9\] and the next values will always range from \[0, 9\].

The variable s ranges randomly from \[0, 9\], and if s equals 9, the function ends, so after printing the first digit the next one will be printed with a probability of 90% (assuming rand() is truly random, and in order to satisfy the third condition). s could be easily assigned as s=rand()%10, however, there is an exception, if the first digit is zero, the function must end. In order to handle such exception, s has been assigned as s=9-rand()%10\*min(d\*d+s+1,1) and initialized as -1. If the first digit is zero, the min will return 0 and s will equal to 9-0=9. s variable's assignment will always range from \[0, 9\], so the exception can only occur at the first digit.

## Characteristics (assuming rand() is truly random)

* The integer is printed digit by digit, with a fixed probability of 90% of printing another digit after printing the last one.
* 0 is the integer with highest chance of being printed, with a probability of aproximately 5.2%.
* The probability of printing an integer on the interval \[-10^6, 10^6\] is aproximately 44% (the calculation is not written here).
* Positive and negative integers are printed with the same probability (~47.4%).
* Not all digits are printed with the same probability. For example: in the middle of printing the integer, if the last digit was 5, the digit 3 will have a slightly lower chance of being printed next. In general, if the last digit was d, the digit (d+18)%10 will have a slightly lower chance of being printed next.

## Example outputs (10 executions)

```
-548856139437
7358950092214
507
912709491283845942316784
-68
-6
-87614261
0
-5139524
7

Process returned 0 (0x0)   execution time : 0.928 s
Press any key to continue.

```

# Answer
> 1 votes
# Java (JDK), ~~140~~ 127 bytes

```
()->{int i;var o=System.out;for(o.print(i=(int)(19*Math.random())-10);i!=0&Math.random()<.9;)o.print((int)(11*Math.random()));}

```

`-13 bytes` by sneaking more logic into the loop header - thanks to @ceilingcat

Try it online!

# Answer
> 1 votes
# BSD `jot`, 17 bytes

```
jot -r 1 -9e9 9e9

```

Try it Online! The above code works correctly on MacOS (and presumably BSD), but TIO (and ATO) do not have the same `jot` as I do. Link is to a truncated version that only generates positive integers.

# Answer
> 0 votes
# Pyth, 11 bytes

```
WOyG~ZtOT)Z

```

Note: this program will probably crash with a memory error on any real computer. To test it, try replacing `G` with a shorter string, such as in this code, which generates numbers averaging around 28000:

```
pyth -c 'WOy"abcdefghijklm"~ZtOUT)Z'

```

This code loops, adding a random number from -1 to 8 to `Z`, with a 2^-26 probability of exiting the loop on each repetition. The 2^-26 probability is attained by selecting a random element (`O`) of the set of all subsets (`y`) of the alphabet (`G`).

Technical details & justification:

The probability 2^-26 is derived from two facts: `y`, when called on sequences, is the power-set function, an constructs the list of all subsets of the input. Since the input, `G`, is 26 characters long, this power-set, `yG` has 2^26 entries. `OyG` selects a random element from those 2^26 entries. Exactly one of those entries, the empty string, will evaluate as falsy when passed to `W`, the while loop. Therefore, there is a 2^-26 probability of exiting the loop each time.

In any fixed number of loop cycles K, the probability of getting the number K\*3.5 + m and getting K\*3.5 - m are equal, because each sequences of addends that achieves one total can be inverted, -1 -\> 8, 0 -\> 7, etc., to achieve the other. Additionally, numbers closer to K\*3.5 are clearly more likely than numbers farther away. Thus, if K \> 2000000/3.5 = 571428.5 the probability of getting a number over 1000000 is greater than 75%, because some of the results above that number can be put into a one-to-one correspondence with all of the results below that number, and the upper less-than-half, can be put into a one-to-one correspondence with those under 1000000. The probability of getting at least 571429 loops is (1-2^-26)^571429, which is no less than (1-2^-26 * 571429), the expected number of times leaving the loop over the first 571429 tries, which is 99.1%. Thus, on 99.1% or more of trials, there is a 75% or more chance of getting at least 1000000, so there is more than a 50% chance of getting over 1000000.

This code relies on a behavior of `O` where a bug was accidentally introduced 3 days ago and was fixed today. It should work on any version of Pyth 3 from before Dec 22nd, or after today. The following code is equivalent, and has always worked:

```
WOyG~ZtOUT)Z

```

# Answer
> 0 votes
# Java, 113 bytes

```
void g(){String a=Math.random()>0?"10":"01";for(;Math.random()>0;)a+=(int)(Math.random()*2);System.out.print(a);}

```

This program prints a binary number to standard output stream. You might have to wait a while because the probability of it ending the number (or it being positive) is approximately 0. The idea that the absolute value of a number generated is less than 1 million is amusing, yet possible.

Ungolfed:

```
void g(){
    String a=Math.random()>0?"10":"01";             //Make sure there are no trailing zeroes.
    for(;Math.random()>0;)a+=(int)(Math.random()*2);//Add digits
    System.out.print(a);                            //Print
}

```

Sample output: *Will post when a number is done being generated.*

---
Tags: code-golf, number, random
---