# Question
Title: Count All Possible Unique Combinations of Letters in a Word
You are given a string, which will contain ordinary a-z characters. (You can assume this will always be the case in any test, and assume that all letters will be lowercase as well). You must determine how many unique combinations can be made of the individual characters in the string, and print that number.

However, duplicate letters can be ignored in counting the possible combinations. In other words, if the string given is "hello", then simply switching the positions of the two `l`s does not count as a unique phrase, and therefore cannot be counted towards the total.

Shortest byte count wins, looking forward to seeing some creative solutions in non-golfing languages!

**Examples:**

```
hello -> 60
aaaaa -> 1
abcde -> 120

```

# Answer
> 29 votes
# Python 2, ~~50~~ 48 bytes

```
f=lambda s:s==''or len(s)*f(s[1:])/s.count(s[0])

```

Try it online!

No boring built-ins! To my surprise, this is even shorter than the brute force approach, calculating all of the permutations with `itertools` and taking the length.

This function uses the formula

\\$\text{# of unique permutations} = \frac{\text{(# of elements)!}}{\prod\_{\text{unique elements}}{\text{(# of occurences of that element)!}}}\\$

and computes it on the fly. The factorial in the numerator is calculated by multiplying by `len(s)` in each function call. The denominator is a bit more subtle; in each call, we divide by the number of occurences of that element in what's left of the string, ensuring that for every character `c`, all numbers between 1 and the amount of occurences of `c` (inclusive) will be divided by exactly once. Since we divide only at the very end, we're guaranteed not to have any problems with Python 2's default floor division.

# Answer
> 16 votes
# 05AB1E, 3 bytes

```
œÙg

```

Try it online!

**Explanation**

```
  g  # length of the list
 Ù   # of unique
œ    # permutations
     # of the input

```

# Answer
> 7 votes
# CJam, 4 bytes

```
le!,

```

Try it online!

### Explanation

Read line as a string (`l`), unique permutations as an array of strings (`e!`), length (`,`), implicit display.

# Answer
> 5 votes
# , ~~69~~ 65 bytes

```
function(s,`!`=factorial)(!nchar(s))/prod(!table(strsplit(s,"")))

```

Try it online!

4 bytes saved thanks to Zahiro Mor in both answers.

Computes the multinomial coefficient directly.

# , ~~72~~ 68 bytes

```
function(s,x=table(strsplit(s,"")))dmultinom(x,,!!x)*sum(1|x)^sum(x)

```

Try it online!

Uses the multinomial distribution function provided by `dmultinom` to extract the multinomial coefficient.

Note that the usual (golfier) `x<-table(strsplit(s,""))` doesn't work inside the `dmultinom` call for an unknown reason.

# Answer
> 5 votes
# JavaScript (Node.js), 49 bytes

`t=t*` is used instead of `t*=` to avoid rounding error (the `|t` rounds down the number) as `t=t*` guarantees that all intermediate (operator-wise) results are whole numbers.

```
a=>[...a].map(g=x=>t=t*y++/(g[x]=-~g[x]),t=y=1)|t

```

Try it online!

```
a=>
 [...a].map(        // Loop over the characters
  g=x=>
   t=t*             // using t*= instead may result in rounding error
    y++             // (Length of string)!
    /(g[x]=-~g[x])  // divided by product of (Count of character)!
  ,t=y=1            // Initialization
 )
 |t

```

# Answer
> 4 votes
# Japt, ~~5~~ 3 bytes

*-2 bytes thanks to @Shaggy*

```
á l

```

Try it online!

# Answer
> 4 votes
# APL (Dyalog Unicode), 14 bytes

```
!∘⍴÷⊂×.(!∘⍴∩)∪

```

Try it online!

Returns the result as a singleton.

# Answer
> 4 votes
# , ~~15~~, 14 bytes

```
[:#@=i.@!@#A.]

```

Try it online!

*-1 byte thanks to FrownyFrog*

# Answer
> 3 votes
# Jelly, 4 bytes

```
Œ!QL

```

Try it online!

Simply does what was asked: find permutations of input, uniquify and print the length.

# Answer
> 3 votes
# C# (Visual C# Interactive Compiler), 59 bytes

```
f=s=>s==""?1:s.Length*f(s.Substring(1))/s.Count(c=>c==s[0])

```

Port of *@ArBo*'s Python 2 answer.

Try it online.

# Answer
> 3 votes
# Brachylog, 3 bytes

```
pᶜ¹

```

Try it online!

```
       The output is
 ᶜ¹    the number of unique
p      permutations of
       the input.

```

`pᵘl` does pretty much exactly the same thing.

# Answer
> 2 votes
# Python 2, 57 bytes

```
lambda s:len(set(permutations(s)))
from itertools import*

```

Try it online!

Self-documenting: Return the length of the set of unique permutations of the input string.

# Python 3, 55 bytes

Credit goes to ArBo on this one:

```
lambda s:len({*permutations(s)})
from itertools import*

```

Try it online!

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

```
⎕CY'dfns'
{≢∪↓⍵[pmat≢⍵]}

```

Try it online!

Simple Dfn, takes a string as argument.

### How:

```
⎕CY'dfns'      ⍝ Copies the 'dfns' namespace.
{≢∪↓⍵[pmat≢⍵]} ⍝ Main function
          ≢⍵   ⍝ Number of elements in the argument (⍵)
      pmat     ⍝ Permutation Matrix of the range [1..≢⍵]
    ⍵[      ]  ⍝ Index the argument with that matrix, which generates all permutations of ⍵
   ↓           ⍝ Convert the matrix into a vector of strings
  ∪            ⍝ Keep only the unique elements
 ≢             ⍝ Tally the number of elements

```

# Answer
> 2 votes
# Ruby, 41 bytes

```
f=->s{s.chars.permutation.to_a.uniq.size}

```

Try it online!

# Answer
> 2 votes
# Java 8, ~~103~~ 102 bytes

```
s->{int r=1,i=s.length();for(;i>0;)r=r*i/~-s.substring(--i).split(s.charAt(i)+"",-1).length;return r;}

```

Port of *@ArBo*'s Python 2 answer.
-1 byte thanks to *@OlivierGrégoire* by making it iterative instead of recursive.

Try it online.

Actually generating all unique permutations in a Set and getting its size would be **221 bytes**:

```
import java.util.*;s->{Set S=new HashSet();p(s,S,0,s.length()-1);return S.size();}void p(String s,Set S,int l,int r){for(int i=l;i<=r;p(s.replaceAll("(.{"+l+"})(.)(.{"+(i++-l)+"})(.)(.*)","$1$4$3$2$5"),S,l+1,r))S.add(s);}

```

Try it online.

# Answer
> 2 votes
# Perl 6, 33 30 chars (34 31 bytes)

Fairly straight forward `Whatever` block. `comb` splits the string into letters, `permutations` gets all possible combinations. Because of the way coercion to `Set` need be `join`ed first ( `»` applies `join` to each element in the list).

```
+*.comb.permutations».join.Set

```

Try it online!

(previous answer used `.unique` but `Set`s guarantee uniqueness, and numerify the same, so it saves 3).

# Answer
> 2 votes
# Perl 5, 43 bytes

Uses the method in @ArBo's Python answer.

```
sub c{!@_||@_*c(@_[1..$#_])/grep/$_[0]/,@_}

```

Try it online!

# Answer
> 2 votes
# K (oK), 12 bytes

**Solution:**

```
#?x@prm@!#x:

```

Try it online!

**Explanation:**

Uses the oK built-in `prm`:

```
{[x]{[x]$[x;,/x ,''o'x ^/:x;,x]}@$[-8>@x;!x;x]}

```

... which, due to `x^/:x` basically generates the permutations of `"helo"` not `"hello"`, hence we need to generate the permutations of `0 1 2 3 4`, use them to index into `"hello"` and then take the count of the unique.

```
#?x@prm@!#x: / the solution
          x: / store input as x
         #   / count (#) length
        !    / range (!) 0..n
    prm@     / apply (@) to function prm
  x@         / apply permutations to input x
 ?           / take the distinct (?)
#            / count (#)

```

# Answer
> 1 votes
# Octave / MATLAB, 35 bytes

```
@(s)size(unique(perms(s),'rows'),1)

```

Anonymous function that takes a character vector and produces a number.

In MATLAB this can be shortened to `size(unique(perms(s),'ro'),1)` (33 bytes).

Try it online!

### Explanation

```
@(s)                                  % Anonymous function with input s
                perms(s)              % Permutations. Gives a char matrix
         unique(        ,'rows')      % Deduplicate rows
    size(                       ,1)   % Number of rows

```

# Answer
> 1 votes
# Pyth, ~~5~~ 4 bytes

```
l{.p

```

Try it online!

This assumes the input is a python string literal. If input must be raw text, this 5-byte version will work:

```
l{.pz

```

Either way, it just computes all permutations of the input as a list, deduplicates it and gets the number of elements in it, and implicitly prints that number.

*-1 byte thanks to @hakr14*

# Answer
> 1 votes
# MATL, 9 bytes

```
jY@XuZy1)

```

Try it online!

Explanation:

```
j input as string
Y@ get permutations
Xu unique members
Zy size matrix
1) first member of size matrix

```

# Answer
> 1 votes
# Retina 0.8.2, 73 bytes

```
(.)(?=(.*?\1)*)
/1$#2$*1x1$.'$*
^
1
+`1(?=1*/(1+)x(\1)+$)|/1+x1+$
$#2$*
1

```

Try it online! Uses @ArBo's formula, but evaluates from right-to-left as this can be done in integer arithmetic while still minimising the size of the unary values involved. Explanation:

```
(.)(?=(.*?\1)*)
/1$#2$*1x1$.'$*

```

For each character, count how many remaining duplicates there are and how many further characters there are, add one to each to take the current character into account, and separate the values so we know which ones are to be divided and which are to be multiplied.

```
^
1

```

Prefix a 1 to produce a complete expression.

```
+`1(?=1*/(1+)x(\1)+$)|/1+x1+$
$#2$*

```

Repeatedly multiply the last and third last numbers while dividing by the second last number. This replaces the last three numbers.

```
1

```

Convert to decimal.

# Answer
> 1 votes
# Wolfram Language (Mathematica), 32 bytes

```
Characters/*Permutations/*Length

```

Try it online!

Explanation: Right-composition with `/*` applies these three operators one after the other to the function argument, from left to right:

* `Characters` converts the input string to a list of characters.
* `Permutations` makes a list of all unique permutations of this character list.
* `Length` returns the length of this list of unique permutations.

This method is very wasteful for long strings: the unique permutations are actually listed and counted, instead of using a `Multinomial` to compute their number without listing.

# Answer
> 1 votes
# K, 27 bytes

```
*/[1+!#:x]%*/{*/1+!x}'#:'x:

```

# K, 16 bytes - not a real answer

```
#?(999999#0N)?\:

```

Take 999999 random permutations of the input string, take the unique set of them and count the length. Most of the time it will give the right answer, for shortish strings.

Improved thanks to @Sriotchilism O'Zaic, @Selcuk

# Answer
> 1 votes
# F# (Mono), 105 bytes

```
let rec f s=if s=""then 1 else s.Length*(f(s.Substring 1))/(s|>Seq.sumBy(fun c->if c=s.[0]then 1 else 0))

```

Try it online!

# Answer
> 1 votes
# , ~~14~~ 13 bytes

```
#(%*/)&:!#/.~

```

Try it online!

*1 byte thanks to miles*

```
#                  length
         #/.~      counts of each unique character
 (%*/)             divide left by the product of right
      &:!          after applying ! to both

```

# Answer
> 1 votes
# PHP, 77 bytes

```
function f($s){return!$s?:strlen($s)*f(substr($s,1))/substr_count($s,$s[0]);}

```

Try it online!

This is basically just a PHP port of @ArBo's winning Python answer which is ridiculously more clever than the recursive answer I originally had. Bravo!

# Answer
> 0 votes
# Ohm v2, 4 bytes

```
ψD∩l

```

Try it online!

**Explanation**

```
   l    output the lenght of
  ∩     the set intersection between
ψD      two copies of all possible permutation of input

```

# Answer
> 0 votes
# Stax, 3 bytes

```
═1╪

```

Run and debug it

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


title: Shifting digits

text:
# Question
Title: Shifting digits
Given a string representing a number and the base that number is in, shift each positional value upward, wrapping back to zero if the value cannot increase. You will never be provided invalid input, nor a base larger than 36.

For example, you may be provided `['5f6', '16']`, which represents the number 1526 in base 16. The expected output in that case would be `'607'` (1543 in base 16).

### Input

* program: separate lines from STDIN: `'5f6\n16'`
* function: a tuple or array: `f(['5f6', '16'])` or `f(['5f6', 16])`
* function: two arguments `f('5f6', '16')` or `f('5f6', 16)`

### Output

* program: to STDOUT: `607`
* function: returned as a string: `'607'`

### Test cases

```
['5f6', '16']
'607'

['abc', '36']
'bcd'

['1', '1'] or ['0', '1']
'1' or '0'

['9540', '10']
'0651' or '651'

['001', '2']
'110'

```

# Answer
# Paradoc (v0.2.10), 10 bytes (CP-1252)

```
DaÅ+<:<oTr

```

Try it online!

Takes the string and the base as an integer from the stack, results in a string on the stack.

Whoops, I don't know why I don't have a `0-9A-Z` constant yet. It would shave two bytes. (Assumes input is uppercase; for lowercase replace `Å` with `La`.)

Explanation:

```
Da         .. Push the digit alphabet
  Å        .. Push the uppercase alphabet
   +       .. Concatenate them
    <      .. Take the slice of the first (base) characters
     :     .. Duplicate
      <o   .. Left-rotate by one
        Tr .. Translate through the last two strings

```
> 7 votes

# Answer
# Japt, 10 bytes

```
®nV Ä sV Ì

```

Test it online!

The 3-byters `nV`  and `sV`  are rather annoying...

### Explanation

```
 ®   nV Ä  sV Ì
UmZ{ZnV +1 sV gJ}   Ungolfed
                    Implicit: U = input string, V = base
UmZ{            }   Map each char in Z to
    ZnV               Z converted from base V to decimal,
        +1            plus 1,
           sV         converted back to base V,
              gJ      and shortened to only the last char. (J = -1)
                    Implicit: output result of last expression

```
> 4 votes

# Answer
# Python 2, ~~77~~ ~~74~~ 72 bytes

```
lambda s,m:''.join(chr(c+[48,55][c>9])for c in[-~int(x,m)%m for x in s])

```

Try it online!

Takes a string and an int base. Works up to base 36.
> 3 votes

# Answer
# JavaScript, 57 bytes

```
(a,b)=>a.replace(/./g,v=>(-~parseInt(v,b)%b).toString(b))

```
> 3 votes

# Answer
# Jelly, ~~15~~ 12 bytes

3 bytes thanks to Jonathan Allan.

```
ØBiÐ€⁸%⁹‘ịØB

```

Try it online!

## How it works

```
ØBiÐ€⁸%⁹‘ịØB
ØB           "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  iÐ€⁸       index of each in first input
      %⁹     modulo the second input
        ‘    increase by 1
         ị   index into
          ØB "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"

```
> 3 votes

# Answer
# Pyth, ~~11~~ 10 bytes

```
.rE<+jkUTG

```

Try it here

Thanks to Mr. XCoder for saving 1 byte!

We use `.r` to cyclically rotate over the alphabet of the given base. We build that using `G` as the built in alphabet, and then a range of numbers, and slicing off the excess.
> 3 votes

# Answer
# C, ~~75~~ ~~74~~ 65 bytes

*Thanks to @tsh for saving 9 bytes!*

```
f(n,b)char*n;{for(;*n;++n)*n=*n-b-(b>10?86:47)?*n-57?*n+1:97:48;}

```

Modifies the input string directly.

Try it online!
> 2 votes

# Answer
# 05AB1E, 10 bytes

```
ö¹в>¹%¹β¹B

```

Try it online!
> 1 votes

# Answer
# Haskell, ~~65~~ ~~64~~ 59 bytes

```
map.(%)
b%c|mod(fromEnum c-b)39==8='0'
_%'9'='a'
_%c=succ c

```

Try it online! Usage: `map.(%) $ 16 "5f6"` yields `"607"`.

**Edit:** -1 byte thanks to nimi, -5 bytes thanks to Ørjan Johansen.
> 1 votes

# Answer
# MY, 8 bytes

```
αωP‘%pέ←

```

I definitely made the right choice adding the basify (`P`) and stringify (`p`) atoms!

Try it online!

## How it works, along with a reason for the codepoint

* `α`, push the second command line argument (taken from APL, but it's the greek symbol instead of the APL one)
* `ω`, push the first command line argument (also taken from APL)
* `P`, pop `n`; push n basified (`0`-`Z` =\> `0`-`35`, `b` flipped is `p`)
* , pop `n`; push `n + 1` (vectorizes \["vecifies" in MY\], taken from jelly)
* `%`, pop `a`; pop `b`; push `a%b` (vecifies, do I really need to give this to you?)
* `p`, pop `n`; push `n` stringified (`0`-`35` =\> `0`-`Z`, vecifies, same origin as `P`)
* `έ`, pop `n`; push `"".join(n)` (`ε` is the **e**mpty string, and just put an accent mark over it)
* , pop `n`; output `n` with no newline. (Pushing it away from the stack to STDOUT)

**THIS** is what MY was meant for!
> 1 votes

# Answer
# PHP, 83 bytes

```
while(($c=$argv[1][$i++])>'')echo base_convert(intval($c,$b=$argv[2])+1,10,$b)[-1];

```

Try it online!
> 1 votes

# Answer
# Python, ~~81~~ ~~78~~ ~~74~~ ~~87~~ 86 bytes

```
import string
lambda a,b:''.join(string.printable[-~int(i,b)%b]for i in a)if b>1else a

```

Alternatively:

```
lambda a,b:''.join(__import__('string').printable[-~int(i,b)%b]for i in a)if b>1else a

```
> 0 votes

# Answer
# Mathematica, 62 bytes

```
(h=#2;""<>ToString/@(Mod[#~FromDigits~h+1,h]&/@Characters@#))&

```

Try it online!
> 0 votes

# Answer
# Ruby, ~~53~~ 59 bytes

```
->n,b{b<2?n:n.chars.map{|c|(c.to_i(b)+1).to_s(b)[-1]}.join}

```

Try it online!

Originally 6 bytes less, but Ruby doesn't like using a base of 1.

Could save 5 bytes by removing `.join` if the output did not need to be a string.
> 0 votes

# Answer
# Charcoal, ~~23~~ 21 bytes

```
≔…⁺⪫ＥχＩιωβＮθＦＳ§θ⁺¹⌕θι

```

Try it online! Link is to verbose version of code. Edit: Saved 2 bytes by using `CycleChop` instead of `Slice`. Explanation:

```
    Ｅχ                  Loop over the digits
      Ｉι                Cast to string
   ⪫    ω               Join together
  ⁺      β              Append the lowercase letters
          Ｎ             First input as a number
 …                      Take `n` characters from the start
≔          θ            Assign to variable `q`
            ＦＳ          Loop over the characters in the second input
                  ⌕θι   Find the character index in `q`
                ⁺¹      Plus 1
              §θ        Cyclically index in `q`
                        Implicitly print

```

Note: Later versions of Charcoal reduce this to 20 bytes: `≔…⁺⪫ＥχＩιωβＮθＦＳ§θ⊕⌕θι`
> 0 votes

# Answer
# PHP, 87 bytes

```
list(,$a,$b)=$argv;for(;$c=intval($a{$i++},$b);)echo$b>1?base_convert(++$c%$b,10,$b):1;

```

Run with `-r` like this:

```
php -r "list(,$a,$b)=$argv;for(;$c=intval($a{$i++},$b);)echo$b>1?base_convert(++$c%$b,10,$b):1;" xyz 36

```

Works with bases 1 to 36, inclusive.
> 0 votes

# Answer
# Bash, 71 bytes

```
b=({0..9} {a..z})
for c in `fold -w1<<<$1`;{ echo -n ${b[-~$2#$c%$2]};}

```

Try it online!
> 0 votes

# Answer
# Perl 5 `-lF`, ~~61~~ 53 bytes

```
$l=(0..9,a..z,aa)[<>];say map{++$_;/$l/?0:s/10/a/r}@F

```

Try it online!
> 0 votes

# Answer
# Stax, 6 bytes

```
╕W─░ì]

```

Run and debug it

### Procedure:

1. Push constant "0123456789abcdefghijklmnopqrstuvwxyz".
2. Get and eval base, now two spots down the stack
3. Truncate digit string to specified count.
4. "Ring" translate using remaining characters. This maps each character to the next, wrapping around to "0" at the end.
> 0 votes

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


# Question
Title: Look mom! I made my own (Base 10) numeral system!
We've all done it, well, maybe not, but making your own alien language and numbering system is a staple of especially fantasy writing, but is mostly just a fun activity.

The task is simple, take two inputs:

1. An ordered list input of 10 \[ten\] unique 'numerals' (any printable ASCII character) and interpret them, in order, as the values 0, 1, 2, 3,...,9

+There are exceptions to what can be a numeral here. Arithmetic operators (+, -, \*, /), Parentheses, and spaces cannot be used as one of the numerals.
2. An arithmetic problem using only those 'numerals'

And output the equivalent integer result in the given form.

Here's an example:

```
INPUT

abcdefghij

bcd + efg + hij

```

```
OUTPUT

bdgi

```

In the example, the input list (you may choose which form the list comes in) of 'abcdefghij' corresponds to '0123456789' just as 'hjkloiwdfp' would also correspond 1 to 1 with '0123456789' where instead of 'a' associating with zero, 'h' does. The arithmetic following 'translates' to 123 + 456 + 789, which equals 1368. This must then be outputted in the form we gave it, so b (which represents 1) d (for 2) g (for 6) and i (for 8).

**TEST CASES**

```
abcdefghij
abc + def - ghij

-gedc

```

```
qwertyuiop
qwerty / uiop

e

```

```
%y83l;[=9|
(83l * 9) + 8%

y9|8

```

***MORE RULES***

* Standard Loopholes are forbidden!
* This is code golf, so shortest answers in bytes wins.
* Must be a full program or function taking the inputs and outputs in whatever format works best for you. (Just cannot add additioal information in the inputs, just 'numerals' and the expression.
* Use any language you'd like (as long as it complies with other rules)

# Answer
> 11 votes
# 05AB1E, ~~10~~ 9 bytes

```
žh‡.Eò¹Åв

```

(Now) outputs as a list of characters.

Try it online or verify all test cases.

**Explanation:**

```
  ‡        # Transliterate the second (implicit) input, replacing every character of
           # the first (implicit) input with:
žh         # The builtin "0123456789"
   .E      # Then evaluate it as Elixir code
     ò     # Round it to the nearest integer
      ¹Åв  # And change it back by using a custom base-conversion with the first input as
           # base (which results in a character list)
           # (after which that result is output implicitly)

```

The new version of 05AB1E is build is build in Elixir. The `.E` function will call `call_unary(fn x -> {result, _} = Code.eval_string(to_string(x)); result end, a)`, where the `Code.eval_string` is an Elixir builtin.

Note that the legacy version of 05AB1E won't work for this, because it is build in Python. The numbers with leading 0s won't be evaluated:
See all test cases in the legacy version (which uses the 10-byte version because the `Åв` builtin is new).

# Answer
> 8 votes
# , 58 bytes

```
function(d,s,`[`=chartr)'0-9'[d,eval(parse(t=d['0-9',s]))]

```

Try it online!

Uses character translation `chartr` to swap the digits, `parse`s and `eval`s the expression, and then `chartr`s back to the original digits.

If rounding to nearest integer is required, this is

# , 65 bytes

```
function(d,s,`[`=chartr)'0-9'[d,round(eval(parse(t=d['0-9',s])))]

```

Try it online!

# Answer
> 6 votes
# T-SQL, 117 bytes

```
DECLARE @ CHAR(99)
SELECT @='SELECT TRANSLATE('+TRANSLATE(e,c,'0123456789')+',''0123456789'','''+c+''')'FROM t
EXEC(@)

```

Line breaks are for readability only.

Input is via a pre-existing table **t** with text columns **c** (characters) and **e** (equation), per our IO rules.

Uses the SQL 2017 function `TRANSLATE` to switch between characters and generate a string that contains not only the equation, but the code to translate back to the original characters:

```
SELECT TRANSLATE(123 + 456 + 789,'0123456789','abcdefghij')

```

This string is then evaluated using `EXEC()`.

There may be some characters (such as a single quote `'`) that would break this code; I haven't tested all possible ASCII characters.

Per the challenge, I am evaluating the expression as given, subject to how my language interprets those operators. As such, the second test case returns 1 (`w`), and not 2 (`e`), due to integer division.

# Answer
> 4 votes
# Perl 6, 38 bytes

```
{*.trans($_=>^10).EVAL.trans(^10=>$_)}

```

Try it online!

I'm not sure how the rounding is supposed to work. If it rounds at the end then I can add `.round` for +6 bytes. If the behaviour of `/` should be different then it may be longer. Takes input curried like `f(arithmetic)(numerals)(arithmetic)`.

### Explanation:

```
{                                    }  # Anonymous codeblock
 *                                      # Returning a whatever lambda
  .trans($_=>^10)       # That translates the numerals to digits
                 .EVAL  # Evaluates the result as code
                      .trans(^10=>$_)   # And translates it back again

```

# Answer
> 3 votes
# Stax, ~~74~~ ~~66~~ 65 bytes

```
┼ö8Q#xóπcM~oÖ÷╦├mî☼yº─▐4ç≥e╘o▄ê‼ø_k╜ø8%N╫ ╗e<.╗P[─╛èA±!xêj«w╠°{B♪

```

Run and debug it

Stax does not do well here, lacking a true "eval" instruction. It has one that's called "eval" in the docs, but it only works on literal values, not full expressions.

# Answer
> 3 votes
# Bash, 97 bytes

```
IFS=''
read S
read O
A=`echo "$O"|tr "$S" 0-9`
printf %0.f `bc<<<"(${A[@]##0})+0.5"`|tr 0-9 "$S"

```

Could be less if we could truncate, rather than round. Also tricky to handle leading zeroes (as in test case #2) since Bash interprets numbers starting with 0 as octal.

# Answer
> 2 votes
# Perl 5 `-p`, 63 bytes

```
$p=<>;eval"y/$p/0-9/";s/\b0+\B//g;$_=int.5+eval;eval"y/0-9/$p/"

```

Try it online!

Takes the expression on the first line of input and the translation list on the second.

# Answer
> 2 votes
# Bean, ~~94~~ 90 bytes

### Hexdump

```
00000000: 53d0 80d6 d800 d3d0 80a0 1f20 8047 53a0  SÐ.ÖØ.ÓÐ. . .GS
00000010: 1753 d080 d3d0 80a0 5e20 800a a181 8100  .SÐ.ÓÐ. ^ ..¡...
00000020: 40a0 5f52 cac3 4da0 6580 53d0 80a0 5d20  @ _RÊÃM e.SÐ. ]
00000030: 8089 205f a065 205f 2080 0aa1 8181 0123  .. _ e _ ..¡...#
00000040: 0058 0020 800a a181 8102 40a0 6550 84a0  .X. ..¡...@ eP.
00000050: 5d20 652e dce2 b02b dc64                 ] e.Üâ°+Üd

```

### JavaScript

```
`${Math.round(
  eval(
    b.replace(
      /./g,
      c => ~(i = a.indexOf(c)) ? i : c
    ).replace(
      /\b0+/g,
      ''
    )
  )
)}`.replace(
  /\d/g,
  i => a[i]
)

```

## Explanation

This program implicitly assigns the first and second lines of input as strings to the variables `a` and `b` respectively.

Each character `c` on line `b` is replaced with the respective index `i` of the character found on line `a`, or itself if it is not found.

Then it removes each sequence of one or more `0`s preceded by a boundary from the resulting string. This is to prevent `eval()` from evaluating any sequence of digits starting with `0` as an octal literal.

After `eval()` and `Math.round()`, the result is coerced back into a string and each digit character `i` is replaced by the corresponding character from line `a` at index `i`.

## Test Cases

Demo

```
abcdefghij
abcd + efg + hij

bdgi

```

Demo

```
abcdefghij
abc + def - ghij

-gedc

```

Demo

```
qwertyuiop
qwerty / uiop

e

```

Demo

```
%y83l;[=9|
(83l * 9) + 8%

y9|8

```

# Answer
> 1 votes
# Perl 5, 130 bytes

```
sub f{eval sprintf"'%.0f'=~y/%s/%s/r",eval(eval(sprintf"\$_[1]=~y/%s/%s/r",@r=map"\Q$_",$_[0],'0123456789')=~s,\b0,,gr),reverse@r}

```

Try it online!

Maybe that double eval somehow can be turned into `s/.../.../geer`.

# Answer
> 1 votes
# Charcoal, 14 bytes

```
⍘ＵＶ⭆η⎇№θι⌕θιιθ

```

Try it online! Link is to verbose version of code. Note: Expression is evaluated according to Python 3 semantics, so for instance leading zeros on non-zero numbers are illegal. Explanation:

```
   ⭆η           Map over expression's characters and join
        ι       Current character
      №θ        Count matches in first input
     ⎇          If non-zero
         ⌕θι    Replace with position in first input
            ι   Otherwise keep character unchanged
 ＵＶ             Evaluate as Python 3
⍘            θ  Convert to base using first input as digits

```

# Answer
> 0 votes
# Python 3, 167 bytes

```
import re
a=[*enumerate(input())]
e=input()
for i,c in a:e=re.sub(c,str(i),e)
e=str(round(eval(re.sub(r'\b0+(?!\b)','',e))))
for i,c in a:e=re.sub(str(i),c,e)
print(e)

```

Try it online!

Room for improvement...

# Answer
> 0 votes
# Lua, ~~162~~ ~~151~~ 150 bytes

* -11 bytes thanks to my idea of using `load` instead of `function(...) end`
* -1 byte by omitting newline

```
l,p=...print(((math.ceil(load('return '..p:gsub('.',load'n=l:find(...,1,1)return n and n-1'))()-0.5)..''):gsub('%d',load'c=...+1 return l:sub(c,c)')))

```

Try it online!

Not shortest thing in the world (Lua forces you to be fancy quite hard, especially by huge keywords), but was pretty fun to create. Full program taking input as arguments and printing result.

## Explanation

### Introduction

```
l,p=...

```

Assign values from arguments to variables. Our dictionary is `l` and expression is `p`.

Following expression is quite hard to understand because it have a weird order of execution, so I'll explain it step-by-step:

### Converting to normal numbers

```
p:gsub('.',
load'n=l:find(...,1,1)return n and n-1')

```

Perform replacement on expression string: take each symbol and pass it to function (`load` proved itself to be shorted than normal declaration here).

Function finds position of occurrence in dict string for passed symbol using `find`. `...` is first (and only) argument here as we're in vaarg function (any `load`ed one is) that is our current symbol. Following arguments are required to make `find` ignore special symbols (`1` is just short value which evaluates as `true` when converted to boolean): starting position (one is default here) and `plain`, which actually disables pattern handling. Without those program fails on third test case due to `%` being special.

If match is found, subtract one as Lua strings (and arrays btw) are 1-based. If no match is found, it will return nothing, resulting in no replacement being done.

### Solving

```
math.ceil(load('return '..ABOVE)()-0.5)

```

Prepend `return` to our expression to let it return result, calculate it by compiling as Lua function and calling it, perform rounding (this turned other way around to make it shorter).

It the end we get a numerical solution to our problem, only converting it back remains.

### Making it crazy again

```
(ABOVE..'')
:gsub('%d',load'c=...+1 return l:sub(c,c)')

```

First line is a short way to convert number to string, so now we can call string methods in a short way. Let's do so!

Now `gsub` is called again to replace everything back to insanity. This time `%d` is used instead of `.` as replacement pattern as our function may and must process only numbers (`.` would result to error on negative numbers). This time function (`load`ed again to save bytes) first adds `1` to its first (and only) vaargument, converting it to position in dict string, then returns character from it at that position.

Hooray, almost there!

### Dramatic finale, or Why Brackets Matter

```
print((ABOVE))

```

Well… why two pairs of brackets anyways? It's time to talk about parall… eh, multiple return in Lua. Thing is that one function may return few values from one call (look at this meta question for more examples).

Here, last `gsub` returned two values: answer string we need and amount of replacements done (count of digits actually, but who cares). If it wasn't for internal pair, both string and number would be printed, screwing us up. So here we sacrifice two bytes to omit second result and finally print product of this insanity factory.

---

Well, I've enjoyed explaining almost as much as golfing in first place, hope you got what's going on here.

# Answer
> 0 votes
# Python 3, 137 bytes

A non-regex approach using `str.translate` and `str.maketrans` to replace the characters. I lost a lot of characters on trimming the leading zeros...

```
lambda s,t,d='0123456789',e=str.translate,m=str.maketrans:e(str(round(eval(' '.join(c.lstrip('0')for c in e(t,m(s,d)).split())))),m(d,s))

```

Try it online!

# Answer
> 0 votes
# Wolfram Language (Mathematica), 121 bytes

I define a pure function with two arguments. Since some functions are repeated I save them in a variable to save a few characters. This code simply does some string replacements and then uses `ToExpression` to evaluate the expression with the Wolfram kernel.

```
(r=Thread[StringPartition[#,1]->(t=ToString)/@Range[0,9]];u[(u=StringReplace)[#2,r]//ToExpression//Round//t,Reverse/@r])&

```

Try it online!

---
Tags: code-golf, arithmetic
---


# Question
Title: Decode a Microsoft MS-DOS 5.0 FAT directory entry
The Microsoft FAT file system has a directory table to represent which "files" are in which "folders" on the disk. For the time, these entries crammed a lot of information into a small amount of bits. There are a bunch of technical specifications over on Wiki for the curious, but the challenge here is going to focus on a "simple" decoding of an entry.

Each entry consists of a 32-byte binary word, broken up into several sections. For consistency in this challenge, we'll be using the MS-DOS 5.0 version, the bytes are ordered as **big endian**, and we're calling byte `0x00` as the left-most, and byte `0x1F` as the right-most.

Below is a brief schematic of the relevant sections, and what should be the output for each section (in **bold**).

* The first 11 bytes are the file name in ASCII format (this is where the famous 8.3 filename comes from -- 8 bytes for the file name, 3 bytes for the extension). These are straight ASCII encoding, and should be **output as ASCII with a period (.) between**.
    + Note: both the 8 and the 3 parts are padded with spaces to make a full-length entry. The output should **ignore spaces** (i.e., don't output them).
    + The file extension may be empty (i.e., all spaces), in which case the output should **not output the dot**.
    + Since ASCII only uses the lower 7 bits, the bytes will all have a leading `0`.
* The next byte (0x0b) is a bitmask of the following:
    + 0x01 Read Only - output **RO**
    + 0x02 Hidden - output **H**
    + 0x04 System - output **S**
    + 0x08 Volume Label - output **VL**. File size (below) should be output as **0**, regardless of its actual entry.
    + 0x10 Subdirectory - output **SD**. File size (below) should be output as **0**, regardless of its actual entry.
    + 0x20 Archive - output **A**
    + 0x40 Device - ignored for this challenge.
    + 0x80 Reserved - ignored for this challenge.
    + Since this is a bitmask, multiple flags are possible - all applicable outputs should be concatenated together in any order. For example, `0xff` could be `ROHSVLSDA` (or any other combination).
* The next two bytes (0x0c and 0x0d) are not used under MS-DOS 5.0.
* The next two bytes (0x0e and 0x0f) are the creation time as follows:
    + Bits 15 to 11 are the hours in 24-hour format - output **00** to **23**
    + Bits 10 to 5 are the minutes - output **00** to **59**
    + Bits 4 to 0 are the seconds/2 - output **00** to **58** (note that seconds are only in two-second resolution)
    + For clarification: `hhhhhmmmmmmsssss` when written big-endian.
* The next two bytes (0x10 and 0x11) are the creation date as follows:
    + Bits 15 to 9 are the year - output **1980** for `0` up to **2107** for `127`
    + Bits 8 to 5 are the months - output **1** to **12** (with or without leading zero)
    + Bits 4 to 0 are the day - output **0** to **31** (with or without leading zero)
    + For clarification: `yyyyyyymmmmddddd` when written big-endian.
* The next two bytes (0x12 and 0x13) are the last access date. While used in MS-DOS 5.0, we're ignoring this portion for this challenge.
* The next two bytes (0x14 and 0x15) are not used by MS-DOS 5.0.
* The next two bytes (0x16 and 0x17) are the last modified time, following the same format as the creation time, above.
* The next two bytes (0x18 and 0x19) are the last modified date, following the same format as the creation date, above.
* The next two bytes (0x1a and 0x1b) are the cluster location of the file on disk. We're ignoring this portion for this challenge.
* The final four bytes (0x1c, 0x1d, 0x1e, and 0x1f) are the file size - output as an **unsigned integer**, unless the **VL** or **SD** flags are set (above), in which case output `0`.

**Visual representation**

```
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
\______________________________FILENAME________________________________________________/\_ATTR_/\___NOTUSED____/\_CREATIONTIME_/\_CREATIONDATE_/\__LASTACCESS__/\___NOTUSED____/\_MODIFIEDTIME_/\_MODIFIEDDATE_/\___NOTUSED____/\___________FILESIZE___________/

```

## Input

* A single 32-byte word (i.e., 256 bits), in whatever format is convenient.
    + This could be as a string of `1` and `0`, as several unsigned `int`s, an array of Boolean values, etc.
    + Please specify in your answer what format you're using for input.
    + You *cannot* take multiple input (i.e., an array pre-broken into the relevant byte sizes) unless that is the *only* way for your language to take input. Parsing the input is part of the challenge.
* You can assume input to be valid (for example, you don't need to perform date checking to verify that the date is valid).
* Bytes that are unused can be all `0`, all `1`, etc., just so long as they are present. In the below examples, I used all `0` for the unused bytes.

## Output

Either printed to screen or returned, the following:

* The filename as an ASCII string
* The file attributes as an ASCII string
* The creation time and creation date, with appropriate separators (colons, slashes, something to distinguish the components)
* The modified time and modified date, again with appropriate separators
* The file size

The output can be a space-separated or newline-separated single string, separate elements in an array, etc. Please specify in your answer how your output is formatted.

## Rules

* Standard I/O formats are acceptable.
* Either a full program or a function are acceptable.
* Standard loopholes are forbidden.
* This is , so all usual golfing rules apply, and the shortest code wins.
* Built-ins that perform exactly this function are forbidden.

### Examples

```
0111000001110010011011110110011101110010011000010110110101101101011010010110111001100111000001100000000000000000101000100100010001001000110101000000000000000000000000000000000010100010010001000100100011010100000000000000000000000000000000001101000000000000

programm.ing HS 20:18:08 2016/06/20 20:18:08 2016/06/20 53248

0010000000100000001000000010000001110000011100000110001101100111001000000010000000100000000101000000000000000000010111010110110000111101100111110000000000000000000000000000000010100010010001000100100011010100000000000000000011110000000100111111001011100001

ppcg SDS 11:43:24 2010/12/31 20:18:08 2016/06/20 0

```

# Answer
> 6 votes
# Verilog, ~~513~~ ~~670~~ 617 bytes

Runs using IVerilog. No special compile flags needed.

This is a monster of nested definitions, bit-twiddling, and the annoyance of having to flip bit order due to the endianness (otherwise either the string doesn't print, or the number bit order is wrong). The input is taken through the `i` port, which is the usual way of taking input into a Verilog module. `$display` is used to print to standard out. 6 bytes could be saved if leading zeros were not required for the timestamp.

```
`define r(o,b)wire[3:0]o;assign o={i[b],i[b+1],i[b+2],i[b+3]};
`define R(t,a,b,c,d,s)`r(a,s)`r(b,s+4)`r(c,s+8)`r(d,s+12)wire[15:0]t;assign t={a,b,c,d};
`define p(m,k)i[90+m]?"k":"",
`define F(a,b)"a a a b\t b%d"
module f(input[0:255]i);`R(d,q,w,e,r,112)`R(D,Q,W,E,R,128)`R(s,z,x,c,v,224)`R(S,Z,X,C,V,240)`R(p,t,y,u,o,176)`R (A,b,n,m,l,192)always@(i)$display(`F(%s%s%s,%02d:%02d:%02d%d/%d/%d),i[0:63],i[64:87]=="   "?" ":".",i[64:87],`p(5,RO)`p(4,H)`p(3,S)`p(2,VL)`p(1,SD)`p(0,A)d[15:11],d[10:5],d[4:0]*2,D[15:9]+1980,D[8:5],D[4:0],p[15:11],p[10:5],p[4:0]*2,A[15:9]+1980,A[8:5],A[4:0],|i[91:92]?0:{s,S});endmodule

```

**Demo**

Testbench (Not scored):

```
`timescale 1ns / 1ps

module ftest;
reg [0:255] i;
f uut (
.i(i)
);
initial begin
    i=256'b0111000001110010011011110110011101110010011000010110110101101101011010010110111001100111000001100000000000000000101000100100010001001000110101000000000000000000000000000000000010100010010001000100100011010100000000000000000000000000000000001101000000000000;
    #100;
i=256'b0010000000100000001000000010000001110000011100000110001101100111001000000010000000100000000101000000000000000000010111010110110000111101100111110000000000000000000000000000000010100010010001000100100011010100000000000000000011110000000100111111001011100001;
end

endmodule

```

Example run:

```
$ iverilog design.sv testbench.sv  && vvp a.out
programm.ing   HS      20:18:08       2016/ 6/20      53248
    ppcg        S  SD  11:43:24       2010/12/31          0

```

# Answer
> 5 votes
# Python, ~~485, 479, 442, 438, 431, 429, 418, 402, 395, 391~~, 370 bytes.

Saved 19 bytes thank to Cᴏɴᴏʀ O'Bʀɪᴇɴ reminding me that I can assign functions to a letter.

Saved 6 bytes thanks to FryAmTheEggman's suggestion to clean up the bitmask filter.

Saved 21 bytes thanks to W0lf's awesome Ruby answer forcing me to golf this down some more. ;)

This is an absolute monster. Pretty sure I can cut it down a bit more, but it's getting pretty close to being golfed out.

```
a=input()
j=''.join
n=lambda v:int(v,2)
f=j('RO H S VL SD A'.split()[i]for i in range(6)if n(a[88:96])&2**i)
print(j(chr(n(a[x:x+8])).strip()+'.'*(x==56)for x in range(0,88,8)).strip('.'),f,j('%02d:%02d:%02d'%(n(a[b-11:b-6]),n(a[b-6:b]),n(a[b:b+6]))+' %d/%d/%d '%(n(a[b+6:b+12])+1980,n(a[b+12:b+16]),n(a[b+16:b+21]))for b in[123,187]),n(a[208:])*(1-('V'in f or'D'in f)))

```

# Answer
> 4 votes
# Haskell, ~~781~~ 710 bytes

Thanks to BlackCap for some simplification

```
w n=('0'<$[1..2-length a])++a where a=show n
x s=tail.foldr(\a b->s:a++b)""
t=snd.span(==' ')
y a|all(==' ')a=""|0<1='.':t a
nm=(\(a,b)->t a++y b).splitAt 8
ms n(r,s)|n`mod`2^(r+1)`div`2^r>0=s|0<1=""
tm n=x ':'[w$n`div`2^11,w$n`mod`2^11`div`32,w$2*n`mod`64]
dt n=x '/'[w$1980+n`div`2^9,w$n`mod`2^9`div`32,w$n`mod`32]
pa s=x ' '[nm.map(toEnum.v.take 8).takeWhile(not.null)$iterate(drop 8)a,t,dt$v i,tm$v g,dt$v o,tm$v m,show u,"\n"]where{z n=splitAt(8*n);(a,b)=z 11 s;(c,d)=z 1 b;(e,f)=z 2 d;(g,h)=z 2 f;(i,j)=z 2 h;(k,l)=z 4 j;(m,n)=z 2 l;(o,p)=z 2 n;(q,r)=z 2 p;t=(zip [0..](words"RO H S VL SD A")>>=).ms$v c;u|any(`elem`t)"LD"=0|0<1=v r;v=foldl((+).(2*))0.map(read.pure).filter(`elem`"01")}
main=interact pa

```

This additionally allows garbage (like a newline character) to appear after the input.

# Answer
> 3 votes
# Java, ~~1721~~ ~~1587~~ ~~1573~~ ~~1560~~ 1511 bytes:

```
import java.util.*;class A{int Q(String a,int b){return Integer.parseInt(a,b);}String P(int a){return Integer.toString(a);}ArrayList<String>B=new ArrayList<String>();void J(String O){B.add(O);}String TD(String l,String p,int a,int c,int d){String X,Y,Z;X=Y=Z=new String();int i=0;for(char F:l.toCharArray()){if(i<a){X+=F;}if(a<=i&i<c){Y+=F;}if(c<=i){Z+=F;}i++;}String[]H=new String[3];H[0]=P(d+Q(X,2));H[1]=P(Q(Y,2));H[2]=(p==":")?P(Q(Z,2)*2):P(Q(Z,2));int T=0;for(String A:H){H[T]=(A.length()<2)?"0"+A:A;T++;}return H[0]+p+H[1]+p+H[2];}String D(String i){String K=new String();int L=0;for(char Y:i.toCharArray()){if(L%8<1){K+=" ";}K+=Y;L++;}String[]C=K.split(" ");String[]z={"RO","H","S","VL","SD","A"};int[]l={1,2,4,8,16,32};Map<Integer,String>U=new HashMap<Integer,String>();for (int e=0;e<l.length;e++){U.put(l[e],z[e]);}String[]N={":","/",":","/"};int[]M={15,17,23,25};int[]O={5,7,5,7};int[]P={0,1980,0,1980};for(int y=1;y<9;y++){if((char)Q(C[y],2)!=' '){J(Character.toString((char)Q(C[y],2)));}}for(int v=9;v<12;v++){if((char)Q(C[v],2)!=' '){if(!B.contains(".")){J(".");}J(Character.toString((char)Q(C[v],2)));}}J(" ");int T=(char)Q(C[12],2);while(T>0){int H=l[0];for(int V:l){if(V<=T){H=V;}}J(U.get(H));T-=H;}for(int w=0;w<4;w++){J(" ");J(TD(C[M[w]]+C[M[w]+1],N[w],O[w],11,P[w]));}J(" ");if(B.contains("SD")||B.contains("VL")){J("0");}else{J(P(Q(C[29]+C[30]+C[31]+C[32],2)));}return String.join("",B);}public static void main(String[]a){A H=new A();System.out.print(H.D(new Scanner(System.in).next()));}}

```

Takes input in the format of 32 byte binary string. Outputs in the format of a space separated string. This may be a very *very* long answer, but I'm still not disappointed. I'm just happy I was able to implement this in Java. I will still try to golf this as much as I can, though.

Try It Online! (Ideone)

# Answer
> 2 votes
# Ruby, 344 bytes

```
m=gets
s=->b,l{b.slice!(0,l).to_i 2}
t=->b{'%02d:%02d:%02d %d/%d/%d'%[s[b,5],s[b,6],2*s[b,5],s[b,7]+1980,s[b,4],s[b,5],]}
i=(0..q=32).map{|i|m[i*8,8].to_i 2}
c=i.map(&:chr).join
n=c[0,8].strip
e=c[8,3].strip
e>?!&&n<<?.+e
f=''
6.times{|j|i[11][j]>0&&f<<%w(RO H S VL SD A)[j]}
$><<[n,f,t[m[112,q]],t[m[176,q]],(f[/VL|SD/]?0:m[-q,q].to_i(2))]*' '

```

The slightly more readable version is available here.

Online test: http://ideone.com/Fww1Rw

# Answer
> 2 votes
# JavaScript (ES6), 369

```
(b,Z=n=>n>9?n:'0'+n,W=n=>s[n]<<8|s[n+1],U=n=>[Z((t=W(n))>>11)+`:${Z(t>>5&63)}:`+Z(t%32*2),((t=W(n+2))>>9)+1980+`/${t>>5&15}/`+t%32],X=l=>String.fromCharCode(...s.slice(p,p+=l)).trim(),s=b.match(/.{8}/g).map(x=>+('0b'+x)),p=0)=>[X(8)+((x=X(3))?'.'+x:x),[...b].map((b,i)=>'A,SD,VL,S,H,RO'.split`,`[z=(2*z|b)%4294967296,i*b-90]||'',z=0).join``,U(14),U(22),b[92]|b[91]?0:z]

```

*Less golfed*

```
(b,
  Z=n=>n>9?n:'0'+n, // zero pad
  W=n=>s[n]<<8|s[n+1], // get word
  U=n=>[
   Z((t=W(n))>>11)+`:${Z((t>>5&63)}:`+Z(t%32*2),  // decode time
   ((t=W(n+2))>>9)+1980+`/${t>>5&15}/`+t%32 // decode date
  ],
  X=l=>String.fromCharCode(...s.slice(p,p+=l)).trim(), // extract space padded string
  s=b.match(/.{8}/g).map(x=>+('0b'+x)), // convert bits to bytes
  p=0
)=>
  [ X(8)+((x=X(3))?'.'+x:x),
    [...b].map((b,i)=>'A,SD,VL,S,H,RO'.split`,`[i*b-90]||'').join``,
    [...b].slice(-32).map((b,i)=>z=2*z|b,z=0), // this line merged with the preceding one in the golfed code
    U(14),U(22),
    b[92]|b[91]?0:z
  ]

```

**Test**

```
f=(b,Z=n=>n>9?n:'0'+n,W=n=>s[n]<<8|s[n+1],U=n=>[Z((t=W(n))>>11)+`:${Z(t>>5&63)}:`+Z(t%32*2),((t=W(n+2))>>9)+1980+`/${t>>5&15}/`+t%32],X=l=>String.fromCharCode(...s.slice(p,p+=l)).trim(),s=b.match(/.{8}/g).map(x=>+('0b'+x)),p=0)=>[X(8)+((x=X(3))?'.'+x:x),[...b].map((b,i)=>'A,SD,VL,S,H,RO'.split`,`[z=(2*z|b)%4294967296,i*b-90]||'',z=0).join``,U(14),U(22),b[92]|b[91]?0:z]

O.textContent+='\n'+f('0111000001110010011011110110011101110010011000010110110101101101011010010110111001100111000001100000000000000000101000100100010001001000110101000000000000000000000000000000000010100010010001000100100011010100000000000000000000000000000000001101000000000000')
O.textContent+='\n'+f('0010000000100000001000000010000001110000011100000110001101100111001000000010000000100000000101000000000000000000010111010110110000111101100111110000000000000000000000000000000010100010010001000100100011010100000000000000000011110000000100111111001011100001')
```

```
<pre id=O></pre>
```

# Answer
> 2 votes
# PHP, ~~301~~ 288 bytes

```
for($b=unpack('A8f/A3e/Cl/n/Nc/N/Nm/n/Ns',$argn);$i<8;$f.=1<<$i++&$b[l]?[RO,H,S,VL,SD,A][$i-1]:'');echo trim($b[f].'.'.$b[e],' .')," $f ",($e=function($a){echo date('H:i:s Y/m/d ',mktime($a>>27&31,$a>>21&63,$a>>15&62,$a>>5&15,$a&31,1980+($a>>9&127)));})($b[c]),$e($b[m]),$b[l]&24?0:$b[s];

```

Try it online!

Input is a 32 byte word string via `STDIN`, output to `STDOUT`.

**-13 bytes** as a standalone program.

# Answer
> 2 votes
# Stax, 111 bytes

```
¼ΘUßU'ïMo^ø¬├▓> I¬i⌠·╥.↕¥½ßqS,=frT`d_`&&↓⌠ÉûÆiü=┌-< │∟Φ☼⌐¢3²Bu╜lJ╛§≥╪║ε┐╓ù♫╨Z░╖!¥É:╬Çß═╤às8Q←φ,ºï◘≥Ä£}èΦ╡FÉçø¶É

```

Run and debug it

# Answer
> 1 votes
# Perl, 249 bytes

Takes 32 bytes as input, output is separated by newlines. `unpack` is perfect for this kind of binary structure parsing.

```
($f,$e,$a,$C,$M,$s)=unpack"A8A3CxxNx4Nx2N",<>;$f=~s/ //g;$e=~s/ //g;printf"%s
@{[map+(RO,H,S,VL,SD,A)[$a&1<<$_?$_:9],0..5]}
"."%02d:%02d:%02d %d/%d/%d
"x2 .$s*!($a&24),$f.".$e"x!!$e,map{$_>>27,$_>>21&63,$_>>15&62,$_/512%128+1980,$_>>5&15,$_&31}$C,$M

```

Some highlights:

* The aforementioned `unpack`.
* The turtle operator `@{[]}` allows to interpolate code in a string. It actually creates an array reference that is then dereferenced.
* `"$str1"x!!$str2` is a nice way to return `$str1` only if `$str2` is a non-empty string.

Below is a version that works on real directory entries, with little-endian fields, and only ignoring right padding on the filename and extension (so, e.g. `" ppcg"` doesn't have its initial whitespace removed) *(254 bytes)*

```
($f,$e,$a,$C,$M,$s)=unpack"A8A3CxxVx4Vx2V",<>;$f=~s/ +$//;$e=~s/ +$//;printf"%s
@{[map+(RO,H,S,VL,SD,A)[$a&1<<$_?$_:9],0..5]}
"."%02d:%02d:%02d %d/%d/%d
"x2 .$s*!($a&24),$f.".$e"x!!$e,map{$_>>11&31,$_>>5&63,2*$_&63,($_>>25)+1980,$_>>21&15,$_>>16&31}$C,$M

```

---
Tags: code-golf, parsing, file-system
---


title: Dropsort with a Twist

text:
# Question
Title: Dropsort with a Twist
This is my first attempt at a Code Golf question. If it needs obvious edits, please feel free to make them.

Below is a description of the basic Dropsort algorithm.

> Dropsort is run on a list of numbers by examining the numbers in sequence, beginning with the second number in the list. If the number being examined is less than the number before it, drop it from the list. Otherwise, it is in sorted order, so keep it. Then move to the next number.
>
> After a single pass of this algorithm, the list will only contain numbers that are at least as large as the previous number in the list. In other words, the list will be sorted!

For example, given a list of numbers `1,65,40,155,120,122`, the `40,120,122` numbers will be dropped, leaving `1,65,155` in the sorted list.

**Let's implement a new sorting algorithm called DropSortTwist.**

This sort is identical to Dropsort except that a number (including the first number) that would be kept in Dropsort may optionally be dropped instead. DropSortTwist must return (one of) the longest possible sorted list.

For example, using the same list of numbers as above, DropSortTwist must return either `1,65,120,122` or `1,40,120,122`. In both cases the `155` number is dropped to achieve a sorted list of length 4, one greater than the Dropsort list.

In this task, you will be given a list of integers as input (STDIN or function argument, you are required to support at least the range of 8-bit signed integers.) You must return the longest possible increasing subsequence.

You may assume that the list is non-empty.

This is code golf, so the shortest program wins.

**Test Cases**

```
input                    output
1 65 40 155 120 122      1 65 120 122  [or]  1 40 120 122
5 1 2 2 3 4              1 2 2 3 4

```

# Answer
# Jelly, 6 bytes

```
ŒPṢƑƇṪ

```

**Try it online!**

### How?

Pretty much the same approach as Grimy's 05AB1E entry

```
ŒPṢƑƇṪ - Link: list of integers
ŒP     - power-set (all subsequences, from shortest to longest)
    Ƈ  - filter keep those which are:
   Ƒ   -   invariant when:
  Ṣ    -     sorted
     Ṫ - tail

```
> 3 votes

# Answer
# 05AB1E, 8 bytes

```
æʒD{Q}éθ

```

Try it online!

```
æ           # list of subsequences
 ʒD{Q}      # filter, keep only the sorted subsequences
      é     # sort by length
       θ    # get the last (longest) one

```
> 3 votes

# Answer
# Japt `-h`, 9 bytes

```
à ñÊf_eZñ

```

Try it
> 1 votes

# Answer
# Python 2, ~~89~~ 83 bytes

```
f=lambda A:A>sorted(A)and max([f(A[:i]+A[i+1:])for i in range(len(A))],key=len)or A

```

Try it online!
> 0 votes

# Answer
# Stax, 9 bytes

```
éÑ<┬Θ╡Lφ0

```

Run and debug it

Naive approach: powerset, filter for sorted, sort on length, get tail.
> 0 votes

# Answer
# Ruby, 63 bytes

```
->a{s=a.size;s-=1until r=a.combination(s).find{|e|e==e.sort};r}

```

Try it online!

```
->a{                                    # Anonymous Proc taking array input
    s=a.size;                           # Get array size

        until                           # Loop until the following condition is non-nil:
              r=a.combination(s)        #   Get all subsequences with length s
                    .find{|e|e==e.sort} #   Find a subsequence that is sorted, else nil
    s-=1                                # Reduce s by 1

    r                                   # Implicit return the found subsequence
}

```
> 0 votes

# Answer
# Wolfram Language (Mathematica), 37 bytes

```
Select[Reverse@Subsets@#,OrderedQ,1]&

```

Try it online!

The elements of `Subsets[ ]` are ordered from shortest to longest, so reversing it puts longer subsets first. Then, select the first one which is ordered.
> 0 votes

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


# Question
Title: Hello world! with limited character repetition
In a language of your choice, write a program that *exactly* outputs the characters `Hello world!` followed by a newline. The code:

* should not use any character more than twice (alphanumeric, symbol, whitespace...anything)
* should not use any external resources
* should not use any user input
* should not output anything else

An example of a valid python program:

```
print("He%so world!"%(2*'l'))

```

An example of an invalid python program (the character 'r' is used three times):

```
print("Hel"+chr(108)+'o world!')

```

Winner is whoever has the most votes after 14 days.

EDIT: A winner has been chosen! Thanks all for your work on this question!

# Answer
# Ruby (1.9+)

Since this is a popularity contest let's try to not use ANY of the characters from 'Hello world!' while still using other characters only a maximum of two times:

```
puts("S\107VsbG8gV29ybGQhCg".unpack(?m))

```

It's 40 chars btw.

# Bash

And this one uses unicode magic.

Notes:

* While the orignal characters appear elsewhere (unlike the ruby example), the printed string contains only non-ascii characters.
* Two from the three spaces are actually tabs, so there are no utf-8 characters that appear more than 2 times
* As binary some of the octets do appear more than 2 times, hopefully that's not against the rules. I'm trying to resolve them though.

Code:

```
echo ' ¡'|iconv -t  asCIi//TRANSLIT

```

For those who don't have a proper font installed it looks like this:

Here is the hexdump:

```
00000000  65 63 68 6f 20 27 f0 9d  93 97 f0 9d 90 9e f0 9d  |echo '..........|
00000010  91 99 f0 9d 92 8d f0 9d  93 b8 e2 80 8a f0 9d 93  |................|
00000020  a6 f0 9d 97 88 f0 9d 96  97 f0 9d 96 91 f0 9d 98  |................|
00000030  a5 c2 a1 27 7c 69 63 6f  6e 76 09 2d 74 09 61 73  |...'|iconv.-t.as|
00000040  43 49 69 2f 2f 54 52 41  4e 53 4c 49 54 0a        |CIi//TRANSLIT.|
0000004e

```

You have to run it on a machine where the default charset is utf-8. I tried on an OSX10.8 using iTerm2 with the following environment:

# PHP 5.4

This uses zLib: (unfortunately it does uses the characters `e` and `o`)

```
<?=gzuncompress('x▒▒H▒▒▒W(▒/▒IQ▒!qh');

```

Hexdump:

```
00000000  3c 3f 3d 67 7a 75 6e 63  6f 6d 70 72 65 73 73 28  |<?=gzuncompress(|
00000010  27 78 9c f3 48 cd c9 c9  57 28 cf 2f ca 49 51 e4  |'x..H...W(./.IQ.|
00000020  02 00 21 71 04 68 27 29  3b                       |..!q.h');|
00000029

```

# +1

Here is the ruby 2.0 code I used to test for duplicates:

```
d=ARGF.read
p [d.split(//),d.unpack('C*')].map{|x|x.inject(Hash.new(0)){|i,s|i[s]+=1;i}.select{|k,v|v>2}}

```
> 62 votes

# Answer
You have to use more expressive languages.

# Chinese,  6 4  3 chars

```
喂世!

```

Running google translate on this produces `Hello world!`

(thanks @sreservoir and @Quincunx for the update)
> 62 votes

# Answer
## HQ9+, 1 char

```
H

```

keeping it simple :)
> 45 votes

# Answer
# Vim command (18 keystrokes)

`iHe``Esc``3al``Esc``io Wor``Right``d!``Enter`

Doesn't repeat any keystroke more than twice.

It *kinda* violates the "user input" rule since it's still the user that needs to input that sequence, but I suppose if you store it as a macro or an nnoremap beforehand it would count, since you're just running it without explicitly doing any input to make it happen.

It also requires `nocompatible` to be set, which may count as using external resources, so I have provided another variation below:

---

# Vim command (21 keystrokes)

`iHe``Esc``3al``Esc``io Wor``Ctrl+[``$ad!``Enter`

This variation doesn't require `nocompatible` to be set, although it does work around using `Esc` three times by using `Ctrl+[` in its place.
> 45 votes

# Answer
## C, 192 chars

```
#
#
/*$$@``*/ATION_[]={9.};main(BBCDDEEFFGGHJJKKLLMMPPQQRRSSUUVVWWXXYYZZabbdefgghhjjkkmpqqsstuuvvwxyyzz) {printf("He%clo \
world!%c\
",2^7&!8.&~1|~-1?4|5?0x6C:48:6<3>2>=3<++ATION_[0],'@'^79-5);}

```

Since this isn't golf, I decided to have some fun and try to use every character *exactly* twice (while putting as few as possible in a comment, because that's boring). I realise that I didn't do terribly well, since my code contains a ton of boring "dead" code too (not in the literal sense, but in the sense of placeholder characters just used in order to fullfil the requirement). Anyway, this was surprisingly hard (but fun) with the two-character limitation, so unfortunately I couldn't come up with anything more interesting. It did give me an idea for a new problem though...

(Updated per @ugoren's comment.)
> 44 votes

# Answer
# Piet-- No characters whatsoever!
> 30 votes

# Answer
**Perl, 29 characters**

This answer includes x-rated clogs!

```
say"07-8*d<#B+>!"^xRATEDkL0GZ

```

**Perl, 23 characters**

Shorter, but no porno shoes. :-( Same basic idea though...

```
say'0@@lo World!'^"x%,"

```

**Perl, 20 characters**

Boring...

```
say"Hello Wor\x6Cd!"

```
> 26 votes

# Answer
## Powershell, 20

```
"He$('l'*2)o world!"

```
> 24 votes

# Answer
# Sclipting, 11 characters

```
丟낆녬닆묬긅덯댦롤긐뤊

```

I saw this beautiful HelloWorld program on esolang's Hello World program list.
> 19 votes

# Answer
# Scala: *34* 29 characters

I'm proud of myself for this one:

```
printf("He%c%co world!\n",108,108)

```

Had a really hard time overcoming duplicate 'l's, 'r's, quotation marks and brackets. Then I discovered the old Java `printf` function, which will happily convert numbers to letters when given the `%c` format specifier.

### Update

*MrWonderful* did a wonderful thing by pointing out that a whole bunch of characters can be saved by using up my second 'l' manually in the string!

```
printf("Hel%co world!\n",108)

```
> 18 votes

# Answer
## Python 3 \[38 bytes\]

```
exec('import '+chr(95)*2+"h\x65llo__")

```

I wouldn't consider `import __hello__` as an external resource.
> 17 votes

# Answer
# Perl: 34 characters

```
$_="He12o wor3d!
";s{\d}{l}g;print

```

Sample run:

```
bash-4.1# perl -e '$_="He12o wor3d!
> ";s{\d}{l}g;print'
Hello world!

```

(Not a big deal. Posted just to use at least once in my life `s///` with those fancy delimiters.)
> 15 votes

# Answer
# PHP, 33 chars

I just love how much PHP is forgiving and understanding!

```
<?=Hel.str_rot13("yb jbe").'ld!';

```

Before it was deleted (or if it's still there, I'm totally blind), I saw a comment saying "No brainf\*ck? :D". Well, it is pretty much impossible to write a solution in BrainF\*ck, as you know. But I managed to code this, just for the lulz.

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

```

If you don't have a BF interpreter, the code above just prints the PHP one :P
> 15 votes

# Answer
# HTML Fiddle \- 21 characters

```
Hello World!<br>

```
> 13 votes

# Answer
# Ruby: 27 characters

```
puts [:Hel,'o wor',"d!"]*?l

```

Sample run:

```
bash-4.1# ruby <<ENDOFSCRIPT
> puts [:Hel,'o wor',"d!"]*?l
> ENDOFSCRIPT
Hello world!

```

# Ruby: 25 characters

(Based on Vache's comment.)

```
puts 'He'+?l*2+"o world!"

```

# Ruby: 23 characters

(Copy of Danko Durbić's Powershell answer.)

```
puts"He#{?l*2}o world!"

```
> 12 votes

# Answer
# C - 43 Characters

```
main(){printf("Hel%co World!%c",'k'+1,10);}

```

## Output

```
Hello World!

```

## Character Counts

```
' ' Count: 1    '!' Count: 1    '"' Count: 2    '%' Count: 2    ''' Count: 2
'(' Count: 2    ')' Count: 2    '+' Count: 1    ',' Count: 2    '0' Count: 1
'1' Count: 2    ';' Count: 1    'H' Count: 1    'W' Count: 1    'a' Count: 1
'c' Count: 2    'd' Count: 1    'e' Count: 1    'f' Count: 1    'i' Count: 2
'k' Count: 1    'l' Count: 2    'm' Count: 1    'n' Count: 2    'o' Count: 2
'p' Count: 1    'r' Count: 2    't' Count: 1    '{' Count: 1    '}' Count: 1

```
> 11 votes

# Answer
## JavaScript, 66 characters

```
alert('Hel'+window.atob("\x62G8gd29ybGQhCg=="));//rH+in.\x689yQhC;

```

Inspired by FireFly, every character used by this code is used exactly twice.
> 11 votes

# Answer
## JavaScript \[37 bytes\]

```
alert(atob("SGVsbG8g")+'wor\x6cd!\n')

```

Too primitive isn't it?
> 9 votes

# Answer
# nginx.conf

```
return  200 "He&#x6clo wo&#x72ld!\n";

```

In action:

```
% curl -6 http://localhost/ | lynx -dump -stdin
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    21  100    21    0     0  20958      0 --:--:-- --:--:-- --:--:-- 21000

   Hello world!

%

```
> 9 votes

# Answer
# Emacs Command (15 keystrokes)

```
He<Ctrl-3>l<Left>o wor<End>d!<Enter>

```

If that vim answers is legal then this must be too :)

Joking aside, macro it can become too :)

More nonsense aside, I can probably squeeze some more, but this seems to be good enough for the time being (since it beats vim).

P.S., please ignore all my nonsense (I (rarely, but)use vim too!).
> 9 votes

# Answer
# Befunge 98

```
a"!dlrow ol":'e'Hck,@

```

Here is a version where every character appears twice.

```
bka!e:dw"H@!dlrow  ol":'e'Hbk,a,@

```

Leaves a bunch of junk on the stack.

As a bonus, every single character has something done with it by the IP.
> 6 votes

# Answer
## Malbolge

```
(=<`#9]~6ZY32Vw/.R,+Op(L,+k#Gh&}Cdz@aw=;zyKw%ut4Uqp0/mlejihtfrHcbaC2^W\>Z,XW)UTSL53\HGFjW

```
> 6 votes

# Answer
Actually I don't like cheating :P

**Python**

```
print("!dlrow os%eH"[::-1]%('l'*2))

```
> 5 votes

# Answer
## GolfScript

```
'He

o world!'n/"l"*

```

Substitutes two newlines (fortunately the third one, needed for the substitution, is provided by the built-in `n`), using both types of string literal to avoid quadruplicate copies of a quote mark. Since `l` is the only character which occurs more than twice in the original string, it's not too hard.
> 4 votes

# Answer
Hmm.

In C, given these rules, we can only have one `#define` (because of `i` and `n`) and at most two function calls OR definitions (`(` and `)`).

I presume there's pretty much only one way to do it (though I'm probably wrong):

```
main(){puts("Hello w\x6fr\154d!");}

```
> 4 votes

# Answer
# XQuery, 19 chars

```
"Hello World!"

```
> 4 votes

# Answer
### BASH

```
printf 'Hel\x6co world!\n'

```

Cred @manatwork

```
echo $'Hel\x6c\x6f world!'

```
> 4 votes

# Answer
# C - 46 Characters

`main(){printf("He%clo wor%cd!\x0d",'l',108);}`

Prints out:

```
Hello world!

```
> 4 votes

# Answer
# PHP

32 Chars

Note how I am not using a character more than twice, since l != L

```
He<?=strtolower("LLO WOR");?>ld!

```

Also note that, despite of Stack Overflow deleting it in the representation, there's a line break after the `!`.
> 4 votes

# Answer
## AWK,34

```
BEGIN{printf"Hel%co world!\n",108}

```
> 3 votes

# Answer
## GolfScript, 21 characters

```
'He'[108]+"lo world!"

```

`108` is the ASCII code for `l`.

First, I push `He` on the stack. Then, `He` gets popped and becomes `Hel`. Then I push `lo world!` on the stack. Now there are two elements on the stack. Because at the end of a GolfScript program, everything of the stack is outputted, this program outputs:

> Hello world!

followed by a newline, because Golfscript always outputs a newline.
> 3 votes

# Answer
# nginx.conf

```
set $i l;
return 202 "Hel${i}o world!\n";

```

In action:

```
opti# curl -6v "http://localhost/"
* About to connect() to localhost port 80 (#0)
*   Trying ::1...
* connected
* Connected to localhost (::1) port 80 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.26.0
> Host: localhost
> Accept: */*
>
< HTTP/1.1 202 Accepted
< Server: nginx/1.4.1
< Date: Fri, 17 Jan 2014 18:02:08 GMT
< Content-Type: application/octet-stream
< Content-Length: 13
< Connection: keep-alive
<
Hello world!
* Connection #0 to host localhost left intact
* Closing connection #0

```
> 3 votes

# Answer
# HTML — 17 characters

```
Hello world!

```

In action:

```
%echo -n "Hello world!" | wc
       0       2      17
%echo -n "Hello world!" | lynx -dump -stdin

   Hello world!

%

```
> 3 votes

# Answer
## Fugue

From the esolang wiki:

And you can listen to the source code.
> 3 votes

# Answer
# Clojure (35)

`(printf "He%c%co world!\n",108,108)`

The whitespace almost got me, but Clojure allows the use of commas to separate parameters.
> 3 votes

# Answer
# Perl, 28 chars

```
printf"He%so world!\n",'l'x2

```

Rules tested with:

```
perl -e '$"="\n";@a=split//,<>;print"@a";' | sort | uniq -c | sort

```
> 3 votes

# Answer
# C (32 characters)

```
main(){puts("He\x6clo world!");}

```
> 3 votes

# Answer
# Plain TeX - 18 chars

```
He^^,lo world!\bye

```

Remark: TeX terminates the paragraph before shipping it, so the "newline" is actually included.
> 3 votes

# Answer
# Taking it directly from the instructions on this page:

```
curl -sL bit.do/gBfx|perl -E'@Q=map{m%OUtPUTS The chARAC.ERS\N*?>([^<]+)%i?$1:()}<>;say$Q[1]'

```

or, if you wanna be strict with the white-spaces:

# PERL

```
`curl -sL v.gd/92XIMS`=~m%ThE\WChAracTERS.*?>\K[^<]+%i;say$&

```

or

```
`curl -sL v.gd/qmwAMh`=~m%outpUtS\WTHE\WChAracTERS.*?>([^<]+)%i;say$1

```

**Advantage:** will work for every sentence, but *please don't* change wording of the question :)

**Rules:** we can consider this question being an "internal" resource. Without *this question*, no one would solve it. **Should it be me or the program reading it? :)**

**Backstage story:** I almost teared out all my hair trying to debug this! :)

First solution

* using `wget -O-` leads to 3x `-`
* `sed` needed too many `/`
* so I need cur`l` and per`l`, but all perl loops like `until`, `while` contain 3rd `l`!
* I needed to replace the loop, this is quite complicated but
    + it seems `$1` only works after positive (`=~`) not negative (`!~`) match
    + I couldn't use `!(..)` \- too many parentheses :x
    + neither I could use `||` (I need a pipe!) or `or` (pe`r`l, cu`r`l ...)

Second solution

* I reread the rules. White-spaces shouldn't be repeated either - oh my!
* At least could recycle the `do{}while` idea. Better said, it was forced, the map solution could not be used for using `()` 2 times, 3rd needed to call `open` since no more whitespaces are left.
* Find proper url shortener was a story, using `goo.gl`, `bit.ly`, `is.gd` or `ow.ly` was obviously impossible for the first solution, as was `bit.do` and `dft.ba` for the second. Then, url-shorten the URL until you get something you can use, especially with `bit.ly` and `v.gd`. Why on earth they use so much lowercase characters?

The regex could be shortened, but I like the instructions to be as long as possible :-)

These rules are damn crazy :)

---

PERL v5.10 say feature has to be enabled, e.g. by running PERL `-E` option
> 3 votes

# Answer
## Keg, 13 bytes

The winner was chosen, but I still want to do it. :) (Astonishingly it is shorter than HTML!)

```
Hel:o world\!

```

This is a popularity contest, but the program is very easy to understand despite of the conciseness.

## Explanation

```
Hel          #Push "Hel" onto the stack
   :         #Duplicate the top of the stack (l)
    o world  #Push "o world" onto the stack
           \!#Escape ! and push it onto the stack(since it is an instruction)

```
> 3 votes

# Answer
# LINQPad, C# Expression - 22 chars

```
"Hello w\x6fr\x006cd!"

```
> 2 votes

# Answer
## PHP, 30 characters

Highly inspired by Vereos's answer.

```
<?=Hello.' wor'.chr(108),"d!";

```
> 2 votes

# Answer
**HTML - (16 Chars):**

```
Hello Wor&#108d!

```

Proper HTML would be to put a `;` after `&#108` but it still compiles fine. :)
> 2 votes

# Answer
## C

```
q=7103816;
main(){printf("%slo world!%c",&q,2+8);}

```

Works on little-endian platforms, where `7103816` is encoded the same as `Hel\0`.
> 2 votes

# Answer
# Lua - 22 characters

```
print"Hel\108o World!"

```

Simple enough, example output

```
lua -e 'print"Hel\108o World!"'
Hello World!

```
> 2 votes

# Answer
# Javascript, 19ch

\> `'Hello Wor\154d!\n'`

Character count:

\> `"'Hello Wor\154d!\n'".length` -\> 15 //cough, cheating

\> `"'Hello Wor\\154d!\\n'".length` -\> 19

With your choice of `return`, `alert()`, or nothing? Man, javascript has too many contexts.

Slightly more interesting: `["He",,'o World\n'].join('l')`
> 2 votes

# Answer
# **Яussian**

`Хелло мир!`

A mix of transliteration and proper language :) Google translate will turn it into proper "Hello world!"
> 2 votes

# Answer
# C, 41

```
main(){printf("He%clo world!%c",108,10);}

```
> 2 votes

# Answer
## R

Not gonna win anything, but I didn't see R yet...

```
'He\154\154o, World!'
'Hello, Wor\154d!'

```
> 2 votes

# Answer
# TI-BASIC, 33 bytes on-calculator

```
"l→Str1:Disp "He..o World!
Str1:Output(2,3,Ans+Ans

```

Since TI-BASIC uses tokens instead of characters, I limited myself by token. Make sure the screen is cleared before running the program. Note that l and o are two-byte tokens, but w is a sequence variable and d, e, and r are statistics variables, which are all one-byte tokens. This program first **Disp**lays the string without the first two l's, and then uses a different command to paste in the other two. Also note that TI-BASIC has no equivalent to a newline, but when the program ends the cursor does move down to allow further input to the calculator.
> 2 votes

# Answer
## Hexish

```
0B

```
> 1 votes

# Answer
# Haskell, 27

`main=print"Hello Wor\108d!"`

Twice-check:

```
import Data.List
main=getContents>>=print.all((<3).length).group.sort

```
> 1 votes

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

```
"hel\154o world"

```
> 1 votes

# Answer
# Node.js - 54 Unicode characters

```
eval([]+Buffer('consolť.ŬůgĨĢHťŬɬů wɯrɬd!Ģĩ',"ascii"))

```

console.log outputs a given string and a line shift, unfortunately that initially leaves me with way too many `l`s and `o`s, so it took some work.

The code creates a buffer from a string and is told to use ascii encoding, this effectively takes all character values mod 256 and stores them in the buffer, the buffer is then added to an empty array, which cause both buffer and array to be converted to string before the addition, an empty array converts to an empty string, and the buffer is implicitly converted using UTF-8 encoding. The result is evaled to produce the desired result.
> 1 votes

# Answer
# PHP 5.1.2+

```
<?="\x48".hasH_file(@cRC32b,__FILE__,'« Tý'|5)." wor\X6Cd!";

```

The code hashes itself to get the remaining characters. Repeats the characters ".\\,'\_

A tab messes up the formatting. Base64:

> PD89Ilx4NDgiLmhhc0hfZmlsZShAY1JDMzJiLF9fRklMRV9fLCfCqwlUw70nfDUpLiIgd29yXFg2Q2QhIjs=
> 1 votes

# Answer
## newLISP

Such a cruel challenge for a Lisp-like language, where so much is possible if only you don't count parentheses... :) But a solution can be found:

```
 (eval-string(encrypt {`4?3%;=6^9z*9&^m=>*],c;W}{HDMZKOQX~B2OUJ1MJQX1HBF~KU2FZD}))

```

(81 characters)

which uses the simple `encrypt` function to pass a command through to the evaluator. The actual command is `(println {Hello world!})`. (Having "z" and "Z" and "Z" is allowed, according to the comments...:)).
> 1 votes

# Answer
# POSIX shell (Bash et al) - 26 chars

```
printf 'Hel\x6Co world!\n'

```
> 1 votes

# Answer
# k/q (25 chars)

`-1@.h.uh"Hello wor%6cd!";`

works in either k or q

(btw, the validity can be checked elegantly with `|/#:'="-1@.h.uh\"Hello wor%6cd!\";"`)
> 1 votes

# Answer
**PHP** I am amazed at how many people give invalid answers without mentioning they are. My attempt, only reusing `o"` characters twice.

`<?Php EchO "Hello wor\154d!";`

*Edit: fixed thanks to @FireFly: i understood to use each character once. This is no challenge anymore.*
> 1 votes

# Answer
# Active Server Pages (Classic ASP):

```
Hel<%REspOnsE.wRite Chr((0<0>-.6&"!")+&H6C+h-dinptO)
%>o world!

```

---

**Each character is used twice!**

To run it, you'll need a web server running IIS.

Save it in the site root with a ".asp" extension, make a HTTP request to the server, and you'll see that the response text is exactly "Hello world!" and a new line:

```
Hello world!

```

---

**Edit:** You could also use this smaller code:

```
Hel<%= Chr((0<0>we=6&"!")+&H6C+hd)
%>o world!

```

Or this:

```
Hel<%= CHr((0<1>wedC=8&"!&")++108)
%>o world!

```
> 1 votes

# Answer
http://esolangs.org/wiki/Hello%2B%2B

```
H

```

1 letter is all it takes to print that
> 1 votes

# Answer
BASH

printf "a\107Vs\x62G8gd29ybGQhCg=="|base64 -d
> 1 votes

# Answer
# JavaScript (52 characters)

```
alert(['He\x6C\x6Co world!'][(!1,0)-0], +-1+"Hadtw")

```

Each character is used 2 times, and it doesn't use any comments!

**Edit**: *I've just posted the same answer here.*
> 1 votes

# Answer
# c-41

```
main(){printf("He%clo world!%c",154,10);}

```
> 0 votes

# Answer
# JavaScript 35

With inspiration from @VisioN

```
alert(atob("SGVsbG8gV29y")+'ld!\n')

```
> 0 votes

# Answer
# Tcl, 21 bytes

```
puts Hello\ wor\x6cd!

```

Try it online!
> 0 votes

# Answer
# SmileBASIC

```
?@H[1]+@e[!0];CHR$(108);"lo world!

```

Another solution:

```
CLS?"He__o world!
LOCATE 2,0?@l[1]*2

```
> 0 votes

# Answer
In C. Choose one of these.

My favourite (crazy but compact in memory):

```
#include <stdint.h>
printf("%s", (char*)(int32_t[]){1819043144,1870078063,6581362});

```

For those who like big numbers:

```
printf("%s", (char*)(int64_t[]){8031924123371070792,43509902450});

```

Or here the more descriptive versions:

```
printf("%s", (char*)(int32_t[]){0x6c6c6548,0x6f77206f,0x646c72});
printf("%s", (char*)(int64_t[]){0x6f77206f6c6c6548,0x0a21646c72});

```

char map:

```
H  e  l  l     o     w  o     r  l  d  !     <LF>
48 65 6c 6c    6f 20 77 6f    72 6c 64 21    0a
(remember to swap big/little endian bytes when composing)

```

Btw: why there is no 128 bit integer in C?

```
printf("%s", (char*)(int128_t[]){0x0a21646c726f77206f6c6c6548});
printf("%s", (char*)(int128_t[]){802616035175250124568770929992}); // string uses only 100 of 128 bits

```
> -1 votes

# Answer
AWK and echo

EDIT: fix the extra o's following the note. (thanks ProgramFOX)

```
echo He: | awk -F: '{print $1,Q,"\157 Wor",Q}' OFS=l ORS=d\!

```

and thanks awk which give me the option to say "-F" instead of "IFS=" (:-)
> -1 votes

# Answer
**Java**

Okay I found this on SO, it doesn't output a big `H`

Rare sequence of random stream of digits for 2 specific seeds.
Probably fixed out by brute forcing
One of the SO solutions also include a brute forcer to make your own sequences.

```
System.out.println(randomString(-229985452) + " " + randomString(-147909649) + "!");

```

And `randomString()` looks like this

```
public static String randomString(int i)
{
    Random ran = new Random(i);
    StringBuilder sb = new StringBuilder();
    for (int n = 0; ; n++)
    {
        int k = ran.nextInt(27);
        if (k == 0)
            break;

        sb.append((char)('`' + k));
    }

    return sb.toString();
}

```

Source: https://stackoverflow.com/questions/15182496/why-does-this-code-print-hello-world
> -2 votes

---
Tags: popularity-contest, restricted-source, hello-world
---


title: The Practice of Programming

text:
# Question
Title: The Practice of Programming
At 1998, Brian Kernighan, while working on the book "The Practice of Programming", wanted to demonstrate realisation of regular expression engine. But struggled to find *small* engine, that cod could fit in the book.

So Brian Kernighan asked Rob Pike to write one for him, and Rob did it gracefully. Here is original source:

```
    /* match: search for regexp anywhere in text */
    int match(char *regexp, char *text)
    {
        if (regexp[0] == '^')
            return matchhere(regexp+1, text);
        do {    /* must look even if string is empty */
            if (matchhere(regexp, text))
                return 1;
        } while (*text++ != '\0');
        return 0;
    }

    /* matchhere: search for regexp at beginning of text */
    int matchhere(char *regexp, char *text)
    {
        if (regexp[0] == '\0')
            return 1;
        if (regexp[1] == '*')
            return matchstar(regexp[0], regexp+2, text);
        if (regexp[0] == '$' && regexp[1] == '\0')
            return *text == '\0';
        if (*text!='\0' && (regexp[0]=='.' || regexp[0]==*text))
            return matchhere(regexp+1, text+1);
        return 0;
    }

    /* matchstar: search for c*regexp at beginning of text */
    int matchstar(int c, char *regexp, char *text)
    {
        do {    /* a * matches zero or more instances */
            if (matchhere(regexp, text))
                return 1;
        } while (*text != '\0' && (*text++ == c || c == '.'));
        return 0;
    }

```

# Rules

* Write regex engine that supports the same operations, as Rob's:
    + Any char (as symbol)
    + `.` to match any char
    + `^` to match start of the string
    + `$` to match end of the string
    + `*` to match any count of char from zero
* Auxiliary code do not count (to accept input, for example)
* Make the shortest solution and beat Rob Pike!

## Input

Two strings: one for regex, one for match.

## Output

* `True` (in your language), if regex matches string
* `False` (in your language), if regex do not match string

# Answer
# Perl 6, 39 bytes

```
->\a{&{?/<{a}>/}}o{S:g/<-[.*$^]>/'$/'/}

```

Try it online!

Simply evaluates the input as a regex, adding quotes to avoid any special characters Perl 6 uses. This takes input curried, as `f(regex)(string)`, though it could be a *lot* shorter if I can just return a regex object.
> 1 votes

---
Tags: code-golf
---


title: Print 'A' 1000 times with BrainFuck

text:
# Question
Title: Print 'A' 1000 times with BrainFuck
What is the best BrainFuck code (in terms of code size) to print 'A' 1000 times ?

My approach is:

* set 'A' to p\[0\]
* set 255 to p\[1\] to display 255 'A', 3 times
* set 235 to p\[1\] to display 235 'A'

This is not effective but I cannot find a way to use tow counters simultaneously like a multiplication

Is there a better approach than a multiplication ?

A more general question: is there a rule to make a multiplication with a large number with the smallest possible code?

# Answer
The method you seem to currently be using is 39 bytes:

`>>+++[<-[-<.>]>-]++++[<----->-]<-[-<.>]` (not including getting the `A`) (Try It Online!)

(loop 3 times, each time set the counter to 255 and print that many times, then subtract 20, subtract 1, and print that many times)

However, it is much shorter to loop 250 times and print 4 times each time (thanks to jimmy23013 for optimizing this over my original loop-4 loop-250 print-1 solution):

`>------[<....>-]` (16 bytes)

If your cells are unbounded (I'm assuming they're 8-bit otherwise you probably wouldn't try using 255 for golfing):

`>>++++++++++[<++++++++++[<..........>-]>-]` (42 bytes).
> 17 votes

# Answer
the shortest way to get the number 65 for 'A' is `>+[+[<]>>+<+]>`, and then you just add HyperNeutrino's `>------[<....>-]` to the end of that. so the full code becomes `>+[+[<]>>+<+]>>------[<....>-]` (30 bytes)
> 2 votes

# Answer
# 47 Bytes ( No Underflows )

I just did this solution in 47 bytes. I tried doing it in a different manner than I normally would trying to save space by juggling counters between two values. It assumes that A is preloaded into p\[4\].

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

```

## Explained

```
Place 5 into p[0]
+++++
Loop 5 times to put p[1]=20, p[2]=25
[>++++>+++++<<-]>
Loop 20 times
[>
Move pointer to p[2] and loop 25 times.
Also move p[2] to p[3]

[
Increment p[3] from 0, effectively moving the value from p[2] to p[3]
>+
Print p[4]
>.
Decrement p[2]
<<-]
Shift over to p[3]
>
[
Decrement p[3]
->
Print p[4]
.<
Increment p[2]
<+>]
Move back to p[1] and decrement
<<-
Repeat until p[1] is 0
]

```
> 1 votes

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


title: Write a function

text:
# Question
Title: Write a function
I honestly can't believe this challenge does not already exist.

# The challenge

Write a function.

# The specifics

* Your program must define some sort of callable function. This includes anything commonly known as a function, a lambda function, or a subroutine. All of these types of callables will be referred to as a "function" in this post.

1. Input to the function is optional and not required.
    2. A return value from the function is also optional and not required but control must return to the calling program.
* The function must be assigned to some sort of variable so that it is possible to be accessed at a later time. This includes indirect assignment (in most common languages where declaring a named function automatically adds the name into the current scope) and direct assignment (assigning an anonymous function to a variable directly).
* The function does not need to be named.
* The function must be created by *you* \- you cannot just assign a default function from the language to a variable.
* None of the standard loopholes, please.

This is , so lowest score in bytes wins.

# Answer
# x86 / x64 machine code, 1 byte

```
c3

```

Assembly:

```
ret

```

Try it online! (nasm)

¯\\\_(ツ)\_/¯
> 31 votes

# Answer
# Jelly, 0 bytes

Try it online!

A monadic link that returns its argument. Since it is the first function to appear in the script, it can be called using `1Ŀ`.

Thanks to @lirtosiast for pointing out that a 0 byte link/function would work in Jelly.

I.e.

```

3,4,5 1Ŀ
```

Try it online!
> 22 votes

# Answer
# Javascript, 6 bytes

```
f=_=>0

```

Includes variable assignment. Not much to see here.
> 14 votes

# Answer
# Haskell, 3 bytes

```
o=9

```

This code defines a polymorphic function called `o` which takes one type parameter and one typeclass instance parameter. When this function is called, it takes the given typeclass instance, gets its `fromInteger` member, calls that member with the `Integer` value for 9, and returns the result.

Granted, what I just described is merely the behavior of the Haskell function `9`, and my code merely defines a function called `o` which is equivalent to `9`.

Now the only question is, is the `9` function "created by you," or is it "a default function from the language"?

I think that it is "created by you." My reason for saying this is that if you read the specification for Haskell, you will (I assume) find no mention of a `9` function anywhere. Instead, the specification states that you can create a number literal by stringing together one or more digits. Therefore, by writing a string of digits, I have written a function—even if I just so happen to have only used one digit.
> 10 votes

# Answer
# Python 3, 9 bytes

```
def f():1

```

Try it online!
> 9 votes

# Answer
## ZX Spectrum BASIC, 6 bytes

```
DEF FN f()=PI

```

Hex dump: `CE 66 28 29 3D A7`. `CE` is a 1-byte keyword for `DEF FN` (including the trailing space), while `A7` is a 1-byte keyword for `PI`. Call using `FN f()`. Example program:

```
  10 PRINT FN f(): DEF FN f()=PI

```

Output:

```
3.1415927

```
> 8 votes

# Answer
# , 9 bytes

```
body(t)=0

```

Try it online!

I think this complies with the rules. The function `t` takes no input and outputs `0`. This works because there already exists a function called `t` (the transposition function) and it redefines the body of the function; it would not work with say `body(a)=0` (no object called `a`) or `body(F)=0` (`F` is a logical, not a function). I think it complies because it is still created by me: I am not reusing what the pre-defined function does, simply its name.

I don't think I've ever seen this used by R golfers, but there may be situations where it allows us to save a few bytes on challenges where we need a helper function.

A more standard solution would have been:

# , 13 bytes

```
f=function()0

```

Try it online!

Function which takes no input and outputs `0`. This is 1 byte shorter than the function which takes no input and outputs nothing, which would be

```
f=function(){}

```

If we try to define a function with no body (`f=function()`), R interprets this as an incomplete command (this might not be true in older versions of R).

As pointed out by OganM, we take this down to 11 bytes with

# , 11 bytes

```
function()0

```

Try it online!

which technically complies with the challenge requirement that the function be assigned to some sort of variable, since it is (ephemerally) assigned to `.Last.value`.
> 8 votes

# Answer
# Perl 6, 5 bytes

```
$!=!*

```

Try it online!

Creates a Whatever lambda that returns the boolean not of its parameter, and assigns it to the variable `$!`.
> 6 votes

# Answer
# C (gcc), 5 bytes

Defines a function `f` that takes no arguments and technically returns an undefined integer value.

```
f(){}

```

Try it online!
> 6 votes

# Answer
# Whitespace, 7 bytes

```

```

Creates a subroutine that returns control to the caller.

Explained in context:

```
[N
S S N
_Create_Label][N
T   N
_Return]

```

Try it online!
> 6 votes

# Answer
# \[Wolfram Language (Mathematica)\], 1 byte

This one is slightly questionable:

```
f

```

Defines `f`, which can be "called" e.g. by `f[]`, which "returns" the expression `f[]`
> 6 votes

# Answer
# Forth (gforth), 5 bytes

This is a function named `f` that does nothing.

```
: f ;

```

**Try it Online**

In the TIO code, I added a footer of `see f`, which prints the definition of the function.
> 5 votes

# Answer
# Lua, 8 bytes

```
f=load''

```

Try it online!

Defines a (global) function `f`.

This uses Lua `load` function to compile given string which happens to be empty in our case (empty code is valid code) into function which does exactly what we wrote in its body: nothing.

For ones wondering, standard solution would be

```
function f()end

```

but this is longer (15 bytes).
> 5 votes

# Answer
# POSIX sh, 6 bytes

```
s()(1)

```

Using curly braces requires one more character.
> 5 votes

# Answer
# Java, 10 Bytes

this should match the rules of the challenge

```
void f(){}

```
> 5 votes

# Answer
# Perl 5, 7 bytes

```
sub f{}

```

Try it online!
> 4 votes

# Answer
# Kotlin, 8 bytes

```
val f={}
```

An empty function stored in a variable f.
Call it using `f()` or `f.invoke()`.
> 4 votes

# Answer
# shortC, 1 byte

```
A

```

Try it online!

Transpiles into this C:

```
 int main(int argc, char **argv){;}

```
> 4 votes

# Answer
# Pascal, 22 bytes

```
procedure A;begin end;

```
> 4 votes

# Answer
# C (gcc), ~~14~~ 13 bytes

```
(*f)()=L"Ã";

```

Try it online!

This defines a function `f` returning `int` and accepting an unspecified number (and type) of parameters, the machine code of which is contained within the string literal. The unicode character `Ã` (stored in memory as `0xc3 0x00 0x00 0x00` on a little endian machine) corresponds to the x86 `ret` instruction that returns from the function. Non x86 architectures may require different opcode(s) to return.

`gcc` may require the `-zexecstack` flag to avoid a segfault.
> 4 votes

# Answer
# Tcl, ~~6~~ ~~5~~ 11 bytes

```
set f {_ ;}

```

Try it online!

Including the assignment to the variable f as part of the bytecount to comply with rules. With this change, the more conventional definition below ties the one above for bytecount:

```
proc f _ {}

```
> 3 votes

# Answer
# Ruby, 6 bytes

Proc called `f` which accepts no argument and returns `nil`.

```
f=->{}

```

Try it online!
> 3 votes

# Answer
# Haskell, 5 bytes

```
f x=0

```

Try it online!
> 3 votes

# Answer
# XSLT, 134 bytes

```
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:template name="a"></xsl:template></xsl:stylesheet>

```

A template is the closest thing this language has to a function. It can definitely be called; it takes zero arguments and "returns" the empty string.
> 3 votes

# Answer
# F# (.NET Core), 9 bytes

```
let f a=a

```

Try it online!
> 3 votes

# Answer
# Python 3, 10 bytes

```
f=lambda:0

```

Try it online!
> 3 votes

# Answer
# Rust, 6 characters

```
f=||0;

```

A closure (also called lambda) that takes no parameters and always returns 0.

(As far as I understand the challenge, only the assignment has to be included, the variable declaration not.)

Try it online!
> 2 votes

# Answer
## AppleScript, 10

```
on a()
end

```

Explained, compiled, and including invocation:

```
on a()    -- declare event handler "a"
end a     -- end declaration

-- invoke it:
a()

```
> 2 votes

# Answer
# Japt, 2 bytes

```
_

```

Called as `$U ($`.

`_` can be replaced with `@`, `Ï`, or `È`.

Try it
> 2 votes

# Answer
# SmileBASIC (\>=3), 9 bytes

```
DEF A
END

```

Function is called by `A`.
> 2 votes

# Answer
# Wolfram Language (Mathematica), 2 bytes

```
#&

```

Try it online!

Unfortunately, just `&` does not work (an anonymous function that does nothing).
> 2 votes

# Answer
# Octave, 4 bytes

**xkcd Random Number Generator**

```
@()4

```

Assigns an anonymous function to the default return variable `ans`. Call using `ans(<parameters>)`. Any number of input parameters are allowed.

Code length is a random number of bytes.

Sample run on ideone.
> 2 votes

# Answer
# Runic Enchantments, 1 byte

```
B
>00B$',$$;

```

Try it online!

The second line is in the *footer* on TIO as all it does is initialize the program and invoke the function, and print the return values thereof (that being a pointer to the next instruction after the return statement--utilizing vs. discarding these values normally distinguishes a *function call* with a *return*), and as such should not be included in the bytecount any more than `static void main(int[] args) { f(); }` would be.

Similarly it shows the function "being assigned to a variable" (that being its literal coordinates, `0,0`) and "invoked later" at position `3,1`. For example, this program invokes the same function after performing some other operations and does so at a different point in the code. Note that the IP does not change direction automatically and may result in unexpected behavior, so functions typically start with a directional command, however in golfing it is insured that the IP is already going in the desired direction, resulting in not needing the extra byte(s).

# Abusing language features, 0 bytes

```

/   B̭
 >00/$',$$;
```

Try it online!

The first line (blank) is the 0-byte function. The second acts as function call and return. The third line initializes the program and produces output.

I definitely don't think that this should count, but thought I'd at least include it after I realized that I could arrange things this way. If bytes were to be counted from `B` call to `B` call in order of program flow, the function contains 8 bytes (four spaces, one `/`, one `B`, and two bytes for the `̭` directional modifier).
> 2 votes

# Answer
# dc, 2

```
[]

```

Try it online!

This pushes a dc macro to the stack. I'm not sure if this is satisfies *"The function must be assigned to some sort of variable"* or not. If not, then it can be stored to a variable for 2 extra bytes:

# dc, 4

```
[]sf

```

Try it online!
> 2 votes

# Answer
# Binary lambda calculus, 1 byte

```
0100_0010

```

In lambda calculus: (λ*f*. \_)(λ*x*. *x*)

The underscore denotes where the rest of the program should go. The function can be accessed through its De Bruijn index.
> 2 votes

# Answer
# Attache -R, 2 bytes

```
{}

```

Try it online!

An empty lambda. This approach takes advantage of the `-R` flag, which automatically saves the results of the topmost expression as `_1` (also accessible through `_`). It can be used later, but only by the next expression which does not create a topmost expression. Usually, the next line.

## Attache, 5 bytes

```
f:={}

```

Try it online!

A more conventional approach. Saves an empty lambda to the variable `f`.

## Attache, 6 bytes

```
f[]:=0

```

Try it online!

Another conventional approach. Defines a named function `f` with no arguments, returning `0`.
> 2 votes

# Answer
# C#, 10 Bytes

Same as Java.

```
void f(){}

```
> 2 votes

# Answer
## Commodore 64 Basic, 13 bytes

```
1DEFFNI(X)=X

```

The identity function. This, or any other function with a 1-byte body, is the shortest possible function in C64 Basic.

(Oddly, the empty function is considered a valid function by the C64 interpreter. But since actually calling it generates a runtime syntax error, it fails the "control must return" criterion.)
> 2 votes

# Answer
# Swift, 8 bytes

```
let f={}

```

Stores in `f` a void function with no parameters.
> 2 votes

# Answer
# Inform 7, 10 bytes

```
To x:stop.

```

This defines a "phrase" (the simplest form of callable function), which does nothing and returns. It can then be called by name:

```
When play begins, x.

```
> 1 votes

# Answer
# Inform 6, 5 bytes

```
[f;];

```

The syntax for defining a routine in Inform 6 looks something like this:

```
[ name arg1 arg2 ;
    contents;
    return;
];

```

So `[f;];` defines a routine named `f` which takes no arguments and does nothing.
> 1 votes

# Answer
# Zozotez: 8

```
(:'q(\))
;; test
(q) ; ==> NIL

```

Explanation:

* `:` is `set`
* `'q` is the quoted symbol (the binding) `q`
* `\` is `lambda` so `(\)` is short for `(\ () ())`

# Common Lisp: 11

```
(defun q())
;; test
(q) ; ==> NIL

```

# R5RS/R6RS/R7RS Scheme: 12

```
(define(q)1)
;; test
(q) ; ==> 1

```
> 1 votes

# Answer
## Clojure, 10 bytes

Returns `nil`.

```
(defn f[])

```
> 1 votes

# Answer
# CJam, 4 bytes

```
{}:F

```

Call it with `F`.

If just leaving a function on the stack is enough, then we can remove 2 bytes:

```
{}

```
> 1 votes

# Answer
# Lua, 15 bytes

```
s=function()end

```

Try it online!
> 1 votes

# Answer
# C++14, 12 bytes

Empty lambda with no params

```
auto f=[]{};

```
> 1 votes

# Answer
# Gema, 4 characters

```
f:=0

```

Actually a domain, which is a bit like namespace, but in Gema is the way to define both new pattern arguments and new functions.

(I guess the function's result could be nothing, but on `f:=` the interpreter segfaults. ☹)

Try it online!
> 1 votes

# Answer
# jq, 8 characters

```
def f:0;

```

A function that takes no parameters and always returns 0.

Try it online!
> 1 votes

# Answer
# \+ dplyr, 20 bytes

```
library(dplyr)
.%>%.

```

Try it at RDRR!

Returns a functional sequence, the identity function.

Much longer than the other R answer but interesting in its own right.
> 1 votes

# Answer
## Pyret, 7 bytes

```
a=_ + 0

```

Returns exactly what is passed to it. Underscore paired with an operand implicitly makes a function.
> 1 votes

# Answer
# PowerShell, 0 bytes

Try it online!

You can save this code as a file with `.ps1` extension (for example, `f.ps1`) and call it `.\f.ps1`. You can directly call this function from another code as scriptblock `&{}`. The function is inside the brackets.
> 1 votes

# Answer
# REXX, 0 bytes

A REXX program may call another REXX program as an external function. Given an empty file as above, saved as `f.rexx`, you may call it from another program as:

```
call f

```

Or, if you're unconcerned by the difference between proper functions and subroutines, call it as:

```
f()

```

# REXX, 8 bytes

```
f:return

```

This is a minimal procedure when called from within the same program. Call using `call f` or `f()` if you're not concerned about the philosophical difference between functions and procedures.
> 1 votes

# Answer
# Commodore C64 BASIC, 30 BASIC bytes (tokens) used.

```
 0pO785,210:pO786,255:?usr(0)

```

This sets the USR BASIC memory pointer to `0xffd2` in the Kernal, which outputs a character on the current device (device 3 being the screen, set to device 4 or 5 and the output is to a printer, and 8 - 15 will be a disk drive, 1 is for tape).

You may therefore write your own machine code function that returns to BASIC if you put the memory location of your routine as above at location 785 (`0x0311`) as low-byte/high-byte. This must always be 16 bits.
> 1 votes

# Answer
# Commodore 64 Basic, 9 bytes

You call the subroutine by GOSUB "\line number" and returns to the caller by RETURN. The function can be accessed anytime by calling the same line number, but the control should always return.

```
0reT   //Program continues after last Gosub executed
8goS0  //Call subroutine at line number 0

```

To execute this smallest program type: RUN8.

This program use tokens similarly to Shaun's answer.

Some facts of this program:

* There is no input to the actual function, but the function can access global variables.
* There is no return value from the function.
* The function has no name.
* The function is assigned a 16-bit variable that represents the basic line number (of low and high byte order).

This is the smallest I can think of, but of course expanding the number of digits in the line numbers will acually increase the codesize of the basic program.

For an demonstration with text-output, run this program by typing RUN8:

```
0 PRINT "INSIDE SUBROUTINE" : RETURN
8 PRINT "CALLING SUBROUTINE" : GOSUB 0
10 PRINT "RETURNED FROM SUBROUTINE"

```
> 1 votes

# Answer
# 33, 2 bytes

```
{}

```

The name of a function is whatever is in the destination string when the function is defined. Since the string registers are initialised empty when the program starts, this is valid and callable.
> 1 votes

# Answer
## GolfScript, 5 bytes

```
{}: ;

```

This assigns a no-op to a space. In order to call the function, type a space.
> 1 votes

# Answer
## Keg, 4 bytes

```
@a|@

```

To call the function:

```
@a@

```

This is unimplemented, but it is in the documentation.
> 1 votes

# Answer
# Pip, 4 bytes

```
a:{}

```

Try it online!

# Pip, 0 bytes?

I don't know if this counts but the empty program in Pip is a function. It can be called by (f). If not then the 1 byte program `a` should count
> 1 votes

# Answer
# Pari/GP, 3 bytes

```
x->

```

Try it online!
> 0 votes

# Answer
# Agda, 22 chars

Surprisingily difficult because of the required type signature and the lack of a preimported anything.

```
f : Set → _
f x = Set

```
> 0 votes

# Answer
# asm2bf, 9 bytes

```
lbl 1
ret

```

It builds to following brainfuck code (*omitting boilerplate*):

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

```
> 0 votes

# Answer
# Zsh, 3 bytes

Anonymous function... Try it online!

```
()x

```
> 0 votes

---
Tags: code-golf, function
---