title: Tips for golfing in Arturo

text:
# Question
Title: Tips for golfing in Arturo
Arturo is a bytecode-compiled/interpreted, garbage-collected general-purpose language filling a role similar to JavaScript, Python and Ruby. It is centered around the concept of blocks, which hold code just as easily as data. It uses fixed-arity prefix syntax and emphasizes the procedural and functional paradigms.

What general tips do you have for golfing in Arturo? I'm looking for ideas that are specific to Arturo (e.g. "remove comments" is not an answer). Please post one tip per answer.

# Answer
> 3 votes
# Converting integers to strings and vice versa

Instead of

```
to :integer s

```

use Arturo's eval function:

```
do s

```

Instead of

```
to :string n

```

use string interpolation:

```
~"|n|"

```

# Answer
> 1 votes
# Don't use .with:

All iterators in Arturo can take a `.with:` attribute label that lets you assign the index of the iteration to a variable. For instance:

```
loop.with:'i[33 95 7]'n[print~"Index: |i|, Value: |n|"]

```

```
Index: 0, Value: 33
Index: 1, Value: 95
Index: 2, Value: 7

```

However, you can always save a byte by declaring your own index variable and incrementing it manually:

```
i:0loop[33 95 7]'n[print~"Index: |i|, Value: |n|"'i+1]

```

And in the best-case scenario, you don't need to use variables at all. Abuse Arturo's (hidden?) stack instead:

```
0loop[33 95 7]'n[print~"Index: |<=|, Value: |n|"1+]

```

Here, we place 0 on top of the stack, duplicate it with `<=`, and increment it with `1+`.

# Answer
> 1 votes
# Shortening ranges

Consider the following function that finds the sum of squares from 1 to n.

```
$->n[∑map 1..n'x->x^2]

```

You might think this is as short as we can go, since removing the space causes `map1` which is a valid, albeit undefined word name. However, we can remove the space by realizing the symbol `..` (range) can go in the prefix position!

```
$->n[∑map..1n'x->x^2]

```

Since words can't start with numbers, `1n` gets parsed as `[1 n]` instead of `[1n]`. So `..1n` is equivalent to `1..n` and `range 1 n`. But is this really as short as we can go? No, it isn't! In Arturo, you may iterate over numbers themselves with the meaning `1..n`. So

```
$->n[∑map n'x->x^2]

```

is equivalent to the above. Finally, we can shorten this even more by using fat-arrow notation:

```
$=>[∑map&'x->x^2]

```

This causes `&` to become the input parameter. Since it's a symbol instead of the word `n`, it can butt up against its surroundings no problem.

# Answer
> 1 votes
# Consider outputting strings via the clipboard

`clip s` sets the clipboard to string `s`. As long as you're outputting a string all at once, this can save a byte over `print s` and function return (which are tied in length). Outputting via the clipboard is allowed by default.

For example,

```
clip~"It's |now\year| already, folks, go home." ; clipboard
print~"It's |now\year| already, folks, go home." ; stdout
$=>[~"It's |now\year| already, folks, go home."] ; function return

```

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


title: Sorted strings filter

text:
# Question
Title: Sorted strings filter
Input a list of strings `a` and a string `s` for search keyword. Find out all strings in `a` which contains `s` as subsequence. And sort them in the following order:

1. Exactly equals to `s`
2. Starts with `s`
3. Contains `s` as substring (continuous subsequence)
4. Contains `s` as subsequence

## Detail

* When two strings belongs to the same sorting group, you may sort them in any order you prefer.
* String matching is case sensitive. "A" and "a" are different characters.
* All strings will only contain printable ASCII (#32~#126).
* All strings will not have leading or trailing whitespaces.
* All strings will be non-empty.
* List `a` does not contain duplicate strings.

## Example

When the list is `["center","encounter","enter","enterprise","event"]`, and the search target is `"enter"`, output should be `["**enter**","**enter**prise","c**enter**","**en**coun**ter**"]`. `"event"` is not included in the output as it doesn't contain `"enter"` as subsequence.

## Test cases

```
["center","encounter","enter","enterprise","event"]
"enter"
-> ["enter","enterprise","center","encounter"]

["celebration","cooperation","generation","operation","ratio"]
"ratio"
-> ["ratio","celebration","cooperation","generation","operation"]

["combination","explanation","international","nation","national","nomination","notation"]
"nation"
-> ["nation","national","combination","explanation","international","nomination","notation"]

["ever","every","here","very","where"]
"everywhere"
-> []

["interaction","traditional","train","training","transformation"]
"train"
-> ["train","training","interaction","traditional","transformation"]

["condition","confusion","construction","contribution","information","organization","recommendation","transportation"]
"onion"
-> ["condition","confusion","construction","contribution","organization","recommendation"]

["...","---",".-.-.-","..--","-..-"]
"--"
-> ["---","..--",".-.-.-","-..-"]

["#","##","###","####","#####"]
"####"
-> ["####","#####"]

["Another", "example", "with spaces", "and also", "question marks", "...??"]
"a"
-> ["and also", "example", "with spaces", "question marks"]

["/.\\", "...", "><", "[[]]", "~.~", ".1.2", "_[(("]
"."
-> ["...", ".1.2", "/.\\", "~.~"]

["(())", "()()", "((()))", "(())()", "()(())", "()()()"]
"(())"
-> ["(())", "(())()", "((()))", "()(())", "()()()"]

["]["]
"]["
-> ["]["]

["\\", "\\\\", "\\\\\\"] # Input is encoded as JSON, while "\\" means a string with a single backslash
"\\"
-> ["\\", "\\\\", "\\\\\\"]

```

Output from your program may be different from above test cases, as the order of words in same group is not required.

## Rules

## Input / Output

Input / Output are flexible. For example, you may use any reasonable ways including but not limited to:

* You may I/O `string` as
    + Your languages built-in `string` in ASCII or any ASCII compatible encoding (e.g. UTF-8);
    + Your languages built-in `string` in any codepage that supports all printable ASCII characters (e.g. UTF-16);
    + NUL terminated array of characters;
    + array of integers, each integer is the ASCII value of character
    + 0 terminated integer array;
* You may I/O the array of `string` as
    + A collection (`OrderedSet`, `LinkedList`, `Array`, ...; or `HashSet` only for input) of `string`s
    + A character (or ASCII value) matrix with NUL (0) padding at the ending to each short ones;
        - Output matrix may have unnecessarily extra 0 padding;
    + Line break (CR / LF / CRLF) separated single string;
    + JSON encoded array of string

# Answer
# Vyxal, 13 bytes

```
≬ṗ⁰cFsµ₌ǎṗJ⁰ḟ

```

Try it online! Input as `a` then `s`. Inefficient approach.

```
≬             # a 3-element lambda:
 ṗ            #   get all subsets
   c          #   does it contain
  ⁰           #   the last input (s)?
    F         # filter according to lambda
     s        # sort alphabetically (handles ordering of 1 and 2)
      µ       # a sorting lambda:
       ₌      #   parallel apply:
        ǎ     #     substrings (handles 1, 2, and 3)
         ṗ    #     subsets (handles 4)
          J   #   join together
            ḟ #   find the first occurrence of
           ⁰  #   last input

```
> 4 votes

# Answer
# Japt, 16 bytes

Outputs a 2D-array; add 1 byte if that isn't permitted. Works in theory for all tests cases but there is a bug in Japt that prevents it from being able to handle mismatched square brackets in strings within an input array.

```
fÈà øVÃüøV ÔËñbV

```

Try it

```
fÈà øVÃüøV ÔËñbV     :Implicit input of array U & string V
f                    :Filter U by
 È                   :Passing each element through the following function
  à                  :  Combinations
    øV               :  Contains V?
      Ã              :End filter
       ü             :Group & sort by
        øV           :  Contains V?
           Ô         :Reverse
            Ë        :Map
             ñ       :  Sort by
              bV     :    First index of V

```
> 3 votes

# Answer
# Retina, 85 bytes

```
~(L$`^.+
$&¶mN$$`^(.$*$\$&)?.$*¶-$$#1¶mO$$`^(.$*?)$\$&.$*¶$$1
\G.
$\$&.$*
^
0A`¶O`¶G`

```

Try it online! Takes the keyword as the first line and the search strings on the remaining lines. Explanation:

```
~(`

```

Evaluate the output of the rest of the program on the original input.

```
L$`^.+

```

Match just the keyword but replace the entire input with...

```
$&¶mN$$`^(.$*$\$&)?.$*¶-$$#1¶mO$$`^(.$*?)$\$&.$*¶$$1

```

... the keyword followed by two sort commands (see below).

```
\G.
$\$&.$*

```

Escape the keyword and insert `.*` between each escaped character.

```
^
0A`¶O`¶G`

```

Prefix two commands to the keyword and turn the keyword into a filter command.

For the example of the input keyword of `train`, the program that gets evaluated is as follows:

```
0A`
O`
G`t.*r.*a.*i.*n.*
mN$`^(.*train)?.*
-$#1
mN$`^(.*?)train.*
$.1

```

Explanation:

```
0A`

```

Delete the keyword.

```
O`

```

Sort the input. (This ensures that `train` appears before `training`.)

```
G`t.*r.*a.*i.*n.*

```

Filter for strings that have `train` as a subsequence.

```
mN$`^(.*train)?.*
-$#1

```

Sort strings that contain `train` first.

```
mO$`^(.*?)train.*
$1

```

Sort strings that contain `train` by the (length of the) prefix of the word `train`.
> 2 votes

# Answer
# Python 3, 104 bytes

```
lambda a,s:sorted([i for i in a if all(j in i for j in s)],key=lambda x:(x==s)-(x[:len(s)]==s)-(x in s))

```

I used `sorted` to order the result of the nested `list` comprehension.

Try it online!
> 2 votes

# Answer
# JavaScript (Node.js), 121 bytes

```
s=>a=>a.filter(a=>g(a,s),g=([c,...x],y)=>c?g(x,y.slice(c==y[0])):!y).sort((x,y)=>(g=i=>s==i?-1:i.indexOf(s)>>>0)(x)-g(y))

```

Try it online!

no regex is shorter

# JavaScript (Node.js), ~~133~~ ~~126~~ 125 bytes

```
s=>a=>a.filter(x=>x.match(s.replace(/(\w)|./g,(c,d)=>'.*'+[d||'\\'+c]))).sort((x,y)=>(g=i=>s==i?-1:i.indexOf(s)>>>0)(x)-g(y))

```

Try it online!

Sort equality then the first occurrence
> 1 votes

# Answer
# Charcoal, 50 bytes

```
Ｆθ«≔ηζＦιＦ¬⌕ζκ≔Φζνζ¿¬ζ⊞υ⟦¬№ιη⌕ιηι⟧»≔⟦⟧εＷ⁻υε⊞ε⌊ιＥε⊟ι

```

Try it online! Link is to verbose version of code. Explanation:

```
Ｆθ«

```

Loop through the list of strings.

```
≔ηζ

```

Start with none of the letters of the search keyword found.

```
Ｆι

```

Loop through the letters in the current string.

```
Ｆ¬⌕ζκ

```

If the search keyword starts with the current letter, then...

```
≔Φζνζ

```

... remove the first letter from the copy of the search keyword.

```
¿¬ζ

```

If the search keyword is now empty, then...

```
⊞υ⟦¬№ιη⌕ιηι⟧

```

... push a list of three terms to the predefined empty list: i) a flag that is zero if the keyword is contained in the string rather than just a subsequence ii) the position of the keyword in the string iii) the string.

