title: The redundant boolean

text:
# Question
Title: The redundant boolean
# Introduction

Classically, booleans are one bit; `true` or `false`, `1` or `0`. Leading zeros would just be redundant. For example, `001` means the same as `00001` or just `1`.

# The 32-bit boolean

Given a truthy/falsey value, output the equivalent 32-bit boolean as a string. (Or as a number if for *some reason* your language supports leading zeros.)

**Your program doesn't have to work for every truthy/falsy type, only what your programming language work best for.**

# Example i/o

```
Input >> Output

truthy >> 00000000000000000000000000000001
falsey >> 00000000000000000000000000000000

```

## This is , so lowest bytes wins!

# Answer
# Python 3, ~~33~~ ~~25~~ ~~18~~ 15 bytes

Thanks @jurjen-bos for the `__mod__` tip.

```
'%.32d'.__mod__

```

Try it online!
> 11 votes

# Answer
# x86-16 Machine Code (DOS), 16 bytes

```
B4 02          mov  ah,  2
B2 30          mov  dl, '0'
B9 1F 00       mov  cx, 31

            PrintZeros:
CD 21          int  0x21
E2 FC          loop PrintZeros

00 CA          add  dl, bl
CD 21          int  0x21
C3             ret

```

The above function receives a boolean value (0 == falsey, 1 == truthy) in the `BL` register (low byte of `BX`), and prints a "redundant boolean" string to the standard output.

It works by invoking an interrupt (0x21) to make a DOS function call (selected by setting `AH` to 2) that prints a single character (in `DL`) to the standard output.

First, the ASCII character '0' is loaded into `DL`, the counter (`CX`) is set to 31, and it loops to print the "redundant" bytes. Then, the input boolean value is added to `DL` (if `BL` is falsey, adding 0 will leave `DL` unchanged as ASCII '0'; if `BL` is truthy, `DL` will be incremented by one to ASCII '1'), and the final byte is printed.

The function does not return a value.

Pretty decent for a language that doesn't really do strings.

---

### Full Program, 21 bytes

If you want to make it into a full program, only 5 more bytes are required. Instead of passing the input in a register, this reads the input from the arguments passed on the command line when invoking the application. An argument of 0 is interpreted as falsey, as is the complete lack of arguments; an argument greater than 0 is interpreted as truthy.

Simply assemble the following code as a COM program, and then execute it on the command line.

```
B4 02            mov   ah,  2
B2 30            mov   dl, '0'
B9 1F 00         mov   cx, 31

               PrintZeros:
CD 21            int   0x21
E2 FC            loop  PrintZeros

3A 16 82 00      cmp   dl, BYTE PTR [0x82]  ; compare to 2nd arg, at offset 0x82 in PSP
D6               salc                       ; equivalent to sbb al, al
28 C2            sub   dl, al
CD 21            int   0x21
C3               ret                        ; you can simply 'ret' to end a COM program

```

Sample Output:

```
C:\>bool.com
00000000000000000000000000000000
C:\>bool.com 0
00000000000000000000000000000000
C:\>bool.com 1
00000000000000000000000000000001
C:\>bool.com 2
00000000000000000000000000000001
C:\>bool.com 7
00000000000000000000000000000001

```

How does it work? Well, it's basically the same thing, until you get down to the `CMP` instruction. This compares the command-line argument with the value of the `DL` register (which, you recall, contains an ASCII '0'). In a COM program, the bytes of code are loaded at offset 0x100. Preceding that is the program segment prefix (PSP), which contains information about the state of a DOS program. Specifically, at offset 0x82, you find the first (actually the second, since the first is a space) argument that was specified on the command line when the program was invoked. So, we are just comparing this byte against an ASCII '0'.

The comparison sets the flags, and then the `SALC` instruction (an undocumented opcode prior to the Pentium, equivalent to `sbb al, al`, but only 1 byte instead of 2) sets `AL` to 0 if the two values were equal, or -1 if they were different. It is then obvious that when we subtract `AL` from `DL`, this results in either ASCII '0' or '1', as appropriate.

(Note that, somewhat ironically, you will break it if you pass an argument with a leading 0 on the command line, since it looks only at the first character. So `01` will be treated as falsey. :-)
> 10 votes

# Answer
# Python 3, 23 bytes

```
lambda n:'0'*31+'01'[n]

```

Try it online!
> 8 votes

# Answer
# Javascript, 23 bytes

```
a=>'0'.repeat(31)+ +!!a

```

`!!a` coerces a into a boolean, which the unary plus turns into an int.
> 7 votes

# Answer
# , 8 bytes

```
32é0Àñl

```

Try it online!

Explanation:

```
32é0            " Insert 32 '0's
    Àñ          " Arg1 times...
      <C-a>     "   Increment the number under the cursor
           l    "   Move one char to the right. This will break the loop since there is
                "   no more room on this line

```
> 6 votes

# Answer
# Neim, 6 5 bytes

```
ᛝΨβ_I

```

Try it online!

Explanation:

```
 ᛝ        # Constant 31
  Ψ       # Apply next token to all in list
    β     # Constant 0
     _    # Push each element to stack
      I   # Take Line of input.

```

Saved a byte thanks to *Okx*
> 5 votes

# Answer
# Octave, 17 bytes

```
@(n)dec2bin(n,32)

```

Anonymous function. Works in MATLAB too.

Try it online!
> 4 votes

# Answer
# ArnoldC, 369 bytes

```
IT'S SHOWTIME
HEY CHRISTMAS TREE A
YOU SET US UP 0
GET YOUR ASS TO MARS A
DO IT NOW
I WANT TO ASK YOU A BUNCH OF QUESTIONS AND I WANT TO HAVE THEM ANSWERED IMMEDIATELY
BECAUSE I'M GOING TO SAY PLEASE A
TALK TO THE HAND "00000000000000000000000000000001"
BULLSHIT
TALK TO THE HAND "00000000000000000000000000000000"
YOU HAVE NO RESPECT FOR LOGIC
YOU HAVE BEEN TERMINATED

```

Try it online!
> 4 votes

# Answer
# Brainfuck, ~~61~~ ~~60~~ 36 bytes

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

```

~~I'm sure there is a clever way of not moving around so much with the pointers.~~

I was right. There were. Thanks to @Graviton for giving me the idea!

Next step: Get the values 32 and 48 quicker!

Try it online!

```
++++        - Increment 1st slot by 4
[           - Loop until 4 becomes 0
    >++++   - Add 4 to 2nd slot
    <-      - Decrement loop
]           - At this point, we point to slot 1 and slot 2 contains 16, which is the Greatest Common Divisor of 48 (value 0 in ASCII) and 32 (final length of answer)
>           - Point to value 16 (slot 2)
[           - Start loop to get our target values 32 and 48
    >++     - Point to slot 3 and multiply 16 by 2 = 32
    >+++    - Point to slot 4 and multiply 16 by 3 = 48
    <<-     - Decrement the loop so that slot 2 becomes 0
]           - We now point slot 2
>-          - Move to slot 3 and remove one so we can spam (output) 31 zeroes
[           - Start outputting until slot 3 is empty
    >.      - Move to slot 4 where our ASCII value for 0 is
    <-      - Decrement the loop so that slot 3 becomes 0
]           - We are now at slot 3 and it is empty.
,.          - We can now gather input from the user and output it.

```

Was fun for a first Golf!

~~It has gotten way too late now.~~ What am I even doing
> 4 votes

# Answer
# Braingolf, ~~10~~ 8 bytes

```
#␟>[0_]N

```

Try it online!

is a Unit Separator, ASCII `0x1F`, or 31. Can't find the actually character to paste into TIO, so TIO instead uses `# 1-`, which pushes space (32) and decrements to 31.

## Explanation

```
#␟>[0_]N  Implicit input from commandline args
#␟        Push unit separator (31)
   >       Move top item to bottom of stack
    [..]   Loop, runs 31 times
     0_    Print 0
        N  Boolean conversion, truthy values become 1, falsey values become 0
           Implicit output of top of stack

```
> 3 votes

# Answer
# Scala, 32 bytes

Sorry but I was forced to do it in 32 bytes \>\_\<

```
var s=t
for(u<-0 to 30)s="0"+s
s

```

It's enclosed by a function taking `t` as parameter (as a `string` that can be "0" or "1" for resp. falsy or truthy), and `s` is returned.

Try It Online!

# Valid response : Scala, 46 bytes

Same as my java response, I was supposed to take a boolean for the parameter. So :

```
var s=if(t)"1"else"0"
for(u<-0 to 30)s="0"+s
s

```

Try It Online!
> 3 votes

# Answer
# Java 8, ~~31~~ 27 bytes

```
b->"".format("%032d",b?1:0)

```

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

Try it here.
> 2 votes

# Answer
# Octave, 23 bytes

```
@(x)[48+[!(1:31),x],'']

```

Try it online!

This is shorter than all the approaches I tried with `printf`. I might have missed something though, since I did this on my phone.

Only one byte longer

```
@(x)[dec2bin(0,31),x+48]

```

This could be 18 bytes if I could take 1/0 as strings.

```
@(x)[48+!(1:31),x]

```

Try it online!
> 2 votes

# Answer
# 05AB1E, 5 bytes

```
¾31×«

```

Try it online!
> 2 votes

# Answer
# Ruby, 21 bytes

Yeah, that space needs to be there.. :/

```
->x{"%032b"%(x ?1:0)}

```

In Ruby *everything* except `false` and `nil` is truthy; Try it online!
> 2 votes

# Answer
# Mathematica, 36 bytes

```
""<>ToString/@PadLeft[{Boole@#},31]&

```

# Mathematica, 26 bytes

```
Row@PadLeft[{Boole@#},31]&

```

Try it online!
> 1 votes

# Answer
# Haskell, ~~37~~ 32 bytes

```
(('0'<$[1..31])++).show.fromEnum

```

Try it online!

Thanks @nimi for `-5` bytes!
> 1 votes

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

```
a=>new string('0',31)+(a?1:0)

```

OP said 1/0 can be used for truthy/falsey, so can make `a` an int and it becomes

```
a=>new string('0',31)+a

```

C# doesn't really have truthy/falsey though so I will not use this answer.

Try it online!
> 1 votes

# Answer
# Japt, ~~13~~ 11 bytes

```
?1:0 ¤i31ç0

```

## Explanation:

```
?1:0 ¤i31ç0
?              // If the input is a truthy, return:
 1             //   1
  :0           //   Else, 0
     ¤         // Convert to a base-2 string
      i        // Insert at index 0:
       31ç0    //   A string filled with 0s, length 31

```

Saved a byte using a base-2 conversion built-in!

To insert the string of 0s in front of the `1`/`0`, I need to cast the `1` and `0` into a string. The typical way of doing that would be `1s` (3 bytes). But because we're only converting 1s and 0s, I can use the base-2 built-in  (2 bytes).

---

Input can be in the form of an integer or string.

`0` and `""` are falsy in Japt.

Try it online!

Test suite
> 1 votes

# Answer
# Ly, ~~20~~ ~~15~~ 13 bytes

```
65*1+[0u1-]nu

```

EDIT: Saved 5 bytes thanks to ovs.
EDIT: Saved another 2 bytes by printing 0 as a number rather than a character.
> 1 votes

# Answer
# Python 2, ~~26~~ 25 bytes

Thanks to *Erik the Outgolfer* for saving a byte!

Goes for the full program approach:

```
print+bool(input(31*'0'))

```

Try it online!
> 1 votes

# Answer
# Charcoal, 5 bytes

```
×0³¹Ｓ

```

Try it online! (Link to the verbose version.)

As Charcoal understand `0` and `1` as `True` or `False`, this just prints 31 `0`s and the input (`0` or `1`) as string.
> 1 votes

# Answer
# Java, 40 chars, 40 bytes

This takes string as parameter, which is not correct (falsy/truthy java value is forced by OP to be represented by a boolean).

```
c->{for(int i=0;++i<32;c=0+c);return c;}

```

Try It Online!

# Valid response : Java, 60 chars, 60 bytes

```
c->{String k="";for(k+=c?1:0;k.length()<32;k=0+k);return k;}

```

Try It Online!

I know there is already a Java answer which is shorter than this one, but still :)
> 1 votes

# Answer
# Octave,~~16~~ 11 bytes

