# Question
Title: Print the amount of ones in a binary number without using bitwise operators
## Description

Given a number, print the amount of `1`s it has in binary representation.

## Input

A number `>= 0` in base 10 that won't exceed the highest number your language is able to handle.

## Output

The amount of `1`s in binary representation.

## Winning condition

The shortest code wins.

## Disallowed

* Bitwise operators. Other operators, like addition and multiplication, are allowed.
* Built-in base conversion functions.

## Examples

```
Input:     Ouput:

56432      8

Input:     Output:

45781254   11

Input:     Output:

0          0

```

# Answer
> 17 votes
## APL, ~~9~~ 12 characters

```
+/2|⌊⎕÷2*⍳32

```

This assumes that the interpreter uses 32-bit integers, and that `⎕IO` is set to 0 (meaning that monadic  begins with 0, rather than 1). I used the 32-bit version of Dyalog APL.

Explanation, from right to left:

* `⍳32` generates a vector of the first `32` integers (as explained before, because `⎕IO` is 0, this vector begins with 0).
* `*` is the power function. In this case, it generates `2` to the power of each element of the vector supplied as its right argument.
* `÷` is the divided-by function. It gives us  (evaluated user input) divided by each element of the vector to its right (each power of two).
* floors each element of the argument to its right.
* `2|` gives us the remainder of each element of to its right divided by `2`.
* `/` reduces (folds) its right argument using the function to its left, `+`.

