# Question
Title: Shortest program to split a string at non-digits without RegExps
***EDIT: If you're using Lisp, I have given some guidelines at the bottom in counting bytes.***

**Objective:** Make the shortest function that splits a string at non-digits and returns an array consisting of only digits in each string, without the use of any regular expressions. Leading zeroes are to be included in each string.

## Current Standings (separated in categories):

* **C/C++/C#/Java:** 68 (C) ....
* **GolfScript/APL/J:** 13 (APL)
* **All others:** 17 (Bash, uses `tr`), 24 (Ruby)

## Rules:

* The format must be as a function with a single string argument. Up to two additional arguments may be added if necessary for the proper return of the array (e.g. sh/csh/DOS Batch needs an extra variable reference to return, etc.).
* The primary function declaration doesn't count, and nor does importing other standard libraries. `#include`s, `import`s, and `using`s don't count. Everything else does. This does include `#define`s and helper functions. Sorry for the confusion. Refer to this as a helpful guide as to what does/does not count (written in C-style syntax)

```
// doesn't count toward total, may be omitted unless
// non-obvious, like half of Java's standard library.
#include <stdio.h>

import some.builtin.Class // doesn't count, see above

#define printf p // counts towards total

/* Any other preprocessor directives, etc. count. */

int i = 0; // counts

someFunction(); // counts

char[][] myMainSplitFunction(char[][] array) { // doesn't count
  // Everything in here counts
  return returnArray; // Even this counts.
} // doesn't count

/* Everything in here counts, including the declaration */
char[][] someHelperFunction(char[] string) {
    // stuff
} // even this counts

```
* The output must be a string array or similar (Array lists in Java and similar are acceptable). Examples of accepted output: `String[]`, `char[][]`, `Array<String>`, `List<String>`, and `Array` (object).
* The array must contain only contain variable-length string primitives or string objects. No empty strings should be present in the return, with the exception below. **Note:** the strings are to contain a string of consecutive matches, such as the example input and output below.
* If there are no matches, then the function body should return `null`, an empty array/list, or an array/list containing an empty string.
* No external libraries allowed.
* DOS line endings count as one byte, not two (already covered in meta, but needs to be emphasized)
* **And the biggest rule here: no regular expressions allowed.**

This is a question, so shortest code wins. Good luck!

And here are some example inputs and outputs (with C-style escapes):

```
Input:  "abc123def456"
Output: ["123", "456"]

Input:  "aitew034snk582:3c"
Output: ["034", "582", "3"]

Input:  "as5493tax54\\430-52@g9.fc"
Output: ["5493", "54", "430", "52", "9"]

Input:  "sasprs]tore\"re\\forz"
Output: null, [], [""], or similar

```

Please put how many bytes used by your answers, and as always, happy golfing!

---

## Guidelines for Lisp

Here's what does and doesn't count in Lisp dialects:

```
;;; Option 1

(defun extract-strings (a b) ; Doesn't count
(stuff) ;;; Everything in here counts
) ; Doesn't count

;;; Option 2

(defun extract-strings (string &aux (start 0) (end 0)) ; Doesn't count
(stuff) ;;; Everything in here counts
) ; Doesn't count.

```
All other lambdas fully count towards the byte count.

# Answer
# APL, 13 chars

(or 28 / 30 bytes, read below)

```
{⍵⊂⍨⍵∊∊⍕¨⍳10}

```

I see you've banned GolfScript from your question. I understand your sentiment, but I hope this community won't eventually ban APL, because it's a truly remarkable programming language with a long history, not to mention a lot of fun to code in. Maybe it could just be scored differently, if people feel it's competing unfairly. I'll post my thoughts on this matter to that thread you've linked.

On that same token, I've always added a footnote to my APL posts, claiming that APL could be scored as 1 char = 1 byte. My claim rests on the fact that a few (mostly commercial) APL implementations still support their own legacy single-byte encoding, with the APL symbols mapped to the upper 128 byte values. But maybe this is too much of a stretch, in which case you may want to score this entry as 28 bytes in UTF-16 or 30 bytes in UTF-8.

**Explanation**

```
{        ⍳10}  make an array of naturals from 1 to 10
       ⍕¨      convert each number into a string
      ∊        concatenate the strings into one (it doesn't matter that there are two 1s)
    ⍵∊         test which chars from the argument are contained in the digit string
 ⍵⊂⍨           use it to perform a partitioned enclose, which splits the string as needed

```

**Examples**

```
      {⍵⊂⍨⍵∊∊⍕¨⍳10} 'ab5c0x'
 5  0
      {⍵⊂⍨⍵∊∊⍕¨⍳10}  'z526ks4f.;8]\p'
 526  4  8

```

The default output format for an array of strings does not make it clear how many strings are there in the array, nor how many blanks. But a quick manipulation to add quotes should make it clear enough:

```
      {q,⍵,q←'"'}¨ {⍵⊂⍨⍵∊∊⍕¨⍳10} 'ab5c0x'
 "5"  "0"
      {q,⍵,q←'"'}¨ {⍵⊂⍨⍵∊∊⍕¨⍳10}  'z526ks4f.;8]\p'
 "526"  "4"  "8"

```
> 10 votes

# Answer
## Python 47

**Implementation**

```
f=lambda s:"".join([' ',e][e.isdigit()]for e in s).split()

```

**Demo**

```
>>> sample=["abc123def456","aitew034snk582:3c","as5493tax54\\430-52@g9.fc","sasprs]tore\"re\\forz"]
>>> [f(data) for data in sample]
[['123', '456'], ['034', '582', '3'], ['5493', '54', '430', '52', '9'], []]

```

**Algorithm**

*Convert each non-digit character to space and then split the resultant string. A simple and clear approach.*

**And a fun solution with itertools (71 characters)**

```
f1=lambda s:[''.join(v)for k,v in __import__("itertools").groupby(s,key=str.isdigit)][::2]

```
> 5 votes

# Answer
### Ruby, 70

```
f=->(s){s.chars.chunk{|c|c.to_i.to_s==c}.select{|e|e[0]}.transpose[1]}

```

Online Version for testing

Since converting any non-digit character to an int returns 0 in Ruby (with to\_i), converting every char to int and back to char is the non-regex way to check for a digit...
> 4 votes

# Answer
# Bash, 21 bytes 17/21 bytes (improved by DigitalTrauma)

Building a space-separated list with `tr`

```
function split() {
tr -c 0-9 \ <<E
$1
E
}

```

replaces any non digit by a space

## Usage

```
$ for N in $(split 'abc123def456'); do echo $N; done
123
456

```

## Edit

as pointed by the comments below, the code can be stripped down to 17 bytes:

```
function split() (tr -c 0-9 \ <<<$1)

```

and as the result is not stricly speaking a Bash array, the usage should be

```
a=(`split "abc123def456"`); echo ${a[@]}

```

and the extra `(``)` should be counted
> 4 votes

# Answer
# bash, 26 (function contents: 22 + array assignment overhead 4)

This isn't going to beat the other `bash` answer, but its interesting because it might make you double-take:

```
f()(echo ${1//+([!0-9])/ })

```

Usage is:

```
$ a=(`f "ab5c0x"`); echo ${a[@]}
5 0
$ a=(`f "z526ks4f.;8]\p"`); echo ${a[@]}
526 4 8
$

```

At the first quick glance, `//+([!0-9])/`  looks a lot like a regexp substitution, but it isn't. It is a bash parameter expansion, which follows pattern-matching rules, instead of regular expression rules.

Returning true bash array types from bash functions is a pain, so I chose to return a space-delimited list instead, then convert to an array in an array assignment outside of the function call. So in the interests of fairness, I feel the `(` `)` around the function call should be included in my score.
> 4 votes

# Answer
# Mathematica 32

```
StringCases[#,DigitCharacter..]&

```

Usage

```
inps ={"abc123def456", "aitew034snk582:3c", "as5493tax54\\430-52@g9.fc",
        "sasprs]tore\"re\\forz"}
StringCases[#,DigitCharacter..]&/@inps

{{"123", "456"},
 {"034", "582", "3"},
 {"5493", "54", "430", "52", "9"},
 {}
}

```

The equivalent using regexes is much longer!:

```
StringCases[#, RegularExpression["[0-9]+"]] &

```
> 3 votes

# Answer
# Smalltalk (Smalltalk/X), 81

```
f := [:s|s asCollectionOfSubCollectionsSeparatedByAnyForWhich:[:ch|ch isDigit not]]

```

f value:'abc123def456' -\> OrderedCollection('123' '456')

f value:'aitew034snk582:3c' -\> OrderedCollection('034' '582' '3')

f value:'as5493tax54\430-52@g9.fc' -\> OrderedCollection('5493' '54' '430' '52' '9')

f value:'sasprs\]tore\\"re\forz' -\> OrderedCollection()

sigh - Smalltalk has a tendency to use veeeery long function names...
> 2 votes

# Answer
# C, 68 bytes (only the function's body)

```
void split (char *s, char **a) {
int c=1;for(;*s;s++)if(isdigit(*s))c?*a++=s:0,c=0;else*s=0,c=1;*a=0;
}

```

The first argument is the input string, the second one is the output array, which is a NULL-terminated string array. Sufficient memory must be reserved for `a` before calling the function (worst case: `sizeof(char*)*((strlen(s)+1)/2)`).

The input string is modified by the function (every non-digit character is replaced by `'\0'`)

## Usage example

```
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

void split (char *s, char **a) {
int c=1;for(;*s;s++)if(isdigit(*s))c?*a++=s:0,c=0;else*s=0,c=1;*a=0;
}

void dump(char **t) {
    printf("[ ");for(;*t;t++)printf("%s ", *t);printf("]\n");
}

int main() {
    char **r = malloc(1024);
    char test1[] = "abc123def456";
    char test2[] = "aitew034snk582:3c";
    char test3[] = "as5493tax54\\430-52@g9.fc";
    char test4[] = "sasprs]tore\"re\\forz";
    split(test1,r);
    dump(r);
    split(test2,r);
    dump(r);
    split(test3,r);
    dump(r);
    split(test4,r);
    dump(r);
    return 0;
}

```

## Output

```
[ 123 456 ]
[ 034 582 3 ]
[ 5493 54 430 52 9 ]
[ ]

```

## Un-golfed version:

```
void split (char *s, char **a) {
    int c=1; // boolean: the latest examined character is not a digit
    for(;*s;s++) {
        if(isdigit(*s)) {
            if(c) *a++ = s; // stores the address of the beginning of a digit sequence
            c=0;
        } else {
            *s=0; // NULL-terminate the digit sequence
            c=1;
        }
    }
    *a = 0; // NULL-terminate the result array
}

```
> 2 votes

# Answer
# K (ngn/k), 27 bytes

```
{x@.t@=t-!#t:&~^(,/$!10)?x}

```

Try it online!

* `(,/$!10)` generate "0123456789"
* `&~^(...)?x` identify indices of digits in the input (e.g. `"abc123def456"` =\> `3 4 5 9 10 11`)
* `.t@=t-!#t:` split the indices into groups of adjacent indices (e.g. `3 4 5 9 10 11` =\> `(3 4 5;9 10 11)`)
* `x@` index back into the original output and return (e.g. `x[(3 4 5;9 10 11)]` =\> `("123";"456")`)
> 2 votes

# Answer
## Perl, 53