```
»≔⟦⟧εＷ⁻υε⊞ε⌊ι

```

Sort the matches.

```
Ｅε⊟ι

```

Output just the strings.
> 1 votes

# Answer
# JavaScript (ES10), 126 bytes

*-7 thanks to @tsh*

Expects `(array)(string)`.

```
a=>s=>[`^${q=s.replace(/\W/g,'\\$&')}$`,"^"+q,q,q.replace(/\\?./g,'.*$&')].flatMap(e=>a.filter(s=>a[0+s]?0:a[0+s]=s.match(e)))

```

Try it online!

Escaping characters in the regular expressions costs  ~~41~~  34 bytes ... :'(
> 1 votes

# Answer
# 05AB1E, 16 bytes

```
ʒæIå}ΣηR¬œ€Œ˜«Ik

```

Try it online. (Way too slow for a test suite of all test cases.)

**Explanation:**

```
ʒ             # Filter the first (implicit) input-list by:
 æ            #  Get the powerset of the current word
  Iå          #  Check if the second input is in this list
}Σ            # After the filter, sort by:
  η           #  Get the prefixes of the current word
   R          #  Reverse this list
    ¬œ        #  Get the permutations of the current word as well
      €Œ      #  Get the substrings of each permutation
        ˜     #  Flatten this list
         «    #  Merge the two lists together
          Ik  #  Get the index of the second input in this list
              # (after which the filtered and sorted list of words is output implicitly)

```

Try just `ηR¬œ€Œ˜«` online to see how its order corresponds to the order of \\$1\\$ through \\$4\\$.
> 1 votes

# Answer
# Haskell, 137 bytes

```
import Data.List
o s a=map snd.filter((<0).fst)$sort[(-length(
 takeWhile($x)[isSubsequenceOf s,isInfixOf s,isPrefixOf s,(==)s]),x)|x<-a]

```

Try it online!
> 0 votes

# Answer
# Raku, 98 bytes

```
{$^s;@^a.grep(/<{S:g[(\W)|.]='\\'x?$0~$/~'.*'
given $s}>/).sort:{first :k,$_~~*,$s,/^$s/,/$s/,!0}}

```

Try it online!

I'm dismayed to learn that Raku has lost Perl 5's `quotemeta` function and `\Q` quoting construct. Reproducing the concept cost many bytes.

Anyway...

* The functions arguments are passed in the placeholder variables `@^a` (the list of strings) and `$^s` (the search keyword).
* The `grep` call on `@^a` filters the list to those elements in which the search keyword appears as a subsequence. This is done by transforming the search keyword into a new string by prefixing every non-word character with a backslash and appending a `.*` to every character.
* Then `sort` sorts the remaining strings. The sort function is `first :k, $_ ~~ *, $s, /^$s/, /$s/, !0`. This returns the index (due to the `:k` flag) of the first of `$s`, `/^$s/`, `/$s/`, or `!0` (a shorter way to write `True`) against which the current word smart-matches. The current word matches the string `$s` if it's the same as the search keyword, matches the regex `/^$s/` if the search keyword appears at the start of the string, matches the regex `/$s/` if the search keyword appears anywhere inside the string, and always matches `True`.
> 0 votes

# Answer
# Wolfram Language (Mathematica), 113 bytes

```
(s=#2;SortBy[Select[#1,StringContainsQ[#,s]&],(d=Last@LongestCommonSequencePositions[s,#];{Length@d,First@d})&])&

```

Try it online!

Thank you for the interesting challenge, golf it on Mathematica is hard, but I tried (-\_-)
`LongestCommonSequencePositions` is one of longest function names in WM 8)
> 0 votes

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


# Question
Title: Write a Program that Writes a function BUT in a different language!
Write the shortest program that takes one input (n) from STDIN (or equivalent) and outputs a simple incrementing function with one argument (x) that returns x + n but the function must be in a different language. Pretty simple!

**This is code-golf, normal rules apply, shortest program wins.**

Example: \>\<\> to Python (Ungolfed)

```
!v"def i(x):"a"    return x+"ir!
 >l?!;o

```

Input:

```
3

```

Output:

```
def i(x):
    return x+3

```

EDIT: Anonymous functions and lambda expressions are allowed!

# Answer
> 26 votes
# GS2 → K, 2 bytes

```
•+

```

This prints a tacit, monadic function. The source code uses the CP437 encoding. Try it online!

## Test run

```
$ xxd -c 2 -g 1 sum-func.gs2
00000000: 07 2b  .+
$ printf 42 | gs2 sum-func.gs2
42+
$ kona
K Console - Enter \ for help

  (42+) 69
111
  f : 42+
42+
  f 69
111

```

## How it works

### GS2

* GS2 automatically reads from STDIN and pushes the input on the stack.
* indicates that the next byte is a singleton string literal.
* Before exiting, GS2 prints all stack items.

### K

Left argument currying is automatic in K.

Here, `n+` turns the dyadic function `+` into a monadic function by setting its left argument to `n`.

# Answer
> 16 votes
# ShapeScript → J, 4 bytes

```
"&+"

```

This prints a tacit, monadic verb. Try it online: ShapeScript,

## Test run

```
$ cat sum-func.shape; echo
"&+"
$ printf 42 | shapescript sum-func.shape; echo
42&+
$ j64-804/jconsole.sh
   42&+ 69
111
   f =: 42&+
   f 69
111

```

## How it works

### ShapeScript

* ShapeScript automatically reads from STDIN and pushes the input on the stack.
* `"&+"` pushes that string on the stack.
* Before exiting, ShapeScript prints all stack items.

### J

`&` performs argument currying.

Here, `n&+` turns the dyadic verb `+` into a monadic verb by setting its left argument to `n`.

# Answer
> 12 votes
# GolfScript → CJam, 4 bytes

```
{+}+

```

This prints a code block (anonymous function). Try it online: GolfScript, CJam

## Test run

```
$ cat sum-func.gs; echo
{+}+
$ printf 42 | golfscript sum-func.gs
{42 +}
$ cjam
> 69 {42 +} ~
111
> {42 +}:F; 69F
111

```

## How it works

### GolfScript

* GolfScript automatically reads from STDIN and pushes the input on the stack.
* `{+}` pushes that block on the stack.
* `+` performs concatenation, which happily concatenates a string and a block.
* Before exiting, GolfScript prints all stack items.

### CJam

`{n +}` is a code block that, when executed, first pushes `n` on the stack, then executes `+`, which pops two integers from the stack and pushes their sum.

# Answer
> 11 votes
# BrainF\*** to JavaScript ES6, 57 bytes

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

```

(Assumes that the input is composed of numeric characters)

Say `1337` is your input. Then, this would compile to:

```
x=>x+1337

```

# Answer
> 10 votes
# R to Julia, 19 bytes

```
cat("x->x+",scan())

```

This reads an integer from STDIN using `scan()` and writes an unnamed Julia function to STDOUT using `cat()`. The Julia function is simply `x->x+n`, where `n` comes from the R program.

# Answer
> 10 votes
# Rotor to K, 2 bytes

```
'+