Not quite 9 characters anymore. :(

*Old, rule-breaking version:*

> ```
> +/⎕⊤⍨32/2
>
> ```
>
> Explanation, from right to left:
>
> * `32/2`: Replicate `2`, `32` times.
> * commutes the dyadic function to its left, which in this case is  (i.e., `X⊤⍨Y` is equivalent to `Y⊤X`).
> * is the encode function. It encodes the integer to its right in the base given to its left. Note that, because of the commute operator, the right and left arguments are switched. The base is repeated for the number of digits required, hence `32/2`.
> * is a niladic function that accepts user input and evaluates it.
> * `+/` reduces (folds) its right argument using `+`. (We add up the 0's and 1's.)

# Answer
> 11 votes
# Brainbool, 2

```
,.

```

The most reasonable interpretation, in my opinion (and what most of the answers use) of "highest number your language is able to handle" is "largest number your language *natively* supports". Brainbool is a brainfuck derivative that uses bits rather than bytes, and takes input and output in binary (`0` and `1` characters) rather than character codes. The largest natively supported number is therefore `1`, and the smallest is `0`, which have Hamming weights `1` and `0` respectively.

Brainbool was created in 2010, according to Esolang.

# Answer
> 8 votes
# Brainfuck, 53 characters

This was missing an obligatory Brainfuck solution, so I made this one:

```
[[->+<[->->>>+<<]>[->>>>+<<]<<<]>>>>[-<<<<+>>>>]<<<<]

```

Takes number from cell 1 and puts the result into cell 6.

Unenrolled and commented version:

```
[  while n != 0
  [  div 2 loop
    -
    >+<  marker for if/else
    [->->>>+<<]  if n != 0 inc n/2
    >
    [->>>>+<<]  else inc m
    <<<
  ]
  >>>>  move n/2 back to n
  [-<<<<+>>>>]
  <<<<
]

```

# Answer
> 7 votes
## J, 13 characters

(+ the number of digits in the number)

```
+/2|<.n%2^i.32

```

Usage: replace the `n` in the program with the number to be tested.

Examples:

```
+/2|<.56432%2^i.32
8
+/2|<.45781254%2^i.32
11
+/2|<.0%2^i.32
0

```

There's probably a way of rearranging this so the number can be placed at the beginning or end, but this is my first J entry and my head's hurting slightly now.

**Explanation**(mainly so that I understand it in the future)

`i.32` \- creates an array of the numbers 1 to 32

`2^` \- turns the list into the powers of two 1 to 4294967296

`n%` \- divides the input number by each element in the list

`<.` \- rounds all the divison results down to the next integer

`2|` \- same as `%2` in most languages - returns 0 if even and 1 if odd

`+/` \- totals the items in the list (which are now just 1s or 0s)

# Answer
> 6 votes
# Python 2.6, 41 characters

```
t,n=0,input()
while n:t+=n%2;n/=2
print t

```

**note:** My other answer uses lambda and recursion and this one uses a while loop. I think they are different enough to warrant two answers.

# Answer
> 6 votes
## Ruby, 38 characters

```
f=->u{u<1?0:u%2+f[u/2]}
p f[gets.to_i]

```

Another solution using ruby and the same recursive approach as Steven.

# Answer
> 5 votes
## GolfScript, 17 16 characters

```
~{.2%\2/.}do]0-,

```

*Edit:* new version saves 1 character by using list operation instead of fold (original version was `~{.2%\2/.}do]{+}*`, direct count version: `~0\{.2%@+\2/.}do;`).

# Answer
> 5 votes
## C, 45

```
f(n,c){for(c=0;n;n/=2)c+=n%2;printf("%d",c);}

```

Nothing really special here for golfing in C: implicit return type, implicit integer type for parameters.

# Answer
> 4 votes
## Perl, 45 43 36 Characters

```
$n=<>;while($n){$_+=$n%2;$n/=2}print

```

Thanks to Howard for 45-\>43, and to User606723 for 43-\>36.

# Answer
> 4 votes
## Python 2.6, 45 characters

```
b=lambda n:n and n%2+b(n/2)
print b(input())

```

# Answer
> 3 votes
## Perl, 30 chars

```
$==<>;1while$_+=$=%2,$=/=2;say

```

Based on PhiNotPi's solution, with some extra golfing. Run with `perl -M5.010` to enable the Perl 5.10 `say` feature.

# Answer
> 3 votes
# C, ~~61 60 57~~ 53 characters

```
void f(x){int i=0;for(;x;x/=2)i+=x%2;printf("%u",i);}

```

The function body only is 38 characters. **Edit**: removed bitwise operator **Edit**: put `printf` out of the loop as suggested in the comments **Edit**: switch to K&R declaration; also, this is no longer C99-specific

# Answer
> 3 votes
## Common Lisp, 12 chars

(assuming a 1 char variable name - i.e.: 11 + number length)

It's not a base conversion function, so it should work:

```
(logcount x)

```

Examples:

```
[1]> (logcount 0)
0
[2]> (logcount 1)
1
[3]> (logcount 1024)
1
[4]> (logcount 1023)
10
[5]> (logcount 1234567890123456789012345678901234567890)
68

```

(Using GNU CLISP.)

# Answer
> 3 votes
## C, 66 characters

```
main(int n,char **a){printf("%u",__builtin_popcount(atoi(a[1])))};

```

Note: requires gcc or gcc-compatible compiler (e.g. ICC, clang).

For some CPUs `__builtin_popcount` compiles to a single instruction (e.g. `POPCNT` on x86).

# Answer
> 3 votes
# dc – 26 chars

This is rather long, mostly due to the lack of loop constructs in `dc`.

```
0?[d2%rsi+li2/d0<x]dsxx+p

```

Keeps adding up the modulo 2 of the number and dividing the number by to until it reaches zero. Can handle arbitrarily long integers.

Example:

```
$ dc -e '0?[d2%rsi+li2/d0<x]dsxx+p' <<< 127
7
$ dc countones.dc <<< 1273434547453452352342346734573465732856238472384263456458235374653784538469120235
138

```

# Answer
> 2 votes
## D (70 chars)

```
int f(string i){int k=to!int(i),r;while(k){if(k%2)r++;k/=2;}return r;}

```

# Answer
> 2 votes
## JavaScript, ~~78 72~~ 71 characters

I'll post my initial solution which I came up with before posting the question as well. There is already a much better JavaScript answer though :)

```
for(n=prompt(a=0),j=1;j<=n;j*=2)for(i=j;i<=n;i+=2*j)n<i+j&&a++;alert(a)

```

http://jsfiddle.net/Mk8zd/1/

The idea comes from certain "mind reading cards" which enable you to obtain the number someone else has in mind, by showing them cards and let them say on which cards their number is apparent.

It works because each number is a unique combination of `1`s / `0`s in binary. My solution checks on which "cards" the number is apparent so as to determine how many `1`s it has. It's just not very efficient, though...

I found this document which outlines the mind reading technique.

# Answer
> 2 votes
## Haskell (60 chars)

```
f n=sum[1|x<-[0..n],odd$n`div`2^x]
main=interact$show.f.read

```

# Answer
> 2 votes
## PHP, 57

```
$i=$s=0;for(;$i<log($n,2);){$s+=$n/pow(2,$i++)%2;}echo$s;

```

This assumes that `$n` holds the value to be tested.

## PHP, 55 (alternative solution)

```
function b($i){return$i|0?($i%2)+b($i/2):0;}echo b($n);

```

Again, this assumes that `$n` holds the value to be tested. This is an alternative because it uses the or-operator to `floor` the input.

Both solutions work and do not cause notices.

# Answer
> 2 votes
# Ocaml, 45 characters

Based on @Leah Xue's solution. Three spaces could be removed and it's sligthly shorter (~3 characters) to use function instead of if-then-else.

```
let rec o=function 0->0|x->(x mod 2)+(o(x/2))

```

# Answer
> 2 votes
# Mathematica 26

```
Count[n~IntegerDigits~2,1]

```

# Answer
> 2 votes
# Java 7, 36 bytes

```
int b(Long a){return a.bitCount(a);}

```

Because of course this, of all things, is something that Java has a builtin for...

# Answer
> 2 votes
# 386 opcode, 10 Bytes

```
2BC0                       SUB EAX,EAX
01C9                       ADD ECX,ECX
1400                       ADC AL,0
41                         INC ECX
E2F9                       LOOP $-5
C3                         RET

```

Thank Peter Cordes for 1B save and 1B rule save

# Answer
> 2 votes
# Vyxal `l`, 49 bits1, 6.125 bytes

```
ʀEṗ'∑?=;f

```

Try it Online!

Brute force solution, so the online interpreter times out. May potentially be made shorter by porting others, but I thought this solution was fun

```
ʀ         # range 0..input+1
 E        # raise 2^n for each value in that range
  ṗ       # powerset
   '   ;  # filtered by
    ∑     # the sum
     ?=   # is equal to the input?
        f # flatten
          # after which the l flag takes the length of the top of the stack and implicitly outputs it

```

# Answer
> 1 votes
## JavaScript, ~~49~~ ~~47~~ ~~45~~ 42 bytes

```
for(n=prompt(o=0);n=n/2|0;o+=n%2);alert(o)

```

Demo: http://jsfiddle.net/hcYdx/4/

**Edit 1:** remove `q` and use `~~` for rounding, save 2 chars.

**Edit 2:** use `|0` rounding operator instead of `~~` to save parentheses (2 chars).

**Edit 3:** simplify `n>0` to `n` and combine with `n=n/2|0` to make entire condition; now have wasted statement space :(

# Answer
> 1 votes
## Scala, 86 characters

```
object O extends App{def f(i:Int):Int=if(i>0)i%2+f(i/2)else 0
print(f(args(0).toInt))}

```

Usage: `scala O 56432`

# Answer
> 1 votes
# R, 53 characters

`o=function(n){h=n%/%2;n%%2+if(h)o(h)else 0};o(scan())`

Examples:

```
> o=function(n){h=n%/%2;n%%2+if(h)o(h)else 0};o(scan())
1: 56432
2:
Read 1 item
[1] 8
> o=function(n){h=n%/%2;n%%2+if(h)o(h)else 0};o(scan())
1: 45781254
2:
Read 1 item
[1] 11
> o=function(n){h=n%/%2;n%%2+if(h)o(h)else 0};o(scan())
1: 0
2:
Read 1 item
[1] 0

```

If inputting the number is not part of the character count, then it is 43 characters:

`o=function(n){h=n%/%2;n%%2+if(h)o(h)else 0}`

with test cases

```
> o(56432)
[1] 8
> o(45781254)
[1] 11
> o(0)
[1] 0

```

# Answer
> 1 votes
# OCaml, 52 characters

```
let rec o x=if x=0 then 0 else (x mod 2) + (o (x/2))

```

# Answer
> 1 votes
# Scheme

I polished the rules a bit to add to the challenge. The function doesn't care about the base of the number because it uses its own binary scale. I was inspired by the way analog to numeric conversion works. I just use plain recursion for this:

```
(define (find-ones n)
  (define (nbits n)
    (let nbits ([i 2])
      (if (< i n) (nbits (* i 2)) i)))
  (let f ([half (/ (nbits n) 2)] [i 0] [n n])
    (cond [(< half 2) i]
      [(< n i) (f (/ half 2) i (/ n 2))]
      [else (f (/ half 2) (+ i 1) (/ n 2))])))

```

# Answer
> 1 votes
Isn't reading a number into binary or printing the number from binary a "builtin base conversion function", thus invalidating every answer above that `print`s an integer? If you permit reading and printing an integer, like almost all the above answers do, then I'll make claims using a builtin `popcount` function :

### Haskell, 50

There was a `popCount` routine added to the `Data.Bits` module for GHC v7.2.1/v7.4.1 this summer (see tickets concerning the primop and binding).

```
import Data.Bits
main=interact$show.popCount.read

```

I cannot beat the above Python and Perl scores using their `GMPY` or `GMP::Mpz` modules for GMP sadly, although GMP does offer a popcount function too.

# Answer
> 1 votes
# JavaScript, ~~57~~ ~~55~~ ~~51~~ 50 bytes

```
a=prompt(b=0);while(a){b+=a%2;a=(a-a%2)/2}alert(b)

```

Modulo is not bitwise operator ☺

# Answer
> 1 votes
# sed, 100 bytes

```
:
s/[13579]/&;/g
y/123456789/011223344/
s/;0/5/g
s/;1/6/g
s/;2/7/g
s/;3/8/g
s/;4/9/g
/[1-9]/b
s/0//g

```

Output is in unary; if you want it in decimal, pipe through `wc -c` or append the following converter (GNU `sed -r`):

```
# unary to decimal
:d
s/;;;;;/v/g
s/vv/x/g
s/x([0-9]|$)/x0\1/
s/;;/b/g
s/bb/4/
s/b;/3/
s/v;/6/
s/vb/7/
s/v3/8/
s/v4/9/
y/;bvx/125;/
td

```

This implements successive division by 2, accumulating carry-out as output. It is able to handle fairly large inputs; for example I tested the all-ones 8192-bit input thus:

```
$ dc <<<'2 8192^1-p' | tr -d '\\\n' | ./4434.sed | wc -c
8192

```

and the mostly-zeros of similar length:

```
$ dc <<<'2 8192^p' | tr -d '\\\n' | ./4434.sed | wc -c
1

```

# Answer
> 1 votes
# TI-Basic (TI-84 Plus CE), 30 bytes

```
Prompt X
0→S
While X
S+remainder(2,X→S
int(X/2→X
End
S

```

TI-Basic is a tokenized language, all tokens but `remainder(` are one-byte, remainder is two

# Answer
> 1 votes
# PHP, 36 bytes

```
while($n){$o+=$n%2;$n/=2*1;}echo $o;

```

Assumes `$n` is the number to be tested, shows a PHP Notice for `$o`, and doesn't exactly work when `$n` is 0 (outputs nothing).

# PHP, 53 bytes

```
$n=$argv[1];$o=0;while($n){$o+=$n%2;$n/=2*1;}echo $o;

```

Accepts command-line input, doesn't show a PHP Notice, and outputs correctly for 0.

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

```
: f dup 0> if 2 /mod recurse + then ;

```

Try it online!

Usually recursion isn't worth it when golfing Forth because it requires the if, then, (possible else), and recurse words. In this case we can do without else and we save more in stack-manipulation than we lose from recursion

### Explanation

* If n is greater than 0, get quotient and remainder of dividing n by 2.
* Call recursively on quotient
* Add remainder to result

### Code Explanation

```
: f         \ start new word definition
  dup       \ duplicate top stack value
  0> if     \ if top stack value is greater than 0
    2 /mod  \ get quotient and remainder of dividing by 2 (quotient on top of stack)
    recurse \ execute current word
    +       \ add remainder to result of recursion
  then      \ end if statement
;           \ end word definition

```

# Answer
> 1 votes
# MathGolf, 12 bytes

```
æ_╫`¡▲ÞÄ½↑;î

```

Try it online!

This fails for input 0, due to a bug in MathGolf. I'll explain why. But I thought it was a fun solution to this problem that might not be obvious.

This method could be seen as disallowed, but I refer to wikipedia: "The bit shifts are **sometimes** considered bitwise operations, because they treat a value as a series of bits rather than as a numerical quantity" (emphasis mine). I have chosen to interpret this to mean that MathGolf's bitshifts are allowed, since they don't operate on a fixed number of bytes. Bit rotating in MathGolf wraps the current number of bits in the number, and rotates using the bit width of the number. Thus, if you do this enough times, any number with \\$n\\$ set bits will converge to \\$2^n-1\\$. If you then divide the result by 2 until you reach 0, the number of divisions will represent the number of ones in the original number.

The reason that this fails for 0 is that 0 is somehow turned into 1 when left-rotated. This is a bug in the implementation of the operator, rather than this program itself, and should be fixed in an upcoming update.

## Explanation

```
æ    ▲         do-while true using 4 operators
 _             duplicate TOS
  ╫            left-rotate bits in int, list/str
   `           duplicate the top two items
    ¡          push a, b, push a != b
               This do-while loop repeats until the left-rotated
      Þ        not implemented yet
       Ä       start block of length 1
        ½      pop a : push(a//2 if int else a/2)
         ↑     while true without popping
          ;    discard TOS
           î   index of current loop (1-based)

```

# Answer
> 1 votes
# `awk`, 65 bytes

```
__=$(_^=___=_<_){++_;do{___+=__%_}while(__=int(__/_))}$!NF=___ ""

```

Example:

```
echo "56432\n45781254\n0" |

mawk '__=$(_^=___=_<_){++_;do{___+=__%_}while(__=int(__/_))}$!NF=___ ""'

8
11
0

```

# Answer
> 1 votes
# Thunno 2 `L`, 8 bytes

```
LOʠæS=;Ḟ

```

Port of emirps's Vyxal answer.

#### Explanation

```
LOʠæS=;Ḟ  # Implicit input
LO        # Push 2 ** [0..input)
  ʠ       # Powerset of this list
   æ  ;   # Filtered by:
    S=    #  Sum equals the input
       Ḟ  # Flatten this list of lists
          # L flag gets the length
          # Implicit output

```

#### Screenshot

# Answer
> 0 votes
Python (48 without spaces, 65 with)

```
x = int(raw_input())
s = 0
while x:
    if x%2:
        s+=1
    x/=2
print s

```

# Answer
> 0 votes
### Op, ~~23~~ 19 (discontinued language of my invention)

```
0N[1~!?@2%{1+}2/])I

```

Here's a commented version:

```
0 # push a 0 onto the stack
N # read an integer from STDIN onto the stack
[ # begin an infinite loop
    1 # push a 1 onto the stack
    ~ # pop the 1 off the stack, and duplicate the top 1 items (i.e. the read number)
    ! # pop a number, push 1 if 0 or 0 otherwise (NOT)
    ? # pop a number, if the number is nonzero...
    @ # ... then break out of the infinite loop. Basically, break out when N reaches 0.
    2 # push a 2 onto the stack
    % # pop number "a" off the stack, then number "b", and push b modulo a.
    { # rotate the stack left
    1 # push a 1 onto the stack
    + # pop a and b, and push a + b (increment)
    } # rotate the stack right
    2 # push a 2 onto the stack
    / # pop number "a" off the stack, then number "b", then push b / a (int)
] # repeat back to start of loop
) # shift the stack right, taking off the 0 and leaving only the result
I # output the result as a number to STDOUT

```

# Answer
> 0 votes
## excel, 35

```
=LEN(A1)-LEN(SUBSTITUTE(A1,"1",""))

```

# Answer
> 0 votes
# GolfScript - 21

```
~{.2%{0):0;}*2/.}do;0

```

# Answer
> 0 votes
# Python 2, 25 bytes

```
lambda n:n and n%2+f(n/2)

```

Try it online!

# Answer
> 0 votes
# Pushy, 12 bytes

```
$&2%v2/;O_S#

```

**Try it online!**

While the input is bigger than 0, it has its least significant bit (using mod) pushed to the second stack, then it is halved (integer division). Once all bits have been placed on the second stack, it is summed and the result is printed.

# Answer
> 0 votes
# SNOBOL4 (CSNOBOL4), 66 bytes

```
	X =INPUT
I	O =O + REMDR(X,2)
	X =GT(X) X / 2	:S(I)
	OUTPUT =O
END

```

Try it online!

# Answer
> 0 votes
# JavaScript, 43 Bytes, assuming `1/2/2/2/...=0`

```
for(a=prompt(b=0);a;a/=2)b+=a%2>=1;alert(b)

```

# Answer
> 0 votes
# J, 32 Bytes

There's probably a more mathematical way to do this that doesn't require finding the binary representation, but I thought this was pretty good none the less:

```
+/@:((}:,(|~2:)@{:,<.@-:@{:)^:])

```

### Explanation:

```
+/@:((}:,(|~2:)@{:,<.@-:@{:)^:])  | Full program
    (                          )  | Convert to binary list:
     (                     )^:]   | do n times:
      }:                            | Curtail the list
        ,(|~2:)@{:                  | Append the remainder mod 2 of the item dropped
                  ,<.@-:@{:       | Append the floor of half the item dropped
+/@:                                | Sum

```

A step by step example:

```
    (}:,(|~2:)@{:,<.@-:@{:) 7
1 3
^ ^
| |
| Floor 7/2
7 % 2

    (}:,(|~2:)@{:,<.@-:@{:) 1 3
1 1 1
^ ^ ^
| | |
| | Floor 3/2
| 3 % 2
The input curtailed

    ((}:,(|~2:^#)@{:,<.@-:@{:)^:]) 7
1 1 1 0 0 0 0 0

    +/@:((}:,(|~2:)@{:,<.@-:@{:)^:]) 7
3

```

Of course, you would only have to do this Ceil(log2 n) times, but thats a lot harder to calculate than just n.

# Answer
> 0 votes
# brainfuck, 34 bytes

```
>+<[[>-]++[>]+[<]>-]>[-<[->+<]>>]<

```

Try it online!

At 53 bytes, I thought the existing brainfuck solution was way too long /s. Starting cell contains the number and ends on the number of binary digits in it. Doesn't work for numbers above 255 unless you use an interpreter with larger than 8 bit or infinite cells.

### How It Works

```
>+<[[>-]++[>]+[<]>-] Converts the number to binary
>[-<[->+<]>>]<       Adds all the numbers in the binary together

```

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

```
0$:&0=?n&:2%:}-2,@+!

```

Try it online!

# Answer
> 0 votes
# dc, 14 bytes

```
[2~rd0<M+]dsMx

```

Try it online!

Input is taken from the stack, output is left on the stack. This is the same general idea as the previous dc entry (repeatedly reduce mod 2 and add remainders), but optimizing by using non-tail recursion makes a huge difference (I'd have made this a comment on that entry, but the user hasn't been active for over a year).

---
Tags: code-golf, number, binary
---


title: Tips for golfing in PARI/GP

text:
# Question
Title: Tips for golfing in PARI/GP
PARI/GP is a free computer algebra system. It is designed for (algebraic) number theory, not golfing, but that's part of the attraction. Unsurprisingly, it fares best at mathematical tasks; its support for string manipulation is primitive. (Having said that, advice for golfing non-mathematical tasks is also welcome.)

As usual, please post one tip per answer.

These tips should be at least *somewhat* specific to PARI/GP; advice which applies to 'most' languages belongs at Tips for golfing in \<all languages\>. Some general tips which don't need to be included:

1. Compress whitespace. (In GP all whitespace outside of strings is optional.)
2. Use single-character variables. (There are 50 choices, a-z and A-Z except I and O.)
3. Use `<` and `>` rather than `<=` and `>=` when possible.
4. Chain assignments. (`a=b=c` or `a+=b*=c`)

# Answer
Use operators to replace commands (or longer operators!) when possible.

`length(v)``#v` (saves 5-7 bytes)

`matsize(M)[2]``#M` (saves 9-11 bytes)

`matsize(M)[1]``#M~` (saves 8-10 bytes)

`floor(x)``x\1` (saves 3-5 bytes)

`round(x)``x\/1` (saves 2-4 bytes)\*

`shift(x,n)``x>>n` or `x<<n` (saves 2-6 bytes)

`sqr(x)``x^2` (saves 1-3 bytes)

`deriv(x)``x'` (saves 4-6 bytes)

`mattranspose(M)``M~` (saves 11-13 bytes)

`factorial(n)``n!` (saves 8-10 bytes)

`&&``&` (saves 1 byte; note that this syntax is deprecated)

`||``|` (saves 1 byte; only works in older versions)

* Prior to 2.8.1 (2016) the `\/` operator did not work correctly on t\_REAL numbers—update if you haven't!
> 9 votes

# Answer
* In a string context (e.g. the arguments of `print` or `Str`), commas are unnecessary:

```
i=99
print(i" bottles of beer on the wall")

```

This is even true if one of the arguments is an assignment. The following is equivalent to the above:

```
print(i=99" bottles of beer on the wall")

```
* Unassigned variables evaluate to their name in a string context:

```
for(i=1,2,print(i" bottl"e" of beer on the wall.");e=es)

```

produces:

```
1 bottle of beer on the wall.
2 bottles of beer on the wall.

```
* In a multi-line context `{ ... }`, the closing brace is unnecessary.

```
print({"this is line one
this is line two")

```

---

**Documentation**

In REPL:
`?*` \- show all commands.
`?<command>` \- show brief documentation for a command.

Online documentation:
http://pari.math.u-bordeaux.fr/dochtml/html.stable/
> 6 votes

# Answer
Some replacements:

* `poldegree(f)` -\> `#f'`
* `subst(f,x,y)` -\> `x=y;eval(f)` if `x` is not used elsewhere
* `subst(f,x,0)` -\> `f%x` but its type is `t_POL` instead of `t_INT`
* `polcoeff(s+O(x^(n+1)),n)` -\> `Pol(s+O(x^n*x))\x^n` but its type is `t_POL`
* `polcoeff(s+O(x^(n+1)),n)` -\> `Vec(s+O(x^n++))[n]` if the constant term of `s` is nonzero
* `Vecrev(v)~` -\> `Colrev(v)`
* `Pol(s+O(x^n))` -\> `s%x^n` if `s` is a rational function (e.g., `1/(1-x)`) and `n > 0`
* `(1-x^n)/(1-x)` -\> `x^n\(x-1)`
* `matrix(n,n,i,j,e)` -\> `matrix(n,,i,j,e)`
* `a[2..#a]` / `a[2..-1]` -\> `a[^1]`
* `a[1..-2]` -\> `a[^#a]`
* `if(cond0,a,if(cond1,b,c))` -\> `if(cond0,a,cond1,b,c)`
* `ceil(x)` -\> `-x\-1`
> 6 votes

# Answer
Use set-builder notation to replace apply and select.

`apply(x->thing1(x)&&thing2(x),select(condition,v))``[thing1(x)&&thing2(x)|x<-v,condition(x)]`

or

`apply(x->thing1(x)&&thing2(x),v)``[thing1(x)&&thing2(x)|x<-v]`

but if you're applying a named function, `apply` is better, since the arguments are implicit:

`[functionName(x)|x<-v]``apply(functionName,v)`
> 5 votes

# Answer
Use specialized loops.

GP provides (at least) the following loops: `for`, `forcomposite`, `fordiv`, `forell`, `forpart`, `forprime`, `forstep`, `forsubgroup`, `forvec`, `prod`, `prodeuler`, `prodinf`, `sum`, `sumalt`, `sumdiv`, `sumdivmult`, `suminf`, `sumnum`, `sumnummonien`, `sumpos`.

So don't write `s=0;for(i=1,9,s+=f(i));s` when you could write `sum(i=1,9,f(i))`, don't write `for(n=1,20,f(prime(n)))` when you could write `forprime(p=2,71,f(p))`, and certainly don't write `apply(v->print(v),partitions(4));` instead of `forpart(v=4,print(v))`.

`prodeuler` can be useful as a product over the primes, but note that it returns a `t_REAL` rather than a `t_INT`, so rounding at the end may be necessary depending on the task.

`sumdiv` can be a real lifesaver compared to a simple loop over `divisors`.

`forvec` is a replacement for a whole collection of loops. You can replace (ungolfed)

```
{
for(i=0,9,
  for(j=i,99,
    for(k=i,200,
      f(i,j,k)
    )
  )
);
}

```

with

```
forvec(v=[[0,9], [0,99], [0,200]],
  call(f, v)
,
  1 \\ increasing sequences only
)

```
> 5 votes

# Answer
# Know your built-ins

Like other computer algebra systems, PARI/GP also has a lot of built-ins for number theory, linear algebra, polynomials, and other branches of algebra.

The easy way to find a built-in is looking at the reference card.

Many built-ins have a prefix to indicate the types they work on. For example:

* Built-ins for matrices usually have the prefix `mat`
* Built-ins for polynomials usually have the prefix `pol`
* Built-ins for power series usually have the prefix `ser`

When you are looking for a built-in, you can type the prefix in the REPL, and press `tab`. The command-line completion will tell you what functions it has.

To see the help message of a built-in in the REPL, just type `? functionname`. For a more detailed help message, sometimes with examples, type `?? functionname`.
> 5 votes

# Answer
Avoid `return` when possible.

The final value in the function is returned, so don't write `...;return(x)` but just `...;x`.

If you must use `return`, note that the bare for `return` yields the PARI value `gnil`, which is falsy (coerced into a GP `0` or PARI `gen_0` as needed), so you can usually write `return` rather than `return(0)`.

And (almost?) needless to say, but if you have two values to choose from, much better to return `if(condition,x,y)` than `if(condition,return(x));y`.
> 3 votes

# Answer
# Truthy and Falsy

There isn't a Boolean type in PARI/GP. Truthy and falsy are defined as the following:

* Values that equal to `0` are falsy. This includes real number `0.0`, complex number `0.0+0.0*I`, polynomial `0*x`, power series `0+O(x^3)`, modulo object `Mod(0,3)`, and many others.
* Vector and matrices that are empty or only contains falsy values are falsy. This includes nested falsy vectors like `[0, [0, 0, [[]]]]`.
* Everything else is truthy. In particular, lists, maps, strings, and `Vecsmall`s are always truthy even if they are empty or only contains falsy values.

The simplest way to convert `a` to the "default" truthy / falsy value (i.e., `1` / `0`) is `!!a`.

When testing equality with `==`, every falsy value is equal to `0`. If you need to distinguish between different falsy values, use `===`.

## Use `-` to test equality

For `a` and `b` that can subtract, we can do:

* `if(a==b,c,d)` =\> `if(a-b,d,c)`
* `a==b&&c` =\> `a-b||c` if we only need the side effect of `c`.
* `a==b||c` =\> `a-b&&c` if we only need the side effect of `c`.

Be careful when testing vector equality: only vectors that have the same length can subtract.

## Any and All

There isn't built-in `any` or `all` function in PARI/GP.

When checking if a predicate is true for all or any integers in a range, we can just use `sum` or `prod`.

When checking if any item in a vector is truthy, we don't need a function: the vector itself is truthy if and only if any item in it is truthy.

When checking if all item in a vector is truthy, the following has the same length:

```
vecprod(a)
![!i|i<-a]

```

## Initialize with truthy/falsy

When using functions like `for`, `sum`, `prod`, we usually initialize some variable to `0` and `1`. If the previous expression returns the opposite truthy/falsy value, we can just use it. For example:

```
a=some_truthy_value;for(i=0,n,do_something())
=>
for(i=!a=some_truthy_value,n,do_something())

```
> 3 votes

# Answer
# String replace

PARI/GP doesn't have a string replace built-in, but when you want to replace every occurrence of `a` in `s` by `b`, you can do `strjoin(strsplit(s,a),b)`.

`strjoin` and `strsplit` are introduced in PARI/GP 2.13.0, so they are not supported on TIO.
> 1 votes

# Answer
# Default parameters

In PARI/GP, function parameters default to `0`. This can be useful when you need to initialize a variable to `0`.

For example, instead of `f(x)=i=0;...`, you can write `f(x,i)=...`.
> 1 votes

---
Tags: code-golf, tips
---


title: Create a binary ruler

text:
# Question
Title: Create a binary ruler
Given a number **n**, generate the first **n** columns of this pattern:

```
                               #
               #               #
       #       #       #       #
   #   #   #   #   #   #   #   #
 # # # # # # # # # # # # # # # #
################################ ...

```

The height of the column at (1-indexed) **n** is the number of trailing `0` bits in **n**'s binary representation, plus one. As a result, the bottom layer has every column filled in, the second layer every second column, the third layer every fourth column, etc.

## Rules

* You may input and output through any standard method.
* You may assume the input is an integer between 1 and 999, inclusive.
* The output may contain any amount of whitespace, as long as the pattern is intact.
* The pattern must be 1-indexed, and in the same format as shown here.
* You may use any single non-whitespace character in place of `#`, but you may not change the space character.

## Test cases

```
1
#

2
 #
##

3
 #
###

4
   #
 # #
####

5
   #
 # #
#####

7
   #
 # # #
#######

32
                               #
               #               #
       #       #       #       #
   #   #   #   #   #   #   #   #
 # # # # # # # # # # # # # # # #
################################

```

A few larger test cases can be found here.

## Scoring

This is , so **the shortest code in bytes in each language wins.**

# Answer
# Python 2, 54 bytes

```
i=n=input()
while i:i-=1;print((' '*~-2**i+'#')*n)[:n]

```

Try it online!

Prints with lots of leading whitespace. Each row `i` counting down from `n` repeats a pattern of `2**i-1` spaces followed by a `#`. This pattern is repeated up to the width of the ruler, which is the input `n`. This is done by multiplying the pattern string by `n` and taking the first `n` characters with `[:n]`.

The pattern can be made by string formatting for an equal length alternative.

```
i=n=input()
while i:i-=1;print('%%%ds'%2**i%'#'*n)[:n]

```

A cute slicing method is longer.

```
n=input();s=~-2**n*' '+'#'
exec"s=s[1::2]*2;print s[:n];"*n

```
> 11 votes

# Answer
# Python 3, 74 bytes

```
n=int(input())
a=1
while a<n:a*=2
while a:print(("%%%dd"%a%4*n)[:n]);a//=2

```

Try it online!
> 10 votes

# Answer
# , ~~17~~, 16 bytes

```
é#Àñä}Är {ñÎÀlD

```

Try it online!

Hexdump:

```
00000000: e923 c0f1 e416 7dc4 7220 7bf1 cec0 6c44  .#....}.r {...lD

```

*Thanks to @KritixiLithos for saving one byte!*

This algorithm is *horribly* inefficient, but it should work in theory for any size input.

It works by generating the first *n* iterations of the following pattern:

```
#

 #
##

   #
 # #
####

       #
   #   #
 # # # #
########

               #
       #       #
   #   #   #   #
 # # # # # # # #
################

                               #
               #               #
       #       #       #       #
   #   #   #   #   #   #   #   #
 # # # # # # # # # # # # # # # #
################################

```

And then chopping off all but the first *n* columns. As such, this will produce a ton of leading whitespace, but the OP said:

> The output may contain any amount of whitespace, as long as the pattern is intact

Explanation:

```
é#                      " Insert an '#'
  Àñ           ñ        " 'N' times:
    ä<C-v>}             "   Duplicate every line blockwise (duplicating horizontally instead of vertically)
           Ä            "   Duplicate the top line. This conveniently puts us on the first non-whitespace character (that is, '#')
            r           "   Replace this character with a space
              {         "   Move to the beginning of the buffer
                Î       " On every line:
                 Àl     "   Move 'N' characters to the right ('l' for right, makes sense, right?)
                   D    "   And delete everything after the cursor

```
> 9 votes

# Answer
# APL (Dyalog), 21 bytes

```
'# '[1+⊖0⍪∨⍀⊖2⊥⍣¯1⍳⎕]

```

Try it online!

`'# '[`…\`\] index the string with

get input

that many **i**ntegers

`2⊥⍣¯1` convert to binary, using as many digits as needed (one number in each *column*)

flip upside down

`∨⍀` vertical cumulative OR reduction

`0⍪` concatenate zeros on top

flip upside down (i.e. back up again)

`1+` add one (for 1-based indexing)
> 5 votes

# Answer
# JavaScript (ES6), ~~61~~ 58 bytes

```
f=(n,c=n,s='')=>c?f(n,c>>1,s+s+' ')+`
`+(s+1).repeat(c):''

```

*Saved 1 byte thanks to @ETHProductions, then 2 more bytes when I saw that any character could be used.*

A recursive solution.

**Test cases:**

```
f=(n,c=n,s='')=>c?f(n,c>>1,s+s+' ')+`
`+(s+1).repeat(c):''

console.log(f(32));
console.log(f(1));
console.log(f(5));
console.log(f(7));
```

**Animation:**

```
f=(n,c=n,s='')=>c?f(n,c>>1,s+s+' ')+`
`+(s+1).repeat(c):''

for(let i = 1 ; i < 64 ; i++) {
  setTimeout(_=>document.querySelector('pre').textContent=f(i), i*40);
}
```

```
<pre>
```
> 5 votes

# Answer
# Jelly, ~~11~~ 10 bytes

```
Rọ2‘4ẋz⁶ṚY

```

Try it online!

1 byte saved after the OP added a relaxation that the character doesn't have to be `#`.
> 3 votes

# Answer
# Japt, 20 17 bytes

*Saved 3 bytes thanks to @Shaggy and @ETHproductions*

```
õ_¤q1 o Ä çoÃ·z w

```

Try it online!

## Explanation:

Input: 5

```
õ_¤q1 o Ä çoÃ·z w
õ           Ã       // Create a range [1...Input] [1,2,3,4,5]
 _                  // Map; At each item:
  ¤                 //   Convert to binary        ["1","10","11","100","101"]
   q1               //   Split on "1"             [["",""],["","0"],["","",""],["","00"],["","0",""]]
      o             //   Get the last item        ["","0","","00",""]
        Ä           //   Add 1                    [["1","01","1","001","1"]]
          ço        //   Fill with "o"            ["o","oo","o","ooo","o"]
             ·      // Join with new-lines        ["o\noo\no\nooo\no"]
              z     // Rotate 90 degrees          ["ooooo\n o o \n o   "]
                w   // Reverse                    ["   o \n o o \nooooo"]

```
> 2 votes

# Answer
# Octave, 45 bytes

```
@(n)[[sort(cummin(de2bi(g=0:n)'));g|1]+32 '']

```

Try it on Octave Online!

Instead of `'#'` prints `'!'`.
> 2 votes

# Answer
# PHP, 139 bytes

```
for($f=array_fill(0,$l=1+log($a=$argn,2)," ");$n++<$a;)for($h=1+strspn(strrev(decbin($n)),$i=0);$i<$h;)$f[$l-++$i][$n]=3;echo join("
",$f);

```

Try it online!
> 2 votes

# Answer
# Pyth, 15 Bytes

```
j_.tm*Nhx_.Bd1S

```

Try it!

### explanation

```
j_.tm*Nhx_.Bd1S
    m         SQ   # map over the numbers from 0 to the implicit input (lambda variable: d)
          .Bd      # Convert d to a binary string: (12 -> 1100)
         _         # reverse: (1100 -> 0011)
        x    1     # get the location of the first 1 ( 2 )
     *Nh           # make one more than that " quotation marks (""")
 _.t               # transpose the list of quotation mark strings and reverse it
j                  # join on newline

```
> 2 votes

# Answer
# C, ~~84~~ 74 bytes

```
f(i,l,m){putchar(32+3*!(i&m));i<l?f(i+1,l,m):m?putchar(10),f(1,l,m>>1):1;}

```

### Ungolfed:

```
void f(int counter, int length, int mask) {
    putchar((counter&mask) ? ' ' : '#');
    if(counter<length) {
        f(counter+1, length, mask);
    } else if(mask) {
        putchar('\n');
        f(1, length, mask>>1);
    }
}

```

### Test with:

```
int main() {
    f(1, 32, 1023);
    putchar('\n');
    f(1, 1, 1023);
    putchar('\n');
    f(1, 999, 1023);
    putchar('\n');
}

```

### Explanation

Once again, recursion takes less characters in C than iteration, so the two loops are expressed as the two recursional invocations.

Also, C is a great language for playing tricks with boolean expressions, allowing the decision of whether to put a blank or a `#` to be expressed by the expression `32+3*!(i&m)`. A space has the ASCII value of 32, the `#` is ASCII 35, so we get a blank if any of the bits in the mask is set in `i`.
> 2 votes

# Answer
# Python 2, 47 bytes

```
f=lambda n:n and' '.join(f(n/2))+'\n'+n*'#'or''

```

Try it online!
> 2 votes

# Answer
# JavaScript (ES8), 71 bytes

The padStart() function was introduced in ECMAScript 2017!

```
N=>eval(`for(s='',n=1;n<=N;n*=2)s='\\n'+'#'.padStart(n).repeat(N/n)+s`)

```

```
f=
N=>eval(`for(s='',n=1;n<=N;n*=2)s='\\n'+'#'.padStart(n).repeat(N/n)+s`)

console.log(f(+prompt()))
```

---

# JavaScript (ES6), 77 bytes

```
N=>eval(`for(s='',n=1;n<=N;n*=2)s='\\n'+(' '.repeat(n-1)+'#').repeat(N/n)+s`)

```

```
f=
N=>eval(`for(s='',n=1;n<=N;n*=2)s='\\n'+(' '.repeat(n-1)+'#').repeat(N/n)+s`)

console.log(f(+prompt()))
```
> 1 votes

# Answer
# Mathematica, 69 bytes

```
Rotate[Grid["#"~Table~#&/@(IntegerExponent[2*#,2]&/@Range[#])],Pi/2]&

```
> 1 votes

# Answer
## (WESRRMICGSE): 237 bytes

```
IF(ROW()<=FLOOR(LOG(COUNTA(R1C:R[-1]C,R[1]C:R[1024]C)+1,2),1)+2,LEFT(REPT(REPT(" ",FLOOR(POWER(2,LOG(COUNTA(R1C:R[-1]C,R[1]C:R[1024]C)+1,2)-ROW()+2),1)-1) &"#",COUNTA(R1C:R[-1]C,R[1]C:R[1024]C)+1),COUNTA(R1C:R[-1]C,R[1]C:R[1024]C)+1),"")

```

Alright. 'splaining time.

First off, replace every `COUNTA(R1C:R[-1]C,R[1]C:R[1024]C)+1` with simply `[i]`, for input. the token counts the number of cells, not including itself, that contain a formula, and then adds one, to include itself. Since WESRRMICGSE drags a formula according to the input you give it, this token always results in the input.

we have:

```
IF(ROW()<=FLOOR(LOG([i],2),1)+3,LEFT(REPT(REPT(" ",FLOOR(POWER(2,LOG([i],2)-ROW()+2),1)-1) &"#",[i]),[i]),"")

```

This is much more readable. You're going to see the `FLOOR(LOG([i],2),1)` token a lot, which simply means take the nearest power of 2 which is less than the input (`[i]`) number. eg: `4->4, 5->4, 6->4, 7->4, 8->8 ...etc`. I'll replace that with `GS[[i]]`

```
IF(ROW()<=GS[[i]]+3,LEFT(REPT(REPT(" ",,FLOOR(POWER(2,LOG([i],2)-ROW()+2),1),1)-1) &"#",[i]),[i]),"")

```

better. breaking down the if clause, we're testing if the row is less than or equal to `GS[[i]]+3`, because all rulers' height is equal to the GS\[\[i\]\]+1, this selects the rows which are equal to the height of the ruler. `+1` for 1-indexing rows, and `+1` again for WESRRMICGSE offset.

The `FALSE` result yields an empty cell (""), and a true result yields `LEFT(REPT(REPT(" ",,FLOOR(POWER(2,LOG([i],2)-ROW()+2),1),1)-1) &"#",[i]),[i])`

currently still editing, stay tuned
> 1 votes

# Answer
# Haskell, ~~64~~ 62 bytes

```
l m=([2..2^m]>>" ")++'#':l m
f n=unlines$take n.l<$>[n,n-1..0]

```

Try it online! Example usage: `f 10`.
> 1 votes

# Answer
# Charcoal, ~~27~~ 23 bytes

```
↶Ｆ…·¹Ｎ«Ｊι⁰#Ｗ¬﹪ι²«Ａ÷ι²ι#

```

Try it online! Link is to verbose version of code. Edit: Saved 4 bytes by switching to `JumpTo`.
> 1 votes

# Answer
# k, 33 bytes

```
`0:|" #"{(1+!x){~y!x}/:(x>)(2*)\1}

```

This only seems to work in AW's interpreter.

The oK version (which you can try online) seems to have a bug, requiring a slight change to make it work:

```
`0:|" #"{(1+!x){~y!x}/:{x>y}[x](2*)\1}

```
> 1 votes

# Answer
## C#, 174 bytes

This method has two parameters, an input for the ruler length, and an output which is the ruler as string.

Golfed:

```
void R(int n,out string s){var l=new int[++n];int i,x=n,y=0;for(s="";x-->1;)for(i=0;0==(l[x]=(x>>i++&1)*i);y=y<i?i:y);for(y++;y-->0;s+='\n')for(x=0;++x<n;s+=y<l[x]?'#':' ');}

```

Indented:

```
void R(int n,out string s){                       // Return the result in an out parameter.
    var l=new int[++n];                           // Use a 1-based array.
    int i,x=n,y=0;                                //
    for(s="";x-->1;)                              // For each number x on the ruler
        for(i=0;0==(l[x]=(x>>i++&1)*i);y=y<i?i:y) // ... find lowest set bit of x, counting the maximum value.
            ;                                     //
    for(y++;y-->0;s+='\n')                        // Count down each line.
        for(x=0;++x<n;s+=y<l[x]?'#':' ')          // Output # for numbers that are tall enough.
            ;                                     //
}

```

### Try it online!
> 1 votes

# Answer
# J, 38 bytes

```
3 :'|.|:''#''#~,.(1+|.i.1:)@#:"0>:i.y'

```

Not great. Lmk if the byte count is off -- I'm on my phone.
> 1 votes

# Answer
# Husk, 13 bytes

```
↔T' ↑moR'#→İr

```

Try it online!

I saw a ruler sequence builtin(`İr`), so I just went ahead and found a challenge I could cheat on.
> 1 votes

# Answer
# Java (OpenJDK 8), 91 bytes

```
n->{int i=10,j;String s="";for(;i-->0;s+="\n")for(j=0;j++<n;)s+=j>>i<<i<j?' ':35;return s;}

```

Try it online!

Ungolfed:

```
n->{
    int i=10,j; // Since we are allowed extra whitespace, set columns always to 10
    String s = "";
    for(;i-->0;s+="\n")      // Every iteration add a newline, i=9..0
        for(j=0;j++<n;)      // j=1..n+1
            s+= j>>i<<i<j    // if j has less than i trailing 0s in binary form
                ?' '         // add a space else
                :35          // # (java handles ternary return types weirdly)
}

```
> 0 votes

# Answer
## CJam, 34 bytes

```
ri{2bW%0+0#)}%_'#f*\:e>f{Se]}zW%N*

```

Meh.
> 0 votes

# Answer
# C (gcc), 70 bytes

```
f(x,l,n){for(l=512;l/=2;)for(n=0;n++<=x;)putchar(n^x+1?n%l?32:35:10);}

```

Try it online!
> 0 votes

# Answer
# Perl 5, 60 + 1 (-n) = 61 bytes

```
$n=0|1+(log)/log 2;say(($"x(2**$n-1),X)x($_/2**$n))while$n--

```

Try it online!
> 0 votes

# Answer
# Japt `-R`, 11 bytes

```
õ_&n)¤çTÃz3

```

Try it

```
õ_&n)¤çTÃz3     :Implicit input of integer U
õ               :Range [1,U]
 _              :Map each Z
  &n            :  Bitwise AND with -Z
    )           :  Group that operation
     ¤          :  Result to binary string
      ç         :  Fill with
       T        :    0
        Ã       :End map
         z3     :Rotate 90° clockwise 3 times
                :Implicit output joined with newlines

```
> 0 votes

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


title: Print a sinusoidal wave (vertically)

text:
# Question
Title: Print a sinusoidal wave (vertically)
Print a continuous sinusoidal wave scrolling vertically on a terminal. The program should not terminate and should continuously scroll down the wave (except until it is somehow interrupted). You may assume overflow is not a problem (i.e. you may use infinite loops with incrementing counters, or infinite recursion).

The wave should satisfy the following properties:

* Amplitude = 20 chars (peak amplitude)
* Period = 60 to 65 lines (inclusive)
* The output should only consist of spaces, newline and `|`
* After each line of output, pause for 50ms

Sample output:

```
                    |
                      |
                        |
                          |
                            |
                              |
                                |
                                 |
                                   |
                                    |
                                     |
                                      |
                                       |
                                        |
                                        |
                                        |
                                        |
                                        |
                                        |
                                       |
                                       |
                                      |
                                     |
                                   |
                                  |
                                |
                               |
                             |
                           |
                         |
                       |
                     |
                   |
                 |
               |
             |
            |
          |
        |
       |
     |
    |
   |
  |
 |
 |
 |
 |
 |
 |
 |
  |
   |
    |
     |
      |
        |
         |
           |
             |
               |
                 |
                   |
                     |
                       |
                         |
                           |
                             |
                              |
                                |
                                  |
                                   |
                                    |
                                      |
                                      |
                                       |
                                        |
                                        |
                                        |
                                        |
                                        |
                                        |
                                       |
                                       |
                                      |
                                    |
                                   |
                                  |
                                |
                               |
                             |
                           |
                         |
                       |
                     |
                   |
                 |
               |
             |
           |
          |
        |
       |
     |
    |
   |
  |
 |
 |
 |
 |
 |
 |
 |
  |
   |
    |
     |
       |
        |
          |
            |
             |
               |
                 |
                   |

```

The above output should go on forever unless otherwise interrupted, e.g. SIGINT or SIGKILL, or closing terminal window, or you power off your machine, or the Sun swallows the Earth, etc.

Shortest code wins.

Note. I am aware of a similar problem on Display Scrolling Waves but this isn't exactly the same. In my problem, the wave is not to be scrolled "in place" - just output it on a terminal. Also, this is an ascii-art problem, so don't use Mathematica to plot it.

# Answer
> 13 votes
## APL (35)

(Yes, it does fit in 35 bytes, here's a 1-byte APL encoding)

```
{∇⍵+⌈⎕DL.05⊣⎕←'|'↑⍨-21+⌈20×1○⍵×.1}1

```

Explanation:

* `{`...`}`1: call the function with 1 at the beginning
* `1○⍵×.1`: close enough for government work to `sin(⍵×π÷30)`. (`1○` is `sin`).
* `-21+⌈20`: normalize to the range `1..40` and negate
* `'|'↑⍨`: take the last `N` characters from the string `'|'` (which results in a string of spaces with a `|` at the end
* `⎕←`: display
* `⌈⎕DL.05`: wait 50 ms and return `1`. (`⎕DL` returns the amount of time it actually waited, which is going to be close to `0.05`, rounding that value up gives `1`).
* `∇⍵+`: add that number (`1`) to  and run the function again.

# Answer
> 23 votes
## C, ~~74~~ ~~73~~ ~~70~~ ~~69~~ 67 characters

67 character solution with many good ideas from @ugoren & others:

```
i;main(j){main(poll(printf("%*c|\n",j=21+sin(i++*.1)*20,0),0,50));}

```

69 character solution with while loop instead of recursion:

```
i;main(j){while(printf("%*c|\n",j=21+sin(i++*.1)*20,0))poll(0,0,50);}

```

Approaching perl territory. :)

# Answer
> 12 votes
# Mathematica ~~121 104 80 67~~ 64

```
n=1;While[0<1,Spacer[70 Sin[n Pi/32]+70]~Print~"|";Pause@.05; n++]

```

# Answer
> 11 votes
## Perl, 48 (68)

GNU sleep version: 48

```
print$"x(25+20*sin).'|
';$_+=.1;`sleep .05`;do$0

```

Cross platform: 68

```
use Time::HiRes"sleep";print$"x(25+20*sin).'|
';$_+=.1;sleep.05;do$0

```

Removed the use of Time::HiRes module by using shell sleep function. Shortened increment as per Ruby example. Shortened using $" and $0 seeing hints from Primo's work Thanks for hints Primo.

# Answer
> 11 votes
## Perl - 64 (or 60) bytes

*The following uses a Windows-specific shell command:*

```
`sleep/m50`,print$"x(20.5-$_*(32-abs)/12.8),'|
'for-32..31;do$0

```

*The following uses a GNU/Linux-specific shell command:*

```
`sleep .05`,print$"x(20.5-$_*(32-abs)/12.8),'|
'for-32..31;do$0

```

Both at 64 bytes.

* Period is 64.
* Maximum amplitude is exactly 20.
* The curve is perfectly symmetric.
* Every period is identical.

```
                    |
                      |
                         |
                           |
                             |
                               |
                                |
                                  |
                                   |
                                    |
                                     |
                                      |
                                       |
                                       |
                                        |
                                        |
                                        |
                                        |
                                        |
                                       |
                                       |
                                      |
                                     |
                                    |
                                   |
                                  |
                                |
                               |
                             |
                           |
                         |
                      |
                    |
                  |
               |
             |
           |
         |
        |
      |
     |
    |
   |
  |
 |
 |
|
|
|
|
|
 |
 |
  |
   |
    |
     |
      |
        |
         |
           |
             |
               |
                  |
                    |
                      |
                         |
                           |
                             |
                               |
                                |
                                  |
                                   |
                                    |
                                     |
                                      |
                                       |
                                       |
                                        |
                                        |
                                        |
                                        |
                                        |
                                       |
                                       |
                                      |
                                     |
                                    |
                                   |
                                  |
                                |
                               |
                             |
                           |
                         |
                      |
                    |
                  |
               |
             |
           |
         |
        |
      |
     |
    |
   |
  |
 |
 |
|
|
|
|
|
 |
 |
  |
   |
    |
     |
      |
        |
         |
           |
             |
               |
                  |
                    |
```

Note that this isn't exactly a sinusoidal wave, but rather a quadratic interpolation. Plotted against an actual sin:

At the granularity required, these are visually indistinguishable.

If the aesthetics aren't so important, I offer a **60 byte** alternative, with period length 62, maximum amplitude of ~20.02, and slight asymmetries:

```
`sleep/m50`,print$"x(20-$_*(31-abs)/12),'|
'for-31..30;do$0

```

# Answer
> 8 votes
# Ruby 56

```
i=0
loop{puts" "*(20*Math.sin(i+=0.1)+20)+?|;sleep 0.05}

```

# Answer
> 7 votes
# Befunge 98 - ~~103~~ 100

```
:1g:02p' \k:02gk,'|,a,$ff*:*8*kz1+:'<\`*
468:<=?ABDEFGGGHGGGFEDBA?=<:86420.,+)'&$#"!!! !!!"#$&')+,.02

```

Cheers for a program that does this, in a language without trigonometric capabilities; the first program in fact. The second line is simply data; the character corresponding with the ascii value of the sin, added to a space character.

**EDIT:** I saved 3 chars by not subtracting the space away; the sinusoid is translated 32 units to the right (which is valid).

Befunge also does not have a sleep command, or something similar. It would be nice to find a fingerprint, but I couldn't find one, so `ff*:*8*` pushes `8*225**2` (`405000`) and `kz` runs a noop that many times (well, that many times + 1). On windows command line with pyfunge, this turns out to be about 50 milliseconds, so I say I'm good. Note: if anyone knows a good fingerprint for this, please let me know.

The last part of the code simply checks if the counter (for the data line) is past the data, if it is, the the counter is reset to 0.

I used this to generate the data.

---

# Taylor Series

Although this version is 105 chars, I just had to include it:

```
:::f`!4*jf2*-:::*:*9*\:*aa*:*:01p*-01g9*/a2*+\$\f`!4*j01-*b2*+:01p' \k:01gk,$'|,a,ff*:*8*kz1+:f3*`!3*j$e-

```

I was trying to shorten my program, and decided to look at the taylor series for cosine (sine is harder to calculate). I changed `x` to `pi * x / 30` to match the period requested here, then multiplied by `20` to match the amplitude. I made some simplifications (adjusted factors for canceling, without changing the value of the function by much). Then I implemented it. Sadly, it is not a shorter implementation.

```
:f`!4*jf2*-

```

checks whether the values of the taylor series are getting inaccurate (about `x = 15`). If they are, then I compute the taylor series for `x - 30` instead of `x`.

```
:::*:*9*\:*aa*:*:01p*-01g9*/a2*+

```

is my implementation of the taylor series at `x = 0`, when `x` is the value on the stack.

```
\$\f`!4*j01-*

```

negates the value of the taylor series if the taylor series needed adjustment.

```
b2*+

```

make the cosine wave positive; otherwise, the printing would not work.

```
:01p' \k:01gk,$'|,a,

```

prints the wave

```
ff*:*8*kz1+

```

makeshift wait for 50 milliseconds, then increment `x`

```
:f3*`!3*j$e-

```

If `x` is greater than 45, change it to -14 (again, taylor series error adjustment).

# Answer
> 6 votes
# Python, ~~108~~,~~93~~,~~90~~,~~89~~,88

```
import math,time
a=0
while 1:print" "*int(20+20*math.sin(a))+"|";time.sleep(.05);a+=.1

```

Now with infinite scrolling :)

Edit: ok, 90. Enough?

Edit:Edit: no, 89.

Edit:Edit:Edit: 88 thanks to boothby.

# Answer
> 5 votes
# PHP, 59 characters

```
<?for(;;usleep(5e4))echo str_pad('',22+20*sin($a+=.1)).~ƒõ;

```

# Answer
> 5 votes
# C64 BASIC, 64 PETSCII chars

On a PAL C64, `For i=0 to 2:next i` cycles for approx. 0,05 seconds, so the delay time is respected.

# Answer
> 4 votes
# C - 86+3 characters

**Thanks shiona and Josh for the edit**

```
i;main(j){for(;j++<21+sin(i*.1)*20;)putchar(32);puts("|");usleep(50000);i++;main(1);}

```

~~i;main(j){for(j=0;j++\<20+sin(i/10.)\*20;)putchar(32);puts("|");usleep(50000);i++;main();}~~

~~float i;main(j){for(j=0;j++\<20+sin(i)\*20;)putchar(32);puts("|");usleep(50000);i+=.1;main();}~~

Compiled with the `-lm` flag, I assume I need to add 3 chars

# Answer
> 3 votes
## Javascript ~~88~~ ~~76~~ 78 characters

```
setInterval('console.log(Array(Math.sin(i++/10)*20+21|0).join(" ")+"|")',i=50)

```

Based on Kendall Frey's code.

# Answer
> 3 votes
**Ti-Basic, 33 bytes**

```
While 1:Output(8,int(7sin(X)+8),"!":Disp "":π/30+X→X:End

```

**The following caveats exist**:

1. Due to screen limitation of 16x8, this sine wave only has an amplitude of 7 (period of 60 is still maintained)
2. Due to lack of an easy way to access the `|` char, `!` is used instead
3. Due to lack of an accurate system timer, the delay is not implemented. However, run speed appears approximately correct.

# Answer
> 2 votes
## JavaScript - 88

```
setInterval(function(){console.log(Array(Math.sin(i++/10)*20+21|0).join(" ")+"|")},i=50)

```

I'm sure someone can come up with something that's actually clever.

# Answer
> 2 votes
# J - ~~103~~,~~58~~,~~57~~,54

Thanks to awesome guys from IRC

```
(0.1&+[6!:3@]&0.05[2:1!:2~' |'#~1,~[:<.20*1+1&o.)^:_]0

```

In words from right to left it reads: starting from 0 infinite times do: sin, add 1 ,multiply by 20, floor, append 1 (so it becomes array of 2 elements), copy two bytes ' |' correspondingly, print it, wait 0.05s and add 0.1

Instead of infinite loop we can use recursion, it would save 2 characters, but will also produce a stack error after some number of iterations

```
($:+&0.1[6!:3@]&0.05[2:1!:2~' |'#~1,~[:<.20*1+1&o.)0

```

Where `$:` is a recursive call.

# Answer
> 2 votes
# Haskell - 75

```
main=putStr$concat["|\n"++take(floor$20+20*sin x)(repeat ' ')|x<-[0,0.1..]]

```

Unfortunately, I couldn't get the program to pause 50 ms without doubling my char count, so it just floods the console, but it does produce the sine wave.

---

Here's the full code with pausing (138 chars with newlines):

```
import GHC.Conc
import Control.Monad
main=mapM_(\a->putStr a>>threadDelay 50000)(["|\n"++take(floor$20+20*sin x)(repeat ' ')|x<-[0,0.1..]])

```

# Answer
> 2 votes
fugly **Javascript - 77**

```
i=setInterval("console.log(Array(Math.sin(i+=.1)*20+20|0).join(' ')+'|')",50)
```

and if we do it in Firefox - **73**

```
i=setInterval("console.log(' '.repeat(Math.sin(i+=.1)*20+20|0)+'|');",50)
```

and if we're nasty - **67**

```
i=setInterval("throw(' '.repeat(Math.sin(i+=.1)*20+20|0)+'|');",50)
```

# Answer
> 2 votes
## Perl 6: 46 chars

```
sleep .05*say ' 'x(25+20*.sin),'|'for 0,.1...*

```

Create an infinite lazy Range using `0,0.1 ... *`, loop over that. `say` returns `Bool::True` which numifies as 1 in multiplication, this way I can keep it in a single statement.

# Answer
> 1 votes
## Python 3, 103

Stupid frikk'n imports...

```
import time,math
t=0
while 1:t+=(.05+t<time.clock())and(print(' '*int(20+20*math.cos(t*1.9))+'|')or.05)

```

Rather than "sleep", this implementation grinds at the cpu because python makes it easier to get a floating-point cpu clock than wall clock. This approach won't beat friol's, but it's fun so I'm leaving it up.

# Answer
> 1 votes
# C#

The Magic Line \[91\] Characters

```
for(var i=0d;;Console.Write("{0,"+(int)(40+20*Math.Sin(i+=.1))+"}\n",'|'))Thread.Sleep(50);

```

Working Program Below. \[148\] Characters

```
namespace System{class P{static void Main(){for(var i=0d;;Console.Write("{0,"+(int)(40+20*Math.Sin(i+=.1))+"}\n",'|'))Threading.Thread.Sleep(50);}}}

```

# Answer
> 1 votes
# Scala, ~~92~~,~~89~~,87

```
def f(i:Int){println(" "*(20+20*math.sin(i*.1)).toInt+"|");Thread sleep 50;f(i+1)};f(1)

```

# Answer
> 1 votes
# C#

**\[152\]** Characters

```
namespace System{class P{static void Main(){for(var i=0d;;){Console.Write("{0,"+(int)(40+20*Math.Sin(i+=.1))+"}\n",'|');Threading.Thread.Sleep(50);}}}}

```

I could not get the Existing C# answer to Run and I couldn't downvote because I don't have enough Reputation

it was missing a couple of `{` and missing a `)` after the For Loop Declaration.

I figure that the variance in the look of the wave when it is run is because of the way we are trying to display this wave.

---

if we aren't counting the Namespace and the Method Declaration then it would be **\[104\]** characters for the working version

```
for(var i=0d;;){Console.Write("{0,"+(int)(40+20*Math.Sin(i+=.1))+"}\n",'|');Threading.Thread.Sleep(50);}

```

# Answer
> 1 votes
# VB \[236\]\[178\]

not sure how you would count the tabs, I just took the count from Notepadd++ before I pasted here. **newlines are mandatory, probably why no one likes using it for code golfing.**

```
Module Module1
Sub Main()
Dim i
While True
Console.WriteLine("{0:" & (40 + 20 * Math.Sin(i = i + 0.1)) & "}", "|")
Threading.Thread.Sleep(50)
End While
End Sub
End Module

```

# Answer
> 1 votes
# Bash+bc (to do the math), 80

```
$ for((;;i++)){ printf "%$(bc -l<<<"a=20*s($i/10);scale=0;a/1+20")s|
";sleep .05;}
                |
                 |
                   |
                     |
                       |
                         |
                           |
                            |
                              |
                               |
                                |
                                 |
                                  |
                                   |
                                   |
                                   |
                                   |
                                   |
                                   |

```

# Answer
> 1 votes
## Julia - 68

Edit: thanks to M L and ace.

```
i=0;while 0<1;println(" "^int(20sin(.1i)+20)*"|");i+=1;sleep(.05)end

```

Well, it can not compete vs APL, but here's my attempt.

Output:

```
                    |
                      |
                        |
                          |
                            |
                              |
                               |
                                 |
                                  |
                                    |
                                     |
                                      |
                                       |
                                       |
                                        |
                                        |
                                        |
                                        |
                                       |
                                       |
                                      |
                                     |
                                    |
                                   |
                                  |
                                |
                              |
                             |
                           |
                         |
                       |
                     |
                   |
                 |
               |
             |
           |
         |
        |
      |
     |
    |
   |
  |
 |
|
|
|
|
|
 |
 |
  |
   |
     |
      |
       |
         |
           |
             |
              |
                |
                  |
                    |
                      |
                        |
                          |
                            |
                              |
                                |
                                 |
                                   |
                                    |
                                     |
                                      |
                                       |
                                       |
                                        |
                                        |
                                        |
                                        |
                                       |
                                       |
                                      |
                                     |
                                    |
                                   |
                                 |
                                |
                              |
                            |
                          |
                        |
                      |
                    |
                  |
                 |
               |
             |
           |
         |
       |
      |
     |
   |
  |
  |
 |
|
|
|
|
|
 |
  |
  |
    |
     |
      |
        |
         |
           |
             |
               |
                 |
                   |
                     |
                       |
                         |
                           |
                            |
                              |
                                |
                                 |
                                   |
                                    |
                                     |
                                      |
                                       |
                                       |
                                        |
                                        |
                                        |
                                        |
                                       |
                                       |
                                      |
                                     |
                                    |
                                  |
                                 |
                               |
                              |
                            |
                          |
                        |
                      |
                    |
                  |
                |
              |
            |
           |
         |
       |
      |
    |
   |
  |
 |
 |
|
|
|
|
|
 |
  |
   |
    |
     |
      |
        |
          |
           |
             |
               |
                 |
                   |
                     |
                       |
                         |
                           |
                             |
                              |
                                |
                                  |
                                   |
                                    |
                                     |
                                      |
                                       |
                                        |
                                        |
                                        |
                                        |
                                        |
                                       |
                                       |
                                      |
                                     |
                                    |
                                  |
                                 |
                               |
                             |
                            |
                          |
                        |
                      |
                    |
                  |
                |
              |
            |
          |
         |
       |
      |
    |
   |
  |
 |
 |
|
|
|
|
 |
 |
  |
   |
    |
     |
       |
        |
          |
            |
             |
               |
                 |
                   |
                     |
                       |
                         |
                           |
                             |
                               |
                                |
                                  |
                                   |
                                    |
                                      |
                                      |
                                       |
                                        |
                                        |
                                        |
                                        |
                                        |
                                       |
                                      |
                                      |
                                     |
                                   |
                                  |
                                |
                               |
                             |
                           |
                         |
                       |
                     |
                   |

```

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

Small size improvement over the other answer, at the cost of some accuracy. Note that TI-Basic technically has the | character, but you have to transfer it via computer or use an assembly program to access it.

```
While 1
Output(8,int(8+7sin(Ans)),":
Disp "
.03π+Ans
End

```

# Answer
> 1 votes
# MATLAB, 81 bytes

```
t=0;while(fprintf('%s\n',i))i=[];t=t+1;i(fix(21+20*sind(t*6)))='|';pause(.05);end

```

I abused the fact that `i` is always initialized in MATLAB, which meant that I could put the `fprintf` in the `while` statement without initializing `i` first. This does mean the program first outputs an empty line, but I think this is not forbidden in the spec.

Furthermore, it abuses the fact that Matlab will ignore most ASCII control characters, printing a space instead of NULL (also for the first empty line).

# Answer
> 0 votes
## F# - ~~90~~ ~~79~~ ~~77~~ 76

Here's a solution using recursion

```
let rec f x=printfn"%*c"(int(20.*sin x)+21)'|';Thread.Sleep 50;f(x+0.1)
f 0.

```

It could probably be improved further.

# Answer
> 0 votes
## AutoHotkey 176

```
SetKeyDelay,-1
run Notepad.exe
WinWaitActive, ahk_class Notepad
p:=0
loop
{
sleep 50
p+=Mod(Floor(A_index/40),2)?-1:1,t:=""
loop % p
t .= " "
sendinput % t "|`n"
}
esc::Exitapp

```

Run the script . It opens Notepad and prints the characters. Press Esc anytime to exit.

# Answer
> 0 votes
**Clojure, 121**

Short version:

```
(loop[a 0](println(clojure.string/join(repeat(int(+ 20 (* 20 (Math/sin a)))) " ")) \|)(Thread/sleep 50)(recur(+ a 0.1)))

```

Pretty version:

```
(loop [a 0]
  (println (clojure.string/join (repeat (int (+ 20 (* 20 (Math/sin a)))) " ")) \|)
  (Thread/sleep 50)
  (recur(+ a 0.1)))

```

Period is 64.

Type this into `lein repl` or save in file `sin.clj` and run with `lein exec sin.clj` (requires lein-exec plugin).

# Answer
> 0 votes
**Groovy 87 Chars**

Okay, now for a serious answer that actually follows the guidelines

```
def x=0;while(true){println ' '*(20*Math.sin(x)+20)+'|';x+=0.1;Thread.sleep(50)}

```

# Answer
> 0 votes
# CJam, 42 bytes

CJam is a bit younger than this challenge, but since this submission doesn't beat APL anyway, I don't see a problem with that.

```
es{es1$m50>{500d/ms21*K+S41*\i'|tN+oes}*}h

```

This won't work in the online interpreter, so you'll have to use the Java one.

The basic idea is to keep a timestamp on the stack, and whenever 50 ms have passed since the last timestamp, a new line is printed (where the sine is computed from that last time), and a new timestamp left on the stack.

# Answer
> 0 votes
# Pascal: 99 characters

```
uses Crt;var i:Real;begin
repeat
Writeln('|':Round(Sin(i)*20+21));i:=i+0.1;Delay(500)until 0=1;end.

```

Another task where Pascal's output formatting comes handy and everything else is pain.

# Answer
> 0 votes
# Julia, 60 chars

Unlike CCP’s solution, mine uses a recursive function:

```
a(n)=(print(" "^int(20sin(.1n)+20)*"|\n");sleep(.05);a(n+1))

```

Example:

```
julia> a(1)
                      |
                        |
                          |
                            |
                              |
                               |
                                 |
                                  |
                                    |
                                     |
                                      |
                                       |
                                       |
                                        |
                                        |
                                        |
                                        |
                                       |
                                       |
                                      |
                                     |
                                    |
                                   |
                                  |
                                |
                              |
                             |

```

# Answer
> 0 votes
# SmileBASIC, 44 bytes

```
@L
A=A+.1?" "*(COS(A)*20+20);"|
WAIT 3GOTO@L

```

# Answer
> 0 votes
# PowerShell, 57 bytes

```
for(;;sleep -m 50){' '*(20*[math]::Sin(($i+=.1))+20)+'|'}

```

Try it online!

# Answer
> 0 votes
# 05AB1E, 20 bytes

```
['|NT/Å½20*21+ú,50.W

```

Try it online.

**Explanation:**

```
[               # Start an infinite loop:
 '|            '#  Push character "|"
 N              #  Push the 0-based loop-index
  T/            #  Divide it by 10
    Å½          #  Take the sine of that
      20*       #  Multiply it by 20
         21+    #  Add 21
            ú   #  Pad that many leading spaces before the "|"
                #  (`ú` will ignore any decimal digits and interpret it as an integer)
             ,  #  Pop and print this string with trailing newline
 50.W           #  Sleep 50 ms

```

# Answer
> 0 votes
# Japt, 20 bytes

Open your browser's console.

```
50i@Ol|ùMsU°/A Ñ0+21

```

Test it

# Answer
> 0 votes
# Scala, ~~92~~ 82 bytes

Saved bytes thanks to the comments.

Golfed version. Try it online!

```
def f={var i=0;while(i<101){println(" "*(21+(math.sin(i*.1)*20).toInt)+"|");i+=1}}

//math.sin
//scala.math.sin
//Math.sin
//java.lang.Math.sin
//WHATEVER

```

Ungolfed version. Try it online!

```
import scala.math._
import scala.concurrent.duration._

object SineWave extends App {
  var i = 0

  def animateWave(): Unit = {
    //while (true) {
    while (i<=100) {
      val j = 21 + (sin(i * 0.1) * 20).toInt
      println(" " * j + "|")
      i += 1
      //Thread.sleep(50)
    }
  }

  animateWave()
}

```

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


# Question
Title: Is it a valid consonant cluster in Lojban?
*.i xu .e'o lo zunsnagri cu drani loka jboge'a*

---

Given an input of a string consisting of two characters, output whether it is a valid consonant cluster in Lojban.

Here is a quote from CLL 3.6 detailing the rules for a valid consonant cluster pair (or rather, an *invalid* one):

```
1) It is forbidden for both consonants to be the same, as this would
   violate the rule against double consonants.

2) It is forbidden for one consonant to be voiced and the other unvoiced.
   The consonants “l”, “m”, “n”, and “r” are exempt from this restriction.
   As a result, “bf” is forbidden, and so is “sd”, but both “fl” and “vl”,
   and both “ls” and “lz”, are permitted.

3) It is forbidden for both consonants to be drawn from the set “c”, “j”,
   “s”, “z”.

4) The specific pairs “cx”, “kx”, “xc”, “xk”, and “mz” are forbidden.

```

The quote references "voiced" and "unvoiced" consonants. Here is a table of the unvoiced consonants and their voiced counterparts (also from CLL 3.6):

```
UNVOICED    VOICED
   p          b
   t          d
   k          g
   f          v
   c          j
   s          z
   x          -

```

Note that {x} has no voiced counterpart. For completeness, the remaining consonants that are not on this list (which can be either voiced or unvoiced for the purposes of the quote) are `lmnr`. (`y` is a vowel, and the letters `hqw` are not used.)

The input must be a single string, but you may assume that it will always consist of exactly two consonants, with optional trailing newline if you wish. The output may be any truthy or falsy value.

This is , so the shortest code in bytes wins.

Test cases (these are all possible input strings placed in the proper categories):

```
Valid consonant clusters:
 bd bg bj bl bm bn br bv bz cf ck cl cm cn cp cr ct db dg dj dl dm dn dr dv
 dz fc fk fl fm fn fp fr fs ft fx gb gd gj gl gm gn gr gv gz jb jd jg jl jm
 jn jr jv kc kf kl km kn kp kr ks kt lb lc ld lf lg lj lk lm ln lp lr ls lt
 lv lx lz mb mc md mf mg mj mk ml mn mp mr ms mt mv mx nb nc nd nf ng nj nk
 nl nm np nr ns nt nv nx nz pc pf pk pl pm pn pr ps pt px rb rc rd rf rg rj
 rk rl rm rn rp rs rt rv rx rz sf sk sl sm sn sp sr st sx tc tf tk tl tm tn
 tp tr ts tx vb vd vg vj vl vm vn vr vz xf xl xm xn xp xr xs xt zb zd zg zl
 zm zn zr zv

Invalid consonant clusters:
 bb bc bf bk bp bs bt bx cb cc cd cg cj cs cv cx cz dc dd df dk dp ds dt dx
 fb fd ff fg fj fv fz gc gf gg gk gp gs gt gx jc jf jj jk jp js jt jx jz kb
 kd kg kj kk kv kx kz ll mm mz nn pb pd pg pj pp pv pz rr sb sc sd sg sj ss
 sv sz tb td tg tj tt tv tz vc vf vk vp vs vt vv vx xb xc xd xg xj xk xv xx
 xz zc zf zj zk zp zs zt zx zz

```

# Answer
> 5 votes
## Pyth, ~~53~~ ~~48~~ 47 bytes

```
!}z+"mz"s.pMs[+VGGc"xcxkcsjz"2*"ptkfcsx""bdgvjz

```

This generates a list of all invalid pairs based on the rules above, then checks if the input is one of them.

```
! }                        A not in B
    z                      input
    +
      "mz"                  "mz"
      s                    flattened
        .pM                permutations of each:
            s [               flatten the three-element array:
                +V              Alphabet vectorized concat with itself.
                   G            That is, duplicate letters
                   G
                c"xcxkcsjz"2     That string chopped every 2
                *               outer product of
                  "ptkfcsx"      voiced letters
                  "bdgvjz        and unvoiced letters

```

Try it here.

# Answer
> 6 votes
## Retina, ~~59~~ ~~57~~ ~~54~~ ~~53~~ 52 bytes

```
(.)\1|[cjsz]{2}|mz

T`fb-jz`svkv
kx|xk|^v?[kpstx]v?

```

The trailing linefeed is significant. For valid clusters, this outputs a non-empty string; for invalid ones the output is empty.

Try it online! This tests all clusters at once (removing all the invalid ones and leaving all the valid ones intact). To make that possible I've had to replace the `^` anchor with a `\b` word boundary.

Another solution for the same byte count:

```
(.)\1|[cjsz]{2}|mz

T`fk-dbz`scv
cx|xc|^v?[cpstx]v?

```

### Explanation

The goal is to remove all invalid pairs completely. We can do with the valid pairs whatever we want as long as at least one character remains.

```
(.)\1|[cjsz]{2}|mz

```

This takes care of three rules: `(.)\1` matches any pair violating rule 1. `[cjsz]{2}` matches any pair violating 3. `mz` matches the specifically disallowed pair from rule 4.

That leaves only rule two and the other specific pairs `xk`, `kx`, `xc` and `cx`. We can save a bunch of bytes by doing some preprocessing so we have to handle fewer cases:

```
T`fb-jz`svkv

```

The idea is to collapse all voiced consonants into one, as well `k` and `c`. I'm also turning `f` into `s` out of necessity. This is a transliteration stage which will substitute individual characters for other characters. To see the actual mapping we need to expand the range and remember that the last character of the target list is repeated indefinitely:

```
fbcdefghijz
svkvvvvvvvv

```

The initial `f => s` is necessary, because it overrides the later `f => v` which would turn `f` into a voiced consonant. We also see that `c` is turned into `k`. And all the voiced consontants `bdgjz` are turned into `v`. That leaves `ehi`... luckily these are either vowels or unused in Lojban. The same could also have been achieved with

```
T`fcb-jz`skv

```

Alternatively, check out the other solution I posted above that uses a very different transliteration (with a reverse range, and it also turns `k` into `c` instead).

Now the remaining invalid combinations can be checked much more easily:

```
kx|xk|^v?[kpstx]v?

```

`cx` and `cx` have become `kx` and `xk` so we only need to check two cases now. For rule 2, we try to match the entire pair, starting from the beginning with an optional voiced consonant (reduced to `v`), a mandatory unvoiced consonant (where we don't need to check for `f` and `c` separately) and another optional voiced consonant. If the pair is a mix of voiced and unvoiced one of the two optional `v`s will match and the entire pair is removed. Otherwise, this can only match if the pair starts with a voiced consonant (and has anything else second) - in that case only the first character will be removed, and the other one will remain, still giving a truthy result.

# Answer
> 3 votes
## TypeScript Compiler,  ~~427~~ 417 bytes

```
type U="p"|"t"|"k"|"f"|"c"|"s"|"x"
type V="b"|"d"|"g"|"v"|"j"|"z"
type S="c"|"s"|"j"|"z"
type G<T,W>=T extends W?0:T extends"l"|"r"|"m"|"n"?1:T extends U?W extends V?0:1:W extends U?0:1
type H<T,W>=T extends"x"?W extends"k"|"c"?0:G<T,W>:T extends"k"|"c"?W extends"x"?0:G<T,W>:T extends"m"?W extends"z"?0:G<T,W>:G<T,W>
type L<T>=T extends`${infer A}${infer B}`?A extends S?B extends S?0:H<A,B>:H<A,B>:0
let y:L<"bd">=1

```

Playground link

If you replace the `bd` on the last line with an illegal pair of consonants, the code will not compile. I may well have missed some optimizations, but I'm just content with the fact that the ``${infer A}${infer B}`` works as intended. Interestingly, any single character is considered valid.

# Answer
> 2 votes
# Pip, 49 bytes

```
$Qa|`[ptkfcsx][bdgvjz]|[ck]x`NPZa|a~=`[cjsz]+|mz`

```

Outputs with the truthy and falsey values switched (i.e. truthy if the consonant cluster is *not* valid, falsey if it is valid). If that's not considered acceptable for this challenge because it predates the linked consensus, then tack `!:` on the front for +2 bytes.

Verify all test cases: Try it online!

### Explanation

The input `a` is an invalid cluster if...

```
$Qa |

```

... its two characters are string-equal; or...

```
`[ptkfcsx][bdgvjz]|[ck]x` N PZa |

```

... the input `P`alindromi`Z`ed (e.g. `xc` -\> `xcx`) contains an unvoiced consonant `[ptkfcsx]` followed by a voiced consonant `[bdgvjz]` or one of `[ck]` followed by `x`; or...

```
a~=`[cjsz]+|mz`

```

... the input consists entirely of one or more (in this case, two) characters from the set `[cjsz]`, or consists entirely of the sequence `mz`.

# Answer
> 0 votes
# Lexurgy, 128 bytes

```
Class U {p,t,k,f,c,s,x}
Class V {b,d,g,v,j,z}
Class J {c,j,s,z}
R:
{{@U,@V,l,m,n,r}$1 $1,@V @U,@U @V,@J @J,{cx,kx,xc,xk,mz}}=>*

```

Replaces invalid clusters with an empty string.

## Ungolfed

```
Class U {p,t,k,f,c,s,x}
Class V {b,d,g,v,j,z}
Class C {@U,@V,l,m,n,r}
Class J {c,j,s,z}

replace:
@C$1 $1 => * # no dups
@V @U => * # no UV/VU pairs
@U @V => *
@J @J => * # no both cjsz
{cx,kx,xc,xk,mz} => * # specific pairs

```

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