**Edit:** on no matches, sub now returns list with empty string (instead of empty list) as required.

It also avoids splitting on single space character, as it triggers *'split on any white-space'* behavior, which probably violates the rules. I could use `/ /` delimiter, which would split on single space, but paradoxically it would *look* like using regexp pattern. I could use `unpack` at the cost of some extra characters and so get rid of `split` controversy altogether, but I think that, what I finish with, splitting on a literal character (other than space) is OK.

```
sub f{shift if(@_=split a,pop=~y/0-9/a/csr)[0]eq''and$#_;@_}

```

And, no, Perl's transliteration operator doesn't do regular expressions. I can unroll 0-9 range to `0123456789` if that's the problem.
> 1 votes

# Answer
## VBScript, 190 (164 without function declaration)

```
Function f(i)
For x=1 To Len(i)
c=Mid(i,x,1)
If Not IsNumeric(c) Then
Mid(i,x,1)=" "
End If
Next
Do
l=Len(i)
i=Replace(i,"  "," ")
l=l-Len(i)
Loop Until l=0
f=Split(Trim(i)," ")
End Function

```

While not competitive at all, I'm surprised that VBScript comes out this short on this given how verbose it is (13 bytes for the CRs alone). It loops through the string, replacing any non-numeric characters with spaces, then reduces all the whitespace to single spaces, and then uses a space delimiter to divide it.

**Test cases**

```
Input: "ab5c0x"
Output: 5,0

Input: "z526ks4f.;8]\p"
Output: 526,4,8

```
> 1 votes

# Answer
## R, 81

```
f=function(x){
s=strsplit(x,"",T)[[1]]
i=s%in%0:9
split(s,c(0,cumsum(!!diff(i))))[c(i[1],!i[1])]
}

```

The function accepts a string and returns a list of strings.

Examples:

```
> f("abc123def456")
$`1`
[1] "1" "2" "3"

$`3`
[1] "4" "5" "6"

```

-

```
> f("aitew034snk582:3c")
$`1`
[1] "0" "3" "4"

$`3`
[1] "5" "8" "2"

$`5`
[1] "3"

```

-

```
> f("as5493tax54\\430-52@g9.fc")
$`1`
[1] "5" "4" "9" "3"

$`3`
[1] "5" "4"

$`5`
[1] "4" "3" "0"

$`7`
[1] "5" "2"

$`9`
[1] "9"

```

-

```
> f("sasprs]tore\"re\\forz")
$<NA>
NULL

```

Note: `$x` is the name of the list element.
> 1 votes

# Answer
## Common Lisp (1 according to the letter; ≈173 according to the spirit)

Here's a readable version. The byte count is fairly high because of the long names in things like `digit-char-p` and `position-if` and `vector-push-extend`.

```
(defun extract-numeric-substrings (string &aux (start 0) (end 0) (result (make-array 0 :adjustable t :fill-pointer 0)))
  (loop
     (unless (and end (setq start (position-if #'digit-char-p string :start end)))
       (return result))
     (setq end (position-if (complement #'digit-char-p) string :start (1+ start)))
     (vector-push-extend (subseq string start end) result)))

```

```
(extract-numeric-substrings "abc123def456")
#("123" "456")

(extract-numeric-substrings "aitew034snk582:3c")
#("034" "582" "3")

(extract-numeric-substrings "as5493tax54\\430-52@g9.fc")
#("5493" "54" "430" "52" "9")

(extract-numeric-substrings "sasprs]tore\"re\\forz")
#()

```

The concept of "function declaration" is sort of vague. Here's a version that only has one byte (the character `x` in the function body); everything else is bundled in to the auxiliary variables of the function's lamba list (part of the function's declaration):

```
(defun extract-numeric-substrings (string
                                   &aux (start 0) (end 0)
                                   (result (make-array 0 :adjustable t :fill-pointer 0))
                                   (x (loop
                                         (unless (and end (setq start (position-if #'digit-char-p string :start end)))
                                           (return result))
                                         (setq end (position-if (complement #'digit-char-p) string :start (1+ start)))
                                         (vector-push-extend (subseq string start end) result))))
  x)

```

The actual byte count will depend on how many of auxiliary declarations would have to be moved into the body for this to be deemed acceptable. Some local function renaming would help, too (e.g., shorten `position-if` since it appears twice, use single letter variables, etc.).

This rendering of the program has 220 characters:

```
(LOOP(UNLESS(AND END(SETQ START(POSITION-IF #'DIGIT-CHAR-P STRING :START END)))(RETURN RESULT))(SETQ END(POSITION-IF(COMPLEMENT #'DIGIT-CHAR-P)STRING :START(1+ START)))(VECTOR-PUSH-EXTEND(SUBSEQ STRING START END)RESULT))

```

If nothing else, this should promote Common Lisp's &aux variables.

This can be written more concisely with `loop`, of course:

```
(defun extract-numeric-substrings (s &aux (b 0) (e 0) (r (make-array 0 :fill-pointer 0)))
  (loop
     with d = #'digit-char-p
     while (and e (setq b (position-if d s :start e)))
     finally (return r)
     do
       (setq e (position-if-not d s :start (1+ b)))
       (vector-push-extend (subseq s b e) r)))

```

The `loop` form, with extra space removed, has 173 characters:

```
(LOOP WITH D = #'DIGIT-CHAR-P WHILE(AND E(SETQ B(POSITION-IF D S :START E)))FINALLY(RETURN R)DO(SETQ E(POSITION-IF-NOT D S :START(1+ B)))(VECTOR-PUSH-EXTEND(SUBSEQ S B E)R))

```
> 1 votes

# Answer
**php**, **204**

```
function s($x){$a=str_split($x);$c=-1;$o=array();
for($i= 0;$i<count($a);$i++){if(ord($a[$i])>=48&&ord($a[$i])<=57)
{$c++;$o[$c]=array();}while(ord($a[$i])>=48&&ord($a[$i])<=57)
{array_push($o[$c],$a[$i]);$i++;}}return $o;}

```

**Descriptive Code:**

```
function splitdigits($input){

    $arr = str_split($input);
    $count = -1;
    $output = array();
    for($i = 0; $i < count($arr); $i++){

    if(ord($arr[$i]) >= 48 && ord($arr[$i]) <= 57){
        $count++;
        $output[$count] = array();
    }

    while(ord($arr[$i]) >= 48 && ord($arr[$i]) <= 57){
        array_push($output[$count], $arr[$i]);
        $i++;
    }

}

return $output;
}

```

This is pretty long code and I'm sure there will be a much shorter php version for this code golf. This is what I could come up with in php.
> 0 votes

# Answer
# C, 158

```
#define p printf
char s[100],c;int z,i;int main(){while(c=getchar())s[z++]=(c>47&&c<58)*c;p("[");for(;i<z;i++)if(s[i]){p("\"");while(s[i])p("%c",s[i++]);p("\",");}p("]");}

```

Since C doesnt have array print functions built-in I had to do that work on my own so I apologive that there is a final comma in every output. Essentially what that code does is it reads the string if it is not a digit it replaces it with '\0' and then I just loop through the code and print out all of the chains of digits.(EOF=0)

> Input: ab5c0x
> Output: \["5","0",\]
> Input: z526ks4f.;8\]\p
> Output: \["526","4","8",\]
> 0 votes

# Answer
# C#, 98

```
static string[] SplitAtNonDigits(string s)
{
    return new string(s.Select(c=>47<c&c<58?c:',').ToArray()).Split(new[]{','},(StringSplitOptions)1);
}

```

First, this uses the LINQ `.Select()` extension method to turn all non-digits into commas. `string.Replace()` would be preferable, since it returns a `string` rather than a `IEnumerable<char>`, but `string.Replace()` can only take a single char or string and can't make use of a predicate like `char.IsDigit()` or `47<c&c<58`.

As mentioned, `.Select()` applied to a string returns an `IEnumerable<char>`, so we need to turn it back into a string by turning it into an array and passing the array into the `string` constructor.

Finally, we split the string at commas using `string.Split()`. `(StringSplitOptions)1` is a shorter way of saying `StringSplitOptions.RemoveEmptyEntries`, which will automatically takes care of multiple consecutive commas and commas at the start/end of the string.
> 0 votes

# Answer
## Python ~~104~~ 83

```
def f(s, o=[], c=""):
    for i in s:
        try:int(i);c+=i
        except:o+=[c];c=""
    return [i for i in o+[c] if i]

```

@Abhijit answer is far clever, this is just a "minified" version of what i had in mind.

```
assert f("abc123def456") == ["123", "456"]
assert f("aitew034snk582:3c") == ["034", "582", "3"]
assert f("as5493tax54\\430-52@g9.fc") == ["5493", "54", "430", "52", "9"]
assert f("sasprs]tore\"re\\forz") == []

```

This yields no output, so the code is working, if ran one by one, as some variables are defined at the declaration.
> 0 votes

# Answer
# JavaScript, 240 bytes

And for those of you who are curious, here's my probably huge golf:

```
function split(a) { // begin function
function f(c){for(var a=-1,d=9;d--;){var e=c.indexOf(d+"");0
>e||e<a&&(a=e)}return 0<a?a:null}var c=f(a);if(null==c)retur
n null;var d=[];for(i=0;;){a=a.substring(c);d[i]||(d[i]="");
c=f(a);if(null==c)break;d[i]+=a.charAt(c);0<c&&i++}return d;
} // end function

```

### Above in pretty print:

```
function split(a) {
    function f(c) {
        for (var a = -1, d = 9;d--;) {
            var e = c.indexOf(d + "");
            0 > e || e < a && (a = e);
        }
        return 0 < a ? a : null;
    }
    var c = f(a);
    if (null == c) return null;
    var d = [];
    for (i = 0;;) {
        a = a.substring(c);
        d[i] || (d[i] = "");
        c = f(a);
        if (null == c) break;
        d[i] += a.charAt(c);
        0 < c && i++;
    }
    return d;
}

```

### Above in normal descriptive code

```
function split(a) {
    function findLoop(string) {
        var lowest = -1;
        var i = 9;
        while (i--) {
            var index = string.indexOf(i + '');
            if (index < 0) continue;
            if (index < lowest) lowest = index;
        }
        return (lowest > 0) ? lowest : null;
    }
    var index = findLoop(a);
    if (index == null) return null;
    var ret = [];
    i = 0;
    for ( ; ; ) {
        a = a.substring(index);
        if (!ret[i]) ret[i] = '';
        index = findLoop(a);
        if (index == null) break;
        ret[i] += a.charAt(index);
        if (index > 0) i++;
    }
    return ret;
}

```
> 0 votes

# Answer
## PHP 134

```
function f($a){
$i=0;while($i<strlen($a)){!is_numeric($a[$i])&&$a[$i]='-';$i++;}return array_filter(explode('-',$a),function($v){return!empty($v);});
}

```
> 0 votes

# Answer
## Ruby, 24

```
f=->s{s.tr("
-/:-~",' ').split}

```

Defines digits using negative space within the printable ascii range.
> 0 votes

# Answer
**JS/Node : 168 162 147 138 Chars**

```
function n(s){
var r=[];s.split('').reduce(function(p,c){if(!isNaN(parseInt(c))){if(p)r.push([]);r[r.length-1].push(c);return 0;}return 1;},1);return r;
}

```

Beautified version:

```
function n(s) {
  var r = [];
  s.split('').reduce(function (p, c) {
    if (!isNaN(parseInt(c))) {
      if (p) {
        r.push([]);
      }
      r[r.length - 1].push(c);
      return 0;
    }
    return 1;
  }, 1);
  return r;
}

```
> 0 votes

# Answer
# JavaScript, 104 97 89

*Golfed:*

**Edit:** When the loops walks off the end of the array, `c` is `undefined`, which is falsy and terminates the loop.

**2/27:** Using `?:` saves the wordiness of `if/else`.

```
function nums(s) {
s+=l='length';r=[''];for(k=i=0;c=s[i];i++)r[k]+=+c+1?c:r[k+=!!r[k][l]]='';
r[l]--;return r
}

```

The carriage return in the body is for readability and is not part of the solution.

*Ungolfed:*

The idea is to append each character to the last entry in the array if it is a digit and to ensure the last array entry is a string otherwise.

```
function nums(s) {
    var i, e, r, c, k;
    k = 0;
    s+='x'; // ensure the input does not end with a digit
    r=[''];
    for (i=0;i<s.length;i++) {
        c=s[i];
        if (+c+1) { // if the current character is a digit, append it to the last entry
            r[k] += c;
        }
        else { // otherwise, add a new entry if the last entry is not blank
            k+=!!r[k].length;
            r[k] = '';
        }
    }
    r.length--; // strip the last entry, known to be blank
    return r;
}

```
> 0 votes

# Answer
## PHP ~~98~~ 89

As in DigitalTrauma's bash answer, this doesn't use a regex.

```
function f($x) {
// Only the following line counts:
for($h=$i=0;sscanf(substr("a$x",$h+=$i),"%[^0-9]%[0-9]%n",$j,$s,$i)>1;)$a[]=$s;return@$a;
}

```

Test cases:

```
php > echo json_encode(f("abc123def456")), "\n";
["123","456"]
php > echo json_encode(f("aitew034snk582:3c")), "\n";
["034","582","3"]
php > echo json_encode(f("as5493tax54\\430-52@g9.fc")), "\n";
["5493","54","430","52","9"]
php > echo json_encode(f("sasprs]tore\"re\\forz")), "\n";
null

```
> 0 votes

# Answer
**Python**

```
def find_digits(_input_):
    a,b = [], ""
    for i in list(_input_):
        if i.isdigit(): b += i
        else:
            if b != "": a.append(b)
            b = ""
    if b != "": a.append(b)
    return a

```
> 0 votes

# Answer
# Haskell 31

```
{-# LANGUAGE OverloadedStrings #-}
import Data.Char (isDigit)
import Data.Text (split)

f=filter(/="").split(not.isDigit)

```

It splits the string on all non-numeric characters and removes the empty strings generated by consecutive delimiters.
> 0 votes

# Answer
# Javascript, 72

```
function f(a){
 a+=".",b="",c=[];for(i in a)b=+a[i]+1?b+a[i]:b?(c.push(b),""):b;return c
}

```

Ungolfed

```
a+=".",b="",c=[];        //add '.' to input so we dont have to check if it ends in a digit
for(i in a)
    b=+a[i]+1?           //check if digit, add to string if it is
        b+a[i]:
    b?                   //if it wasnt a digit and b contains digits push it
        (c.push(b),""):  //into the array c and clear b
    b;                   //else give me b back
return c

```

Sample input/output

```
console.log(f("abc123def456"));
console.log(f("aitew034snk582:3c"));
console.log(f("as5493tax54\\430-52@g9.fc"));
console.log(f("sasprs]tore\"re\\forz"));

["123", "456"]
["034", "582", "3"]
["5493", "54", "430", "52", "9"]
[]

```

**JSFiddle**
> 0 votes

# Answer
## VBA 210, 181 without function declaration

```
Function t(s)
Dim o()
For Each c In Split(StrConv(s,64),Chr(0))
d=IsNumeric(c)
If b And d Then
n=n&c
ElseIf d Then:ReDim Preserve o(l):b=1:n=c
ElseIf b Then:b=0:o(l)=n:l=l+1:End If:Next:t=o
End Function

```
> 0 votes

# Answer
# Rebol (66 chars)

```
remove-each n s: split s complement charset"0123456789"[empty? n]s

```

Ungolfed and wrapped in function declaration:

```
f: func [s] [
    remove-each n s: split s complement charset "0123456789" [empty? n]
    s
]

```

Example code in Rebol console:

```
>> f "abc123def456"
== ["123" "456"]

>> f "aitew035snk582:3c"
== ["035" "582" "3"]

>> f "as5493tax54\\430-52@g9.fc"
== ["5493" "54" "430" "52" "9"]

>> f {sasprs]torer"re\\forz}
== []

```
> 0 votes

# Answer
## R 52

This function splits strings by character class (this is not regex! :)) class is N - numeric characters and P{N} means negation of this class. o=T means omit empty substrings.

```
x
## [1] "wNEKbS0q7hAXRVCF6I4S" "DpqW50YfaDMURB8micYd" "gwSuYstMGi8H7gDAoHJu"
require(stringi)
stri_split_charclass(x,"\\P{N}",o=T)
## [[1]]
## [1] "0" "7" "6" "4"

## [[2]]
## [1] "50" "8"

## [[3]]
## [1] "8" "7"

```
> 0 votes

# Answer
## PHP 99

```
<?php

$a = function($s) {
foreach(str_split($s)as$c)$b[]=is_numeric($c)?$c:".";return array_filter(explode('.',implode($b)));
};

var_dump($a("abc123def456"));
var_dump($a("aitew034snk582:3c"));
var_dump($a("as5493tax54\\430-52@g9.fc"));
var_dump($a("sasprs]tore\"re\\forz"));

```

### Output

```
array(2) {
  [3]=>
  string(3) "123"
  [6]=>
  string(3) "456"
}
array(3) {
  [5]=>
  string(3) "034"
  [8]=>
  string(3) "582"
  [9]=>
  string(1) "3"
}
array(5) {
  [2]=>
  string(4) "5493"
  [5]=>
  string(2) "54"
  [6]=>
  string(3) "430"
  [7]=>
  string(2) "52"
  [9]=>
  string(1) "9"
}
array(0) {
}

```
> 0 votes

# Answer
# JavaScript 88

88 chars when not counting function n(x){}

```
function n(x){
y=[],i=0,z=t=''
while(z=x[i++])t=!isNaN(z)?t+z:t&&y.push(t)?'':t
if(t)y.push(t)
return y
}

```
> 0 votes

# Answer
# Racket 149

Golfed (according to the rules, only the length of the second line counts)

```
(define (extract-numeric-substrings s)
(let L([x(map string->number(string-split s""))])(set! x(dropf x false?))(if(null? x)x(let-values([(h t)(splitf-at x number?)])(cons(apply ~a h)(L t)
)))))

```

Ungolfed

```
(define (extract-numeric-substrings s)
  (let L ([x (map string->number (string-split s ""))])
    (set! x (dropf x false?))
    (if (null? x)
        x
        (let-values([(h t) (splitf-at x number?)])
          (cons (apply ~a h) (L t))))))

```

Results

```
(map extract-numeric-substrings '("abc123def456"
"aitew034snk582:3c"
"as5493tax54\\430-52@g9.fc"
"sasprs]tore\"re\\forz"))

'(("123" "456")
("034" "582" "3")
("5493" "54" "430" "52" "9")
())

```
> 0 votes

# Answer
## Javascript with lambdas, 84

```
extract=s=>[].reduce.call(s,(r,c)=>r+=(c!=+c?r[r.length-1]==" "?"":" ":c),"").trim().split(" ")

```

Tested in Firefox 27
> 0 votes

# Answer
## VB.NET, 87

```
Imports System.Console
Imports System.String
Imports System.Char
Imports System.StringSplitOptions

Module All
  Public Function Parse(S As String) As String()
    Return Join("",From C In S Select If(IsDigit(C),C," ")).Split({" "},RemoveEmptyEntries)
  End Function

  Public Sub Main()
    For Each S As String In {"abc123def456", "aitew034snk582:3c", "as5493tax54\\430-52@g9.fc", "sasprs]tore\""re\\forz"}
      WriteLine(Join(":", Parse(S)))
    Next S
  End Sub
End Module

```

According the rules, only content of parse function is calculated:

```
Return Join("",From C In S Select If(IsDigit(C),C," ")).Split({" "},RemoveEmptyEntries)

```
> 0 votes

# Answer
# Haskell 37

I am not counting the imports towards the bytecount, as per the scoring rules. The body of the code is a 1 liner (with semicolons, so there is actually no advantage other than looking more golfed), though I am not sure what to count and what not to count in the function definitions. This was originally longer, but I got inspiration from Coaumdio's and DigitalTrauma's `bash` solutions.

```
import Data.Char {-Not counted-}
i x|isDigit x=x;i _=' ';f=words.map i {-Fully Counted-}

```

`i` preserves digit characters, and replaces all other characters with space. `f` just maps `i` onto a string and then applies `words`, which splits a string into a list of substrings that were separated by arbitrarily long runs of whitespace. If I am missing any of the rules whereby I can reduce my bytecount by omitting certain characters from the score, I would appreciate comments to that effect.
> 0 votes

# Answer
**APL: 22**

```
{(a/1,2</a)⊂⍵/⍨a←⍵∊⎕D}

```

**Explanation:**

```
a←⍵∊⎕D creates boolean of argument (⍵) being a digit (system variable ⎕D contains '0123456789')

⍵/⍨a  takes just the numeric part of the argument

(a/1,2</a)⊂  makes substrings of numbers only, starting at first number found

```
> 0 votes

# Answer
# Pharo Smalltalk, 60

```
f:=[:s|(s splitOn:[:e|e isDigit not])reject:[:e|e isEmpty]]

```

Outputs:

```
f value:'abc123def456' -> OrderedCollection('123' '456')
f value:'aitew034snk582:3c' -> OrderedCollection('034' '582' '3')
f value:'as5493tax54\430-52@g9.fc' -> OrderedCollection('5493' '54' '430' '52' '9')
f value:'sasprs]tore\"re\forz' -> OrderedCollection()

```
> 0 votes

# Answer
# C (gcc), 50 bytes

**Note that the TIO counts 48, that is because it doesn't count the global at the top**

```
c;
void split(unsigned char *s, unsigned char **a) {
for(c=0;*s;s++)c=*s-48u>9?*s=0:c?:(*a++=s);*a=0;
}

```

Try it online!

Significant improvement of Coaumdio's algorithm which I would comment on, but the user hasn't been active since then.

The most notable difference is that it uses `unsigned char *` instead of `char *`. This is because the function signature is free, and it allows us to do unsigned arithmetic instead of `ctype`. This doesn't affect the test cases, but if we were to have a character with the high bit set, it would.

```
for(c=0;*s;s++)

```

I moved the variable to a global variable with implicit int and initialized in the for loop. Saves 3 bytes.

Otherwise, this simply loops through `s` until it reaches the null terminator.

Now to explain this glorious hot garbage.

```
c=*s-48u>9?*s=0:c?:(*a++=s);

```

Let's format it a little better, convert it to an if-else, and step through it.

Overview of the logic:

```
if (*s - (unsigned)'0' > 9) { // c=*s-48u>9?
    c = *s = '\0';            //   *s=0
} else if (c != 0) {          // :c?
    c = c;                    //   // implicit: c
} else {                      // :
    c = (int)(*a++ = s);      //   (*a++ = s)
}                             // ;

```