```

Might as well jump in on the K bandwagon.

# Answer
> 9 votes
# to K, 5 bytes

```
i'++o
```

Thanks to **@kirbyfan64sos**

Another version using features added after the challenge was created.

```
i'+
```
* Gets input, pushes to stack
* Pushes '+' as a string
* Outputs stack contents

# Answer
> 9 votes
# Malbolge to JavaScript ES6, 71 bytes

```
('&%@9]!~}43Wyxwvutsr)Mon+HGi4~fBBdR->=_]:[875t4rT}0/Pf,d*((II%GEE!Y}Az

```

It's always fun to generate Malbolge code.

# Answer
> 9 votes
# Minecraft 1.8.7 to K, ~~7~~ 6 + 33 + 27 + 62 = ~~129~~ 128 Bytes

This is using this version of byte counting.

Command blocks (going from left to right):

```
scoreboard objectives add K dummy
```

```
scoreboard players set J K <input>
```

```
tellraw @a {score:{name:"J",objective:"K"},extra:[{text:"+"}]}
```

This could probably be golfed a little more, but it's fairly simple: generate a variable `J` with the objective `K` and set its score for that objective to the input (there is no STDIN - I figured this was close enough). Then, after a tick, output the score of the variable `J` for the objective `K` followed by a `+`. Easy peasy.

# Answer
> 8 votes
## Seriously to Python, 15 bytes

`,"lambda n:n+"+`

Expects input to be in string form, i.e. `"3"`

Explanation:

```
,: read value from input
"lambda n:n+": push this literal string
+: concatenate top two values on stack

```

Try it online (you will have to manually enter the input because the permalinks don't like quotes)

# Answer
> 7 votes
# Pyth to APL, ~~7~~ 5 bytes

```
+z"--

```

The Pyth code simply concatenates the input (`z`) with the string `"--"`. This creates an unnamed monadic train in APL with the form `n--`, where `n` comes from Pyth. When calling it in APL, `(n--)x` for some argument `x` computes `n--x = n-(-x) = n+x`.

Try: Pyth, APL

Saved 2 bytes thanks to Dennis!

# Answer
> 6 votes
# rs -\> K, 2 bytes

```
/+

```

Live demo.

# Answer
> 5 votes
# Mouse to Ruby, 19 bytes

```
?N:"->x{x+"N.!"}"$

```

Ungolfed:

```
? N:       ~ Read an integer from STDIN, store in N
"->x{x+"   ~ Write that string to STOUT
N. !       ~ Write N
"}"$       ~ Close bracket, end of program

```

This creates an unnamed Ruby function of the form `->x{x+n}` where `n` comes from Mouse.

# Answer
> 5 votes
## \>\<\> to Python, 25 + 3 = 28 bytes

```
"v+x:x adbmal
o/?(3l
;>~n

```

Takes input via the `-v` flag, e.g.

```
py -3 fish.py add.fish -v 27

```

and outputs a Python lambda, e.g. `lambda x:x+27`.

For a bonus, here's an STDIN input version for 30 bytes:

```
i:0(?v
x+"r~/"lambda x:
o;!?l<

```

# Answer
> 5 votes
# Mathematica to C#, 22 bytes

```
"x=>x+"<>InputString[]

```

Outputs a C# `Func<int, int>` of form

```
x=>x+n

```

# Answer
> 5 votes
# Haskell to Mathematica, 14 bytes

```
(++"+#&").show

```

# Answer
> 4 votes
# Pyth -\> K, 4 bytes

```
+z\+

```

K is really easy to abuse here...

Live demo.

# Answer
> 4 votes
# Brainfuck to Java, 273

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

Outputs a method like `int d(int i){return i+42;}` (which doesn't *look* like a Java method, but... Java!)

# Answer
> 3 votes
# POSIX shell to Haskell, 19 bytes

```
read n;echo "($n+)"

```

Anonymous functions being allowed, Haskell is a good output choice with the operator sections.

# Answer
> 3 votes
# Python 2 to CJam, ~~18~~ 20 bytes

*Thanks to LegionMammal978 for correcting the functionality.*

```
print"{%f+}"%input()

```

The Python does a basic string format. `%f` is the code for a float, and since I wouldn't lose any bytes for handling floats, I went ahead and did so.

The CJam is much the same as the Golfscript-\>CJam answer. It looks something like this:

```
{7.4+}

```

or:

```
{23+}

```

It's a block that takes the top value off the stack, pushes the special number, then adds them.

# Answer
> 3 votes
# PHP → JavaScript (ES6), 20 ~~24~~ bytes

Reading from *STDIN* is always expensive in PHP. It looks a bit strange:

```
x=>x+<?fgets(STDIN);

```

It prints `x=>x+` and waits for user input to complete the string, terminates with the complete anonymous JavaScript function, e.g. `x=>x+2`.

**First version (24 bytes**)

```
<?='x=>x+'.fgets(STDIN);

```

# Answer
> 3 votes
# JavaScript to Lambda Calculus, 39 bytes

(This uses the linked document as a basis.)

```
alert((x=>`λa(${x}(add a))`)(prompt()))

```

Say input is `5`. Then this becomes:

```
"λa(5(add a))"

```

# Answer
> 3 votes
# Retina to Pip, 4 bytes

Uses one file for each of these lines + 1 penalty byte; or, put both lines in a single file and use the `-s` flag.

```
$
+_

```

Matches the end of the input with `$` and puts `+_` there. This results in something of the form `3+_`, which is an anonymous function in Pip.

# Answer
> 3 votes
# Bash → C/C++/C#/Java, 33 bytes

and maybe others

```
echo "int f(int a){return a+$1;}"

```

# Answer
> 3 votes
## Tiny Lisp to Ceylon, ~~68~~ 61

```
(d u(q((n)(c(q(Integer x))(c(q =>)(c(c(q x+)(c n()))()))))))

```

Tiny Lisp doesn't have real input and output – it just has expression evaluation. This code above creates a function and binds it to `u`. You can then call `u` with the argument `n` like this: `(u 7)`, which will evaluate to this Tiny Lisp value:

```
((Integer x) => (x+ 7))

```

This is a valid Ceylon expression, for an anonymous function which adds 7 to an arbitrary integer.

*Thanks to DLosc for an improvement of 7 bytes.*

# Answer
> 2 votes
# Microscript II to Javascript ES6, 9 bytes

```
"x=>x+"pF

```

# Answer
> 2 votes
# GNU sed to C, 46 bytes

```
sed -r 's/^([0-9]+)$/f(int x){return x+\1;}/'

```

# Answer
> 2 votes
# Vitsy to K, 5 Bytes

\o/ K will be being used very soon if it can do this.

```
N'+'Z
```

or maybe...

```
N'+'O
```

If the input is taken as a string (only for 0-9 input)...

```
i'+'Z
```

All of these, for input 2, will output:

```
2+
```

# Answer
> 2 votes
## Ceylon to Tiny lisp, 76

```
shared void run(){print("(q((x)(s ``process.readLine()else""``(s 0 x))))");}

```

This produces (after reading a line of input) output like `(q((x)(s 5(s 0 x))))`, which evaluates in Tiny Lisp to `((x) (s 5 (s 0 x)))`, a function which takes an argument `x`, subtracts it from 0, and subtracts the result from 5. (Yeah, this is how one adds in Tiny Lisp, there is only a subtraction function build in. Of course, one could define an addition function first, but this would be longer.)

You can use it like this as an anonymous function:

```
((q((x)(s 5(s 0 x)))) 7)

```

(This will evaluate to 12.)

Or you can give it a name:

```
(d p5 (q((x)(s 5(s 0 x)))))
(p5 7)

```

*Corrections and Golfing Hints from DLosc, the author of Tiny Lisp.*

# Answer
> 2 votes
# JaptTeaScript, 5 bytes

```
U+"+x

```

This is pretty simple.

---

### Explanation

```
U+     // Input added to the string...
  "+x  // This is the string

```

# Answer
> 2 votes
# Fith to Forth, 28 bytes (non-competitive)

*Fith was created after the challenge was posted.*

```
": p " line " + ;" + + .

```

This pushes the first part, then reads the number, then pushes the last part. The two `+` words then concatenate the three strings, and `.` prints.

The output looks something like this:

```
: p 7 + ;

```

This defines a function named `p`, and as far as I know, it is the shortest method in Forth to define the necessary function.

# Answer
> 2 votes
# Python 3 to 05AB1E, 14 bytes

```
lambda n:n+'+'

```

Try it online! Takes a string as input.

The Python function simply returns `'n+'`, where `n` is the input. In 05AB1E, pushes implicit input, push `n`, add them, and implicitly output.

# Answer
> 2 votes
# KnightSquire, 13 bytes

```
O+"\(x)=>x+"P

```

Attempt This Online!

Knighting this code will inquire thee, in which thou shalt enscribe numerals on thine keyboard. Whilst one can be a jest and use Arabic numerals, true royalties use Roman numerals, such as \\$\text{CCCXIV}\\$ (that's 314 for you jests). (It doesn't matter as it is string concatenation - Squire parses both).

Upon striking the return key, the following journey shall be proclaimed:

```
\(x)=>x+CCCXIV

```

Some foreigners might entitle this as an 'anonymous lambda' but true Squire users lack this brash peasant vocabulary.

Squire program

```
f=\(x)=>x+CCCXIV
# embark and proclaim
proclaim(f(X)) # CCCXXIV (314 + 10 = 414)

```

# Answer
> 1 votes
# Chaîne to JavaScript ES6, 7 bytes

Again, assumes numeric input.

```
x=>x+{i
~~~~~~~
x=>x+   ; write that text
     {  ; command sequence
      i ; read input and push to stack
        ; implicit: take top entry on stack and pushes it to writing string
        ; implicit: close }
        ; implicit: print string

```

# Answer
> 1 votes
## Powershell to EmacsLisp, 37 bytes

```
function p($a){"(defun p(x)(+ $a x)"}

```

## EmacsLisp to Powershell, 44 bytes

```
(defun p(x)(format"function p($a){%s+$a}"x))

```

# Answer
> 1 votes
# Python to C++, ~~49 bytes~~ 39 bytes

```
print"[](int x){return x+%d;}"%input()

```

Thanks @Mego !

Basically, this prints out lambda with the argument x and adds it to the input of the Python program.

# Answer
> 1 votes
# Javascript (ES6) \> PHP/Javascript, ~~38~~ ~~48~~ 47 bytes

This code is an anonymous function that creates a **VALID** PHP and Javascript function called `anonymous`.

```
P=prompt;P(Function('$x',`return $x+${P()};`));

```

As of the writting of this code, only Firefox has implemented ES6 nativelly (without flags and suchs).

This code uses the `prompt()` function to request input and for output. Firefox supports copying the output of `prompt()`, making this a legitime output method for Javascript.

---

Considerations:

* The `;` at the end is required for PHP
* The space in `return $x` is required by Javascript
    + Ignoring it will say that `return$x` is undefined
* The function name is automatic: I have no choice over it
* Picking only PHP or only Javascript will only reduce the code in 1 byte, and would reduce the fun-factor by half
* May work with other languages

---

Old answer (48 bytes):

```
alert(Function('$x',`return $x+${prompt()};`));

```

Old invalid answer:

```
y=>''+Function('$x',`return $x+${y};`)

```

# Answer
> 1 votes
# Ruby to Thue, 139 bytes

Not as short as i thought it should be, but I will post anyway. Thue may not be the best language for golfing in.

```
10.times{|n|puts "#{n}+::=#{n==9?'+':''}#{(n+1)%10}\n#{n}|::=|*#{n}\n>#{n}::=~#{n}"};puts "_::=:::\n||::=<\n<*::=<>\n::=\n|_#{'+'*($*[0]).to_i}|"

```

Takes a command-line augment in ruby, and regular input in Thue.

# Answer
> 1 votes
## Seriously to K, 4 bytes

```
'+,+

```

Everyone else is posting "to K" answers, I might as well too. Takes input in the form of a string (`"3.14"`).

Try it online

# Answer
> 1 votes
# Python to Lisp - ~~34~~ 36 Bytes

```
print"(lambda (x) (+ x %s))"%input()

```

# Answer
> 1 votes
# Go → LOLCODE, 192 bytes

```
package main;import."fmt";func main(){a:="";Scanln(&a);Println("HAI1.3\nHOW IZ I ADDIN YR X\nI HAS A VAR\nVAR R SUM OF X AN "+a+"\nVISIBLE VAR\nIF U SAY SO\nKTHXBYE")}

```

the resulting output compiles with `lci`.

# Answer
> 1 votes
# Python3 → Go, 89 bytes

```
print('package main;import"fmt";func main(){a()};func a(x int)int{fmt.Println(x+'+input()+')}')

```

also a full program which compiles/runs with any of `go build`, `go install` or `go run`.

if we allow just a function (which is an error/will not compile) then **47 bytes**:

```
print('func a(x int)int{return x+'+input()+'}')

```

# Answer
> 1 votes
# Go → Python (any version), 109 bytes

```
package main;import"fmt";func main(){var a string;_,_=fmt.Scanln(&a);fmt.Println("def a(x):\n return x+"+a)}

```

# Answer
> 1 votes
# Java (OpenJDK 8) -\> Python 3, ~~155~~ 153 bytes

```
import java.util.Scanner;class Main{public static void main(String[] args){Scanner s=new Scanner(System.in);System.out.println("lambda x:x+"+s.next());}}

```

Try it online!

Not exactly a winning combination but it gave me a chance to practice using java.

Saved 2+ bytes thanks to @WheatWizard

# Answer
> 1 votes
# 05AB1E to , 4 bytes

```
„&+«

```

Try it online!

# Answer
> 1 votes
# C (gcc) to Python, 85 57 50 bytes

Borrowing @Oskar Skog's suggestions

```
main(n){scanf("%d",&n);printf("lambda m:m+%d",n);}

```

# Python 3 to C (gcc), 43 bytes

```
print('i(p){printf("%d",p+'+input()+');}')

```

## Joke answers (I couldn't hold myself back)

### 1. C (gcc) to C (gcc), 66 bytes

> `main(n){scanf("%d",&n);printf("i(p){printf('%s',p+%d);}","%d",n);}`

### 2. Python 3 to Python 3, 30 bytes

> `print(f"lambda n:n+{input()}")`

# Answer
> 1 votes
# Ruby to Myby, 14 bytes

```
$><<"+&"+$**""
```

```
C:\Myby>ruby -e "$><<'+&'+$**''" 3 > out  && myby -l out 3
Nibbles: 4A 03
4 nibbles, 2 bytes
6

```

Myby is exactly J in this case, where one can bond an argument to a dyadic verb to create a monadic verb.

# Answer
> 1 votes
# Nibbles to Husk, 2 bytes (4 nibbles)

```
"+"$

```

Outputs the Husk function `+2` for input `2`.
Try the Husk function online

---

# Husk to Nibbles, 4 bytes

```
:'+s

```

Try it online!

Outputs the Nibbles function `+2` for input `2`. Here's a Nibbles program that uses this function to add 2 to every elemnt of the input:

```
.$ +2
.$      # map over every element of the input
   +2   # using the function '+2'

```

# Answer
> 1 votes
# Charcoal to Vyxal, 2 bytes

```
θ+

```

Try it online!

Takes input (for example 5) on stdin. Outputs `5+`, which adds 5 to the input when run as vyxal.

# Answer
> 0 votes
# C# to Mathematica, ~~85~~ 81 bytes

```
using C=System.Console;class C{static void Main(){C.Write(C.ReadLine()+"+#&");}}

```

Outputs a Mathematica `Function` of form

```
n+#&

```

# Answer
> 0 votes
# Pyth to C++, 32 bytes

```
%"[](int x){return x+%d;}"Q

```

Just a Pyth version of my Python one.

# Answer
> 0 votes
# Python to Pyth, 20 bytes

```
print"L+%db"%input()

```

Basically, it prints out a lambda function (L) that takes in the argument (b, implicit variable) and adds the input from the Python program.

# Answer
> 0 votes
# Batch, 8 bytes

```
echo;%1+

```

Fun fact: you don't have to use a space to separate `echo` from the text to be echo-ed, but you can pick from a whole series of different characters. For example: `.`, `,`, `:`, `;` and some others.

# Answer
> 0 votes
## QBIC to Jelly, 6 bytes

```
;?A+@+

```

Given `n=3`, this will output the Jelly code `3+`. When another number is passed to this link, it will add 3 to it. Try that online!

The QBIC code:

```
;   Read cmd line param as A$
?A  PRINT A$
+@+ plus the string literal '+'
    The string literal is auto-closed by QBIC at EOF.

```

# Answer
> 0 votes
# Java -\> C (GCC) ~~144~~ 134 bytes

```
class m{public static void main(String[]a){System.out.print(String.format("a(b){return %s+b;}",a[0]));}}

```

Takes the number(string, it is supposed to be a number, no error checking) as the first argument and prints the function to stdout.

# Answer
> 0 votes
# Clojure -\> JavaScript, 14 bytes

```
#(str"a=>a+"%)

```

An anonymous function in Clojure that returns an anonymous function in JavaScript (and potentially a few other languages). `%` is the implicit `n`.

```
(#(str"a=>a+"%) 3)

"a=>a+3"

```

# Answer
> 0 votes
# Haskell -\> Clojure, 25 bytes

```
\n->"#(+ % "++show n++")"

```

Anonymous Haskell function which takes `n`, and returns an anonymous Clojure function.

```
let f = \n->"#(+ % "++show n++")"

f 3

#(+ % 3)

```

# Answer
> 0 votes
# sB~ -\> Befunge, 7 bytes

```
iN?N;`+

```

Explained:

```
i N 'input N
?N;`+ 'print N and "+"

```

# Answer
> 0 votes
# Keg to Vyxal, 3 bytes

```
᠀\+

```

Try it online!

This takes the input at a string, pushes a plus sign, and outputs everything on the stack. It prints `<input>+`, which adds the input to a number in Vyxal.

# Answer
> 0 votes
# dc to Haskell, 12 bytes

```
?[+)][(]nrnn

```

Try it online!

Could be -1 byte if input can be taken on the stack, instead of prompting the user.

# Answer
> 0 votes
# Japt to JavaScript, 9 bytes

Takes input as an integer string

```
i+i¨ÔiÍin

```

Try it

It was only 2 bytes longer than the boring literal string version (below), so why not?!

```
i"n=>n+

```

Try it

And going the other way, from JS to Japt is only 8 bytes:

```
n=>"+"+n

```

Try it online!

# Answer
> 0 votes
# FactorRed, 24 bytes

```
[ [I func[x][x +${}]I] ]

```

Attempt This Online!

# Answer
> 0 votes
# Phooey -\> ARM Thumb machine code, 7 bytes

```
$c."0pG

```

Try it online!

```
$c."0pG
$c       print char value of...
  .      ...an integer from stdin
   "0pG  then print "0pG"

```

Works with values 0-255, with integers typed in base 10.

This will encode to `NN 30 70 47`, which results in the following Thumb code:

```
    .syntax unified
    .globl func
    .thumb_func
    // c callable
    // int func(int x);
func:
    // add N to r0   NN 30   .0
    adds    r0, #N
    // return        70 47   pG
    bx      lr

```

# Answer
> 0 votes
# Go to Forth, 78 bytes

```
package main
import."fmt"
func main(){x:="";Scanln(&x);Printf(": N %s + ;",x)}

```

Attempt This Online!

Outputs a word `: N x + ;` that expects an integer on the stack, and adds it to the input.

## Joke Answers

### Go to Go, 95 bytes

```
package main
import."fmt"
func main(){x:="";Scanln(&x);Printf("func(n int)int{return n+%s}",x)}

```

Attempt This Online!

Outputs an anonymous Go function `func(n int)int{return n+x}`.

### Go returning a function, 114 bytes

```
import(."fmt";."strconv")
func f()func(int)int{x,n:="",0
Scanln(&x)
n,_=Atoi(x)
return func(k int)int{return k+n}}

```

Attempt This Online!

Returns a Go function.

# Answer
> 0 votes
# Thunno 2Jelly, 3 bytes

```
'++

```

Attempt This Online! (Thunno 2 program)

Try it online! (Jelly function)

The Thunno 2 program appends `+` to the input.

---
Tags: code-golf
---


title: String to Binary

text:
# Question
Title: String to Binary
This is a code golf challenge. Just like the title says, write a program to covert a string of ascii characters into binary.

For example:

`"Hello World!"` should turn into `1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100 100001`.

Note: I am particularly interested in a pyth implementation.

# Answer
# CJam, 8 bytes

```
l:i2fbS*

```

Easy-peasy:

```
l:i           "Read the input line and convert each character to its ASCII value";
   2fb        "Put 2 on stack and use that to convert each ASCII value to base 2";
      S*      "Join the binary numbers by space";

```

Try it here
> 13 votes

# Answer
# Python 3, 41 bytes

```
print(*[bin(ord(x))[2:]for x in input()])

```

Like KSFT's answer, but I thought I'd point out that, in addition to `raw_input -> input`, Python 3 also has an advantage here due to the splat for `print`.
> 14 votes

# Answer
# Pyth, 10 bytes

```
jdmjkjCd2z

```

Python mapping and explanation:

```
j           # join(                               "Join by space"
 d          #      d,                             "this space"
 m          #      Pmap(lambda d:                 "Map characters of input string"
  j         #                    join(            "Join by empty string"
   k        #                        k,           "this empty string"
    j       #                        join(        "This is not a join, but a base conversion"
     C      #                             Pchr(   "Convert the character to ASCII"
      d     #                                  d  "this character"
            #                                 ),
     2      #                             2       "Convert to base 2"
            #                            )
            #                        ),
  z         #           z)))                      "mapping over the input string"

```

Input is the string that needs to be converted without the quotes.

Try it here
> 9 votes

# Answer
# MITS Altair 8800, 0 bytes

Input string is at memory address `#0000H` (allowed). Output in binary via front panel I/O lights `D7-D0`.

Example, do `RESET`, then `EXAMINE` to see the first byte, followed by repeating `EXAMINE NEXT` to see the rest.

`"H" = 01 001 000:`

`"e" = 01 100 101:`

`"l" = 01 101 100:`

Try it online!

Non-competing, of course. :)
> 5 votes

# Answer
# Python 3 - 43 bytes

---

```
print(*map("{:b}".format,input().encode()))

```

No quite the shortest, but an interesting approach IMO. It has the added advantage that if the number of significant bits varies, E.G. `Hi!`, padding with zeros is trivial (2 more bytes, as opposed to 9 for `.zfill(8)`):

```
print(*map("{:08b}".format,input().encode()))

```
> 4 votes

# Answer
# Python - 52

```
print" ".join([bin(ord(i))[2:]for i in raw_input()])

```

~~I'll work on translating this into Pyth.~~ Someone else did a Pyth answer already.

If you don't care about it being a full program or about I/O format and use Python 3, you can do it in 23 bytes like this:

```
[bin(ord(i))for i in x]

```

`x` is the input.

I know this doesn't count because the interpreter wasn't released before the challenge was posted, but here it is in KSFTgolf:

```
oan

```
> 3 votes

# Answer
# Ruby, ~~34~~ ~~28~~ 24 bytes

```
$<.bytes{|c|$><<"%b "%c}

```

Takes input via STDIN. 6 bytes saved thanks for AShelly and another 4 thanks to britishtea.
> 3 votes

# Answer
# PowerShell, ~~63~~ ~~59~~ 46 bytes

-13 bytes thanks to @mazzy

```
"$($args|% t*y|%{[Convert]::ToString(+$_,2)})"

```

Try it online!
> 3 votes

# Answer
# Forth (gforth), 45 bytes

```
: f 0 do dup i + c@ 2 base ! . decimal loop ;

```

Try it online!

### Code Explanation

```
: f           \ start a new word definition
  0 do        \ start a loop from 0 to string length - 1
    dup i +   \ duplicate the address and add the loop index to get addr of current character
    c@        \ get the character at that address
    2 base !  \ set the base to binary
    .         \ print the ascii value (in binary)
    decimal   \ set the base back to decimal
  loop        \ end the loop
;             \ end the word definition

```
> 3 votes

# Answer
# JavaScript ES6, 63 65 bytes

```
alert([for(c of prompt())c.charCodeAt().toString(2)].join(' '))

```

This is rather long, thanks to JavaScript's long function names. The Stack Snippet below is the rough ES5 equivalent, so it can be run in any browser. Thanks to edc65 for the golfing improvements.

```
alert(prompt().split('').map(function(e){return e.charCodeAt().toString(2)}).join(' '))
```
> 2 votes

# Answer
# Matlab

This is an anonymous function

```
f=@(x) dec2bin(char(x))

```

usage is `f('Hello World')`.

Alternatively, if `x` is defined as the string `Hello World!` in the workspace, then just `dec2bin(char(x))` will work.
> 2 votes

# Answer
# J - 9

```
1":#:3&u:

```

No idea how to make this in a row without doubling the length of the code, I need J gurus to tell me :)

```
1":#:3&u:'Hello world!'
1001000
1100101
1101100
1101100
1101111
0100000
1110111
1101111
1110010
1101100
1100100
0100001

```
> 2 votes

# Answer
# Java - 148 Bytes

```
public class sToB{public static void main(String[] a){for(int i=0;i<a[0].length();i++){System.out.print(Integer.toString(a[0].charAt(i) ,2)+" ");}}}

```

Edited to include full file
> 2 votes

# Answer
# Scala - 59 \- 55 Bytes

```
readLine().map(x=>print(x.toByte.toInt.toBinaryString))

```

Normally, one should use foreach and not map.
> 2 votes

# Answer
# Python 3.6, 39 bytes

```
print(*[f'{ord(c):b}'for c in input()])

```

Try it online!
> 2 votes

# Answer
# x86-16 machine code, IBM PC DOS, ~~33~~ ~~31~~ 28 bytes

**Binary:**

```
00000000: d1ee ad8a c849 b308 ac92 b000 d0e2 1430  .....I.........0
00000010: cd29 4b75 f5b0 20cd 29e2 ebc3            .)Ku.. .)...

```

**Listing:**

```
D1 EE       SHR  SI, 1          ; point SI to DOS PSP (80H)
AD          LODSW               ; load input string length into AL, SI to 82H
8A C8       MOV  CL, AL         ; set up loop counter
49          DEC  CX             ; remove leading space/slash from char count
        LOOP_CHAR:
B3 08       MOV  BL, 8          ; loop 8 bits
AC          LODSB               ; load next char
92          XCHG AX, DX         ; use DX for bit shift
        LOOP_BIT:
B0 00       MOV  AL, 0          ; clear AL
D0 E2       SHL  DL, 1          ; high-order bit into CF
14 30       ADC  AL, '0'        ; AL = '0' + CF
CD 29       INT  29H            ; write AL to screen
4B          DEC  BX             ; decrement bit counter
75 F5       JNZ  LOOP_BIT       ; loop next bit
B0 20       MOV  AL, ' '        ; display a space
CD 29       INT  29H            ; write AL to screen
E2 EB       LOOP LOOP_CHAR      ; loop next char
C3          RET                 ; return to DOS

```

A standalone PC DOS executable COM file. Input is via command line, output to screen.
> 2 votes

# Answer
# Ruby, 24 bytes

I was hoping to beat Martin Ender, but I only managed to tie him.

Takes input on STDIN; +1 bytes for `-p` flag.

```
gsub(/./){"%b "%$&.ord}

```

Try it online!
> 2 votes

# Answer
# Python 3, 39 bytes

```
print(*[f'{ord(i):b}'for i in input()])

```

Try it online!

Slight improvement over the current leading Python answer
> 2 votes

# Answer
# Vyxal `S`, 3 bytes

```
bƛṅ

```

Try it Online!

Explanation:

```
b    # Convert each letter to a list of bits
 ƛ   # In each list of bits:
  ṅ  #   Join elements
     # 'S' flag - join top of stack with spaces and output

```
> 2 votes

# Answer
# Rust, 47 45 bytes

```
|s:&str|for i in s.bytes(){print!("{:b} ",i)}

```

Try it online!

A closure iterating over the string, converting each character to its ascii number, then printing out it's binary equivalent with `:b`

Turns out you don't need `{}` always to define a closure
> 2 votes

# Answer
# C++ - 119 bytes

Freeing memory? What's that?

```
#include<cstdio>
#include<cstdlib>
int main(int c,char**v){for(*v=new char[9];c=*(v[1]++);printf("%s ",itoa(c,*v,2)));}

```

(MSVC compiles the code with warning)
> 1 votes

# Answer
# Haskell, 65

```
m s=tail$do c<-s;' ':do j<-[6,5..0];show$mod(fromEnum c`div`2^j)2

```

heavy use of the list monad. it couldn't be converted to list comprehentions because the last statements weren't a `return`.
> 1 votes

# Answer
# Tcl, 52 bytes

```
proc B s {binary s $s B* b;regsub -all .{8} $b {& }}

```

Try it online!
> 1 votes

# Answer
# Jelly, 3 bytes

```
OBK

```

Try it online!
> 1 votes

# Answer
# APL (Dyalog), 12 bytes

```
10⊥2⊥⍣¯1⎕UCS

```

Try it online!

Thanks to Adám for help with this solution.
> 1 votes

# Answer
# JavaScript ES6, 71 bytes

```
alert(prompt().split('').map(c=>c.charCodeAt(0).toString(2))).join(' ')

```
> 1 votes

# Answer
# Commodore VIC-20/C64/128 and TheC64Mini, 101 tokenized BASIC bytes

Here is the obfuscated listing using Commodore BASIC keyword abbreviations:

```
 0dEfnb(x)=sG(xaNb):inputa$:fOi=1tolen(a$):b=64:c$=mI(a$,i,1):fOj=0to6
 1?rI(str$(fnb(aS(c$))),1);:b=b/2:nEj:?" ";:nE

```

Here for explanation purposes is the non-obfuscated symbolic listing:

```
 0 def fn b(x)=sgn(x and b)
 1 input a$
 2 for i=1 to len(a$)
 3 let b=64
 4 let c$=mid$(a$,i,1)
 5 for j=0 to 6
 6 print right$(str$(fn b(asc(c$))),1);
 7 let b=b/2
 8 next j
 9 print " ";
10 next i

```

The function `fn b` declared on line zero accepts a numeric parameter of `x` which is `AND`ed with the value of `b`; SGN is then used to convert `x and b` to `1` or `0`.

Line one accept a string input to the variable `a$`, and the loop starts (denoted with `i`) to the length of that input. `b` represents each bit from the 6th to 0th bit. `c$` takes each character of the string at position `i`.

line 5 starts the loop to test each bit position; `right$` is used in line 6 to remove a auto-formatting issue when Commodore BASIC displays a number, converting the output of `fn b` to a string; `asc(c$)` converts the current character to its ascii code as a decimal value.

Line 7 represents the next bit value. The loop `j` is ended before printing a space, then the last loop `i` is ended.
> 1 votes

# Answer
# \>\<\>, 34 bytes

```
i\~48*o
?\:0(?;:2%:}-2,:0=
?\{nl1=

```

Try it online!
> 1 votes

# Answer
# 05AB1E, 4 bytes

```
Çbðý

```

Try it online.

**Explanation:**

```
Ç     # Convert the (implicit) input-string to a list of unicode values
 b    # Convert each integer to a binary string
  ðý  # Join by spaces (and output the result implicitly)

```

Could be just the first two bytes if a list output is allowed, or 3 bytes with `»` if a newline delimiter instead of space delimiter is allowed.
> 1 votes

# Answer
# Perl 5, 21 bytes

```
printf'%b ',ord for@F

```

Try it online!
> 1 votes

# Answer
# Gaia, 4 bytes

```
ċb¦ṡ

```

Pretty happy with this

# How it works

```
ċ   Get a list of all the code points in the input string
b¦  Convert every number in that list to binary
ṡ   Joins the element of the list with spaces
Implicit Output

```

Try it Online!
> 1 votes

# Answer
# Zsh `--extendedglob`, 30 bytes

```
<<<${1//(#m)?/$[[##2]#MATCH] }

```

Try it online!

`//`Replace every `(#m)` matched `?` single character with its binary representation. `[#2]` leaves a `2#` prefix on, `[##2]` strips it.

---

# Zsh, ~~43~~ 36 bytes

```
for c (${(s::)1})printf $[[##2]#c]\

```

~~Try it online! Try it online!~~ Try it online!

```
for c (${(s::)1})                           # for character in string $1   (e.g. H)
                       $[       ]          # arithmetic evaluation
                       $[     #c]          # get character code           (e.g. 72)
                       $[[##2]#c]          # convert to base 2            (e.g. 1001000)
               printf  $[       ]\    # append space, print

```

---

If all binary strings need to be 8 characters long, **+5 bytes**:

```
for c (${(s::)1})printf %08d\  $[[##2]#c]

```

Try it online!
> 1 votes

# Answer
# Shakti, ~~8~~ 3 bytes

In 2020.02.19:

```
10/2\`c?

```

Example:

```
 10/2\`c?"Hello World!"
1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100 100001

```

Update: **3 bytes** in 2020.02.23, via Arthur: `2\'`
> 1 votes

# Answer
# JavaScript (V8), 52 bytes

```
a=>[...a].map(p=>p.charCodeAt().toString(2)).join` `

```

Try it online!

Beats all existing JS answers.
> 1 votes

# Answer
# brainfuck, ~~465~~ ~~455~~ ~~443~~ 356 bytes

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

```

Try it online!
> 1 votes

# Answer
# K (ngn/k), ~~12~~ 6 bytes

```
{2\'x}

```

Try it online!

*-6 bytes thanks to @coltim*

Returns a 2D array.
> 1 votes

# Answer
## STATA 158

I used a different approach than most. Read in via the display \_request() prompt (shortened to di \_r(r)). Write the string to a file called b in text mode. Open b in binary mode and read each character as a byte and convert to binary. Technically the b file should be closed at the end, but it is a valid program and runs successfully without it.

```
di _r(r)
file open a using "b",w
file w a "$r"
file close a
file open a using "b",b r
file r a %1bu t
while r(eof)==0 {
loc q=t
inbase 2 `q'
file r a %1bu t
}

```
> 0 votes

# Answer
# Golang - 68

I'm new to Go and I'm not sure on the rules for counting characters in this language on here either.

Imports (11 bytes):

```
import"fmt"

```

Function (55 bytes):

```
func c(s string){for _,r:=range s{fmt.Printf("%b ",r)}}

```

You can run it here.
> 0 votes

# Answer
# Erlang, 71 Bytes

```
f(S)->L=lists,L:droplast(L:flatten([integer_to_list(X,2)++" "||X<-S])).

```

If a trailing whitespace at the end is allowed then

# 55 Bytes

```
f(S)->lists:flatten([integer_to_list(X,2)++" "||X<-S]).

```
> 0 votes

# Answer
Never will C# win these kinds of questions but here's a try, completely without encoding. :)

# C# - 84

```
Console.Write(String.Join(" ",Console.ReadLine().Select(x=>Convert.ToString(x,2))));

```
> 0 votes

# Answer
# Cobra - 64

As a Lambda:

```
do(s='')=(for c as int in s get Convert.toString(c,2)).join(' ')

```
> 0 votes

# Answer
# Postscript, 17 bytes (13 byte program + 4 character command line switch)

```
s { 2 7 string cvrs = } forall

```

Which is 31 bytes in tokenized form: (backticks denote literal characters, everything else is hexidecimal)

```
`s{2 7` 92A5 9230 `=}` 9249

```

Run using Ghostscript as:

```
gs -ss="Hello World!" string-to-binary.ps

```
> 0 votes

# Answer
# JavaScript 78

```
alert(eval('""'+prompt().replace(/./g,"+' '+'$&'.charCodeAt().toString(2)")))

```
> 0 votes

# Answer
# Ruby 38 Bytes

```
p gets.bytes.map{|i|i.to_s 2}.join ' '

```
> 0 votes

# Answer
# Julia, 23 bytes

```
f(n)=[bin(a)for a in n]

```
> 0 votes

# Answer
# q/kdb+, 18 bytes

**Solution:**

```
" "sv"01"0b vs'4h$

```

**Example:**

```
q)" "sv"01"0b vs'4h$"Hello World!"
"01001000 01100101 01101100 01101100 01101111 00100000 01010111 01101111 01110010 01101100 01100100 00100001"

```

**Explanation:**

Convert string to byte array, convert each byte to binary, index into the string `"01"` and then join strings together with whitespace `" "`:

```
" "sv"01"0b vs'4h$ / the solution
               4h$ / cast ($) to type byte (4h)
         0b vs'    / convert each (') byte to binary (0b vs)
     "01"          / (implicit) index into "01" (false;true)
" "sv              / join (sv) with " "

```
> 0 votes

# Answer
# Shell utils, 102 bytes

I'm kind of ashamed of this.

```
xxd -b|sed -r "s/^.*: //;s/  .+$//;s/0*([01]+)/\1/g"|tr \n\r " "|sed -r "s/ +/ /g;s/ *1101 *1010 *$//"

```

Since I'm (possibly) running utilities from various archives across the Internet on Windows, I'll list the version information for each:

```
xxd V1.10 27oct98 by Juergen Weigert
GNU sed version 4.2.1
tr (GNU textutils) 2.0
Microsoft Windows [Version 10.0.15063]

```
> 0 votes

# Answer
# PHP, 59 bytes

```
<?foreach(str_split($argv[1])as$a)echo decbin(ord($a)).' ';

```

Try it online!
> 0 votes

# Answer
# Deorst, 8 bytes

```
vombkE]_

```

Try it online!

## How it works

Example input: `ab`

```
vo       - Map ordinal;      STACK = [[97, 98]]
  mb     - Map binary;       STACK = [['1100001', '1100010']]
    k    - Turn off sort;    STACK = [['1100001', '1100010']]
     E]  - Flatten;          STACK = ['110001', '1100010']
       _ - Join with spaces; STACK = ['110001 1100010']

```
> 0 votes

# Answer
# Java 8, 112 bytes

Takes input as a command line argument

```
interface M{static void main(String[]a){a[0].chars().forEach(i->System.out.print(Long.toBinaryString(i)+" "));}}

```

Try it online!
> 0 votes

# Answer
# Japt `-S`, 4 bytes

```
¬®c¤

```

Try it

```
¬®c¤     :Implicit input input of string U
¬        :Split
 ®       :Map
  c      :  Character code
   ¤     :  To binary string
         :Implicitly join with spaces and output

```

Or, if we can take input as an array of characters ...

## Japt `-mS`, 2 bytes

Try it
> 0 votes

# Answer
# Perl 6, 16 bytes

```
*.ords>>.base(2)

```

Try it online!

Converts the string to codepoints and then each to base 2.
> 0 votes

# Answer
# 05AB1E, 10 bytes

```
SvyÇ2Bнð«?

S           //Split string
 v          //Loop on every character
  y         //Push current character to the stack
   Ç        //Get ASCII value of character
    2B      //Convert to base 2
      н     //Convert from 1-element array to string
       ð«   //Append space
         ?  //Print with no newline

```

Try it online!
> 0 votes

# Answer
# Python 3, 39 bytes

```
for i in input():print(bin(ord(i))[2:])

```

Try it online!
> 0 votes

# Answer
# Elixir 47

```
for c<-:io.read(''),do: :io.fwrite('~.2B ',[c])

```

As function:

```
& for<<c<-&1>>,do: :io.fwrite('~.2B ',[c])

```

As function working on charlists (`'` delimited strings):

```
& for c<-&1,do: :io.fwrite('~.2B ',[c])

```
> 0 votes

# Answer
# Erlang 41

```
[io:fwrite('~.2B ',[C])||C<-io:read("")].

```
> 0 votes

# Answer
# Burlesque, 10 bytes

```
XX{**b2}mw

```

Try it online!

```
XX  # Break into characters
{
 ** # Convert to ascii val
 b2 # Convert to binary
}mw # Map and spaces between elements

```
> 0 votes

# Answer
# PHP, 44 bytes

```
while($c=decbin(ord($argn[$i++])))echo"$c ";

```

Try it online!
> 0 votes

# Answer
# Pip `-s`, 6 bytes

```
TB*A*a

```

Converts to ASCII/Unicode, then to binary. the `-s` flag joins lists on space.

Try it online!
> 0 votes

# Answer
# Husk, 7 bytes

```
wm(ṁsḋc

```

Try it online!
> 0 votes

# Answer
# 05AB1E, ~~2~~ 1 byte

```
b

```

Try it online! Beats all other answers. Takes input as a list of code points.
> 0 votes

# Answer
# Rust, 40 bytes

```
|s|for c in s.bytes(){print!("{:b} ",c)}

```

Try it online!

An anonymous function that takes in an `&str`, iterates over bytes, and prints them as a binary string.
> 0 votes

# Answer
# MUMPS, ~~77~~ 76 bytes

```
r s,! f i=1:1:$l(s) s r=$a($e(s,i)) s b=" " f  s b=(r#2)_b,r=r\2 i r=0 w b q

```

**Example**

```
REPL > r s w ! f i=1:1:$l(s) s r=$a($e(s,i)) s b=" " f  s b=(r#2)_b,r=r\2 i r=0 w b q
Hello World!
1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100 100001

```

**Explanation**

* M is great at keeping things to one line.
* We assign user input to variable `s` and write a newline (`!`).
* For each character in our string, get the ASCII value with `$ascii()` and `$extract()` (intrinsic functions can be abbreviated).
* `b` is meant to hold the binary value of our character, but we will quickly set it to be a space since we need that to separate the binary representation of each character.
* Now we enter an unconditional loop (two spaces after declaring the for loop). We prefix `b` with out ascii value (`r`) modulo 2. You can do string operations on numbers in M.
* We then reduce our ascii value by half, disregarding the remainder (`\` is floor division)
* We do this until our ascii value hits 0, at which point we write our binary value
> 0 votes

# Answer
# Go, 116 bytes

```
package main
import(."fmt";"os";."io/ioutil")
func main(){b,_:=ReadAll(os.Stdin);for c:=range b{Printf("%b ",b[c])}}

```

Try it online!
> 0 votes

# Answer
# Thunno 2 `ṠB`, 1 byte

Attempt This Online!

#### Or, 4 bytes flagless:

```
Cḃðj

```

Attempt This Online!
> 0 votes

---
Tags: code-golf, string, binary, conversion
---


title: Count the changes in an array

text:
# Question
Title: Count the changes in an array
Your task today is to write a program or function that takes an array of integers, and counts the number of times, reading it left to right, that the value changes. This is easier to show with an example: `[1 1 1 2 2 5 5 5 5 17 3] => [1 1 1 **2** 2 **5** 5 5 5 **17** **3**] => 4`

Test case:

```
Input           |   Output
[]              |   0
[0]             |   0
[0 1]           |   1
[0 0]           |   0
[1 2 3 17]      |   3
[1 1 1 2 2 3]   |   2
[-3 3 3 -3 0]   |   3

```

This is , fewest bytes wins!

# Answer
> 18 votes
# MATL, 2 bytes

```
dz

```

Try it online! Or verify all test cases.

### Explanation

```
     % Implicit input
d    % Consecutive differences
z    % Number of nonzeros
     % Implicit display

```

# Answer
> 9 votes
# Python 3, 38 bytes

```
f=lambda x=0,*y:y>()and(x!=y[0])+f(*y)

```

Try it online!

# Answer
> 7 votes
# Haskell, 33 bytes

```
f(a:b:r)=sum[1|a/=b]+f(b:r)
f _=0

```

Try it online!

---

**Bonus:** Somewhat curious point-free arithmetic version (44 bytes)

```
sum.(tail>>=zipWith((((0^).(0^).abs).).(-)))

```

Try it online!

Given an input `[1,1,4,3,3,3]`, we first take the difference of adjacent entries (`[0,3,-1,0,0]`), then the `abs`olute value: `[0,3,1,0,0]`. Taking zero to the power of each element the first time yields `[1,0,0,1,1]`, and a second time inverts the list: `[0,1,1,0,0]` (`(1-)` would also work here instead of `(0^)`). Finally we take the `sum` of the list to get `2`.

# Answer
> 6 votes
# Python 2, 42 bytes

```
lambda a:sum(x!=y for x,y in zip(a,a[1:]))

```

Try it online!

# Answer
> 5 votes
# Brain-Flak, 50 bytes

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

```

Try it online!

Outputs nothing for 0, which in brain-flak is equivalent. If this is not acceptable, than append this for `+4` bytes: `({})`

Explanation:

```
#Push stack-height-1
([][()])

#While true:
{

    #Pop the stack-height-1 off
    {}

    #If 'a' is the element on top of the stack, and 'b' is the element underneath it, then
    #Pop 'a' off, and push (a - b)
    ({}[({})])

    #If (a-b) is not 0...
    {
        #Pop (a-b) off
        {}

        #Switch stacks
        <>

        #Increment the value on the other stack
        ({}())

        #Push a 0 back to the main stack
        (<>)

    #Endif
    }

    #Pop either (a-b) or the 0 we pushed
    {}

    #Push stack-height-1
    ([][()])

#Endwhile
}

#Toggle to the alternate stack and display the counter
<>

```

# Answer
> 5 votes
# K (oK), 8 bytes

**Solution:**

```
+/1_~~':

```

Try it online!

**Examples:**

```
+/1_~~':1 1 1 2 2 5 5 5 5 17 3
4
+/1_~~':()
0
+/1_~~':-3 3 3 -3 0
3

```

**Explanation:**

Interpreted right-to-left:

```
+/1_~~': / the solution
     ~': / equal each-previous
    ~    / not (ie differ)
  1_     / 1 drop, remove first as this is different to null
+/       / sum up trues

```

# Answer
> 5 votes
# Haskell, 35 bytes

*-8 bytes thanks to H.PWiz.*

Out-golfed by a recursive version. Haskell is pretty much the best at recursion and I missed it. \>\_\<

```
f l=sum[1|x<-zipWith(/=)l$tail l,x]

```

Try it online!

It'd be awesome if anybody figured out how to employ this tip.

## Alternate solution, 36 bytes

```
f l=sum[1|True<-zipWith(/=)l$tail l]

```

Try it online!

# Answer
> 5 votes
# Brain-Flak, 50 bytes

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

```

Try it online!

```
# Get ready to push the answer
(

# Push stack height - 1
([][()])

# Loop until 0 (until the stack has a height of 1)
{

  # Pop the old stack height and subtract it
  #(cancels the loop counter from the final answer)
  [{}]

  # Pop the top of the stack and subtract the next element from that
  # Don't include this in the final answer
  <({}[({})])>

  # If not 0
  {

    # Pop the difference between the last two numbers
    # Don't include this in the final answer
    (<{}>)

    # Add 1 to the final answer
    ()

  # End if
  }{}

  # Push stack height - 1
  ([][()])

# End while
}

# Switch to the off stack so we don't print anything extra
<>

# Push the total sum. This is the number of times the if was true
)

```

# Answer
> 5 votes
# Java (OpenJDK 8), 65 bytes

Not as short as I'd like, but that's just Java for you.

Test by passing the array as a comma delimited list.

```
a->{int s=0,i=1;for(;i<a.length;s+=a[i-1]!=a[i++]?1:0);return s;}

```

Try it online!

# Answer
> 4 votes
# Jelly, 3 bytes

```
ITL

```

Try it online!

## How it works

```
ITL  - Full program.

I    - Increments (deltas).
 T   - Get the indices of truthy values (gets the indexes of non-0 elements).
  L  - Length.

```

# Answer
> 4 votes
# Retina, ~~24~~ ~~21~~ 16 bytes

*Thanks to @MartinEnder for -3 bytes and noticing a bug*
*-1 byte thanks to @tsh*
*-4 bytes thanks to @Leo*

```
m`^(\S+)¶(?!\1$)

```

Try it online!

# Answer
> 4 votes
# Wolfram Language (Mathematica), 23 ~~24~~ ~~26~~ ~~29~~ bytes

```
Length@Split@#~Max~1-1&

```

Try it online!

* -1 byte thanks to Martin Ender!
* -2 bytes thanks to JungHwan Min! nice use of `Split[]`.
* -3 bytes thanks to totallyhuman!

a little explanation:

`Split` will divide an array into a list of lists (of same elements), that is, turning `{1, 2, 2, 3, 1, 1}` into `{{1}, {2, 2}, {3}, {1, 1}}` . So, `Length@Split@#` is the quantity of consecutive segements. `Max[*****-1, 0]` is used to deal with `{}` input.

# Answer
> 4 votes
# Ohm v2, 3 bytes

```
ΔyΣ

```

Try it online!

**Explanation**

```
Δ     absolute differences between consecutive elements
 y    sign: 1 if positive, -1 if negative, 0 if zero
  Σ   sum

```

# Answer
> 4 votes
# Husk, 3 bytes

```
Ltg

```

Try it online!

### Explanation

```
Ltg    Input: [1,1,1,2,2,3]
  g    Group equal elements together: [[1,1,1],[2,2],[3]]
 t     Drop the first group (if any): [[2,2],[3]]
L      Return the length of the list: 2

```

# Answer
> 4 votes
# Perl 6, 18 bytes

```
{sum $_ Z!= .skip}

```

Test it

## Expanded:

```
{ # bare block lambda with implicit parameter ｢$_｣

  sum         # count the number of True values

      $_      # the input
    Z!=       # zip using &infix:«!=»
      .skip   # the input, but starting from the second value
              # (implicit method call on ｢$_｣
}

```

# Answer
> 4 votes
# Symbolic Python, ~~120~~ 117 bytes

Golfed 3 bytes by removing an explicit cast to integer (using unary `+`) for the counter variable - this means that if there are no changes in the array the output will be `False` instead of `0`, but this is allowed by meta.

```
___=-~(_==_)
__('___=~-'+`_>_`[___::___]+`__`[-~___]+'(_)')
__('__=___=_>_'+';___+=_[__]!=_[-~__];__=-~__'*___)
_=___

```

**Try it online!**

```
# LINE 1: Generate value '2' for utility
___=-~(_==_)

# LINE 2: Get len(input) - 1
__('___=~-'+`_>_`[___::___]+`__`[-~___]+'(_)')
   '___=~-'+`_>_`[___::___]+`__`[-~___]+'(_)'     # Generate string '___=~-len(_)'
            `_>_`[___::___]                       #    'le' spliced from 'False'
                           +`__`[-~___]           #    'n' indexed from '<function ...>'
   '___=~-'+                           +'(_)'     #    Remaining characters in plaintext
__(                                          )    # Execute this to get len(input) - 1

# LINE 3: Main calculation loop
__('__=___=_>_'+';___+=_[__]!=_[-~__];__=-~__'*___)
__(                                               ) # Execute:
   '__=___=_>_'                                     #   Set var1, var2 to 0
               +';                           '*___  #   len(input) - 1 times do:
                       _[__]!=_[-~__]               #   Compare input[var1, var1 + 1]
                  ___+=              ;              #   Add this to var2
                                      __=-~__       #   Increment var1

# LINE 4: Set output variable ('_') to the result calculated.
_=___

```

# Answer
> 4 votes
# Elm, 59 bytes

```
f x=case x of
 a::b::c->f(b::c)+if a/=b then 1 else 0
 _->0

```

You can test this out here. Paste the following code to get started:

```
import Html exposing (text)

f x=case x of
 a::b::c->f(b::c)+if a/=b then 1 else 0
 _->0

main =
  f [0,0,1,0]
  |> Debug.toString
  |> text

```

# Answer
> 3 votes
# PowerShell, ~~52~~ 45 bytes

*(-7 bytes thanks to Julian)*

```
$i=0
$args|%{$i+=$p-ne$_-and$p-ne$n
$p=$_}
$i

```

Try it online!

Takes input `$args`, dumps it into a for loop, each iteration checking whether the `$p`revious value is `-n`ot`e`qual to the current value `$_`, and whether the previous value is `$n`ull. Exploits the Boolean-to-int implicit converstion to accumulate that into `$i`. Outputs `$i` at the end.

The initial `$i=0` is needed to account for if the input is empty, and to (properly) account for when the input is a single value.

# Answer
> 3 votes
# Husk, 4 bytes

```
#IẊ≠

```

Try it online!

# Answer
> 3 votes
# 05AB1E, 3 bytes

```
¥ĀO

```

Try it online!

# Answer
> 3 votes
# , 24 bytes

```
cat(sum(!!diff(scan())))

```

Try it online!

Same as the MATL answer, just used `sum(!!diff))` since there's no `nnz`.

# Answer
> 3 votes
# Cubix, 24 bytes

```
UpO@0I>I!^-u>q.uvv$!^;)p

```

Try it online

Note that Cubix uses 0 to indicate that there are no more inputs, so 0 cannot be in the list.

### Explanation

Unfolded:

```
    U p
    O @
0 I > I ! ^ - u
> q . u v v $ !
    ^ ;
    ) p

```

We start at the `0`, pushing the counter (initialized with `0`) and the first input (`I`) onto the stack.

We then enter the loop. At each iteration of the loop, we get the next input with `I`. If it's 0, we've run out of inputs, so we rotate the counter to the top (`p`), `O`utput, and exit (`@`).

Otherwise, we take the difference of the top two elements. If it's nonzero, we rotate the counter to the top, increment it, and rotate it back to the bottom with `p)q`. We then pop the difference with `;` before moving to the next iteration.

All the characters not mentioned here are just control flow. There tend to be a lot of those in Cubix programs.

# Answer
> 3 votes
# APL (Dyalog), 8 bytes

```
+/2≠/⊃,⊢

```

Try it online!

**How?**

`⊃,⊢` \- the list, with the first value repeated for the case of single element

`2≠/` \- changes list, not equal for every 2 elements

`+/` \- sum

# Answer
> 3 votes
# Brain-Flak, 50 bytes

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

```

Try it online!

Since everyone is posting their 50 byte solutions here is mine (I have a 48 byte one but it was a simple modification of DjMcMayhem's so I did feel it worth posting)

# Explanation

This answer extensively uses value canceling.

Un-golfed it looks like

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

```

Here we compute the delta's until the stack has one item left, each time we accumulate one value from the inner loop if the delta is non zero.

This is a pretty straight forward way of doing it.

To make this golfy we begin value canceling. The first one and the one that should be obvious to any hardened brain-flak golfer is the stack heights. It is a well known fact that

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

```

is the same as

```
(([]){[{}]...([])}{})

```

When the values are modified by one, the same holds. This gives us

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

```

You may notice this didn't even save us bytes, but don't fret it will become more useful as we go on.

We can perform another reduction, if you see a statement

```
<(...)>{<{}> ...

```

you can actually reduce it to

```
[(...)]{{} ...

```

This works because if we enter the loop `[(...)]` and `{}` will cancel, and if we don't the value of `[(...)]` already was zero in the first place and doesn't need to be canceled. Since we have an occurrence of this pattern in our code we can reduce it.

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

```

That saved us 2 bytes but it also put two negs next to each other. These can be combined to save us another 2.

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

```

And that's our code.

# Answer
> 3 votes
# Gaia, 2 bytes

```
ėl

```

Try it online!

This abuses a bug (or feature?) of Gaia, that run-length-encoding doesn't take the last run of elements into account. Note that I have double checked, it works for all test cases.

* `ė` \- Run length encoding (with the flaw described above).
* `l` \- Length.

# Answer
> 2 votes
## JavaScript (ES6), 35 bytes

```
a=>a.filter((e,i)=>e-a[i+1]).length

```

# Answer
> 2 votes
# Pyth, 5 bytes

```
l #.+

```

Test suite.

Explanation:

```
   .+  Deltas
  #    Filter on identity (space)
l      Get length

```

# Answer
> 2 votes
# Perl 5, 37 + 2 (`-ap`) = 39 bytes

```
$\+=$F[$_]!=$F[$_-1]for 1..$#F}{$\|=0

```

Try it online!

# Answer
> 2 votes
# J, 10 bytes

```
[:+/2~:/\]

```

Infixes of length 2... are they unequal? `2 ~:/\ ]`

Sum the resulting list of `0`s and `1`s: `+/`

Try it online!

# Answer
> 2 votes
# Pyth, 4 bytes

```
ltr8

```

Test suite

"literate"

The number of changes is equal to the number of runs, ignoring the first run if any. `r8` run length encodes the input, `t` removes the first element if any, and `l` finds the length of the resulting list.

# Answer
> 2 votes
# Ruby, 31 bytes

```
->a{a.chunk{|x|x}.drop(1).size}

```

Try it online!

# Answer
> 2 votes
# C (gcc 5.4.0), 61 bytes

```
f(c,v)int*v;{int*p=v,s=0;for(;p<v+c-1;s+=*p++!=*p);return s;}

```

Try it Online!

`f` is a function taking the length of the array and a pointer to the first element of the array, and returning the number of changes in the array;

This submission utilizes undefined behavior (`*p++!=*p`, p is used twice in an expression in which it is changed), which works on my machine (gcc 5.4.0) and on TIO, but may not work on other implementations or versions.

Explanation:

```
f(c,v)int*v;{ // old-style declaration for v, and implicit-int for c and return value
    int*p=v,s=0; // p is a pointer to the current item, s is the number of changes
    for(;p<v+c-1;s+=*p++!=*p); // for each consecutive pair of integers, if they are different, add one to the number of changes
    return s; // return the number of changes
}

```

# Answer
> 2 votes
# 05AB1E, 3 bytes

```
γ¦g

```

Try it online!

An alternative to Erik's answer.

```
γ¦g  ~ Full program.

γ    ~ Group into runs of equal adjacent elements.
 ¦   ~ Remove the first group (if there are any).
  g  ~ Length.

```

# Answer
> 2 votes
# J-uby, 37 bytes

```
:zip%:rotate|~:[]&(0..-2)|:count++:!=

```

More "readable":

```
(:zip % :rotate) | (~:[] & (0..-2)) | (:count + +:!=)

```

Explanation:

```
:zip%:rotate                        # zip a with itself, rotated by one position. this yields [[a[0], a[1]], [a[1], a[2]], [a[2], a[3]], ...]
           |~:[]&(0..-2)            # discard the last pair, as that's [a[-1], a[0]], not one of our changes
                       |:count++:!= # count the pairs with unequal first and second elements (those are changes)

```

### 25 bytes (conversion of @daniero's Ruby answer)

```
~:each_cons&2|:count++:!=

```

Explanation

```
~:each_cons&2            # for every pair [a[i],a[i+1]] in a:
            |:count++:!= # count the number of pairs with unequal first and second elements

```

# Answer
> 2 votes
# Bash, 17 bytes

Packages: Core Utilities, sed

```
uniq|sed 1d|wc -l

```

Takes an input array of one element per line.

## How does it work?

The input goes to stdin, one array element per line, to `uniq`. `uniq` squeezes multiple *consecutive* identical lines into one, then `sed 1d` purges the first line, passing the rest to `wc`. `wc -l` simply counts the number of lines and outputs the count.

# Answer
> 2 votes
# Jq 1.5, 51 bytes

```
[range(1;length)as$i|select(.[$i]!=.[$i-1])]|length

```

Expanded

```
[                              # create an array containing
    range(1;length) as $i      # a copy of the input for
  | select(.[$i]!=.[$i-1])     # each successive element difference
]
| length                       # length of final array

```

Try it online!

# Answer
> 2 votes
# Julia 1.0, 23 bytes

```
~a=sum([0;diff(a).!=0])

```

Try it online!

* The unary operator `~` is redefined to save bytes.
* `sum` returns an error on an empty (untyped) array, so the array is padded with a `0`.

# Answer
> 2 votes
# Vyxal, 3 bytes

```
ĠḢL

```

Try it Online!

Alternatively:

# Vyxal, 3 bytes

```
¯TL

```

Try it Online!

`¯ꜝL` would also work.

All of these solutions can be 2 bytes by removing `L` and adding the `l` flag.

# Answer
> 2 votes
# Rust, 68 bytes

```
|u:Vec<_>|u.iter().fold((0,0,0),|(u,v,w),&x|(u+w*(v!=x)as i8,x,1)).0

```

Attempt This Online!

## Non-Competing Rust, 63 bytes

This version crashes on 0-length inputs so doesn't technically complete the challenge. I think it's more elegant though.

```
|u:Vec<_>|u.iter().fold((0,u[0]),|(u,v),&x|(u+(v!=x)as i8,x)).0

```

Attempt This Online!

# Answer
> 2 votes
# Haskell + hgl, 7 bytes

```
l<tl<gr

```

Attempt This Online!

## Explanation

* `gr` group the list into chunks of equal sized elements
* `tl` drop the first element
* `l` get the length

## Alternate versions

### 8 bytes

```
cne 0<δ

```

## Reflection

I'm quite happy with this. It's hard to imagine any improvements that could be made here. However while looking for alternative versions I found a few things that might be useful to add:

* `cn id` and `cn n` should likely be added. `cn id` counts the number of `True` values in a list and `cn n` counts the number of `False` values in a list.
* `pa eq` should likely be added.

With both of these there would be another 7 byte solution:

```
cnn<paq

```

# Answer
> 2 votes
# Thunno, \\$4 \log\_{256}(96) \approx\\$ 3.29 bytes

(This is only for v1.1.1+, ATO is on v1.1.0)

```
z[wL

```

Or, for \\$5 \log\_{256}(96) \approx\\$ 4.12 bytes (works on all versions)

```
zyL1-

```

Attempt This Online!

**Explanations:**

```
        # Implicit input                [1, 1, 1, 2, 2, 3]
z[      # Forward-differences           [0, 0, 1, 0, 1]
  w     # Truthy items only             [1, 1]
   L    # Length                        2
        # Implicit output

```

```
        # Implicit input                [1, 1, 1, 2, 2, 3]
zy      # Group by consecutive items    [[1, 1, 1], [2, 2], [3]]
  L1-   # Length - 1                    2
        # Implicit output

```

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

```
i0\  ;n$\.13$\
1+>i:0(?/:{=?^$

```

Try it

# Answer
> 1 votes
# Pyth, 8 bytes

```
ssmndZ.+

```

Try it online!

# Answer
> 1 votes
# Ruby, 36 bytes

```
->a{a.each_cons(2).count{|x,y|x!=y}}

```

Try it online!

# Answer
> 1 votes
# C# (.NET Core), 94 bytes

```
using System.Linq;
n=>{int?i=0,a=n.FirstOrDefault();n.ForEach(x=>{i+=x==a?0:1;a=x;});return i;}

```

Try it online!

# Answer
> 1 votes
# Japt, 6 bytes

```
ä- è¦0

```

Try it online!

# Answer
> 1 votes
# Octave, 16 bytes

```
@(x)nnz(diff(x))

```

Verify all test cases here!

Quite short, seeing that Octave is a conventional language.

### Explanation:

```
@(x)               % Anonymous function that takes x as input
    nnz(       )   % Count the number of non-zero ...
        diff(x)    % ... differences between elements

```

# Answer
> 1 votes
# PHP, 63 bytes

```
foreach($_GET as$g){$c+=$g!=$l?isset($l)?1:0:0;$l=$g;}echo$c*1;

```

pass the sequence as a get query with any indexes, or Try it online!

my attempt, not the shortest, but it's something

# Answer
> 1 votes
# Stacked, 26 bytes

```
[2 infixes 0\[...!=+]fold]

```

Try it online!

## Explanation

```
[2 infixes 0\[...!=+]fold]
[                        ]   anonymous function; argument = arr
 2 infixes                   generate infixes of length 2
           0\[      ]fold    fold the inside function over the infixes (starting = 0)
                               when iterating, stack looks like: (acc (a0 a1))
              ...              merge (a0 a1) into the stack      (acc a0 a1)
                 !=            check for inequality              (acc a0!=a1)
                   +           add to accumulator                (acc+(a0!=a1))

```

This gives the number of unequal infixes in the array, equivalent to the given problem.

# Answer
> 1 votes
# Ruby, 44 Bytes

```
->a{a.zip(a.rotate)[0..-2].count{|x,y|x!=y}}

```

Takes the array, and zips the elements with the array rotated one place. This gives pairs of `[a[0],a[1]], [a[1],a[2]], [a[2],a[3]], ...`

Then we cut off the last element because that's `a[-1],a[0]`, which we don't need here.

Finally, we count the number of pairs with inequal first and second elements (or spaces in between items of the array which change).

# Answer
> 1 votes
# AWK, 35 bytes

```
{for(i=1;i<NF;)s+=$i!=$++i;$0=s+0}1

```

Try it online!

This requires at least 1 character as input (the character can be a space).

A version without this restriction but with several more bytes is:

```
BEGIN{RS=" "}{s+=NR>1&&p!=$1;p=$1}END{print s+0}

```

Try it online!

# Answer
> 1 votes
# GNU sed, ~~30~~ 23 + 3 = 26 bytes

+3 bytes for `-r` flag. Output is in unary.

```
s/(\S+)( \1)*//g
y/ /;/

```

Try it online!

Technically I could drop the second line and say each space is a unary digit for -7 bytes, but I don't want to push it.

# Answer
> 1 votes
# Pyke, 4 bytes

```
$0-l

```

Try it here!

```
$    -   delta(input)
 0-  -  ^.remove(0)
   l - len(^)

```

# Answer
> 1 votes
# Common Lisp, 56 bytes

```
(loop as(x y)on(coerce(read)'list)while y count(/= x y))

```

Try it online!

# Answer
> 1 votes
## **Python 3, 31 bytes**

```
f=lambda y:sum(y[1:]-y[:-1]!=0)

```

Try it online!

# Answer
> 1 votes
# PHP, ~~48~~ 47 bytes

```
<?foreach($_GET[a]as$a)$n+=$_GET[b]!=$a;echo$n;

```

Run with arrays `a` and `b` as GET parameters.

empty output for `0`.

# Answer
> 1 votes
# J-uby, 21 bytes

Port of my Ruby answer.

```
:chunk+I|~:drop&1|:+@

```

Attempt This Online!

# Answer
> 1 votes
# Japt `-x`, 2 bytes

```
ä¦

```

Try it

I'm not sure if this uses features introduced after the other Japt answer, but this is much shorter

```
ä    # Map each adjacent pair through:
 ¦   #  1 if they are different, 0 otherwise

-x   # Sum the new array and print

```

# Answer
> 1 votes
# Factor, 29 bytes

```
[ 2 clump [ std 0 > ] count ]

```

Try it online!

Counts the number of adjacent pairs whose standard deviation is greater than zero.

# Answer
> 1 votes
# Swift, 51 bytes

This works for any collection whose element type defines the operator `!=`, not just arrays of integers.

```
{zip($0,$0.dropFirst()).filter{$0.0 != $0.1}.count}

```

The spaces around the `!=` operator are necessary; it parses `$0.0!=$0.1` as `$0.0! = $0.1`.

This can be assigned to a variable or called inline:

```
print({zip($0,$0.dropFirst()).filter{$0.0 != $0.1}.count}([0, 1, 2]))

let x: ([Int]) -> Int = {zip($0,$0.dropFirst()).filter{$0.0 != $0.1}.count}
print(x([0, 1, 2]))

```

Try it online!

# Answer
> 1 votes
# Vyxal, 3 bytes

```
¯ꜝL

```

Try it Online!

```
¯ꜝL
¯   # delta (consecutive diff)
 ꜝ  # non-zero
  L # length

```

# Answer
> 1 votes
# Desmos, 27 bytes

```
f(l)=sgn(l[2...]-l)^2.total

```

TIL `sgn` exists. I've been using `sign` the entire time... -\_-

Try It On Desmos!

Try It On Desmos! - Prettified

# Answer
> 1 votes
# Pip, 10 bytes

```
_MS_!=BMPg

```

Attempt This Online!

### Explanation

```
_MS_!=BMPg
         g  ; List of command-line arguments
       MP   ; Map this function to each pair of consecutive elements:
   _!=B     ;   1 if elements are not equal, 0 if equal
 MS         ; Map this function over that list and sum the results:
_           ;   Identity function

```

# Answer
> 1 votes
# Thunno 2 `S`, 2 bytes

```
Ṣɓ

```

Attempt This Online!

#### Explanation

```
Ṣɓ  # Implicit input
Ṣ   # Forward-differences
 ɓ  # Boolify
    # Sum the list
    # Implicit output

```

# Answer
> 0 votes
# BQN, 10 bytes

```
+´1⊸↓≠¯1⊸↓

```

Anonymous tacit function. Try it at BQN online!

### Explanation

```
+´1⊸↓≠¯1⊸↓
  1⊸↓       Drop the first element from the argument list
      ¯1⊸↓  Drop the last element from the argument list
     ≠      Compare those two lists element-wise: 1 if not equal, 0 if equal
+´          Sum the resulting list of 0s and 1s

```

---
Tags: code-golf, array
---