```
@(x)x(1:32)

```

Try it online!

A function handle that takes `"00000000000000000000000000000001"` as truthy and `"00000000000000000000000000000000\0"` as falsey.

Explanation:

In Octave an array is considered as falsey if at least one of its elements is zero. The 33th element of the second string is a character with the ASCII value of 0 so it can be considered as falsey.
> 1 votes

# Answer
# Unwanted, Unnecessary, Opportunistic, 7 bytes

```
P0M31P*

```

Pass either 1 or 0 into the register.
> 1 votes

# Answer
# C, 26 bytes

Pretty much the same idea as 1bluestone's solution, but in C it's shorter, and it does work correctly for any integer input:

```
f(a){printf("%032i",!!a);}

```

Of course, this includes some implicitly typed variables/functions as all good C-golf answers do... The `!!` operator is the shortest way to convert any truthy value to `1` in C (via double negation, `!` is defined to return either `1` or `0`).

Test with:

```
#include <stdio.h>
f(a){printf("%032i",!!a);}
int main() {
    f(0), printf("\n");
    f(1), printf("\n");
    f(2), printf("\n");
    f(-1), printf("\n");
}

```
> 1 votes

# Answer
# PHP, 28 bytes

```
<?=str_pad($argv[1],32,0,0);

```

Save as bool.php and run:

```
$ php bool.php 0
00000000000000000000000000000000
$ php bool.php 1
00000000000000000000000000000001

```
> 1 votes

# Answer
# MY, ~~10~~ 9 bytes

```
BṄiℑpέ←←

```

Try it online!

Explanation (codepage \[with reasoning behind the character\]/hex code):

```
: 1A - Push an integer from STDIN (lowercase integers)
B: 0B - Push 11 (B is 11 in hex)
Ṅ: 36 - Pop n; push the nth prime, 11th prime is 31 (Ṅ-th)
i: 49 - Pop n; push [1,...,n] (index/iota)
ℑ: 34 - Pop n; push imag(n) (ℑmaginary part, applied to each element, which gives 0 for real numbers)
p: 60 - Pop n; push stringified n (0=>"0" ... 35=>"Z", the b in base upside down)
έ: 56 - Pop n; push n joined by "" (έmpty string)
←: 26 - Pop n; output n with no newline (out←in)
←: 26 - Pop n; output n with no newline (out←in)

```

I can't believe that this is possible without any two-argument commands whatsoever!

Edit: Saved 1 byte by using primes instead of arithmetic to get 31.
> 1 votes

# Answer
# Julia 0.6, 12 bytes

```
~x=bin(x,32)

```

Nothing clever here, there is basically a built in for it.
> 1 votes

# Answer
# Stax, 5 bytes

```
⌡Ö├⌡→

```

Run and debug it

Numeric 0 and empty lists are considered falsy. All other values are truthy.
> 1 votes

# Answer
# Starry, 82 bytes

```
     +          + + +  **      +*`      + *  + +.  + +', '.      +  ' `      +.  `

```

```
5+                 Push 0
10+1+1+2*0*6+0*    Push 31 (5*(5+1)+1)
0`                 [Label 0]
  6+1*             Subtract 1 from top of stack
  2+1+0.           Print '0'
  2+1+0'           If top is not zero, goto label 0
0,1'               If input is non-zero, goto label 1
  0.6+2'           Print '0', goto label 2
  1`6+0.           [Label 1] print '1'
2`                 [Label 2]

```

(The number before each symbol represents the number of spaces)

It's pretty straightforward: print 31 zeroes, then print zero if the input is zero, or one if the input is non-zero. Normally, you would need to push a zero to print on the eighth line, but I just used one the zero from the first half of the program. The \[Label 2\] at the end is important so that the falsey case doesn't fall into the truthy case, and instead jumps to the end.

Try it online!
> 1 votes

# Answer
# Vyxal, ~~8~~ 5 bytes

```
S32↳›

```

Try it Online!
> 1 votes

# Answer
# APL, 11 bytes

```
⍕¯32↑1↑1\⍨⊢

```

**How?**

`1\⍨⊢` \- repeat 1 input times - return empty array on falsy value

`1↑` \- take the first item

`¯32↑` \- align right with 31 zeros

\- format as string
> 0 votes

# Answer
# J, 11 bytes

```
(31#'0'),":

```

Try it online!

## how?

```
31 zeros
00...000  append     turn the 0 or 1 input into string
(31#'0')    ,       ":

```

note: in J, booleans are 0 or 1, also known as "the iverson convention," after ken iverson, creator of J and APL
> 0 votes

# Answer
# Jelly, 8 bytes

```
31”0x⁸ṆṆ

```

Try it online!
> 0 votes

# Answer
# Pyth, 9 bytes

```
+*31\0-1!

```

Test suite

Explanation:

```
+*31\0-1!
+*31\0-1!Q | Implicit Q (input)
 *31\0     | repeat the character '0' 31 times
        !Q | logical negation of input
      -1   | subtract from 1
+          | concatenate

```
> 0 votes

# Answer
# MATL, 5 bytes

```
32&YB

```

Uses inputs `1`/ `0`, or `T`/ `F`.

**Try it online!**

### Explanation

```
32     % Push 32
&YB    % Convert implicit input to binary with 32 digits. Gives char output

```
> 0 votes

# Answer
# Carrot, 7 bytes

```
0^*30^#

```

There is no truthy/falsey type in Carrot at the moment. However, `1` and `0` are usually considered to be truthy/falsey so that is how I am expecting the input.

Explanation:

```
0   //Set the string stack to 0
^   //Change to operations mode
*30 //Duplicate the string stack 30 times
^   //Convert to string stack mode
#   //Add the input to the end of the stack
    //Implicitly output the string stack

```
> 0 votes

# Answer
# Retina, 13 bytes

```
Ms`.+
^
31$*0

```

Try it online! Assumes empty input is falsy and everything else is truthy, which is about all you can do when your only type is string.
> 0 votes

# Answer
# Lua, 30 bytes

```
("%032d"):format(b and 1 or 0)

```

Try it online!
> 0 votes

# Answer
# \>\<\>, ~~18~~ 16 bytes

```
<n0v?)*3a:l
;oi<

```

Try it online!

# Explanation

```
<n0v?)*3a:l
;oi<
<              | Move the direction left
         :l    | Push the length of the stack onto the stack and duplicate it
      *3a      | Push 10*3 onto the stack
     )         | Compare the stack top item is greater than the next stack item, push 1 is true else 0
   v?          | Check if stack top is 0, if 0 then jump else go to line 2
 n0            | Print 0 (this will then loop line 1 again)
;oi<           | Take input (1 byte), print input then end program

```
> 0 votes

# Answer
# Clojure, 28 bytes

```
#(format "%031d" (if % 1 0))

```

Truthy is everything but `nil` and `false`
> 0 votes

# Answer
# JavaScript, 25 bytes

```
v=>'0'.repeat(31)+(v?1:0)

```

31 zeroes and conditionally add a 1 or 0.
> 0 votes

# Answer
# JavaScript (ES6), 25 bytes

```
b=>`${+b}`.padStart(0,32)

```

A different approach. Takes input as specifically `true` or `false`.

## Test Snippet

```
let f=
b=>`${+b}`.padStart(32,0)

console.log(true, f(true))
console.log(false, f(false))
```

```
.as-console-wrapper{max-height:100%!important}
```
> 0 votes

# Answer
# Befunge-98, 16 bytes

```
'0'k:'k,&!!+,@

```

Try it online!

Hexdump:

```
00000000: 2730 271e 6b3a 271e 6b2c 2621 212b 2c40  '0'.k:'.k,&!!+,@

```

---

**output as space sperated digits, 9 bytes:**

```
'k.&!!.@

```

Try it online!

Hexdump:

```
00000000: 271e 6b2e 2621 212e 40                   '.k.&!!.@

```
> 0 votes

# Answer
## Dyvil v0.33.0, 15 Bytes

```
b=>"0"*31+b?1:0

```

**Usage**:

```
let f: boolean -> String =
b=>"0"*31++b?1:0

print f(true)  // 00000000000000000000000000000001
print f(false) // 00000000000000000000000000000000

```

**Explanation**:

Returns the string `0` repeated 31 times followed by `1` for `true` and `0` for `false`. This does not work in v0.34.0 anymore because it removes the `+` operator for Strings.
> 0 votes

# Answer
# Excel, ~~22~~ ~~20~~ 18 bytes

Saved two bytes thanks to Wernisch and my own lack of critical analysis before posting.
Saved two bytes by changing the formula completely

```
=BASE(OR(A1),2,32)

```

~~It feels like there should be a shorter answer than this but I can't think of one.~~
I found the shorter function that I felt must exist.
> 0 votes

# Answer
# Common Lisp, 71 bytes

```
(defun f(i)(format t "~v@{~A~:*~}" 31 0)(prin1(cond((null i) 0)(t 1))))