```
if (*s - (unsigned)'0' > 9) { // c=*s-48u>9?

```

Thanks to unsigned arithmetic, we can remove the `isdigit` call entirely.

Basically, what the subtraction does is an unsigned subtraction, with negatives being converted to really big positives.

So for example:

```
' ' = 32 - 48 = -16 = 4294967280 (for a 32-bit int)
'0' = 48 - 48 = 0 = 0
'9' = 54 - 48 = 9 = 9
'A' = 65 - 48 = 17 = 17

```

As you can see, `'0'` to `'9'` will be turned into `0`-`9`, and anything else will be larger than that, so we can just check if the result of the subtraction is greater than 9.

```
    c = *s = '\0';            //   *s=0

```

If it is not a digit, we will replace the contents of `*s` with a `'\0'` byte. The result of this assignment makes the ternary return 0, also assigning `c` to 0.

```
} else if (c != 0) {          // :c?
    c = c;                    //   // implicit: c

```

If it *is* a digit and `c` is set, we set it to itself using GCC's `?:` extension, which evaluates to the condition itself for true if the middle of the ternary is left out.

```
} else {                      // :
    c = (int)(*a++ = s);      //   (*a++ = s)
}                             // ;

```

Last, if it is a digit and `c` is not set, we will store `s` into `a` and advance it, and here is the disgusting part: We then use the result of that assignment to set `c` to a non-zero value...assigning an integer to a pointer.

```
*a=0;

```

Finally, we `NULL` terminate `a` and return.
> 0 votes

# Answer
**C# 66**

```
static char[] n(string s){return s.Where(Char.IsDigit).ToArray();}

```
> -1 votes

---
Tags: code-golf, string, restricted-source
---


title: Implement Multiplicative Fuzzy Logic

text:
# Question
Title: Implement Multiplicative Fuzzy Logic
Inspired by this excellent challenge (from which the bulk of this text is blatantly duct-taped) – and my highschool philosophy project...

I define the following operators:

**Fuzzy Conjunction** *a* ×F *b* is *a* × *b*

**Fuzzy Division** *a* ÷F *b* is *a* ÷ *b*

**Fuzzy Negation**F *b* is 1 – *b*