```

Try it online!

Because nil is a falsey value and anything else is truthy:

(f nil) = 00000000000000000000000000000000

(f 123) = 00000000000000000000000000000001

(f t) = 00000000000000000000000000000001
> 0 votes

# Answer
# CJam, 6 bytes

```
q31Te[

```

Try it Online

Takes 1 for true and 0 for false. pads input with 31 0's on the left.

```
q     e# read input
31Te[ e# pad input with 31 0's on the left.

```
> 0 votes

# Answer
# Cubix, 24 bytes

```
1&u3I!|1^...0O;($\!vuO;@

```

Nonzero values are truthy in Cubix (as handled by `!`)

Try it online!

```
    1 &
    u 3
I ! | 1 ^ . . .
0 O ; ( $ \ ! v
    u O
    ; @

```

Explanation:

* `I` : read in input as a number
* `!|` : reflect go left if falsey, proceed if truthy

falsey:

* `I` : read in input; it's blank, so push `0`

truthy:

* `1` : push `1`

both branches reach here:

* `^3u1&\` : put `31` to the top of the stack and enter the loop

Loop:

* `!v0O;($\` : if top is zero, go south, otherwise push `0`, `O`utput as a number, pop (`;`), decrement (`(`), then `$`kip `\` and continue.

Finally:

* `;uO@` : pop the zero, `O`utput the `0/1`, and `@` exits.
> 0 votes

# Answer
# QBIC, 21 bytes

```
[31|?A';`]~:|?!1$\?@0

```

## Explanation

```
[31|        DO 31 times
?           PRINT
 A          A$, which is later diefined as a literal 0
            (represented as string, because QBasic spaces out printed numbers)
 ';`        Followed by a semicolon (to prevent newlines, tabs ect)
]           Close the loop
~:          IF the (numeric) input (is anything but 0)
|?!1$       THEN print a literal 1 (cast to string, to prevent the spacing thingy again)
\?@0        ELSE print a 0; Here we finally define A$. We could use it earlier,
            because the complie-process from QBIC to QBasic moves literal declarations to the
            top of the file.

```
> 0 votes

# Answer
# Perl 6, 11 bytes

```
'0'x 31~+?*

```

Try it online!

* `'0' x 31` produces the first 31 zeroes.
* `*` is the argument to the function. `?` coerces it to a boolean, and then `+` coerces that boolean into a number, either `0` or `1`, which is appended to the leading zeroes with `~`.
> 0 votes

# Answer
# Groovy - 17 bytes

A Groovy closure which takes a value and according to "groovy truth" outputs either a falsey or truthy value.

`{"0"*31+(it?1:0)}`

### Explanation

So, all we do is emit a string with 31 zeroes and then append either 0 or 1 onto the end, depending upon whether the input is false or true, according to "groovy truth".

Try it online!
> 0 votes

# Answer
## /Kona, 10 bytes

Sadly not as clever as I'd have liked, but it works.

```
(31#"0"),$

```

String-casts the input, and staples it to the end of 31 "0" chars

E.g.

```
k)(31#"0"),$1b
"00000000000000000000000000000001"
k)(31#"0"),$0b
"00000000000000000000000000000000"

```
> 0 votes

# Answer
# Perl 5, 17 + 1 (-p) = 18 bytes

```
$_=0 x31 .($_&&1)

```

Try it online!
> 0 votes

# Answer
# AWK, 20 bytes

```
{printf"%032d",!!$0}

```

Try it online! Here, to deal with multiple lines of input, I added `\n` to the printf modifier.

```
{                  }  For every input,
 printf"%    ",       prints, without a trailing newline,
         0            with leading zeros,
          32d         a 32-digit number,
               !!$0   and this number is the negative of the negative of the input.
                      In awk, only zero(s) and blank lines return false.
                      Anything else return true.
                      See examples in the TIO link above.

```

Another working code, with 24 bytes: `$0=sprintf("%032d",!!$0)`
> 0 votes

# Answer
# Thunno 2, 4 bytes

```
Ṙ32ṛ

```

Attempt This Online!

Input as a Python boolean: `True` or `False`.

#### Explanation

```
      # Implicit input.
      # The interpreter implicitly converts
      # True and False to 1 and 0, since
      # integers look better than booleans.
Ṙ     # Convert this integer into a string.
 32ṛ  # And pad it with zeros on the left
      # until the length is equal to 32.
      # Implicit output.

```
> 0 votes

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


title: Random ticket code generator

text:
# Question
Title: Random ticket code generator
A lottery company wants to generate a random lottery ticket number of length 10 characters.

Write a code in any language to create such a number in which every digit comes only once for example `9354716208` in this number all integers from 0 to 9 comes only once. This number should be a random number.

* The generated number should be shown on screen.
* It must be able to generate all permutations of all allowable characters.
* The code is required to be as small as possible (in bytes).

# Answer
## J (4 bytes)

Couldn't resist.

```
?~10

```

In J, if `F` is dyadic , `F~ x` is the same as `x F x`.
> 41 votes

# Answer
### J, 5 characters and APL, 8 characters

**J**

```
10?10

```

J has the built-in deal operator (`?`). Thus, we can take 10 out of 10 (`10?10`).

**APL**

```
1-⍨10?10

```

APL has the same operator which unfortunately starts with one instead of zero. We are therefore subtracting one from each number (`1-⍨X` means `X-1` due to the commute operator).
> 12 votes

# Answer
**Python 2.7 (~~64~~ ~~63~~ 57)**

Not a chance here compared to the operator heavy languages and due to the lack of default loaded random :) This is the shortest I could come up with;

```
from random import*
print''.join(sample("0123456789",10))

```

It creates a range and samples 10 numbers from it without replacement.

(Thanks to @xfix for the shorter import format fix and @blkknght for pointing out my somewhat über complicated sampling range)

**Python 2.7 (40)**

If you run it from the interactive prompt and can read comma separated, you can shave it to 40, but it feels a bit like breaking the spirit of the rules;

```
from random import*
sample(range(10),10)

```
> 9 votes

# Answer
# Perl 6 (~~18~~ 16 characters)

```
print pick *,^10

```

This generates array containing all random elements (`pick *`) from `0` to `9` and outputs the result (`print`).

Sample output:

```
$ perl6 -e 'print pick *,^10'
4801537269
$ perl6 -e 'print pick *,^10'
1970384265
$ perl6 -e 'print pick *,^10'
3571684902

```
> 8 votes

# Answer
## Ruby, 18

Run this in `irb`:

```
[*0..9].shuffle*''

```

If you want this to be a stand-alone program, with output to `stdout` (the rules don't seem to *require* this), then add these 4 chars at the start:

```
$><<

```
> 8 votes

# Answer
# PHP - 37 Characters

```
<?=join('',array_rand(range(0,9),10))

```

I had an 18-character solution that should theoretically work but PHP is weird.

Or, if you want an xkcd answer:

```
<?="5398421706" // Chosen by program above; guaranteed to be random ?>

```

EDIT: Thanks xfix, it's now 5 characters shorter and complete. EDIT AGAIN: Live example.
> 8 votes

# Answer
**PHP, 29 chars**

`<?=str_shuffle('0123456789');`

With PHP, the closing tag isn't required. But if that's against the rules, then you can replace ; with ?\> for 1 net increase.
> 8 votes

# Answer
### GolfScript, 12 characters

```
10,{;9rand}$

```

Simply generates the list of digits (`10,`) and sorts it `{...}$` according to some random keys - which yields a random order of the digits.

Examples (try online):

```
4860972315

0137462985

```
> 7 votes

# Answer
## R (23 characters)

```
cat(sample(0:9),sep="")

```

Sample output:

```
> cat(sample(0:9),sep="")
3570984216
> cat(sample(0:9),sep="")
3820791654
> cat(sample(0:9),sep="")
0548697132

```
> 6 votes

# Answer
## TI-BASIC, 5 bytes

```
randIntNoRep(1,10

```
> 6 votes

# Answer
**Octave (14)**

```
randperm(10)-1

```

`randperm` unfortunately creates a selection from 1..n, so have to subtract 1 at the end to get 0-9.
> 5 votes

# Answer
# In sql server

```
DECLARE @RandomNo varchar(10)
SET @RandomNo = ''

;WITH num as (
SELECT 0 AS [number]
Union
select 1
Union
select 2
Union
select 3
Union
select 4
Union
select 5
Union
select 6
Union
select 7
Union
select 8
Union
select 9
)
SELECT Top 9 @RandomNo = COALESCE(@RandomNo + '', '') + cast(n.number AS varchar(1))
FROM numbers n
ORDER BY NEWID()

SELECT cast(@RandomNo AS numeric(10,0))

```

# See Demo

OR something similar (courtesy of @manatwork) using recursion and xml.

```
with c as(select 0i union all select i+1from c where i<9)select i+0from c order by newid()for xml path('')

```
> 5 votes

# Answer
# Javascript (~~79~~ ~~78~~ 68 characters)

Rather than creating an array with the numbers 0-9 and sorting it, I decided to generate random numbers. When it came up with a number that was not already in the array then added it. This repeats ten times and then alerts the output.

`for(a="";!a[9];){~a.indexOf(b=~~(Math.random()*10))||(a+=b)}alert(a)`
> 5 votes

# Answer
# Mathematica 40

The number is created as a string so as to allow zero to be displayed as the first character, when needed.

```
""<>RandomSample["0"~CharacterRange~"9"]

```

**Output examples**

> "0568497231"
> "6813029574"

**Explanation**

`"0"~CharacterRange~"9"` is infix notation for `CharacterRange["0","9"]`. Either of these returns the list, `{"0","1","2","3","4","5","6","7","8","9"}`.

`RandomSample[list]` by default returns a permutation of the list. (It can also be used for other kinds of sampling, when parameters are included. E.g. `RandomSample[list, 4]` will return a Random sample of 4 characters, with no repeats.
> 4 votes

# Answer
# C#, 145 bytes

## Ungolfed

```
using System;
using System.Linq;
class P
{
    static void Main()
    {
        Enumerable.Range(0,10).OrderBy(g => Guid.NewGuid()).ToList().ForEach(Console.Write);
    }
}

```

## Golfed

```
using System;using System.Linq;class P{static void Main(){Enumerable.Range(0,10).OrderBy(g => Guid.NewGuid()).ToList().ForEach(Console.Write);}}

```
> 4 votes

# Answer
## JavaScript, 82 characters

**EDIT:** Thanks to Rob W, code length is reduced to 90 characters.

**EDIT:** Thanks to George Reith, code length is reduced to 82 characters (using for loop).

Pretty straightforward way: pick random element of `[0,1,2,3,4,5,6,7,8,9]` array and append it to the output, then reduce array and replay.

*Old version (106 characters):*

```
a=[0,1,2,3,4,5,6,7,8,9],l=11,t="";while(--l){r=Math.floor(Math.random()*l);t+=a[r];a.splice(r,1);}alert(t)

```

Readable version:

```
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], l = 10,t = "";
while(l--) {
  r = Math.floor(Math.random() * l);
  t += a[r];
  a.splice(r, 1);
}
alert(t);

```

*Better version (90 characters):*

```
a="0123456789".split(t=""),l=11;while(--l)t+=a[r=0|Math.random()*l],a.splice(r,1);alert(t)

```

*Last version (82 characters):*

```
a="0123456789".split(t='');for(l=11;--l;t+=a.splice(0|Math.random()*l,1));alert(t)

```

JSFiddle: http://jsfiddle.net/gthacoder/qH3t9/.
> 4 votes

# Answer
## Mathematica, 27

```
Row@RandomSample@Range[0,9]

```
> 4 votes

# Answer
## Shell/Coreutils, 23

```
shuf -i0-9|paste -sd ''

```
> 4 votes

# Answer
## K/Kona (6)

```
-10?10

```

As with J, `?` is the deal operator; the `-` forces the values to not repeat.
> 3 votes

# Answer
## Scala, 37

```
util.Random.shuffle(0 to 9).mkString

```
> 3 votes

# Answer
## JavaScript (80 characters)

```
alert("0123456789".split("").sort(function(){return .5-Math.random()}).join(""))

```

JS-Fiddle: http://jsfiddle.net/IQAndreas/3rmza/
> 2 votes

# Answer
## Forth, 72

```
needs random.fs : r ': '0 do i loop 9 for i 1+ random roll emit next ; r

```

Room still to golf, maybe, but Forth made this one hard. I think.
> 2 votes

# Answer
# Prolog, 177/302 characters

I'm a beginner on Prolog, so probably this is not the most condensed code.

```
:- use_module(library(clpfd)).
sort(N) :-
    N = [N0,N1,N2,N3,N4,N5,N6,N7,N8,N9],
    domain([N0],1,9),
    domain([N1,N2,N3,N4,N5,N6,N7,N8,N9],0,9),
    all_different(N),
    labeling([],N).

```

Returns:

```
| ?- sort2(N).
N = [1,0,2,3,4,5,6,7,8,9] ? ;
N = [1,0,2,3,4,5,6,7,9,8] ? ;
N = [1,0,2,3,4,5,6,8,7,9] ? ;
N = [1,0,2,3,4,5,6,8,9,7] ? ;
N = [1,0,2,3,4,5,6,9,7,8] ?
yes

```

If you want it to return an integer:

```
:- use_module(library(clpfd)).
sort(M) :-
    N = [N0,N1,N2,N3,N4,N5,N6,N7,N8,N9],
    domain([N0],1,9),
    domain([N1,N2,N3,N4,N5,N6,N7,N8,N9],0,9),
    all_different(N),
    labeling([],N),
    M is (N0*1000000000)+(N1*100000000)+(N2*10000000)+(N3*1000000)+
         (N4*100000)+(N5*10000)+(N6*1000)+(N7*100)+(N8*10)+N9.

```

Returns:

```
| ?- sort(N).
N = 1023456789 ? ;
N = 1023456798 ? ;
N = 1023456879 ? ;
N = 1023456897 ? ;
N = 1023456978 ?
yes

```

Using instead:

```
labeling([down],N)

```

Gives the numbers in the opposite order:

```
| ?- sort(N).
N = 9876543210 ? n
N = 9876543201 ? n
N = 9876543120 ? n
N = 9876543102 ? n
N = 9876543021 ?
yes

```

Unlike some other codes posted, this returns all possibilities (with no repetitions).
> 2 votes

# Answer
**Clojure, 42**

```
(println (apply str (shuffle (range 10))))

```

> 6209847315
> 2 votes

# Answer
# q/kdb \[6 chars\]

```
-10?10

```

will generate 10 unique random numbers.
> 2 votes

# Answer
# √ å ı ¥ ® Ï Ø ¿ , 4 bytes

```
XrśO

X    › Push 10 to the stack
 r   › Push the range from [1...10]
  ś  › Shuffle the stack
   O › Output the whole stack separated by spaces

```
> 2 votes

# Answer
# Javascript, 83 characters

```
a=[];while(!a[9]){b=Math.floor(Math.random()*10);!a.includes(b)&&a.push(b)}alert(a)

```

While running until array has 10 elements.

Generating random number from 0 - 9 then check if array !includes this number and add it to the array.
> 2 votes

# Answer
# Vyxal `s`, 4 bytes

```
kdÞ℅

```

Try it Online!

Explanation:

```
kd   # Digits `0123456789`
  Þ℅ # Random permutation
     # 's' flag - Print the sum of the top of the stack

```
> 2 votes

# Answer
# F#, 71 63 characters

I'm new to F#, but here's what I've come up with:

```
{ 0..9 }
    |> Seq.sortBy (fun _ -> System.Guid.NewGuid())
    |> Seq.iter (printf "%d")

```

compacted:

```
{0..9}|>Seq.sortBy(fun _->Guid.NewGuid())|>Seq.iter(printf"%d")

```
> 1 votes

# Answer
This is not much smaller than JMK's answer, but here's a slightly smaller C# solution (135):

```
using System;
using System.Linq;
class P {
    static void Main()
    {
        Console.Write(string.Join("", "0123456789".OrderBy(g => Guid.NewGuid())));
    }
}

```

Compacted (134):

```
using System;using System.Linq;class P{static void Main(){Console.Write(string.Join("", "0123456789".OrderBy(g => Guid.NewGuid())));}}

```

Alternate version (135):

```
using System;
using System.Linq;
class P {
    static void Main()
    {
        "0123456789".OrderBy(g => Guid.NewGuid()).ToList().ForEach(Console.Write);
    }
}

```

Compacted:

```
using System;using System.Linq;class P{static void Main(){"0123456789".OrderBy(g => Guid.NewGuid()).ToList().ForEach(Console.Write);}}

```

They're equal in length, but it really just depends on whether you want to use Linq's ForEach function or String's Join function. I was able to remove 10 characters in length by spelling out the range "0123456789" in a string instead of using Enumerable.Range(0, 10).
> 1 votes

# Answer
**LOGO**, 64 characters

```
make "d 1234567890
repeat 10 [
    make "n pick d
    show n
    make "d butmember n d
]

```

**pick** returns random item of the supplied list. **butmember** returns list with all occurrences of the specified item removed. *Note: Not all Logo implementations support `butmember` command.*
> 1 votes

# Answer
# Racket ~~45~~ 43

```
(map print(shuffle'(0 1 2 3 4 5 6 7 8 9)))

```
> 1 votes

# Answer
**Javascript (96)**

```
function x(){return s.search(r=0|Math.random()*10)<0?r:x()}for(i=0,s='';++i<=10;s+=x());alert(s)

```

*First attempt (109)*

```
s='';for(i=0;++i<=10;s+=(x=function(){return s.indexOf(r=(m=Math).floor(m.random()*10))<0?r:x()})())alert(s);

```
> 1 votes

# Answer
# Java 8, ~~153~~ ~~150~~ ~~143~~ ~~139~~ 130 bytes

```
import java.util.*;v->{List l=new Stack();for(int i=0;i<=9;l.add(i+++""));Collections.shuffle(l);System.out.print("".join("",l));}

```

-7 bytes thanks to *@KritixiLithos*

**Explanation:**

Try it here.

```
import java.util.*;                // Required import for List, Stack, Collections
v->{                               // Method with empty unused parameter and no return-type
  List l=new Stack();              //  List
  for(int i=0;i<=9;                //  Loop from 0 to 9 (inclusive)
    l.add(i+++""));                //   Add these numbers to the List (as String)
  Collections.shuffle(l);          //  Randomly shuffle the List
  System.out.print("".join("",l));}//  Print the List content without delimiter

```
> 1 votes

# Answer
# SmileBASIC, 50 bytes

```
S$="0123456789
@L
SWAP S$[RND(10)],S$[0]?S$GOSUB@L

```

Explained:

```
S$="0123456789" 'create string with digits 0-9
@LOOP 'label
SWAP S$[RND(10)],S$[0] 'swap a random character with the first character
PRINT S$ 'print the string
GOSUB @LOOP 'Loop. Using GOSUB without RETURN will eventually cause a stack overflow, ending the program.

```
> 1 votes

# Answer
# Sinclair ZX81/Timex TS1000/1500 BASIC, 133 bytes 144 bytes 97 bytes (listing)

I started this by trying to imagine how PHP's `str_shuffle()` would work in Sinclair \[ZX81\] BASIC, and ended here (new and improved version):

```
1 LET A$="0987654321"
2 LET R=INT (RND* LEN A$)+1
3 PRINT A$(R);
4 LET A$=A$( TO R-1)+A$(R+1 TO )
5 GOTO 2+((A$="")*4)

```

This solution is based on a post by XavSnap on the Sinclair ZX World forums after I posted my solution below.

### Initial entry (slower and bloated):

```
1 LET A$="0123456789"
2 LET B$=""
3 FOR I=0 TO 9
4 GOSUB 8
5 NEXT I
6 PRINT B$
7 STOP
8 LET A=1+INT (RND*10)
9 IF A$(A)=" " THEN GOTO 8
10 LET B$=B$+A$(A)
11 LET A$(A)=" "
12 RETURN

```

Some things to note

1. Sinclair ZX80 and ZX81 BASIC does not accept multi-statemented lines, like `10 PRINT "HELLO":GOTO 10`
2. The interpreter adds in white spaces before and after most commands, so this version of BASIC is one of the most difficult to golf
3. You can manipulate strings by position like a `char[]` in C, although strings are indexed from 1 and not 0
4. This new version will work on an unexpanded (1K/2K) machine for real
5. When I've worked it out, the byte count is the listing only, it's using more system RAM. As this is 8 bit tech, I'll also work out the actual byte count (listing + variable stack)
> 1 votes

# Answer
# 05AB1E, 4 bytes

The language probably changed in between the exercise and my solution, so this is not really competing.

`žh.r`

Try online
> 1 votes

# Answer
# Japt, ~~6~~ 4 bytes

```
Aö¬q

```

Try it online

---

## Explanation

`ö¬` generates a random permutation of the range `[0-10)` (with `A` being the Japt constant for `10`) and `q` joins it to string.
> 1 votes

# Answer
# Tcl, 84 bytes

```
proc f a\ b {expr rand()>.5}
puts [join [lsort -command f {1 2 3 4 5 6 7 8 9 0}] ""]

```

Try it online!
> 1 votes

# Answer
# Perl 5, 21 bytes

```
@k{0..9}++;say keys%k

```

Try it online!

Perl's hash algorithm puts the hash keys into a a random order, so this should satisfy the requirements.

If it doesn't, here's the old method:

### Perl 5, 38 bytes

```
@a=0..9;print splice@a,rand@a,1while@a

```

Try it online!
> 1 votes

# Answer
# LibreLogo, 96 bytes

**Code:**

```
x=list(range 10)
c=1
z='' while c>0[ r=int(ps any) if r<c[ z+=str(x.pop(r)) ] c=count x ]print z

```

**Explanation:**

```
x = list(range 10)                 ; x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
c = 1
z = ''
while c > 0 [                      ; While !empty( x )
    r = int(ps any)                ;     r = random 10
    if r < c [                     ;     If Random # < count( x )
        z += str(x.pop(r))         ;         z.append( x[random] ), x.remove( x[random] )
    ]
    c = count x                    ; Keep track of leftover elements
]
print z                            ; Print Result

```

**Result:**
> 1 votes

# Answer
# Pyt, 3 bytes

```
ɳᒆʀ

```

Explanation:

```
ɳ           Push the string "0123456789" onto the stack
 ᒆ         Push an array containing all possible permutations (of "0123456789") onto the stack
  ʀ         Pick an element from the array uniformly at random

```

Try it online!
> 1 votes

# Answer
# \>\<\>, ~~17 11~~ 12 bytes

-6 bytes thanks to @Teal pelican suggesting a better way to generate the numbers 0-9. Thanks to @Not a Tree for pointing out the previous version only starts with a 9 or a 0.

```
<v?=9:l
{xn!

```

Try It Online!

Adds all the numbers to the stack and then randomly chooses between cycling the stack or outputting the number until the stack is the empty. Biased towards larger numbers first, but the random wasn't specified to be uniform.

An 11 byte version that doesn't work on TIO due to `{` erroring on an empty stack, but works on other platforms such as here.

```
{l:b=?.!
xn

```
> 1 votes

# Answer
# Chip, 75 + 17 = 92 bytes

`+17` bytes for args `-g0i -w -mq -c20`

```
 8 ?]v~S
?/--^]~9
A\0)0/a
B\1)1/b
C\2)2/c
D\3)3/d
,L-v-^e
)\sf
`zzzzzzzzzz*

```

Try it online! Try adding `-vv` to the args list to see the values on the queue as it runs, in the debug output.

Not the most straightforward solution... The strategy here is like this:

1. fill a queue with the numbers `0` through `9`
2. pop the head of the queue, call this `x`
3. generate a random number `0` to `3`
    * if `3`, print `x`
    * if not `3`, append `x` back onto the queue
4. jump to step 2 until all ten numbers have been printed

This strategy ensures that all permutations are possible, however the permutations are not evenly distributed. Also, it is theoretically possible to never finish printing.

This could potentially be slightly smaller if I generate a single random bit (`0` or `1`) instead of two (`0` to `3`), but it would have a more extreme effect on the distribution. My initial attempt, however, didn't actually save many bytes.

If there is interest, I will endeavor to explain further the actual implementation details.
> 1 votes

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

```
()=>string.Join("",Enumerable.Range(0,10).OrderBy(x=>new System.Random().Next()))

```

Try it online!
> 1 votes

# Answer
# Zsh, 20 bytes

```
shuf -i0-9|tr -d \\n
```

Attempt This Online!
> 1 votes

# Answer
# Thunno 2, 4 bytes

```
kDµr

```

Attempt This Online!

#### Explanation

```
kDµr  # Implicit input
kD    # Push the string "0123456789"
  µr  # Take a random permutation
      # Implicit output

```
> 1 votes

# Answer
## SPSS (174 bytes)

Most of the commands in SPSS can be shortened to the first three letter. It is convenient for code golfing.

```
new fil.
inp pro.
loo i=0 to 9.
comp R=uni(1).
end cas.
end loo.
end fil.
end inp pro.
sor cas R.
fli i.
for var001 to var010 (f1).
wri /var001 to var010.
exe.

```
> 0 votes

# Answer
# Bash (79 characters)

```
seq 0 9|awk 'BEGIN{srand()}{print rand()"\t"$0}'|sort -nk1|cut -f2-|tr -d '\n'

```

Note that the lottery company should not run this more than once per second!

Edit: Oh rats, this answer blows mine away.
> 0 votes

# Answer
## C, 97 characters

C is unrepresented...time to fix that!

```
d[10],i;main(j){srand(&j);while(i++<10){doj=rand()%10;while(d[j]);d[j]=putchar(j+'0');}puts("");}

```

Slightly more legible:

```
d[10],i;
main(j){
  srand(&j);
  while(i++<10){
    do
      j=rand()%10;
    while(d[j]);
    d[j]=putchar(j+'0');
  }
  puts("");
}

```
> 0 votes

# Answer
# CJam, 5 bytes

```
10,mr
10,    e#Range 0..9 inclusive
   mr  e#Shuffle

```
> 0 votes

# Answer
# Powershell, 24 Bytes

```
-join(0..9|sort{random})

```

Explanation:

```
-join( #Join an array of
0..9 #The numbers 0-9
|sort{random} #Sorted into a random order
)

```

running it 10 times results in:

```
9184702653
7813529406
0458237691
2158604793
5391782046
4673980251
4870532196
9412576380
4816275309
1098624537
4257910683

```
> 0 votes

# Answer
## C 144 bytes

```
f(){srand(time(0));j,i,a[10];for(i=0;i<=9;i++){a[i]=i;}for(i=0;i<4;i++){j=rand()%9;a[j]=9-j;a[9-j]=9-a[j];}for(i=0;i<=9;i++)printf("%d",a[i]);}

```

Ungolfed version:

```
void f()
{
   srand(time(NULL));
   int j, i, a[10];

   for (i = 0; i <= 9; i++)
      a[i] = i;

   //jumble the array elements
   for (i = 0; i<4; i++)
   {
       j = rand() % 9;
       a[j] = 9 - j;
       a[9 - j] = 9 - a[j];
   }

    for (i = 0; i <= 9; i++)
       printf("%d ", a[i]);

}

```

## Usage

Every time this binary is executed, a new random array of numbers from 0 to 9 is printed.

## Explanation

* `srand` is used so that a new seed is produced everytime for `rand` function.
* Store the elements from 0 to 9 in an array.
* Jumble the array elements by generating four random values between 0-9. (I'm not sure if that step was so wise, can be done in a better way i guess.)
* Print the array elements
> 0 votes

# Answer
## Lithp, 66 bytes

```
(print(join(list-rand(permutations(list 0 1 2 3 4 5 6 7 8 9)))""))

```

Try it online!

`permutations/1` generates all permutations of the given list. There will be no duplicates. We pick a random item from the generated permutations and print it.

The try it online link has a better example for printing out a number of unique entries.

This could be a little shorter if the `lists` module is imported, but importing it takes up more space than is saved by a `(seq 0 9)` call.
> 0 votes

# Answer
# Python 2, 77 bytes

```
from random import*;x=range(10);shuffle(x);print ''.join([str(i) for i in x])

```

Try it online!

This creates the desired list using Python's `range`, then shuffles it using `random.shuffle`. `random.shuffle` just randomizes the list. Then it prints out each item in the list joined by `''`.
> 0 votes

# Answer
# Factor, 33 bytes

```
10 iota 10 sample [ pprint ] each

```

Try it online!

| Snippet | Comment | Data stack (top on right) |
| --- | --- | --- |
| `10 iota` | A range of numbers from 0 inclusive to 10 exclusive | `{ 0 1 2 3 4 5 6 7 8 9 }` |
| `10 sample` | Take 10 random samples from a sequence without replacement | `{ 7 3 8 4 2 5 1 9 6 0 }` |
| `[ pprint ] each` | Prettyprint each element without a newline |  |
> 0 votes

# Answer
# Ly, 24 bytes

```
9[:,]y[0f?[fsprlr,]puy]p

```

Try it online!

This adds the digits 0-9 onto the stack, then as long as the stack isn't empty, it picks a random number, rotates the stack entries that many times, then prints the top of the stack.

```
9[:,]                     - pushes 9, 8, 7, ... 0 onto the stack
     y[              y]p  - loops as long as the stack size>0
       0f?                - generate random number in 0-(stack-size) range
          [      ,]p      - loops for as many rotations as we want to do
           fsp            - flip the random digit to the top, save and delete
              rlr         - reverse the stack, load saved digit, reverse again
                    u     - print the random digit we picked

```

The number of rotations used really should be in the range `0-(stack-size-1)` but the possible extra rotation doesn't hurt anything and it saves a character to use the larger range.
> 0 votes

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


title: Integer logarithms

text:
# Question
Title: Integer logarithms
Given integers `N , P > 1` , find the largest integer `M` such that `P ^ M ≤ N`.

### I/O:

Input is given as 2 integers `N` and `P`. The output will be the integer `M`.

### Examples:

```
4, 5 -> 0
33, 5 -> 2
40, 20 -> 1
242, 3 -> 4
243, 3 -> 5
400, 2 -> 8
1000, 10 -> 3

```

### Notes:

The input will always be valid, i.e. it will always be integers greater than 1.

### Credits:

Credit for the name goes to @cairdcoinheringaahing. The last 3 examples are by @Nitrodon and credit for improving the description goes to @Giuseppe.

# Answer
> 8 votes
# Brain-Flak, 74 bytes

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

```

Try it online!

This uses the same concept as the standard Brain-Flak positive integer division algorithm.

```
# Push P and P-1 on other stack
(({}<>)[()])

# Count iterations until N reaches zero:
({()<

  # While keeping the current value (P-1)*(P^M) on the stack:
  (({})<

    # Multiply it by P for the next iteration
    ({([{}]()({}))([{}]({}))}{})

  >)

  # Subtract 1 from N and this (P-1)*(P^M) until one of these is zero
  {<>({}[()])}{}

# If (P-1)*(P^M) became zero, there is a nonzero value below it on the stack
>}

# Subtract 1 from number of iterations
[()])

```

# Answer
> 7 votes
# JavaScript (ES6), 22 bytes

*Saved 8 bytes thanks to @Neil*

Takes input in currying syntax `(p)(n)`.

```
p=>g=n=>p<=n&&1+g(n/p)

```

Try it online!

# Answer
> 6 votes
# Excel, 18 bytes

```
=TRUNC(LOG(A1,A2))

```

Takes input "n" at A1, and input "p" at A2.

# Answer
> 5 votes
# Jelly, 3 bytes

```
bḊL

```

This doesn't use floating-point arithmetic, so there are no precision issues.

Try it online!

### How it works

```
bḊL  Main link. Left argument: n. Right argument: p

b    Convert n to base p.
 Ḋ   Dequeue; remove the first base-p digit.
  L  Take the length.

```

# Answer
> 3 votes
# , 25 bytes

```
function(p,n)log(p,n)%/%1

```

Try it online!

Take the log of `P` base `N` and do integer division with `1`, as it's shorter than `floor()`. This suffers a bit from numerical precision, so I present the below answer as well, which should not, apart from possibly integer overflow.

# , 31 bytes

```
function(p,n)(x=p:0)[n^x<=p][1]

```

Try it online!

# Answer
> 3 votes
# C (gcc) \+ `-lm`, 24 bytes

```
f(n,m){n=log(n)/log(m);}

```

Try it online!

# Answer
> 3 votes
# Retina 0.8.2, 35 bytes

```
.+
$*
+r`1*(\2)+¶(1+)$
#$#1$*1¶$2
#

```

Try it online! Explanation:

```
.+
$*

```

Convert the arguments to unary.

```
+r`1*(\2)+¶(1+)$
#$#1$*1¶$2

```

If the second argument divides the first, replace the first argument with a `#` plus the integer result, discarding the remainder. Repeat this until the first argument is less than the second.

```
#

```

Count the number of times the loop ran.

# Answer
> 3 votes
# Japt, 8 bytes

```
@<Vp°X}a

```

Try it

# Answer
> 3 votes
# Haskell, 16 bytes

```
(floor.).logBase

```

Try it online!

Haskell was designed by mathematicians so it has a nice set of math-related functions in Prelude.

# Answer
> 3 votes
# Haskell, 30 bytes

```
n!p=until((>n).(p^).(1+))(1+)0

```

Try it online!

# Answer
> 3 votes
# Perl 6, 13 bytes

```
&floor∘&log

```

Try it online!

Concatenation composing log and floor, implicitly has 2 arguments because first function log expects 2. Result is a function.

# Answer
> 2 votes
# Python 2, 39 bytes

```
lambda a,b:math.log(a,b)//1
import math

```

Try it online!

# Answer
> 2 votes
# Japt, 5 bytes

```
ìV ÊÉ

```

Try it online!

---

## 8 bytes

```
N£MlXÃäz

```

Try it online!

# Answer
> 2 votes
# JavaScript, ~~40~~ 33 bytes

*-3 bytes thanks to DanielIndie*

Takes input in currying syntax.

```
a=>b=>(L=Math.log)(a)/L(b)+.001|0

```

Try it online!

# Answer
> 2 votes
# 05AB1E, 6 bytes

```
Lm¹›_O

```

Try it online!

# Answer
> 2 votes
# Emojicode, ~~49~~ 48 bytes

```
ij➡➖i j 1

```

Try it online!

# Answer
> 2 votes
# APL (Dyalog Unicode), 2 bytes

```
⌊⍟

```

Try it online!

Pretty straightforward.

Log

floor

# Answer
> 2 votes
# Pari/GP, 6 bytes

```
logint

```

(built-in added in version 2.7, Mar 2014. Takes two arguments, with an optional third reference which, if present, is set to the base raised to the result)

# Answer
> 2 votes
# Ruby, 31 bytes

OK, so all those log-based approaches are prone to rounding errors, so here is another method that works with integers and is free of those issues:

```
->n,p{(0..n).find{|i|p**i>n}-1}

```

Try it online!

But going back to logarithms, although it is unclear up to what precision we must support the input, but I think this little trick would solve the rounding problem for all more or less "realistic" numbers:

# Ruby, 29 bytes

```
->n,p{Math.log(n+0.1,p).to_i}

```

Try it online!

# Answer
> 2 votes
# Python 2, 3, 46 bytes

*-1 thanks to jonathan*

```
def A(a,b,i=1):
 while b**i<=a:i+=1
 return~-i

```

## Python 1, 47 bytes

```
def A(a,b,i=1):
 while b**i<=a:i=i+1
 return~-i

```

# Answer
> 2 votes
# JavaScript (Node.js), 22 bytes

```
m=>f=n=>n<m?0:f(n/m)+1

```

Try it online!

Curried recursive function. Use as `g(P)(N)`. Less prone to floating-point errors than using `Math.log`, and (I believe) the code gives correct values as long as both inputs are safe integers (under `2**52`).

# Answer
> 1 votes
# Haskell, ~~35~~ 34 bytes

```
n!p=last.fst$span((<=n).(p^))[0..]

```

Thanks @Laikoni for saving 1 byte

Try it online!

# Answer
> 1 votes
# Pyth, 6 4 bytes

```
s.lF

```

Saved 2 bytes thanks to Mmenomic
Try it online

## How it works

`.l` is logB(A)
To be honest, I have no idea how `F` works. But if it works, it works.
`s` truncates a float to an int to give us the highest integer for `M`.

# Answer
> 1 votes
# Husk, ~~8~~ ~~7~~ 4 bytes

```
Lt`B

```

Try it online!

# Answer
> 1 votes
# , 5 bytes

```
<.@^.

```

Try it online!

# Answer
> 1 votes
## Wolfram Language (Mathematica) ~~15~~ 10 Bytes

```
Floor@*Log

```

(requires reversed order on input)

Original submission

```
⌊#2~Log~#⌋&

```

# Answer
> 1 votes
# Forth (gforth), 35 bytes

```
: f swap s>f flog s>f flog f/ f>s ;

```

Try it online!

Could save 5 bytes by swapping expected input parameters, but question specifies N must be first (an argument could be made that in a postfix language "First" means top-of-stack, but I'll stick to the letter of the rules for now)

## Explanation

```
swap       \ swap the parameters to put N on top of the stack
s>f flog   \ move N to the floating-point stack and take the log(10) of N
s>f flog   \ move P to the floating-point stack and take the log(10) of P
f/         \ divide log10(N) by log10(P)
f>s        \ move the result back to the main (integer) stack, truncating in the process

```

# Answer
> 1 votes
# Wonder, 9 bytes

```
|_.sS log

```

Example usage:

```
(|_.sS log)[1000 10]

```

# Explanation

Verbose version:

```
floor . sS log

```

This is written pointfree style. `sS` passes list items as arguments to a function (in this case, `log`).

# Answer
> 1 votes
# Gforth, 31 Bytes

```
SWAP S>F FLOG S>F FLOG F/ F>S .

```

## Usage

```
242 3 SWAP S>F FLOG S>F FLOG F/ F>S . 4 OK

```

Try it online!

## Explanation

Unfortunately FORTH uses a dedicated floating-point-stack. For that i have to `SWAP` (exchange) the input values so they get to the floating point stack in the right order. I also have to move the values to that stack with `S>F`. When moving the floating-point result back to integer (`F>S`) I have the benefit to get the truncation for free.

## Shorter version

Stretching the requirements and provide the input in float-format and the right order, there is a shorter version with 24 bytes.

```
FLOG FSWAP FLOG F/ F>S .
3e0 242e0 FLOG FSWAP FLOG F/ F>S . 4 OK

```

Try it online!

# Answer
> 1 votes
# C (gcc), 61 bytes

```
i(n,t,l,o,g){for(l=g=0;!g++;g=g>n)for(o=++l;o--;g*=t);g=--l;}

```

Try it online!

# Answer
> 1 votes
# PowerShell 3,  ~~44~~ 38 Bytes

```
param($n,$p)for(;($n/=$p)-ge1){$z++}$z

```

Truncating to an int is too dang long in this language. However, looting the formula others are using bypasses this. ~~Crossed-out 44 is still 44~~

# Answer
> 1 votes
# x86(16/32 bit) opcode, 13 bytes

```
83 CB FF  31 DB  F7 F1  43  09 C0  75 F7  C3

```

Input `EAX`, `ECX`, output `EBX`

```
OR  EBX, -1
XOR EDX, EDX
DIV ECX
INC EBX
OR  EAX, EAX
JNZ $-7
RET

```

# Answer
> 1 votes
# MATL, 5 bytes

```
:YAnq

```

Try it online!

Simple arbitrary base conversion to avoid using floating point math.

# Answer
> 1 votes
# Ruby, ~~29~~ 26 bytes

```
f=->n,p{n<p ?0:1+f[n/p,p]}

```

Try it online!

# Answer
> 1 votes
# Pyth, 8 bytes

```
tf<Q^vzT

```

Test suite.

## Explanation

```
tf<Q^vzT – Full program.
 f       – First positive integer T that satsfies:
   Q       – The first input
  <        – Is less than
     vz    – The second input
    ^  T   – Raised to the T-th power.
t        – Decrement the integer and output implicitly.

```

# Answer
> 1 votes
# Intel 8087 FPU assembly, 38 bytes

Uses only the Intel 8087 math co-processor.

```
d9e8 df06 3c01 d9f1 d9e8 df06 3e01 d9f1 def9 9bd9
3e3e 0181 0e3e 0100 0c9b d92e 3e01 df1e 3c01

```

Unassembled:

```
; Integer logarithm
; input: integers N, P > 1 (mem16,mem16)
; output: N (mem16) largest integer such that P ^ M ≤ N
INTLOG  MACRO N,P
        FLD1        ; ST(1) = 1
        FILD N      ; ST = N
        FYL2X       ; ST = 1 * LOG2(N)
        FLD1        ; ST(1) = 1
        FILD P      ; ST = P
        FYL2X       ; ST = 1 * LOG2(P)
        FDIV        ; ST = LOG2(N) / LOG2(P)
        FWAIT       ; sync CPU/FPU
        FSTCW P     ; get the current CW register
        OR P, 0C00H ; set RC for floor rounding mode
        FWAIT       ; sync CPU/FPU
        FLDCW P     ; set the modified CW register
        FISTP N     ; N = FLOOR(ST)
        ENDM

```

Example IBM PC DOS test program:

```
    FINIT           ; reset 8087
    CALL INDEC      ; generic decimal input routine
    MOV  N, AX      ; first input into N
    CALL INDEC      ; generic decimal input routine
    MOV  P, AX      ; second input into P
    INTLOG N,P      ; calculate
    MOV  AX, N      ; result in N into AX for display
    CALL OUTDEC     ; generic decimal output routine

```

## Tests:

```
A>INTDEC.COM
: 4
: 5
0
A>INTDEC.COM
: 33
: 5
2
A>INTDEC.COM
: 40
: 20
1
A>INTDEC.COM
: 242
: 3
4
A>INTDEC.COM
: 243
: 3
5
A>INTDEC.COM
: 400
: 2
8
A>INTDEC.COM
: 1000
: 10
3

```

*Note*: **16 bytes** of this code are *just* for putting the FPU into floor rounding mode.

# Answer
> 1 votes
# Python 3 with mpmath, 52 bytes

```
import mpmath
def f(N,P):return int(mpmath.log(N,P))

```

Test it:

```
for N, P in zip([4, 33, 40, 242, 243, 400, 1000], [5, 5, 20, 3, 3, 2, 10]):
    print(f(N,P))

```

How I would really do it. The mpmath (included with SymPy) logarithm seems more accurate, even at default. I always love some arbitrary precision floating-point. I was really surprised that the standard methods led to such inaccuracies.

# Answer
> 1 votes
# Keg, `-hr`, 19 bytes

```
¿&¿0{:^:'$Ë&:&≤|⑨};

```

Try it online!

Uses the same technique as the Pyth answer

## Explained

# Answer
> 1 votes
# Wren, 32 bytes

Log, log, floor.

```
Fn.new{|a,b|(a.log/b.log).floor}

```

Try it online!

# Answer
> 0 votes
# Lua, 47 37 bytes

```
(N,P)return math.floor(math.log(N,P))

```

Try it online!

Thanks to *@user9549915* for saving 10 bytes

# Answer
> 0 votes
## PHP, 43 Bytes

Try it online!

**Code**

```
function f($p,$n){echo intval(log($p,$n));}

```

`intval()` truncates a float number, as for `log($p,$n)` the integer part of the result will always be the maximum positive integer that satisfies the inequation.

## 34 Bytes

If passing arguments to the script

Try it online

**Code**

```
<?=intval(log($argv[0],$argv[1]));

```

# Answer
> 0 votes
# Ruby, 31 bytes

```
->n,p,d=0{n<p**(d+=1)?d-1:redo}

```

Try it online!

Curse you, floating point errors

# Answer
> 0 votes
# Python 3, ~~40~~ 39 bytes

-1 @Jonathan

```
g=lambda n,p,a=1:a*p<=n and-~g(n,p,a*p)

```

Try it online!

# Answer
> 0 votes
# PHP, 28 bytes

```
<?=log($argv[1],$argv[2])|0;

```

Try it online

# Answer
> 0 votes
# Perl 6, 22 bytes

```
{(1,*×$^p...*>$^n)-2}

```

Try it online!

`1, * × $^p ... * > $^n` is a sequence that starts with 1, where each succeeding element is generated from the previous by multiplying by `$^p` (the second argument to the function), and continues up to the element `*` such that `*` is greater than `$^n` (the first argument to the function). Subtracting two from this sequence coerces it to a number, specifically its length. Two less than the length is the desired integer logarithm.

# Answer
> 0 votes
# Tcl, 39 bytes

```
proc L n\ p {expr int(log($n)/log($p))}

```

Try it online!

Gives `4` for `(243,3)` as it is the integer truncation of `4.99999999999999...`! The same happens when I tried other answers!

# Answer
> 0 votes
# C (gcc), ~~41~~ 31 bytes

Thanks to Kevin for his suggestion, which is reproduced below:

```
f(n,p,m){for(;n/=p;m++);n=m-2;}

```

Try it online!

Previous submission:

```
f(n,p){int m;for(m=0;n/=p;m++);return m;}

```

Try it online!

No library functions required.

# Answer
> 0 votes
# dc, 30 bytes

```
sp0sm[dlplm1+dsm^!>M]dsMxlm1-p

```

Try it online!

No logs in `dc` means no FP errors... Also means doing the thing repeatedly and testing to see when we go over, which... is not very golfy.

Straightforward, but here's the gist: `sp` stores our *p* value in `p`; `0sm` stores a zero in what will ultimately be our *m* value, `m`. Macro `M` duplicates what's left on the stack (*n*), loads `p`, loads `m`, spends a lot of bytes incrementing `m` (`lm1+dsm`), does the exponentiation `^` and tests if the result is less than or equal to *n* (left on stack). Keeps going so long as this is true, then loads `m`, subtracts 1, and prints it.

# Answer
> 0 votes
# Java 8, ~~36~~ 34 bytes (with floating point errors on one test case)

```
a->b->b+=Math.log(a)/Math.log(b)-b

```

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

Try it online.

**Explanation:**

Java only has `Math.log(double val)` as builtin, which is basically *log10*. For *logn(val)* you'll have to use `Math.log(val)/Math.log(n)`.
So this is what the `Math.log(a)/Math.log(b)` does. The `b+=...-b` is used to cast the doubles of the `Math.log` to an integer, which is shorter than `a->b->(int)(Math.log(a)/Math.log(b))` (thanks *@OlivierGrégoire*).

---

# Java 10, ~~245~~ ~~240~~ ~~239~~ 231 bytes

```
a->b->(int)(l(a)/l(b));double l(java.math.BigInteger v){int n=v.bitLength(),i=0,j=0;long t=1L<<52,M=t,m=0;for(;++i<54&&(j=n-i)>=0;M>>=1)m|=v.testBit(j)?M:0;return(n-1+Math.log((j>0&&v.testBit(j-1)?m+1:m)*1f/t)*1.4426950408889634);}

```

-5 bytes thanks to *@ceilingcat*.

Try it online.

**Explanation:**

To fix the floating point errors we'll have to use a BigInteger log. `a->b->(int)(l(a)/l(b))` is basically the same as before (note that `a` and `b` are now `java.math.BigInteger` inputs instead of `int`, so the same `b+=...-b` won't work here.

The separated log-method for better precision I got from this Stackoverflow answer.

```
double l(java.math.BigInteger v){
  // Get the minimum number of bits necessary to hold this value
  int n=v.bitLength(),
  // Index integers
      i=0,j=0;
  // Calculate the double-precision fraction of this numbers; as if the
  // binary point was left of the most significant '1' bit.
  // (Get the most significant 53 bits and divide by 2^53)
  // mantissa is 53 bits (including hidden bit)
  long t=1L<<52,M=t,m=0;
  for(;++i<54&&(j=n-i)>=0;M>>=1)m|=v.testBit(j)?M:0;
  // Round up if next bit is 1.
  // Add the logarithm to the number of bits, and subtract 1 because the
  // number of bits is always higher than necessary for a number
  // (i.e. log2(v)<n for every `v`)
  return(n-1+Math.log((j>0&&v.testBit(j-1)?m+1:m)*1f/t)*1.4426950408889634);}
  // Magic number converts from base e to base 2 before adding. For other
  // bases, correct the result, NOT this number!

```

# Answer
> 0 votes
# Haskell, 30 bytes

```
f n p=head[x|x<-[0..],p^x>n]-1

```

Should be no round-off errors

# Answer
> 0 votes
# q, 42 bytes

```
{r::x;{$[r>=y xexp x;x;.z.s[x-1;y]]}[x;y]}

```

# Answer
> 0 votes
# Gol\>\<\>, 7 bytes

```
IISLS(h

```

Can take the inputs seperated by a comma. (ex. \[4,5\], \[6,8\])

I'm pretty sure that this is the absolute smallest it can get..

# Answer
> 0 votes
# Runic Enchantments, 13 bytes

```
i'LAi'LA,'fA@

```

Try it online!

Nothing fancy here. Reads an input and calls `Log` on it, repeats for the second input, divides, and floors. Runic is very permissive with typing, using implicit conversions where it makes sense to do so, with only a couple of explicit conversion operators (to-number, to-char, and dictionary-lookup).

Equivalent to `(int)Math.Floor((double)Math.Log(a) / Math.Log(b))`

# Answer
> 0 votes
# Vyxal, 3 bytes

```
$•⌊

```

Try it Online!

```
$•⌊
$   # swap input
 •  # log
  ⌊ # floor

```

# Answer
> 0 votes
# nroff, 95 bytes

It's stupid that I had to increment one more than expected, then decrement the value. I tried replacing initial value `.nr M -1` and deleting decrementing part but the result went something very crazy (e.g. `.F 4 5` returned -3 and `.F 1000 10` returned 1526194161). How does nroff really represent numerical value!?

```
.de F
.nr t 1
.nr M 0
.while \\nt<=\\$1 \\{.nr t \\nt*\\$2
.nr M \\nM+1\\}
.nr M \\nM-1
\\nM
..

```

Attempt This Online!

# Answer
> 0 votes
# Pyt, 7 bytes

```
Đ←⇹ř^≥Ʃ

```

Try it online!

Couldn't use built-in log function because of floating-point inaccuracies. Takes N, then P.

```
Đ              implicit input; Đuplicate
 ←             get input
  ⇹            swap top two on stack
   ř           řangify
    ^          raise to power element-wise
     ≥         is N greater than or equal to each element?
      Ʃ        Ʃum; implicit print

```

# Answer
> 0 votes
# Thunno 2 `L`, 2 bytes

```
Bḣ

```

Attempt This Online!

Convert the second input to `B`ase-first input, then remove the ead (first item). The `L` flag takes the length.

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


# Question
Title: Find the occurrences of a character in an input string
## Challenge

Write a program that, given a string `x` which is 10 characters long and a character `y`, outputs the number of times character `y` occurs in string `x`.

The shortest program in bytes to do so wins.

## Example

```
Input: tttggloyoi, t
Output: 3

```

---

```
Input: onomatopoe, o
Output: 4

```

# Answer
# Pyth, 3 bytes

```
/ww

```

Example run:

```
$ pyth -c '/ww'
sdhkfhjkkj
k
3

```

Of course, the user could input more or less than 10 letters on the first input, but we don't need to worry about what happens when the user violates the spec.
> 18 votes

# Answer
# Pyth - 3 bytes

A different, less obvious, Pyth answer of the same size. It folds counting over the input.

```
/FQ

```

Test Suite.
> 11 votes

# Answer
# JavaScript, 32

```
(p=prompt)().split(p()).length-1

```
> 7 votes

# Answer
# Bash, 24 characters

```
x=${1//[^$2]}
echo ${#x}

```

Sample run:

```
bash-4.3$ bash letter-count.sh tttggloyoi t
3

bash-4.3$ bash letter-count.sh onomatopoe o
4

```
> 7 votes

# Answer
# Retina, 12 bytes

```
(.)(?=.*\1$)

```

Simply a regex which matches a character which is equal to the last character in the input (except itself). When given a single regex, Retina simply returns the number of matches.
> 6 votes

# Answer
# Python 3, 29 bytes

```
print(input().count(input()))

```

Meh, this was easy. Assumes that input is a ten letter string.
> 4 votes

# Answer
# Labyrinth, ~~32~~ ~~29~~ ~~27~~ 24 bytes

```
),}{)-
@ ,  +);__
!-`{:}

```

This reads the single character first, followed by the string in which to count, and assumes that there are no null-bytes in the string.

## Explanation

The code starts with `),}`, which sets the bottom of the stack to `1`, reads the first character and moves it to the auxiliary stack for future use. The `1` will be our counter (the offset of 1 will be cancelled later and is necessary for the IP to take the required turns).

The IP will now move down to read the first character of the search string with `,`. The value is negated with ```, again to get the correct turning behaviour. While we're reading characters from STDIN, the IP will now follow this loop:

```
  }{)-
  ,  +);__
  `{:}

```

`{:}` makes a copy of the stored character code and `+` adds it to the current value. If the result is `0` (i.e. the current character is the one we're looking for), the IP moves straight ahead: `-` simply gets rid of the `0`, `)` increments the counter, `{}` is a no-op.

However, if the result after `+` is non-zero, we don't want to count the current character. So the IP takes a right-turn instead. That's a dead-end, so that code there is executed twice, once forwards and once backwards. That is, the actual code in this case becomes `);___;)+-){}`. `);` just gets rid of that non-zero difference, `___` pushes 3 zeroes, but `;` discards one of them. `)` increments one of the two remaining two zeroes, `+` adds them into a single `1`, `-` subtracts it from the counter and `)` increments the counter. In other words, we've created a very elaborate no-op.

When we hit EOF, `,` pushes `-1`, which ``` turns into `1` and the IP takes a right-turn. `-` subtracts the `1` from the counter (cancelling the initial offset). `!` prints the counter and `@` terminates the program.
> 4 votes

# Answer
# C++ Template-Metaprogramming, ~~160~~ ~~154~~ 116 bytes

Just for the giggles.

*Thanks to ex-bart for golfing it down!*

```
template<int w,int x,int y,int...s>class A:A<w+(x==y),x,s...>{};A<0,'t','t','t','t','g','g','l','o','y','o','i',0>a;

```

Usage: The first char in the template instanciation is the character to search.

Complile with *clang -std=c++11 -c* -\> the result is at the beginning of the error message.

```
Occurences.cpp:1:66: error: too few template arguments for class template 'A'
template<int w,char x,char y,char...s>class A{static const int a=A<w+((x==y)?1:0),x,s...>::a;};
                                                             ^
Occurences.cpp:1:66: note: in instantiation of template class 'A<3, 't', '\x00'>' requested here
template<int w,char x,char y,char...s>class A{static const int a=A<w+((x==y)?1:0),x,s...>::a;};

```

Complile with *gcc -std=c++11 -c* -\> the result is at the bottom of the error message.

```
Occurences.cpp: In instantiation of ‘const int A<3, 't', '\000'>::a’:
Occurences.cpp:1:64:   recursively required from ‘const int A<1, 't', 't', 't', 'g', 'g', 'l', 'o', 'y', 'o', 'i', '\000'>::a’
Occurences.cpp:1:64:   required from ‘const int A<0, 't', 't', 't', 't', 'g', 'g', 'l', 'o', 'y', 'o', 'i', '\000'>::a’
Occurences.cpp:2:62:   required from here
Occurences.cpp:1:64: error: wrong number of template arguments (2, should be at least 3)

```

*Search for the A\<**3**, 't', '\000'\> and A\<**3**, 't', '\x00'\>*

**154 byte version**

```
template<int w,char x,char y,char...s>class A{static const int a=A<w+(x==y),x,s...>::a;};
int a=A<0,'t','t','t','t','g','g','l','o','y','o','i','\0'>::a;

```

**160 byte version:**

```
template<int w,char x,char y,char...s>class A{static const int a=A<w+((x==y)?1:0),x,s...>::a;};
int a=A<0,'t','t','t','t','g','g','l','o','y','o','i','\0'>::a;

```
> 4 votes

# Answer
## Snowman 1.0.2, 16 characters

```
~vgvgaSaLNdEtSsP

```

Surprisingly short. Explanation:

```
~      make all vars active (even though we only need two, we don't really care)
vgvg   get two lines of input
aS     split first line on second line
aL     length of the new array
NdE    decrement (because ex. "axbxc""x"aS -> ["a" "b" "c"] which is length 3)
tSsP   to-string and print

```
> 4 votes

# Answer
# PHP, ~~36~~ 35 bytes

```
<?=substr_count($argv[1],$argv[2]);

```

**Usage:**
Call the script with two arguments.
`php script.php qwertzqwertz q`

# PHP, 23 bytes

If you register global Variables (only possible in PHP 5.3 and below) you can save 12 bytes (thanks to Martijn)

```
<?=substr_count($a,$b);

```

**Usage:**
Call the script and declare global variables `php script.php?a=qwertzqwertz&b=q`
> 3 votes

# Answer
# Perl, ~~21~~ 16 characters

(13 characters code + 3 character command line option.)

```
$_=0+s/$^I//g

```

Sample run:

```
bash-4.3$ perl -it -pe '$_=0+s/$^I//g' <<< tttggloyoi
3

bash-4.3$ perl -io -pe '$_=0+s/$^I//g' <<< onomatopoe
4

bash-4.3$ perl -i5 -pe '$_=0+s/$^I//g' <<< 1234
0

```
> 3 votes

# Answer
# Bash + grep, 26 bytes

```
grep -o "$1"<<<"$2"|wc -l

```
> 3 votes

# Answer
# Javascript (ES6), 26 bytes

```
(a,b)=>a.split(b).length-1

```

This quick'n'easy solution defines an anonymous function. To use it, add a variable declaration to the beginning. Try it out:

```
z=(a,b)=>(a.split(b)||[0]).length-1;

input1=document.getElementById("input1");
input2=document.getElementById("input2");
p=document.getElementById("a");
q=function(){
  setTimeout(function(){
    p.innerHTML=z(input1.value,input2.value)||0;
  },10);
};
input1.addEventListener("keydown",q);
input2.addEventListener("keydown",q);
```

```
<form>Text to search: <input type="text" id="input1" value="hello world!"/><br>Char to find: <input type="text" id="input2" value="l"/></form>

<h3>Output:</h3>
<p id="a">3</p>
```

**EDIT:** Oh, I see there's a very similar solution already. I hope that's OK.
> 3 votes

# Answer
# Haskell, 21 bytes

```
a!b=sum[1|x<-a,x==b]

```
> 3 votes

# Answer
# Julia, ~~26~~ 25 bytes

```
f(s,c)=endof(findin(s,c))

```

The `findin` function returns the indices in the first argument at which the second argument is found as a vector. The length of the vector is the number of occurrences.

Saved one byte thanks to Glen O.
> 3 votes

# Answer
# APL, ~~7~~ 3 bytes

```
+/⍷

```

This creates a function train. It works by creating a vector of zeros and ones corresponding to the indices at which the character appears in the string (). The vector is then summed (`+/`).

Saved 4 bytes thanks to kirbyfan64sos and NBZ!
> 3 votes

# Answer
# T-SQL, ~~99~~ 40 Bytes

```
SELECT 11-LEN(REPLACE(s,c,'')+'x')FROM t

```

Simply does a difference between the input string and the string with the character removed. Takes input from table t

**Edit** changed to remove an issue with counting spaces and to take into account current acceptable inputs for SQL. Thanks @BradC for all the changes and savings
> 3 votes

# Answer
# C++, 78 bytes

```
int main(int,char**v){int c=0,i=0;while(i<10)v[1][i++]==*v[2]&&++c;return c;}

```

Call like this:

```
$ g++ -std=c++14 -O2 -Wall -pedantic -pthread main.cpp && ./a.out tttggloyoi t; echo $?
3

```
> 3 votes

# Answer
# Element, 23 bytes

```
__);11'[)\
~="0 1@][+]`

```

The newline is part of the program. I am actually using it as a *variable name*.

This program basically works by storing the target character in a variable, keeping the current string on the top of the stack, and then looping the "chop, compare, and move result underneath" process, adding up the results in the end.

The newline as a variable name comes from using the newline at the end of input by chopping it off and storing into it. The newline in the code is where I read from it.

Input is like this:

```
qqqqwwweee
q

```

Output is like this

```
4

```
> 3 votes

# Answer
# Dyalog APL, 3 bytes

```
      +/=

```

I.e. "The sum of the equal bytes". E.g.:

```
      f ← +/=
      'onomatopoe' f 'o'
4

```

or just

```
      'onomatopoe'(+/=)'o'
4

```

K doesn't beat APL this time.

Try it online.
> 3 votes

# Answer
## Octave / Matlab, 33 bytes

```
sum(input('','s')==input('','s'))

```
> 2 votes

# Answer
# Ruby, ~~22~~ 20 bytes

```
p gets.count(gets)-1

```

Demo: http://ideone.com/MEeTd2

The `-1` is due to the fact that `gets` retrieves the input, plus a newline character. Ruby's `String#count` counts the number of times *any* character from the argument occurs in the string.

For example, for the input \[`test\n`, `t\n`\], the `t` occurs twice and the `\n` occurs once, and needs to be subtracted.
> 2 votes

# Answer
# PowerShell, 32 Bytes

A four-for-one! And they're all the same length! :)

```
($args[0]-split$args[1]).Count-1

```

or

```
param($a,$b)($a-split$b).Count-1

```

Alternatively,

```
$args[0].Split($args[1]).Count-1

```

or

```
param($a,$b)$a.Split($b).Count-1

```

The first two styles use the inline operator `-split`, while the second two implicitly casts the first argument as a String and uses the `.Split()` string-based operator. In all instances an array is returned, where we must decrement Count by one, since we're getting back one more array item than occurrences of the second argument.

This one was kinda fun...
> 2 votes

# Answer
# J, 5 bytes

```
+/@:=

```

I feel like J would have a built-in for this, but I haven't been able to find one - maybe one of the active J users can enlighten me. So instead this first applies `=` to the inputs, turning each character into `1` if it's equal to the requested one or `0` otherwise. Then `+/` computes the sum of that list.
> 2 votes

# Answer
# Batch File, 121 Bytes

Because I'm a masochist ...

```
SET c=0
SET e=_
SET t=%1%%e%
:l
SET a=%t:~0,1%
IF "%a%"=="%2" SET /A c+=1
SET t=%t:~1%
IF NOT "%t%"=="%e%" GOTO l
ECHO %c%

```

### Warning: Assumes that `_` doesn't occur in the input string. If it does, then the variable `e` needs to be adjusted appropriately.

This sets up our counter variable, `c`, and our end-of-string demarcation as `_`, before appending that to our input string `%1` and setting the concatenated string to `t`. Then, we're entering loop `:l`, we set a temporary character variable `a` to be the first character of `t`, check if it matches our second input string `%2` and increment `c` if true, then trim the first character off of `t`. Our end-of-loop condition checks `t` against our end-of-string demarcation, and loops back if not. We then `echo` out the value of our counter.

It would probably be possible to use a `FOR` loop instead, but that would necessitate enabling DelayedExpansion, which I think will actually be longer byte-wise than this. Verification of that is left as an exercise to the reader.
> 2 votes

# Answer
# CJam, 5 bytes

```
ll/,(

```

## Explanation

```
l      e# read x
 l     e# read y
  /    e# split x by y
   ,   e# count
    (  e# subtract one

```
> 2 votes

# Answer
## \>\<\> (Fish), 30 bytes

```
0&v
=?\ilb
=?\:@=&+&l1
n&/;

```

Takes the string, then character to count. Input isn't separated (at least in the online interpreter). Try it on the online interpreter: http://fishlanguage.com I counted the bytes by hand, so let me know if I'm wrong.

**Explanation**

First off, \>\<\> is 2 dimensional and and loops through a line or column until it hits a `;` or error. This means that if it's proceeding left to right (like it does at the beginning of a program), it will wrap around the line if it reaches the end and is not moved or told to stop the program. Some characters per line will be repeated because they have different functions depending on the direction of the pointer, and the fourth line will have characters in reverse order because the pointer moves right to left.

A summary of the program is provided below. Look at the instructions listed for \>\<\> on esolangs to see what each individual character does.

Line 1: `0&v`

```
0&v -put 0 into the register and change direction to down-up

```

Line 2: `=?\ilb`

(starting where line 1 moves the pointer to, i.e. the third character)

```
\ -reflect the pointer and make it move left-right
i -read input
lb=?\ -reflect downwards if there are 11 values in the stack

```

line 3: `=?\:@=&+&l1`

(starting at the third character)

```
:@ -duplicate y and shift the stack e.g. ['x','y','y'] -> ['y','x','y']
=&+& -increment the register if the character popped from x = y
l1=?\ -reflect downwards if there is 1 value in the stack

```

Line 4: `n&/;`

(starting at the third character)

```
/ -reflect right-left
&n; -print value of the register

```
> 2 votes

# Answer
# Julia, 21 bytes

```
f(s,c)=sum(i->c==i,s)

```

Note that it requires that `c` be a char, not a single-character string. So you use it as `f("test me",'e')` (which returns 2) and not `f("test me","e")` (which returns 0, because `'e'!="e"`).
> 2 votes

# Answer
# Ruby, 18 bytes

```
->s,c{p s.count c}

```

# Usage:

```
->s,c{p s.count c}.call 'tttggloyoi', 't'

->s,c{p s.count c}.call 'onomatopoe', 'o'

```
> 2 votes

# Answer
# Japt, 2 bytes

```
èV

```

Try it online!
> 2 votes

# Answer
# rs, 33 bytes

```
+(.)(.* (?!\1).)/\2
(.*)../(^^\1)

```

Live demo and test cases.

This is pretty simple. The first line removes all characters except the ones we're counting. The next line counts the number of characters that are left, *excluding* the one we're searching for.

Takes input separated by spaces, e.g.:

```
onomatopoe o

```
> 1 votes

# Answer
# C#, 36 51 48

```
Debug.Write(args[0].split(args[1][0]).Length-1);

```
> 1 votes

# Answer
# K, 3 bytes

```
+/=

```

~~K actually beat APL!!! :D~~ Well, now it's a tie... :/

You can call it like this:

```
+/=["hello";"l"]

```

Or assign it to a variable first:

```
f:+/=
f["hello";"l"]

```

Also note that **this does not work in oK**. It *does* work in the official K2 and K5 interpreters, as well as Kona.
> 1 votes

# Answer
# O, ~~23~~ 10 bytes

```
ie\i-e@-_p

```

## Original:

```
0K;i""/iJ;l{J=K+:K;}dKp

```

~~I don't think I can get this any shorter... :/~~

Ah, I'm stupid. I forgot the traditional method of counting occurrences: subtract the string lengths.
> 1 votes

# Answer
## STATA, 52 bytes

```
di _r(a)_r(b)
di 10-length(subinstr("$a","$b","",.))

```

Gets the two strings as inputs. Replaces all occurrences of the second string (the character) with empty string. Subtract that from 10, since the length of the first string is 10.

Unfortunately functions in STATA can't be shortened the same way that variable names and commands can. Also, this doesn't work in the online interpreter, since it doesn't include these functions.
> 1 votes

# Answer
# scala, 31 bytes

```
(x:String,y:Char)=>x.count(y==)

```
> 1 votes

# Answer
# Pip, 3 bytes

Joining the 3-byte cavalcade...

```
bNa

```

Read as "b in a". `a` and `b` are command-line arguments. The `N` operator, unlike its Python counterpart, doesn't just return a truth value; it returns the count.
> 1 votes

# Answer
# R, 27 bytes

```
sum(strsplit(x,"")[[1]]==y)

```

**Usage**

```
sum(strsplit("tttggloyoi","")[[1]]=="t")
[1] 3
sum(strsplit("onomatopoe","")[[1]]=="o")
[1] 4

```

# Or, Another one with 42 bytes

```
f<-function(x,y)length(gregexpr(y,x)[[1]])

```

**Usage**

```
f("tttggloyoi", "t")
[1] 3
f("onomatopoe", "o")
[1] 4

```
> 1 votes

# Answer
# Javascript

## Program, 48 chars

```
alert(prompt().match(/(.)(?=.*\1$)|$/g).length-1)

```

## Function with 1 argument (ES6), 39 chars

```
f=s=>s.match(/(.)(?=.*\1$)|$/g).length-1

```

## Function with 2 arguments (ES6), 28 chars

```
f=(s,c)=>s.split(c).length-1

```
> 1 votes

# Answer
# Jelly, 1 byte

```
ċ

```

**TryItOnline**

The obvious implementation would be 3 bytes: `s1ċ`, which splits a string or list (left argument) into slices of length 1 with `s1` and counts occurrences of the character (right argument) with `ċ`.

However, since the character will only ever be of length 1, we could, instead, inspect all non-empty contiguous slices of a string with ; the character will only ever match those slices that are of length 1.

...and since a string is an array of characters, the function can just be `ċ`.
> 1 votes

# Answer
# Java 7, ~~69~~ ~~68~~ ~~54~~ 52 bytes

```
int c(String...a){return a[0].split(a[1]).length-1;}

```

Surprisingly enough there wasn't a Java answer yet..
14 bytes saved thanks to *@Geobits*!

If a completely flexible input is allowed, we can save an additional byte by having a `String`-array parameter (**51 bytes**):

```
int c(String[]a){return a[0].split(a[1]).length-1;}

```

**Ungolfed & test code:**

Try it here.

```
class M{
  static int c(String... a){
    return a[0].split(a[1]).length-1;
  }

  public static void main(String[] a){
    System.out.println(c("tttggloyoi", "t"));
    System.out.println(c("onomatopoe", "o"));
  }
}

```

**Output:**

```
3
4

```
> 1 votes

# Answer
# APL (Dyalog Extended), 1 byteSBCS

Try it online!

is **C**ount **I**n
> 1 votes

# Answer
# 05AB1E, 1 byte

```
¢

```

First input is the character, second the string.

Try it online or verify both test cases at once.

**Explanation:**

```
¢  # Count the amount of occurrences of the first (implicit) input-character
   # in the second (implicit) input-string
   # (after which the result is output implicitly)

```
> 1 votes

# Answer
# Zsh, 15 bytes

```
<<<${#1//[!$2]}

```

Try it online!

Similar to the bash answer, but more compact thanks to Zsh allowing both `${ //}` and `${# }` in the same expansion.
> 1 votes

# Answer
# Retina, 11 bytes

```
w`^(.)¶.*\1

```

Try it online!

Takes input as two lines - the first line is the character, the second is the string.

Could be 10 bytes if taking input as the character preprended to the string, but that felt a bit too cheaty.

### Explanation

```
w`^(.)¶.*\1     # (implicit count stage as there is just one line)
w`              # Include overlapping matches for the pattern
   (.)          # Match a single character...
  ^             # ...at the start of the input...
      ¶         # ... and followed by a newline...
       .*       # ...then zero or more arbitrary characters...
         \1     # ...and then the first character again
                # (implicitly output the number of matches)

```
> 1 votes

# Answer
# Wren, 29 bytes

Very hard to golf.

```
Fn.new{|a,b|a.count{|i|i==b}}

```

Try it online!

## Explanation

```
Fn.new{|a,b|                  // Anonymous function with parameters a & b
            a.count           // Count every item
                   {|i|       // that...
                       i==b}} // is equal to b

```

# Wren, 36 bytes

```
Fn.new{|a,b|a.trim(a.trim(b)).count}

```

Try it online!

## Explanation

```
Fn.new{|a,b|                       } // Uninteresting anonymous function
                   a.trim(b)         // Remove all occurences of b in a
            a.trim(         )        // Trim this result with a, keeping the removed occurences
                             .count  // Find the length of this result

```
> 1 votes

# Answer
# naz, 92 bytes

```
2x1v2a2x2v8a2x3v1r2x4v1x1f3r3x2v3e3x4v2e1f0x1x2f1v1a2x1v1f0x1x3f1v3x3v4e1o0x1x4f9s1o1s1o0x1f

```

Works for any valid input string terminated with the control character STX (U+0002), with the character to search for appearing first (e.g. `t, tttggloyoi`).

**Explanation** (with `0x` commands removed)

```
2x1v                 # Set variable 1 equal to 0
2a2x2v               # Set variable 2 equal to 2
8a2x3v               # Set variable 3 equal to 10
1r2x4v               # Store the first byte of the input string in variable 4
1x1f                 # Function 1
    3r               # Read the 3rd byte of input, then remove it from the input
                     # This has the effect of skipping over the comma and space
      3x2v3e         # Jump to function 3 if it equals variable 2
            3x4v2e   # Jump to function 2 if it equals variable 4
                  1f # Otherwise, jump back to the start of the function
1x2f                 # Function 2
    1v1a2x1v1f       # Load variable 1 into the register, add 1,
                     # and store the new value in variable 1
                     # Then, jump to function 1
1x3f                 # Function 3
    1v3x3v4e1o       # Load variable 1 into the register
                     # Jump to function 4 if the register equals variable 3
                     # Otherwise, output once
1x4f                 # Function 4
    9s1o1s1o         # Subtract 9 and output, then subtract 1 and output
                     # (outputs "10")
1f                   # Call function 1

```
> 1 votes

# Answer
# Burlesque, 4 bytes

```
peCN

```

Try it online!

Takes input as `"string" 'i` to search `string` for `i`.

If special inputs are not allowed:

# Burlesque, 6 bytes

```
pe-]CN

```

Try it online!

Takes input as two quoted strings.

```
pe  # Parse and evaluate
CN  # Count

```
> 1 votes

# Answer
# Vyxal, 2 bytes

```
$O

```

Try it Online!
> 1 votes

# Answer
I have been outgolfed.

> # PowerShell, 75 Bytes (Single Run)
>
> ```
> nv a (read-host).split(", ");foreach($b in $a[0]){if($b=$a[2]){$c++}};$c|oh
>
> ```
>
> The above will only work once, will error if variables still have values from last run(run twice in same environment).
>
> # PowerShell, 82 Bytes (Infinite Use)
>
> ```
> $c=0;nv a (read-host).split(", ")-f;foreach($b in $a[0]){if($b=$a[2]){$c++}};$c|oh
>
> ```
>
> The above can be used any number of times in the same environment.
> 0 votes

# Answer
# C, 55 bytes

```
t;c(char* i,char z){t=0;for(;*i;)t+=*i++==z;return t;}

```
> 0 votes

# Answer
# Jelly, 2 bytes, non-competing

There is a one-byte Jelly solution, but that takes in the argument in a rather particular way. With 1 byte extra, we can just input `test` instead of `["t", ...]`

```
fL

```

Try it online!

```
f   filter all elements from the first implicit input that are not in the second implicit input
    "onomatopoe" f "o" filters out all non-"o" chars --> oooo
 L  Get the length of the remainder.

```
> 0 votes

# Answer
## W, 4 bytes

Basically the same algorithm as my second Wren answer.

```
Sttk

```
> 0 votes

# Answer
# Ahead, 16 bytes

The first character on stdin is the counted character, and the remainder of stdin is the string.

```
i&>jlir
 @Or+=t<

```

Try it online!
> 0 votes

# Answer
# Fortran (GFortran), 60 bytes

```
character a(10),b
read('(10a,a)'),a,b
print*,count(a==b)
end

```

Try it online!

Takes input as an 11 length string, the last char being b.
> 0 votes

# Answer
# Factor, 16 bytes

```
[ histogram at ]

```

Try it online!

Oddly enough, I don't think Factor has a built-in for this. This is two bytes shorter than both

```
[ '[ _ = ] count ]

```

and

```
[ indices length ]

```
> 0 votes

# Answer
# Thunno 2, 1 byte

```
c

```

Attempt This Online!

Built-in for "count"
> 0 votes

# Answer
# J-uby, 6 bytes

```
:count

```

Attempt This Online!
> 0 votes

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