**Fuzzy Disjunction** *a* +F *b* is –F ((–F *a*) ×S (–F *b*) which is equivalent to 1 – (1 – *a*) × (1 – *b*)

With all this in mind, create an interpreter that will evaluate infix expressions that use the following operators (i.e., `a + b`, not `a b +` or `+ a b`). Alternatively, extend the language of your choice to include the notation.

```
×    Multiplication
÷    Division
–    Subtraction
+    Addition
×F   Fuzzy Conjunction
÷F   Fuzzy Division
–F   Fuzzy Negation
+F   Fuzzy Disjunction

```

Notice that *a* -F *b* is **not** defined. You may leave it undefined, or define it as you see fit.

You may substitute `*` for `×` and/or `-` for  and/or `/` for `÷`, (or use whatever single symbols your language uses for the four basic arithmetic operations) as long as you stay consistent: You may not use `*` and `×F` together.

You may choose to require or prohibit spacing around tokens.

You may choose any of the following rules for order of precedence:

1. As normal mathematics, and *each* Fuzzy operator has a *higher* order precedence than their normal counterpart.
2. As normal mathematics, and *each* Fuzzy operator has a *lower* order precedence than their normal counterpart.
3. As normal mathematics, and the Fuzzy operators *all* have *higher* order precedence than all the normal operators.
4. As normal mathematics, and the Fuzzy operators *all* have *lower* order precedence than all the normal operators.
5. Strict left-to-right.
6. Strict right-to-left.
7. Normal and *Fuzzy* operators have the *same* precedence and are evaluated left-to-right.
8. Normal and *Fuzzy* operators have the *same* precedence and are evaluated right-to-left.

Leave a comment if you desire another precedence rule.

Test cases using precedence rule 6:

```
> 5 +F 10 + 3
-47     // 1 - (1 - 5) × (1 - 13)
> 10 × 2
20      // 2 × 10
> 10 ×F 1
10      // 1 × 10
> 23 × 3
69      // 23 × 3
> 123 ×F 2 × 3
738     // 123 × 2 × 3
> 5 + 3 +F 2
4       // 5 + 1 - (1 - 3) × (1 - 2)
> 150 ÷F 3
50      // 150 ÷ 3
> 150 ÷ 53
2.83    // 150 ÷ 53
> -F -F -F 0
1       // 1 - (1 - (1 - 0))
> -500
-500    // - 500
> -F 6 - 1
-4      // 1 - 5
> 12 +F 633 ×F 3
-20877  // 1 - (1 - 12) × (1- 633 × 3)

```

This is a , so the shortest program in bytes wins.

# Answer
> 6 votes
# Jelly, 20 bytes

```
⁾-Cyœṣ⁾+Fj“+_×ɗ”ḟ”FV

```

Try it online!

~~To quote myself:~~

~~Well, it's disgustingly hacked together, but it works :D
~~

Well, it's much more elegantly hacked together.

Haha, beating QuadR!

Jelly doesn't like strings. For a more elegant solution that exploits Jelly natural infix notation, see below. Takes input from ARGV. The Footer in the link takes a multiline string, splits it on newlines, runs each line and returns a list of results.

This uses precedence rule 5, which is consistent (I believe) with Jelly's parsing rules in this case, and we use `_` for regular subtraction and for regular negation.

## How it works

```
⁾-Cyœṣ⁾+Fj“+_×ɗ”ḟ”FV - Main link. Takes an expression E on the left
⁾-C                  - Yield ["-", "C"]
   y                 - Replace all occurrences of "-" with "C"
      ⁾+F            - Yield ["+", "F"]
    œṣ               - Split on "+F"
          “+_×ɗ”     - Yield "+_×ɗ"
         j           - Join on "+_×ɗ"
                ḟ”F  - Remove any leftover "F"s
                   V - Execute as Jelly code

```

### Why `C` and `+_×ɗ`?

First, `C`. `C` is Jelly's builtin for \\$1 - x\\$

Now, `+_×ɗ`. The `ɗ` at the end tells Jelly to consider the previous 3 atoms as a single link, acting similarly to `(...)` in other languages. The three atoms implement the formula

$$\begin{align} 1 - (1-a)(1-b) & = 1 - (1-a-b+ab) \\ & = (a+b)-(a\times b) \end{align}$$

```
+_× - Takes a on the left and b on the right
+   - a+b
  × - a×b
_   - a+b - a×b

```

---

# Jelly, 9 + 8 = 17 bytes

```
×
÷
C
+_×

```

Try it online! or Try it online!

Slightly convoluted here, but bear with me. This uses the

> Alternatively, extend the language of your choice to include the notation.

rule to avoid any parsing or complicated stuff that Jelly isn't too good at. Instead we define 4 functions , , `3Ŀ` and  (Conjuction, Division, Negation and Disjuction respecitively), which "extends" Jelly to include the fuzzy operations by including the above 9 bytes before any code. I'm counting my byte count here as 9 bytes for the code above plus 8 bytes for the names of the functions.

This uses precedence rule 5, which is consistent (I believe) with Jelly's parsing rules in this case, and we use `_` for regular subtraction.

In the test suite above, we include our 4 functions in the header, then execute the lines of test cases with the Footer.

## How it works

The names of the functions are fairly easy to understand. Jelly allows you to call each line as a function using the `Ŀ` (call as monad) or the `ŀ` (call as dyad) quicks, which is what we use here.

and  are obvious how they work. `3Ŀ` simply takes advantage of Jelly's builtin for \\$1 - x\\$: `C`.  works the same way as specified above, but doesn't need the `ɗ` for grouping

# Answer
> 4 votes
# CJam, 45 bytes

```
q"-F"/"1 -"*"+F"/"1Y$-*+"*'F-S/)d\2/'\f*W%S*~

```

Uses precedence rule 6: strictly right-to-left. It expects ASCII input.

Take it for a spin!

## Explanation

Read input, and perform the following transformations in order:

```
"-F"   to   "1 -"
"+F"   to   "1Y$-*+"
 "F"   to   ""

```

Then split over spaces (`S/`). Extract the rightmost element and convert it to a double (`)d`). Then take pairs from the rest of the list (`\2/`), join them all by `\` (`'\f*`) and evaluate the resulting strings as CJam code in reverse order (`W%S*~`).

For example, it converts `5 +F 10 + 3`

* to `5 1Y$-*+ 10 + 3` in the first step,
* then to `3 [["10" "+"] ["5" "1Y$-*+"]]`,
* then to `3 ["10\+" "5\1Y$-*+"]`,
* then to `3 10\+ 5\1Y$-*+`, which is CJam code that computes the right answer, `-47`.

# Answer
> 4 votes
# QuadR, 21 bytes

```
⍎⍵
\+F
-F
F
(+-×)
1-

```

Try it online! or a version that accepts newline-separated test cases.

QuadR port of Razetime's APL answer, as it happens to be a set of `⎕R` substitution followed by post-processing code. I moved `⍵~'F'` part into the regex substitution `'F' → ''`, which saves a byte. It has no problem running multiple test cases separated by , but it does have some problem with newlines (which can be fixed by changing the first line to `⍎⍤1⎕FMT⍵`).

# Answer
> 3 votes
# APL (Dyalog Unicode), ~~38 37 35~~ 30 bytes

```
⍎'F'~⍨'\+F' '-F'⎕R'(+-×)' '1-'

```

Try it online!

A tacit function which accepts a string.

Evaluation is done as per Rule 6: strict right to left, as per APL's evaluation.

-1 byte from Adám.

-2 more from Adám.

-5 bytes from Bubbler.

## Explanation

```
⍎'F'~⍨'\+F' '-F'⎕R'(+-×)' '1-'
            '-F'⎕R        '1-'  regex replace '-F' with '1-'
      '\+F'     ⎕R'(+-×)'       regex replace '+F' with function to perform 1-((1-x)×(1-y))
 'F'~⍨                          remove any other Fs
⍎                               execute as APL code

```

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

Saved 3 bytes thanks to @Adám!

```
F←{⍺←1⋄⍺(×-⍣(2=⍺⍺2)⍺⍺)⍵}

```

Try it online!

Extends the language with a monadic operator `F`. Uses rule 6 (strict right-to-left). This fixes the issues Adám pointed out in the original answer.

`⍺⍺` is the input function (`+`, `-`, `×`, or `÷`),  is the left argument (`⍺←1` gives it a default value of `1`), and  is the right argument. `×-⍣(2=⍺⍺2)⍺⍺`, which Adám came up with, is applied to  and . It's equivalent to `(⍺×⍵) -⍣(2=⍺⍺2) (⍺ ⍺⍺ ⍵)`. If `⍺⍺` is `+`, then `2=⍺⍺2` (`2 = +2`) is true. If so,  subtracts its right argument `⍺+⍵` from its left argument `⍺×⍵` (this is equivalent to `1-(1-⍺)×(1-⍵)`. Otherwise, we just return what's on the right side. If it's multiplication or division, it's the same as normal `×` or `÷`. If it's fuzzy negation, then  is 1, so it'll be `1-⍵`.

# Answer
> 2 votes
# Nim, 106 bytes

```
type f=float
func`*~`(a,b:f):f=a*b
func`/~`(a,b:f):f=a/b
func`-~`(b:f):f=1-b
func`+~`(a,b:f):f=1- -~a* -~b

```

Try it online!

Adds the four operators to Nim. Since operator names can't contain letters, it uses a tilde `~` instead, which I consider a very fuzzy character. Precedence is the same as the corresponding normal operators.

---
Tags: code-golf, math, interpreter
---


title: ASCII art reflection

text:
# Question
Title: ASCII art reflection
In this challenge, you will be given a text block, and you need to perform reflection on the text.

# Input:

1. A string to be reflected. The text may *not* be supplied as an array whose elements are the lines of text. For example, `"ab\ncd"` and `['a','b','\n','c','d']` are allowed, but `['ab','cd']` or `[['a','b'],['c','d']]` are not. You can assume that all of the lines have the same number of characters (padded with whitespace where needed).
2. A boolean where `True` indicates Y reflection and `False` indicates X reflection

The two inputs can be passed in any order.

# Output:

The reflected string. The characters do not change, only their position. The resulting image block should be aligned to the top left (the first row and column must each contain a non-whitespace character). Trailing whitespace (on any of the lines) is allowed.

# Test cases:

```
False
  o /
--|/
  |
 / \

/ o
 /|--
  |
 \ /

```

---

```
True
  o /
--|/
  |
 / \

 / \
  |
--|/
  o /

```

---

```
True
text

text

```

---

```
False
text

txet

```

---

```
True
P
P
C
G

G
C
P
P

```

---

```
False
P
P
C
G

P
P
C
G

```

---

```
True
abcde
fghij
kl mn
opqrs
tuvwx

tuvwx
opqrs
kl mn
fghij
abcde

```

This is a , so answer with the shortest answer in your favorite language!

# Answer
> 11 votes
## C#, ~~168~~ ~~144~~ ~~141~~ 120 Bytes

```
using System.Linq;i=>y=>string.Join("\n",y?i.Split('\n').Reverse():i.Split('\n').Select(x=>string.Concat(x.Reverse())));

```

New version utilizes the obvious string.Join overload that takes an IEnumerable, the first solution was using it inadvertently I was just able to use it for the else side of the ternary as well.

### Update:

New version is an anonymous lambda and uses currying to save 21 bytes total. This changes usage to be `f("text")(false)` where f is the anonymous function.

### Ungolfed:

```
using System.Linq;

//Using currying to save one byte
input => IsYReflect =>
         //Lambda makes return implicit
         string.Join("\n", IsYReflect
            //Y Reflect, just need to reverse the array
            ? input.Split('\n').Reverse()
            //X Reflect, reverse each line into an IEnumerable
            : input.Split('\n').Select(x => string.Concat(x.Reverse())));

```

# Answer
> 10 votes
## Pyke, 7 bytes

```
!I_)ncX

```

Try it here!

```
!I )    - if not boolean:
  _     -  input = reversed(input)
    nc  - input.split("\n")
      X - splat(input)
        -  (print lines backwards)

```

# Answer
> 9 votes
# Brainfuck, ~~143~~ ~~140~~ 131 bytes

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

```

Beat~~s~~ C#.

The challenge was easy enough for Brainfuck, and I apparently was tired enough to just have to do it.

Takes the boolean as a `0x00` (falsy) or any other (truthy) byte in the start of the input, then a rectangle-padded string.

Outputs a trailing newline for the Y flip, and none for the X flip.

Requires an interpreter that supports memory locations to the left of the start (unsure if still required) and gives EOF as `0x00`. One such interpreter is here. Obviously doesn't support null bytes in the input because of that.

The code has a lot of blocks with 10 `+`'s or `-`'s; those can probably be reduced.

### Commented version

```
, get mode
[ check truthy input
    ,[ loop thru input
        ---------- subtract newline
        >+ set flag
        < go back to char
        [ was not newline
            > move to flag
            - reset flag
        ]
        > move to flag or one past flag
        [ hit flag; was newline
            - reset flag
            > skip a cell
        ]
        < go to next position
        , read next input
    ]
    < find end of line
    [ loop thru lines
        [<]> find start of line
        [ loop thru line
            ++++++++++ add newline back
            . print this cell
            > go to next cell
        ]
        ++++++++++ change to newline
        . print newline
        <[<]< find end of previous line
    ]
]
,[ loop thru any input left
    ---------- subtract newline
    >+ set flag
    < go back to char
    [ was not newline
        ++++++++++ add newline back
        > move to flag
        - reset flag
    ]
    > move to flag or one past flag
    [ hit flag; was newline
        - clear flag
        < go back to char
        < go back to line chars
        [ loop thru line
            . print this cell
            < go to previous cell
        ]
        ++++++++++. print newline
        [>]>> find empty cell
    ]
    < go to next position
    , read next input
]
< go to line
[ loop thru line
    . print this cell
    < go to previous cell
]

```

# Answer
> 6 votes
# 32-bit x86 machine code, 76 bytes

In hex:

```
31c031c9495789f7fcf2aef7d15192b00a89f7f2ae5829f7f7f787f95f4b89c3741287d94b534b8a041eaa75f95b01dea4e2f2c348f7e101c6b00a5651f3a4595e29ce4f4b0f44c3aa75f0c3

```

Input: `EBX`: direction flag (0/1), `ESI`: input string, `EDI`: output buffer. Input is required to be rectangular.

```
0:  31 c0               xor eax,eax         ;EAX=0
2:  31 c9               xor ecx,ecx
4:  49                  dec ecx             ;ECX=(uint)-1
5:  57                  push edi
6:  89 f7               mov edi,esi
8:  fc                  cld
9:  f2 ae               repne scasb         ;Scan input string for terminating NULL
b:  f7 d1               not ecx             ;ECX==<input string length (including NULL)>
d:  51                  push ecx
e:  92                  xchg edx,eax        ;EDX=0
f:  b0 0a               mov al,0x0a         ;'\n'
11: 89 f7               mov edi,esi
13: f2 ae               repne scasb         ;Scan input string for the first newline
15: 58                  pop eax             ;EAX==<input string length (including NULL)>
16: 29 f7               sub edi,esi         ;EDI==<single line length (including '\n')>
18: f7 f7               div edi             ;EAX==<# of lines>
1a: 87 f9               xchg ecx,edi        ;ECX=EDI
1c: 5f                  pop edi             ;EDI=<dest buffer>
1d: 4b                  dec ebx             ;Test input flag (0/1)
1e: 89 c3               mov ebx,eax         ;EBX=<# of lines>
20: 74 12               je _vertical
22: 87 d9               xchg ecx,ebx        ;Horisontal flip, exchange ECX & EBX so we can use LOOP
24: 4b                  dec ebx             ;EBX=<single line length (excluding '\n')>
_hfouter:
25: 53                  push ebx
_hfinner:
26: 4b                  dec ebx             ;Decrement inner loop counter
27: 8a 04 1e            mov al,[esi+ebx]    ;AL=ESI[EBX]
2a: aa                  stosb               ;*EDI++=AL
2b: 75 f9               jne _hfinner        ;EBX==0 => break
2d: 5b                  pop ebx
2e: 01 de               add esi,ebx         ;*ESI=='\n' (\0 on the last line)
30: a4                  movsb               ;*EDI++=*ESI++, ESI now points to the next line
31: e2 f2               loop _hfouter       ;--ECX==0 => break
33: c3                  ret                 ;Nothing more to do here
_vertical:
34: 48                  dec eax             ;# of strings less one
35: f7 e1               mul ecx             ;Line length (including '\n')
37: 01 c6               add esi,eax         ;ESI+=ECX*(EAX-1), ESI now points to the beginning of the last line
39: b0 0a               mov al,0x0a         ;'\n'
_vfloop:
3b: 56                  push esi
3c: 51                  push ecx
3d: f3 a4               rep movsb           ;Copy the whole line to the output including newline/NULL at the end
3f: 59                  pop ecx
40: 5e                  pop esi
41: 29 ce               sub esi,ecx         ;Set ESI to the beginning of the previous line
43: 4f                  dec edi             ;*EDI=='\n' (0 on the first iteration), should overwrite it with correct value
44: 4b                  dec ebx             ;Decrement loop counter
45: 0f 44 c3            cmove eax,ebx       ;if (EBX==0) EAX=EBX, this clears EAX on the last iteration
48: aa                  stosb               ;*EDI++=EBX?'\n':0
49: 75 f0               jne _vfloop         ;EBX==0 => break
4b: c3                  ret

```

# Answer
> 5 votes
## Haskell, ~~51~~ ~~49~~ 45 bytes

```
r=reverse
f b=unlines.last(map r:[r|b]).lines

```

Usage example:

```
f True "abc\ndef\nghi\njkl"
"jkl\nghi\ndef\nabc\n"

f False "abc\ndef\nghi\njkl"
"cba\nfed\nihg\nlkj\n"

```

Split into lines, either reverse the lines (True) or reverse each line (False) and join into a single string again. In case of a `True` input, `map r:[r|b]` is a list of two functions `[<reverse each line>, <reverse lines>]` and for a `False` input a list with one function `[<reverse each line>]`. `last` picks the last element of this list.

# Answer
> 5 votes
# Jelly, 8 bytes

```
ṣ⁷ṚU⁴?j⁷

```

Try it here.

```
ṣ⁷         Split over newlines.
  ṚU⁴?     If ⁴ (2nd argument), then Ṛ (reverse rank ∞), else U (reverse rank 1).
      j⁷   Join with newlines.

```

# Answer
> 4 votes
# Python, 56 bytes

```
lambda s,r:'\n'.join(s[::2*bool(r)-1].split('\n')[::-1])

```

Call with a string `s` and any truthy/falsey value `r`.

# Answer
> 4 votes
# Python 3.5, 61 bytes:

```
lambda f,j:[print(r[::-1])for r in j[::[1,-1][f]].split('\n')]

```

A simple anonymous lambda function that assumes rectangular input. Call it by by first naming the function, and then calling it wrapped inside `print()`. In other words, if the function were named `H`, call it like `print(H(<Bool value>, <String>))`, where `<Bool Value>` is any true or false value (i.e. `0/1`, `true/false`, etc.) and `<String>` is the input string.

See it in Action! (repl.it)

Here is another version with the same length that also assumes rectangular input, but this time a *named* function, i.e. you don't have to name it first nor wrap it inside `print()`:

```
def J(f,j):[print(r[::-1])for r in j[::[1,-1][f]].split('\n')]

```

Simply call this one like`J(<Bool Value>,<String>)`.

See this in Action! (repl.it)

However, I'm not the one to stop there. Although we are allowed to assume rectangular input, I also created a version that does *not* assume that type of input. Therefore, it will space-pad all of the lines to the same length based on the line with the maximum length if and only if the `<Bool>` input is `False`, as only a X-reflection will result in the string being "flipped". Now, without further ado, here is the non-rectangular assuming version with a length of **~~134~~ 129 bytes** in the form of a normal function:

```
def J(f,j):print('\n'.join([' '*((max([len(i)for i in j.split('\n')])-len(r))*(not f))+r[::-1]for r in j[::[1,-1][f]].split('\n')]))

```

See this Last One in Action! (repl.it)

# Answer
> 2 votes
# Brachylog, ~~26~~ ~~24~~ 16 bytes

```
t1,?h@nr~@nw|hrw

```

Expects a list containing the string and the boolean `1` or `0`, e.g.

```
run_from_file('code.bl',["P
|    P
|    C
|    G":1]).

```

### Explanation

```
t1,              If the tail of the input is 1
   ?h@n              Split the string on \n
       r             Reverse the resulting list
        ~@n          Join the list of strings with \n
           w         Write to STDOUT
|                Or
hr                   Reverse the string
  w                  Write to STDOUT

```

# Answer
> 2 votes
# MATL, 11 bytes

```
10&Ybc2i-&P

```

**Try it online!**

The **first input** is the multiline string. Since MATL doesn't recognize `\n` as linefeed, the multiline string should be defined as a concatenation of substrings, or individual characters, and `10` (ASCII for line feed, which is interpreted as a character). Concatenation in MATL is `[... ...]` or `[..., ...]` (commas are optional). So for example, input can be as follows (concatenation of a string, linefeed, and another string):

```
['first line' 10 'second']

```

or equivalently (concatenation of individual characters)

```
['f' 'i' 'r' 's' 't' ' ' 'l' 'i' 'n' 'e' 10 's' 'e' 'c' 'o' 'n' 'd']

```

or (same with commas)

```
['f', 'i', 'r', 's', 't', ' ', 'l', 'i', 'n', 'e', 10, 's', 'e', 'c', 'o', 'n', 'd']

```

The **second input** can be entered as `1`/`0` or equivalently as `T`/`F` for `true`/`false` respectively.

### Explanation

```
10     % Push 10 (ASCII for linefeed)
&Yb    % Take input string implicitly. Split at linefeeds. Gives a cell array
c      % Convert to a 2D char array, right-padding with spaces
i~Q    % Input Boolean value. Negate and add 1. Gives 1/2 for true/false resp.
&P     % Flip along that dimension (1: vertically; 2: horizontally). Display implicitly

```

# Answer
> 2 votes
# Pyth, 10 bytes

```
j?Q_.z_M.z

```

Test suite.

```
j?Q_.z_M.z  first line evaluated as Q, all other lines as .z
 ?Q         if Q:
   _.z         yield reverse(.z)
      _M.z  else: yield map(reverse, .z)
j           join by newlines

```

# Answer
> 2 votes
# Julia, 59 bytes

```
x\y=(y=split(y,'
');! =reverse;join(x?!y:[!a for a=y],'
'))

```

Try it online!

# Answer
> 2 votes
## Perl, 35 bytes

**34 bytes code + 1 for `-n`.**

Requires the input lines be padded with spaces. 13 (!) bytes saved thanks to @Dada.

```
print/T/?reverse<>:map~~reverse,<>

```

### Usage

```
perl -ne 'print/T/?reverse<>:map~~reverse,<>' <<< 'False
  o /
--|/
  |
 / \ '

/ o
 /|--
  |
 \ /

 perl -ne 'print/T/?reverse<>:map~~reverse,<>' <<< 'True
  o /
--|/
  |
 / \ '
 / \
  |
--|/
  o /

```

# Answer
> 2 votes
# APL (Dyalog Unicode), ~~9~~ ~~11~~ 9 bytes (SBCS)

Fixed answer ~~but only had to add 2 bytes~~ and kept it the same length thanks to @Adám

```
⌽[⎕]⎕FMT⎕

```

Try it online!

Takes a character vector using `\r` as a separator through STDIN first, then 1 or 0. Requires 0-indexing.

accepts input. `⎕FMT` formats it into a character matrix because of `\r`. `⌽[⎕]` reflects that over either the x- or y-axis, depending on the second input. With 0-indexing, `⌽[0]` or just  reflects over the x-axis, `⌽[1]` or  over the y-axis.

# Answer
> 1 votes
# JavaScript (ES 6) 83 bytes

```
(c,b)=>(p=c.split`
`)&&(b?p.reverse():p.map(a=>a.split``.reverse().join``)).join`
`

```

---

```
f=(c,b)=>(p=c.split`
`)&&(b?p.reverse():p.map(a=>a.split``.reverse().join``)).join`
`

f("abcde\nfghij\nkl mn\nopqrs\ntuvwx",1)

c="
  o /
--|/
  |
 / \
";

f(c,1)
" / \
   |
 --|/
   o / "

f(c,0)
"/ o
  /|--
   |
  \ / "

```

# Answer
> 1 votes
# Bash + common linux utils, 16

```
(($1))&&tac||rev

```

Boolean value (zero or non-zero) passed as a command-line parameter. I/O of text block via STDIN/STDOUT. Assumes that all lines are the same length, as indicated in the comments.

# Answer
> 1 votes
# C (Ansi), 193 Bytes

## Golfed:

```
i,y,x;main(g,o,p)char**o;{p=(o[1][0]=='t');while(o[2][++i]!='\n');p?y=(strlen(o[2])-1)/i:(x=i);do do printf("%c",o[2][x+y*i]);while(p?++x<i:x-->0);while(p?x=0,y--:++y<(x=i-1,strlen(o[2])/i));}

```

## Ungolfed:

```
i,y,x;
main(g,o,p)char**o;{
    p=(o[1][0]=='t');
    while(o[2][++i]!='\n');
    p?y=(strlen(o[2])-1)/i:(x=i);
    do{
        do{
            printf("%c",o[2][x+y*i]);
        }while(p?++x<i:x-->0);
    }while(p?x=0,y--:++y<(x=i-1,strlen(o[2])/i));
}

```

## Usage:

### Compilation Arguments:

```
gcc -O3 -ansi

```

### Example Input:

Input is a t or not t for true of false followed by a newspace lead and trailed string.

```
./reverseString t "
truck
ducky
quack
moose
"

```

### Example Output:

```
moose
quack
ducky
truck

```

# Answer
> 1 votes
# J, 29 bytes

```
}:@,@(,.&LF@{|."1,:|.)>@cutLF

```

LHS input is the boolean where 0 is false and 1 is true. RHS is the string input.

# Answer
> 1 votes
# Java 99 bytes

```
public String[] reverse(String[]a){
  int i=-1,j=a.length;
  for(;++i<--j;){
    String b=a[i];
    a[i]=a[j];
    a[j]=b;
  }
  return a;
}

```

Golfed:

```
String[] e(String[]a){int i=-1,j=a.length;for(;++i<--j;){String b=a[i];a[i]=a[j];a[j]=b;}return a;}

```

# Answer
> 1 votes
# 05AB1E, 10 bytes

```
U|XiRë€R}»

```

# Explanation

```
U          Remove the first input line and store it in variable X
 |         Aggregate the rest of the input into an array
  XiR      If x is true, revert the array
     ë€R   Else revert each element
        }  End if
         » Join everything with newlines and implicitly display

```

Try it online!

# Answer
> 1 votes
# Charcoal, 6 bytes

```
θ¿η‖↓‖

```

Link is to verbose version of code.

Try it online!

# Answer
> 0 votes
## Mathematica, 70 bytes

```
If[#,Reverse,StringReverse]@ImportString[#2,l="Lines"]~ExportString~l&

```

Anonymous function, takes a boolean value as first argument (explicitly `True` or `False` in Mathematica) and the (multiline) string as the second argument. Imports the string as a list of strings corresponding to the lines of the multiline string (the string is NOT passed to the function as an array). If `True`, reverse the list. If `False` `StringReverse` the list, which automatically is applied to each element in turn. Then export the list as a string, where each element is a new line.

# Answer
> 0 votes
# JavaScript (ES6), 76

```
s=>b=>(s=s.split`
`,b?s.reverse():s.map(r=>[...r].reverse().join``)).join`
`

```

```
F=s=>b=>(s=s.split`
`,b?s.reverse():s.map(r=>[...r].reverse().join``)).join`
`

function test()
{
  var rows=I.value, r

  // Trim trailing newlines, pad to blank
  rows=rows.split('\n')
  while(!(r=rows.pop()));
  rows.push(r)
  var maxlen=Math.max(...rows.map(r=>r.length))
  rows=rows.map(r=>r+' '.repeat(maxlen-r.length)).join`\n`

  var t1=F(rows)(false)
  var t2=F(rows)(true)

  O.textContent = 'False\n'+t1+'\n\nTrue\n'+t2
}

test()
```

```
#I { width:50%; height:10em }
```

```
<textarea id=I>
  o /
--|/
  |
 / \
</textarea>
<button onclick=test()>Go</button>
<pre id=O></pre>
```

# Answer
> 0 votes
# Vim, 33 bytes

Changed previous V answer to Vim. Any V answer would be way different, so it wasn't really fair.

```
DgJ:if@"
g/^/m0
el
se ri
en
cG"

```

Try it online!

Hexdump

```
00000000: 4467 4a3a 6966 4022 0a67 2f5e 2f6d 300a  DgJ:if@".g/^/m0.
00000010: 656c 0a73 6520 7269 0a65 6e0a 6347 1222  el.se ri.en.cG."
00000020: 08                                       .
```

# Answer
> 0 votes
# 05AB1E, 8 bytes

```
|ćiRëí}»

```

Try it online!

```
|ćiRëí}»  # full program
       »  # join...
|         # list of lines in input...
 ć        # excluding the first element...
   R      # reversed...
  i       # if...
 ć        # first element of...
|         # list of lines in input...
  i       # is truthy...
    ë     # else...
     í    # with each element in list reversed...
       »  # by newlines
      }   # end if statement
          # implicit output

```

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


title: Levenshtein distance bias

text:
# Question
Title: Levenshtein distance bias
Write a program in a language with name `A` that, given a string `S`, outputs the name of a different programming language `B`. The length of `B` must be equal to the Levenshtein distance (abbr. "LD") between `A` and `S`. To be considered a programming language, `B` must have an esolangs page or a Wikipedia page.

## Example:

```
(Suppose the program is coded in Python)
Input: Jython
Output: R
Input: Pyt4oq
Output: Go
Input: Rs7hon
Output: C++

```

The LD between `Python` and `Jython` is one, so the output `R`

You only need to cover up to an LD of up to `12`. You can assume that an LD of `0` will never occur.

This is , so the shortest program in bytes wins.

(This is my first challenge! Feedback is appreciated)

---

# Leaderboard

```
var QUESTION_ID=58974,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
# O, 107 bytes

Using the tip from @histocrat to make the distance calculation simpler. Also used languages with The same starting letter to remove a few characters

```
"pyrodecimal""hakespeare""tackstack""nowflake""nowball""nowman""onata""ADOL""taq""oT""R"""ie\'O<-1-{;}d'Soo

```

Try it here
> 4 votes

# Answer
# PHP, ~~137~~ 135

Requires error reporting off and PHP 5.4+. Input is GET variable `a`.

```
<?=explode(~ß,~ß¼Üß¼ÔÔßµž‰žß¬œž“žß¾Š‹¶‹ß¾‘“›¼ß«¶Ò½¾¬¶¼ß½Š“š˜Š’ßµž‰žŒœ–‹ß²ž‹—š’ž‹–œžß¾œ‹–‘¬œ–‹)[levenshtein(PHP,$_GET[a])-1];

```

Hexdump:

```
00000000: 3C 3F 3D 65 78 70 6C 6F - 64 65 28 7E DF 2C 7E AD |<?=explode(~ ,~ |
00000010: DF BC DC DF BC D4 D4 DF - B5 9E 89 9E DF AC 9C 9E |                |
00000020: 93 9E DF BE 8A 8B 90 B6 - 8B DF BE 8D 91 90 93 9B |                |
00000030: BC DF AB B6 D2 BD BE AC - B6 BC DF BD 8A 9D 9D 93 |                |
00000040: 9A 98 8A 92 DF B5 9E 89 - 9E 8C 9C 8D 96 8F 8B DF |                |
00000050: B2 9E 8B 97 9A 92 9E 8B - 96 9C 9E DF BE 9C 8B 96 |                |
00000060: 90 91 AC 9C 8D 96 8F 8B - 29 5B 6C 65 76 65 6E 73 |        )[levens|
00000070: 68 74 65 69 6E 28 50 48 - 50 2C 24 5F 47 45 54 5B |htein(PHP,$_GET[|
00000080: 61 5D 29 2D 31 5D 3B    -                         |a])-1];|
00000087;

```

Readable version:

```
<?=explode(' ','R C# C++ Java Scala AutoIt ArnoldC TI-BASIC Bubblegum Javascript Mathematica ActionScript')[levenshtein(PHP,$_GET[a])-1];

```
> 6 votes

# Answer
# C, 183

```
main(s){char* a[12]={"R","C#","C++","Java","COBOL","Python","Clipper","VBScript","Smalltalk","Javascript","Mathematica","ActionScript"};printf(a[strlen(gets(&s))-!!strchr(&s,67)-1]);}

```

Picking a language with a one character name lets you cheat with the distance calculation: any string's distance from "C" is just the length of the string, minus one if it includes "C". I imagine R or J could beat this using the same strategy.
> 6 votes

# Answer
# Perl 5, ~~325~~ 276

Using a bit of recursion to calculate the Levenshtein distance.

```
@X=(P,e,r,l);$y=@Y=split//,pop;sub L{my($n,$m)=@_;return$m,if!$n;return$n,if!$m;my$c=$X[$n]eq$Y[$m]?0:1;(sort{$a<=>$b}(L($m-1,$n)+1,L($m,$n-1)+1,L($m-1,$n-1)+$c))[0]}print qw(C C# C++ Java COBOL Python Clipper VBScript Smalltalk Javascript Mathematica ActionScript)[L(4,$y)-1]

```

My original version had some issues with the longer inputs.
Till I realised that the Perl sort function sorts alphabetically.

Using substrings instead of arrays turns out to make it slightly longer.

```
@L=qw(C C# C++ Java COBOL Python Clipper VBScript Smalltalk Javascript Mathematica ActionScript);sub l{my($s,$t)=@_;return length($t)if!$s;return length($s)if!$t;my($u,$v)=(substr($s,1),substr($t,1));substr($s,0,1)eq substr($t,0,1)?l($u,$v):(sort{$a<=>$b}(l($u,$v),l($s,$v),l($u,$t)))[0]+1}print$L[l('Perl',pop)-1]

```

### Test

```
$ perl levenshtein.pl Php
C++

```
> 5 votes

# Answer
# J, 115 bytes

```
{&((}.&'YABC'&.>|.i.4),(g'SMITHb'),'Clojure';(g'ComeFrom2'),((g=:}:;])'StackStacks'),<'CoffeeScript')@<:@(#-'J'&e.)

```

This is using histocrat's calculation trick (using a 1-letter language), and generates the following list of languages:

```
┌─┬──┬───┬────┬─────┬──────┬───────┬────────┬─────────┬──────────┬───────────┬────────────┐
│C│BC│ABC│YABC│SMITH│SMITHb│Clojure│ComeFrom│ComeFrom2│StackStack│StackStacks│CoffeeScript│
└─┴──┴───┴────┴─────┴──────┴───────┴────────┴─────────┴──────────┴───────────┴────────────┘

```

e.g.:

```
   {&((}.&'YABC'&.>|.i.4),(g'SMITHb'),'Clojure';(g'ComeFrom2'),((g=:}:;])'StackStacks'),<'CoffeeScript')@<:@(#-'J'&e.) 'C++'
┌───┐
│ABC│
└───┘
   {&((}.&'YABC'&.>|.i.4),(g'SMITHb'),'Clojure';(g'ComeFrom2'),((g=:}:;])'StackStacks'),<'CoffeeScript')@<:@(#-'J'&e.) 'ActionScript'
┌────────────┐
│CoffeeScript│
└────────────┘
   f=:{&((}.&'YABC'&.>|.i.4),(g'SMITHb'),'Clojure';(g'ComeFrom2'),((g=:}:;])'StackStacks'),<'CoffeeScript')@<:@(#-'J'&e.)
   f 'Jython'
┌─────┐
│SMITH│
└─────┘
   f 'Python'
┌──────┐
│SMITHb│
└──────┘

```
> 3 votes

# Answer
# 05AB1E, 73 bytes

Not even a single-character language name and still the shortest answer here!

```
•äƵí•hR.L<Uõ'R„oT…taq.•₃γ•.•~ÙÚ•„€Ó…Ž„€Óïß…€ÓfŠ°„Â‚Â‚¦'Ïº¦“p¾»oãá“)Xè'Sìá

```

Try it online!

```
•äƵí•hR.L<U...Xè'Sìá  # full program
                   á  # get only letters of...
       .L             # Levenshtein distance between...
                      # implicit input...
       .L             # and...
•äƵí•                 # 14793296...
     h                # in hexadecimal...
      R               # reversed...
         <            # minus 1...
          U   Xè      # th element of...
           ...        # ["", "R", "oT", "taq", "ADOL", "onata", "now man", "now ball", "nowf lake", "tack stack", "hakespeare", "p yro decimal"]
                  ì   # prepended with...
                'S    # literal

```
> 1 votes

---
Tags: code-golf, string, edit-distance
---


# Question
Title: Recursively count lines of code, excluding empty lines and comments
**Requirement:** Write a program (in any language) that counts the number of lines of code in files matching `*.sh` in the directory tree starting from the directory that the program is executed in, excluding lines that are empty, only contain whitespace, or are just single-line comments (a line which the first character that is not a whitespace character is `#`). Files will only contain printable ASCII characters.

**Output:** A single integer representing the total count (can be followed by a newline too).

Here is an expanded solution in Python:

```
import os, sys

def recurse(dir = './'):
    count = 0

    for file in os.listdir(dir):
        if not os.path.isfile(dir + file):
            count += recurse(dir + file + '/')
        elif file.endswith('.sh'):
            with open(dir + file, 'r') as f:
                for line in f.read().split('\n'):
                    if (not line.strip().startswith('#')) and (not line.strip() == ''):
                        count += 1

    return count

sys.stdout.write(recurse())

```

# Answer
# Powershell 3+, 40 byte

```
(ls *.sh -r|sls '^\s*(#|$)' -a -n).Count

```

`ls *.sh -r` gets a file names from the directory tree. `sls` (alias for Select-String) gets all strings (`-a` is shortcut for `-AllMatches`) that not mathces (`-n` is alias for `-NotMatch`) to the pattern `'^\s*(#|$)'`.
> 3 votes

# Answer
# PowerShell, ~~47~~ 46 bytes

```
ls *.sh -r|gc|%{$o+=!($_-match'^\s*(#|$)')};$o

```

Try it online! (will always return `0` since there aren't any files)

Try it online! (here's a link that populates a dummy file so you can see the process)

*-1 byte thanks to Neil*

`ls` is alias for `Get-ChildItem`, specifying `*.sh` with the `-r`ecurse parameter, then we `g`et-`c`ontent of files. For each of those lines `|%{...}`, we accumulate into our `$o`utput a one if the Boolean `!(...)` statement is truthy. Inside the statement is a simple regex `-match` against the whitespace-only/comment/blank lines. Finally we leave `$o` on the pipeline.

~~The implicit `Write-Output` that happens at program completion adds a trailing newline, but that shouldn't matter in this case because the variable `$o` itself doesn't have a trailing newline nor does the actual return variable. It's a quirk of the shell, not a quirk of the program. For example, saving this to a script and executing that script in a pipeline will not have a newline.~~
> 4 votes

# Answer
# Linux Shell, ~~30~~ 60 bytes

confirmed in `dash`

```
cat `find . -name \*.sh`|tr -d " \t"|grep .|grep -v ^#|wc -l

```
1. `find . -name \*.sh`: find files matching the pattern, list with path
2. `cat ''`: list contents of these files
3. `tr -d " \t"`: trim tabs and spaces
4. `grep .`: remove empty lines
5. `grep -v ^#`: remove comments
6. `wc -l`: count lines of output
> 3 votes

# Answer
# , ~~70~~ 64 bytes

```
sum(!grepl("^(#|$)",unlist(lapply(dir(,".sh$",r=T),readLines))))

```

Explanation:

The `dir` function has the `recursive` flag set.

`readLines` returns the lines of a file in a vector, which are then flattened with `unlist`.
> 2 votes

# Answer
## Haskell, ~~211~~ 210 bytes

```
import System.Directory
f x=listDirectory x>>=fmap sum.mapM(\d->doesFileExist d>>=(#d)).map((x++"/")++)
p#d|p=do c<-readFile d;pure$sum[1|take 3(reverse d)=="hs.",(q:_):_<-map words$lines c,q/='#']|1<2=f d
f"."

```

Oh dear, without shell glob and regex you have to do all the work by yourself. Maybe there's somewhere a module for it. Also, IO code in Haskell requires some overhead to get the types right.

```
f x =                             -- main function, expects a directory 'x'
    listDirectory x >>=           -- read content of directory (without "." and "..")
              map((x++"/")++)     --   for each entry: prepend current directory 'x' and a slash
          mapM(\d->doesFileExist d>>=(#d))
                                  --   for each entry: call function '#' with
                                  --        first parameter: a boolean, True if it's a regular file, False if it's a directory
                                  --        second parameter: the filename itself
                                  --        '#' returns a list of valid lines for each file
     fmap sum                     --   sum this list

p#d
   |p                             -- if 'p' is True (i.e. 'd' is regular file)
     do c<-readFile d;            --   read the content 'c' of file 'd' and
        pure$sum[1|      ]        --   return the number of lines
              take 3(reverse d)=="hs."
                                  --     (only if the file end with .sh)
              (q:_):_<-map words$lines c,q/='#'
                                  --     where the first word doesn't start with a hash sign
                                  --       (function 'words' strips leading whitespace)
   |1<2                           -- else ('d' is a directory)
       =f d                       --   examine d

f"."                              -- start with current directory

```
> 2 votes

# Answer
# Bash \+ GNU utilities, 55

```
find . -name \*.sh -exec cat {} +|grep -Evc '^\s*(#|$)'

```

Try it online!
> 1 votes

# Answer
## Batch + Internal tools, ~~80~~ 76 Bytes

```
@for /F %%F IN ('findstr/SV "^\s*# ^\s*$" *.sh^|find/C":"')DO @set/P=%%F<NUL

```

Uses the builtin `findstr` to fetch the lines, then counts these line using `find /C`.

This however produces output with a newline, so we need to convert that into an output without. This is done by using `for /F` to fetch the output and then use `<NUL set /P` to output without the trailing newline.
> 1 votes

# Answer
# Python 2, ~~149~~ ~~146~~ ~~144~~ ~~140~~ ~~149~~ ~~146~~ 116 bytes

```
import os
print sum(l.strip()[:1]not in'#'for a,b,c in os.walk(".")for n in c for l in open(a+"/"+n)if'.sh'==n[-3:])

```

Try it online!

~~Reports 0 on TIO but works locally. Probably not any `.sh` files in whatever is the current directory.~~

I think it now works correctly on TIO and fixed a bug for +6, both thanks to @JonathanAllen

-30 with thanks to @ovs

Alternative for **139 bytes** but only works on Windows.

```
import os
os.system('dir/s/b *.sh>f')
print sum(sum((0,1)[x.strip()>''and'#'!=x.strip()[0]]for x in open(l[2:].strip()))for l in open("f"))

```

Creates a temporary file `f` to store the results for the `dir` command.
> 1 votes

# Answer
# Ruby, 61 bytes

```
p Dir.glob("**/*.sh").sum{|x|open(x).grep(/^\s*[^#\s]/).size}

```

Try it online!
> 1 votes

# Answer
# Röda \+ find, 98 bytes

```
{bufferedExec"find",".","-name","*.sh"|{|x|try readLines x}_|{|x|x~=`\s|#.*`,"";[1]if[#x>0]}_|sum}

```

Try it online!

# Pure Röda, 129 bytes

```
{["."]|[_]if isFile(_1)else unpull(x)for x in[ls(_1)]|{|x|try readLines x if[x=~`.*\.sh`]}_|{|l|l~=`\s|#.*`,"";[1]if[#l>0]}_|sum}

```

Try it online!

Explanation:

```
{
["."]|                     /* Push "." to the stream */
                           /* For each _1 in the stream: */
[_]if isFile(_1)           /*   If _1 is a file, push it to the output stream */
else                       /*   Else (if _1 is a directory): */
unpull(x)for x in[ls(_1)]| /*     Push each file/dir in _1 to the *input stream* */
{|x|                       /* For each x in the stream: */
  try readLines x          /*   Push lines of x to the stream ignoring errors */
    if[x=~`.*\.sh`]        /*     if x ends in .sh */
}_|
{|l|                       /* For each l in the stream: */
  l~=`\s|#.*`,"";          /*   Remove whitespace and comments from l */
  [1]if[#l>0]              /*   Push 1 to the stream if l is not empty */
}_|
sum                        /* Sum all numbers in the stream */
}

```
> 1 votes

# Answer
# C (clang), ~~248~~ 209 bytes

```
#import <regex.h>
*l,i,j;*k;regex_t r;f(n,s,t){if(fnmatch("*.sh",n,0))return 0;k=fopen(n,"r");for(regcomp(&r,"^\\s*(#|$)",1);i=getline(&l,&i,k)>0;)regexec(&r,l,0,0,0)&&j++;}main(){ftw(".",f,1);printf("%d",j);}

```

Try it online!
> 0 votes

# Answer
# PHP, ~~105 140 174 186 184~~ 172 bytes

```
function f($d){foreach(glob("$d/*")as$n)$n[strlen($d)+1]^_^A&&$s+=!is_dir($n)?fnmatch("*.sh",$n)?preg_match_all("/^\s*[^#]/m",join(file($n))):0:f($n);return$s;}echo f(".");

```

skips hidden directories and files (name starts with a dot). Run with `-nr`.

## breakdown

```
function f($d)
{
    # loop through directory entries
    foreach(glob("$d/*")as$n)
        # if name does not start with a dot
        $n[strlen($d)+1]^_^A
        # then increase sum:
        &&$s+=
            # not a directory?
            !is_dir($n)
                # filename matches pattern?
                ?fnmatch("*.sh",$n)
                    # count lines that are neither empty nor begin with a "#"
                    ?preg_match_all("/^\s*[^#]/m",join(file($n)))
                    # else 0
                    :0
                # is a directory: recurse
                :f($n)
        ;
    return$s;
}
echo f(".");

```

---

I could save two more bytes with `fnmatch()*preg_match_all()` instead of `fnmatch()?preg_match_all():0`; and then another one with `is_dir()?B:A` instead of `!is_dir()?A:B`; but that could make it insanely slow.
> 0 votes

# Answer
# Zsh, 57 bytes

```
for f (**/*.sh(D))a+=(${${(f)"$(<$f)"//[ 	]}%%#*})
<<<$#a

```

Try it online!

Almost beat bash+coreutils with native zsh constructs.

```
for f (**/*.sh(D))                    # the (D) flag enables globdots
   a+=(${${(f)"$(<$f)"//[   ]}%%#*})
 #       ${(f)"$(<$f)"       }        # read in file, split on newlines
 #       ${           //[   ]}        # remove all spaces and tabs
 #     ${                     %%#*}   # remove longest trailing #comment
 # a+=(                            )  # if append non-empty lines to array
<<<$#a                                # print array length

```

---

## Zsh `-oextendedglob -oglobstarshort -oglobdots`, 51 bytes

```
for f (**.sh)a+=(${${(f)"$(<$f)"}/[ 	]#\#*})
<<<$#a

```

Try it online!

globstarshort allows `**.sh`, globdots removes the `(D)` flag, and extendedglob makes `[ \t]#` work like the regex `[ \t]*`.

Sidenote: I think some answers here don't match hidden files. If they can be safely ignored, then `-oglobdots` or `(D)` is not needed.
> 0 votes

# Answer
# Nim, 114 bytes

```
import os,re
var c=0
for f in walkDirRec".":
 if f=~re".*\.sh$":
  for l in f.lines:c+=int l=~re"\s*[^#\s]"
echo c

```
> 0 votes

---
Tags: code-golf, counting, file-system, recursion
---


# Question
Title: Find a sequence in the binary digits of π
Given a binary sequence of finite length, find the starting position where this sequence first appears in the binary digits of π (after the decimal). You can assume that an answer exists for any input sequence.

The binary digits of π start with

```
11.001001000011111101101010100010001000010110100011...

```

and digits will be counted such that the first one after the decimal (the first 0 digit) has index 1.

### Examples

The requested function is related to OEIS A178707 but differs in that input sequences may have leading zeros. OEIS A178708 and OEIS A178709 provide good test cases for large sequences of 0's and 1's.

Some test cases below 10^9:

* 00100 → 1
* 11 → 11
* 00000000 → 189
* 11111111 → 645
* 0101000001101001 → 45038
* 00000000000000000000 → 726844
* 11111111111111111111 → 1962901
* 01000111010011110100110001000110 → 105394114
* 111111111111111111111111111111 → 207861698
* 100000000110000001100111100001 → 987654321

### Input/output formats

You can use any input and output formats: strings, lists, encoding the binary digits in integers, etc. Just use what is convenient for you.

### Limitations

Your program must be able to accept sequences of arbitrary (finite) length if run on an infinite-size computer, and terminate in finite time (assuming that a match always exists, which is what most people seem to believe in 2021 based on the pseudo-randomness of the digits of π).

### Scoring

This is code golf, so the shortest program (in bytes or bits/8) wins.

# Answer
# MATL, 28 bytes

```
`YPX$3-@X$W*kc4Y22@&ZaGXftn~

```

**Try it online!**

The code is very inefficient. Test cases beyond the second time out in the online compiler, but work offline. Here's an example with the fourth case (it takes about 25 seconds):

### Explanation

The code keeps trying increasingly long truncated binary expansions of the fractional part of , until the input is contained in the expansion.

```
`        % Do...while
  YP     %   Push pi as a double
  X$     %   Convert to symbolic. This recognizes pi's double representation
  3-     %   Subtract 3
  @      %   Push iteration index, n, starting at 1
  X$     %   Convert to symbolic. This avoids overflow in the next operation
  W      %   Exponential with base 2
  *      %   Multiply
  k      %   Floor(round down). This gives floor((pi-3)*2^n) as a symbolic variable
  c      %   Convert to char. This gives a sequence of decimal digits
  4Y2    %   Push '0123456789' (input alphabet for base conversion)
  2      %   Push 2 (output base for conversion)
  @      %   Push n (number of digits in the output)
  &Za    %   Base conversion. This gives the binary expansion with n digits
  G      %   Push input
  Xf     %   Index of ocurrences of the input. May be empty
  t      %   Duplicate
  n~     %   Number of elements, negate. This gives 1 if the input was not found
         % End (implicit). A new iteration is run if the top of the stack is 1
         % Display (implicit). The stack contains several empty arrays, and a
         % non-empty array with the solution. Empty arrays are not displayed

```
> 4 votes

# Answer
# JavaScript (Node.js),  ~~167~~  165 bytes

This is long and slow ... but it should work for any input in theory.

```
s=>{for(k=t=1n,l=q=2n,n=0n,r=6n,o='#';!~(i=o.search(s));)n=4n*q+t*~n<r?(o+=n,q+(q+=q)-r)/t-n<<(r+=r+t*n*2n)/r:(q*7n*k+2n-r*++l)/(r=(r-q-q)*l,q*=k++,t*=l++);return i}

```

Try it online!

This is derived from the C# entry on this Rosetta Code page.

The C# code is derived from Java, which is derived from Icon, which is derived from PicoLisp, which is derived from Haskell, which is based on this paper. :-p
> 12 votes

# Answer
# Wolfram Language (Mathematica), 49 bytes

```
0//.n_/;RealDigits[Pi,2,Tr[1^#],-n][[1]]!=#:>n+1&

```

Try it online!

thanks @Roman for -2bytes and @att for -3 bytes
> 4 votes

# Answer
# Charcoal, 114 bytes

```
≔²η≔±⁶ρ≔¹τ≔¹κ≔⁰ν≔³λＷ¬№ψθ¿‹⁺×⁴ηρ×⊕ντ«≔⁺ψνψ≔⊗⁻ρ×τνσ≔⁻÷⊗⁺×³ηρτ⊗νν≦⊗η≔σρ»«≔×⁺⊗ηρλσ≧×κη≧×λτ≔÷⁺⁺×⁷η²×ρλτν≧⁺²λ≦⊕κ≔σρ»Ｉ⌕ψθ

```

Try it online! Link is to verbose version of code. Uses the same source as @Arnauld's answer, so you can read up on the spigot algorithm there. Builds up the entire binary expansion as it goes and searches from the beginning on each loop but that turns out to be faster than just keeping the necessary number of bits.
> 3 votes

# Answer
# , ~~261~~ 259 bytes

```
function(x,p=''){while((a=regexpr(x,p<-paste0(c(p,(16*(4*s(F,1)-2*s(F,4)-s(F,5)-s(F,6))%%1)%/%2^(3:0)%%2),collapse='')))<0)F=F+1;a}
s=function(n,d){for(k in 0:n){p=1;for(i in seq(l=n-k))p=(16*p)%%d;F=(F+p/d)%%1;d=d+8};while((f=(T=T/16)/(d=d+8))>2e-16)F=F+f;F}

```

Try it online!

This is pretty long and can almost certainly be golfed better...

The function `s` calculates the value of one of the four summations of the Bailey–Borwein–Plouffe forumla.

We then use four calls to `s` to implement a spigot algorithm to sequentially calculate each hexadecimal digit of pi, and convert these into groups of 4 bits.

Finally, each iteration of the `while` loop adds these next 4 bits to the string `a`, and checks whether it now contains the search string `x`, halting and ouputting the index if this is true.
> 3 votes

---
Tags: code-golf, sequence, binary, pi
---