# Question
Title: The first, the last, and everything between
Given two integers, output the two integers, and then the range between them (excluding both).

The order of the range must be the same as the input.

### Examples:

```
 Input        Output
 0,  5   ->   [0, 5, 1, 2, 3, 4]
-3,  8   ->   [-3, 8, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7]
 4,  4   ->   [4, 4]
 4,  5   ->   [4, 5]
 8,  2   ->   [8, 2, 7, 6, 5, 4, 3]
-2, -7   ->   [-2, -7, -3, -4, -5, -6]

```

# Answer
# , ~~39~~ ~~33~~ 30 bytes

```
c(a<-scan(),setdiff(a:a[2],a))

```

Try it online!

Thanks for saved bytes to user2390246 and J.Doe.
> 16 votes

# Answer
# 05AB1E, 4 bytes

```
Ÿ¦¨«

```

Try it online!

**Explanation**

```
    Ÿ      # inclusive range [a ... b]
     ¦¨    # remove the first and last element
       «   # append to input

```
> 13 votes

# Answer
# Python 3, ~~52~~ ~~48~~ ~~47~~ ~~42~~ 41 bytes

```
lambda a,b:[a,b,*range(a,b,-(a>b)|1)[1:]]

```

Try it online!

---

Combined former implementations.
> 12 votes

# Answer
# Python 2 (Cython), ~~36~~ 35 bytes

```
lambda x:x+range(*x,-cmp(*x)|1)[1:]

```

*Thanks to @nwellnhof for golfing off 1 byte!*

Try it online!

---

# Python 2, 37 bytes

```
lambda x:x+range(*x+[-cmp(*x)|1])[1:]

```

*Thanks to @JonasAusevicius for the port to CPython!*

Try it online!
> 10 votes

# Answer
# Perl 6, ~~26~~ 22 bytes

```
{|@_,|[...^](@_).skip}

```

Try it online!

### Explanation

```
{                    }
 |@_,   # Slip args a,b into result
      [...^](@_)  # Reduce args a,b with ...^ operator, same as a...^b
                .skip  # Skip first element
     |  # Slip into result

```
> 8 votes

# Answer
# Python 2, 40 bytes

```
lambda x,y:[x,y]+range(x,y,-(y<x)|1)[1:]

```

Try it online!
> 7 votes

# Answer
# Japt, 8 bytes

```
cUr!õ kU

```

Try it here

```
             :Implicit input of array U
c            :Concatenate
 Ur          :  Reduce U by
   !õ        :   Inclusive range
      kU     :  Remove all elements in original U

```
> 6 votes

# Answer
# Python 2, ~~47~~ ~~41~~ 40 bytes

```
lambda a,b:[a,b]+range(a,b,a<b or-1)[1:]

```

Try it online!

Here's mine, now that a lot of other Python answers have been posted

<sub>-6 bytes, thanks to G B</sub>
> 6 votes

# Answer
# **Python 3, ~~64~~ ~~62~~ 51 bytes**

`lambda a,b:[a,b]+[*range(a+1,b)]+[*range(a-1,b,-1)]`

Try it online!

# **Python 2, ~~58~~ 45 bytes**

`lambda a,b:[a,b]+range(a+1,b)+range(a-1,b,-1)`

Try it online!
> 6 votes

# Answer
# Java 10, ~~109~~ ~~108~~ ~~104~~ ~~102~~ ~~93~~ 62 bytes

Using a space-delimited String:

```
b->a->{var r=a+" "+b;for(;a<b?++a<b:--a>b;)r+=" "+a;return r;}

```

Try it online.

Using a List:

```
b->a->{var r=new java.util.Stack();for(r.add(a),r.add(b);a<b?++a<b:--a>b;)r.add(a);return r;}

```

Try it online.

(`a<b?++a<b:--a>b` can be `++a<b||(a-=2)>b` for the same byte-count: Try it online for the String or Try it online for the List.)

---

**Old (~~109~~ ~~108~~ ~~104~~ ~~102~~ 101 bytes) answer using an array:**

```
a->b->{int s=a<b?1:-1,i=a!=b?(b-a)*s+1:2,r[]=new int[i];for(r[0]=a,r[1]=b;i>2;)r[--i]=b-=s;return r;}

```

-7 bytes thanks to *@nwellnhof*.

Try it online.

**Explanation:**

```
a->b->{                // Method with 2 int parameters & int-array return-type
  int s=               //  Step integer, starting at:
        a<b?1          //   1 if the first input is smaller than the second
        :-1;           //   -1 otherwise
      i=               //  Array-index integer, starting at:
        a!=b?          //   If the inputs aren't equal:
         (b-a)*s+1     //    Set it to the absolute difference + 1
        :              //   Else:
         2,            //    Set it to 2
      r[]=new int[i];  //  Result-array of that size
  for(r[0]=a,          //  Fill the first value with the first input
      r[1]=b;          //  And the second value with the second input
      i>2;)            //  Loop `i` downwards in the range [`i`,2):
    r[--i]=            //   Decrease `i` by 1 first with `--i`
                       //   Set the `i`'th array-value to:
           b-=s;       //    If the step integer is 1: decrease `b` by 1
                       //    If the step integer is -1: increase `b` by 1
                       //    And set the array-value to this modified `b`
  return r;}           //  Return the result-array

```
> 5 votes

# Answer
# Jelly, 4 bytes

```
,œ|r

```

Try it online!

### How it works

```
,œ|r  Main link. Left argument: a. Right argument: b

,     Pair; yield [a, b].
   r  Range; yield [a, ..., b].
 œ|   Perform multiset union.

```
> 5 votes

# Answer
# JavaScript (ES6), 51 bytes

Takes input as `(a)(b)`.

```
a=>g=(b,c=b)=>(b+=b<a|-(b>a))-a?[...g(b,c),b]:[a,c]

```

Try it online!

### Commented

```
a =>                // main function, taking a
  g = (             // g = recursive function
    b,              //     taking b
    c = b           // we save a backup of the original value of b into c
  ) =>              //
    (b +=           // add to b:
      b < a |       //   +1 if b is less than a
      -(b > a)      //   -1 if b is greater than a
    )               //   (or 0 if b = a)
    - a ?           // if the updated value of b is not equal to a:
      [             //   generate a new array:
        ...g(b, c), //     prepend all values generated by a recursive call
        b           //     append the current value of b
      ]             //
    :               // else:
      [a, c]        //   stop recursion and return the first 2 values: a and c

```
> 5 votes

# Answer
# APL (Dyalog Extended), 5 bytes

Anonymous infix function.

```
,,…~,

```

Try it online!

`,` the first and last (lit. the concatenation of the arguments)

`,` and (lit. concatenated to)

the range

`~` without

`,` the first and last (lit. the concatenation of the arguments)
> 5 votes

# Answer
# Octave, 45 bytes

```
@(a,b)[a b linspace(a,b,(t=abs(a-b))+1)(2:t)]

```

Try it online!
> 4 votes

# Answer
## Haskell, 34 bytes

```
a#b=a:b:[a+1..b-1]++[a-1,a-2..b+1]

```

Try it online!
> 4 votes

# Answer
# , 26 bytes

```
,,[|.@]^:(>{.)<.+1}.i.@|@-

```

Try it online!

## Explanation:

A dyadic verb (takes left and right argument)

```
                         -    subtracts the arguments
                       |@     and finds the absolute value
                    i.@       and makes a list 0..absolute difference
                 1}.          drops the fist element
                +             adds to the entire list
              <.              the smaller of the arguments
   |.@]                       reverses the list
       ^:                     only if
  [                           the left argument
         (>{.)                is greater than the first item of the list
 ,                            appends the list to
,                             the right argument appended to the left one

```
> 4 votes

# Answer
# , 13 bytes

```
,,<.+i.@-~-.=

```

Try it online!

```
     i.@-~       range [0 .. |difference|-1], reverse if the difference is positive
          -.=    remove the zero (either "=" is 0 or there’s nothing to remove)
  <.+            to each element add the smaller of the args
,,               prepend args

```
> 4 votes

# Answer
# Ruby, ~~33~~ 40 bytes

```
->a,b{[a,b]+[*a..b,*a.downto(b)][1..-2]}

```

Try it online!

Temporary fix, trying to find a better idea
> 3 votes

# Answer
## Batch, 107 bytes

```
@echo %1
@echo %2
@for %%s in (1 -1)do @for /l %%i in (%1,%%s,%2)do @if %1 neq %%i if %%i neq %2 echo %%i

```

Takes input as command-line arguments. Explanation:

```
@echo %1
@echo %2

```

Output the two integers.

```
@for %%s in (1 -1)do

```

Try both ascending and descending ranges.

```
@for /l %%i in (%1,%%s,%2)do

```

Loop over the inclusive range.

```
@if %1 neq %%i if %%i neq %2

```

Exclude the two integers.

```
echo %%i

```

Output the current value.
> 3 votes

# Answer
# Python 2, ~~52~~ ~~47~~ 41 bytes

```
lambda i,j:[i,j]+range(i,j,(i<j)*2-1)[1:]

```

Try it online!

-5 with thanks to @JoKing

-6 by slicing the first element from the range (idea stolen from and with credit to @TFeld)

Non-lambda version...

# Python 2, ~~51~~ ~~49~~ 47 bytes

```
i,j=input();print[i,j]+range(i,j,(i<j)*2-1)[1:]

```

Try it online!

-2 with thanks to @JoKing
> 3 votes

# Answer
# Pyth, 5 bytes

```
+QtrF

```

Input is a two-element list, `[input 1, input 2]`. Try it online here, or verify all the test cases at once here.

```
+QtrFQ   Implicit: Q=eval(input())
         Trailing Q inferred
   rFQ   Generate range [input 1 - input 2)
  t      Discard first element
+Q       Prepend Q

```
> 3 votes

# Answer
# Red, 75 bytes

```
func[a b][s: sign? d: b - a prin[a b]loop absolute d - s[prin[""a: a + s]]]

```

Try it online!
> 3 votes

# Answer
# Clean, 49 bytes

```
import StdEnv
@a b=init[a,b:tl[a,a+sign(b-a)..b]]

```

Try it online!
> 3 votes

# Answer
# APL (Dyalog Classic), 29 bytes

```
{⍺,⍵,(⌽⍣(⍺>⍵))(⍺⌊⍵)+¯1↓⍳|⍺-⍵}

```

Try it online!

A port of my `J` solution
> 3 votes

# Answer
# TI-BASIC, ~~35~~ 34 bytes

-1 byte from Misha Lavrov

```
Prompt A,B
Disp A,B
cos(π(A>B
For(I,A+Ans,B-Ans,Ans
Disp I
End

```
> 3 votes

# Answer
## PHP (102 bytes)

```
function t($a,$b){count($r=range($a,$b))>1?array_splice($r,1,0,array_pop($r)):$r=[$a,$b];print_r($r);}

```

Sandbox

Unfortunately (for golf) PHP has rather verbose function names, which contribute a lot to the length. But the basic idea is to create a range, then pop off the last element and stitch it back in at offset 1. For the `4,4` example I had to add `count($r=range($a,$b))>1?...:$r=[$a,$b];` which adds quite a bit, and unfortunately `array_splice()` is by reference which hit me for a few more bytes (`$r= and a ;`). All because of that "edge case", lol.

Well anyway enjoy!
> 3 votes

# Answer
# Clojure, 61 bytes

```
(fn[[a b]](def s(if(> a b)-1 1))(list* a b(range(+ a s)b s)))

```

An anonymous function that takes a 2-vector as input and returns a list.

Try it online!

## Explanation

```
(fn [[a b]] ; An anonymous function that accepts a 2-vector as input, and destructures it to a and b
  (def s (if (> a b) -1 1)) ; If a > b assigns -1 to s and assigns 1 to s otherwise. This determines the order of the elements of the output list.
  (list* a b ; Creates a list with a and b as the first two elements. The remaining elements will be appended from the following range:
    (range (+ a s) b s))) ; A range starting at a+s and ending at b with step s

```
> 3 votes

# Answer
# , 85 bytes

```
T[]f(T)(T a,T b){T[]v=[a,b];T c=2*(b>a)-1;for(T i=a+c;a!=b&&b!=i;i+=c)v~=i;return v;}

```

Try it online!

A port of @HatsuPointerKun's C++ answer into D.
> 3 votes

# Answer
# JavaScript, 73 bytes

Without recursion:

```
(s,e,m=s>e?-1:1)=>[s,e,...[...Array(m*(e-s||1)-1)].map((_,i)=>s+m*(i+1))]

```

Try it:

```
f=(s,e,m=s>e?-1:1)=>[s,e,...[...Array(m*(e-s||1)-1)].map((_,i)=>s+m*(i+1))]

console.log(JSON.stringify(f(0,5)));
console.log(JSON.stringify(f(-3,8)));
console.log(JSON.stringify(f(4,4)));
console.log(JSON.stringify(f(4,5)));
console.log(JSON.stringify(f(8,2)));
console.log(JSON.stringify(f(-2,-7)));
```
> 3 votes

# Answer
# Charcoal, 15 bytes

```
ＩＥ²ＮＩ…⊕θηＩ⮌…⊕ηθ

```

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

```
ＩＥ²Ｎ

```

Print the inputs on separate lines.

```
Ｉ…⊕θη

```

Print the ascending range, if any.

```
Ｉ⮌…⊕ηθ

```

Print the reverse ascending reverse range, if any.
> 2 votes

# Answer
# Dart, ~~85~~ 84 bytes

```
f(a,b)=>[a,b]+((a-b).abs()>1?List.generate((a-b).abs()-1,(i)=>(a>b?-i-1:i+1)+a):[]);

```

Try it online!

- -1 by going from `>=` to `>`
> 2 votes

# Answer
# QBASIC, ~~39~~ 53 bytes

```
INPUT a,b
?a
?b
FOR q=a+1TO b-1 STEP SGN(b-a)
?q
NEXT

```

Added the `STEP` parameter to account for `a>b`, and that uses the `SGN()` function to get a -1 or a +1 as increment. This however breaks the REPL because the `SGN()` function isn't implemented there...

Try it (the old answer) online!
> 2 votes

# Answer
# C (gcc), 65 bytes

```
f(a,b){for(printf("%d %d",a,b);a<b?++a<b:--a>b;)printf(" %d",a);}

```

Try it online!

Not very exciting. The loop increment is borrowed from an early version of Kevin Cruijssen's Java answer.
> 2 votes

# Answer
# Powershell, 41 bytes

```
param($a,$b)$a;$b;$a..$b|?{$_-notin$a,$b}

```

Less golfed test script:

```
$f = {

param($a,$b)
$a                # push $a to a pipe
$b                # push $b to a pipe
$a..$b|?{         # push to pipe all integers from $a to $b
    $_-notin$a,$b # ...except $a and $b itself
}

}

@(
    ,( 0,  5  ,   0, 5, 1, 2, 3, 4)
    ,(-3,  8  ,   -3, 8, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7)
    ,( 4,  4  ,   4, 4)
    ,( 4,  5  ,   4, 5)
    ,( 8,  2  ,   8, 2, 7, 6, 5, 4, 3)
    ,(-2, -7  ,   -2, -7, -3, -4, -5, -6)
) | % {
    $a,$b,$expected = $_
    $result = &$f $a $b
    "$("$result"-eq"$expected"): $result"
}

```

Output:

```
True: 0 5 1 2 3 4
True: -3 8 -2 -1 0 1 2 3 4 5 6 7
True: 4 4
True: 4 5
True: 8 2 7 6 5 4 3
True: -2 -7 -3 -4 -5 -6

```

Explanation:

The basic concept of Powershell is the pipe. Pipe is an array. All results that push into the pipe fall into the array. So we should just push the values into the pipe in the correct order.
> 2 votes

# Answer
# Java, 739, 555 bytes

```
 public static List<Integer> firstLastAndEverythingBetween(final int a, final int b) { if (a == b) { return addAB(a, b); } final List<Integer> result = addAB(a, b); int initial = getInitial(a, b); for (int n = 1; n < Math.abs(b - a); n++) { result.add(initial); if (b > a) { initial++; } else { initial--; } } return result; } private static int getInitial(int a, int b) { return (b > a) ? (a + 1) : (a - 1); } private static List<Integer> addAB(int a, int b) { final List<Integer> result = new ArrayList<>(); result.add(a); result.add(b); return result; }

```
> 2 votes

# Answer
# Python 3, ~~53~~ 48 bytes

-5 bytes thanks to @mypetlion.

```
lambda a,b:[a,b,*range(a+1-2*(a>b),b,1-2*(a>b))]

```

Try it online!
> 2 votes

# Answer
## C++, ~~143~~ 140 bytes

-3 bytes thanks to Zacharý

```
#define V std::vector<int
#include<vector>
V>f(int a,int b){V>v{a,b};int c=2*(b>a)-1;for(int i=a+c;a!=b&&b!=i;i+=c)v.push_back(i);return v;}

```

How to use :

In the main function :

```
std::cout << f(0, 5) << '\n';
std::cout << f(-3, 8) << '\n';
std::cout << f(4, 4) << '\n';
std::cout << f(4, 5) << '\n';
std::cout << f(8, 2) << '\n';
std::cout << f(-2, -7) << '\n';

```

also add :

```
template<typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
    os << "[ ";
    for (const auto& a : v) {
        os << a << ' ';
    }
    return os << ']';
}

```
> 2 votes

# Answer
# C (clang), 60 bytes

```
f(a,b,c)int*c;{for(*c++=a,*c++=b;(a<b?++a<b:--a>b);*c++=a);}

```

Try it online!
> 2 votes

# Answer
# APL(NARS), 14 chars, 28 bytes

```
{⍺⍵,¯1↓1↓⍺..⍵}

```

test

```
  f←{⍺⍵,¯1↓1↓⍺..⍵}
  ¯3 f 8
¯3 8 ¯2 ¯1 0 1 2 3 4 5 6 7
  0 f 5
0 5 1 2 3 4

```
> 2 votes

# Answer
# Haskell, ~~18~~ 34 bytes as function, ~~46~~ 52 as an IO action, ~~56~~ 62 as program

```
x!y=x:y:[x+1..y-1]++[x-1,x-2..y+1]

```

or, as an IO action to take input, there are these options (all the same length):

```
main=(\x y->x:y:[x+1..y-1]++[x-1,x-2..y+1])<$>readLn<*>readLn
--
x!y=x:y:[x+1..y-1]++[x-1,x-2..y+1]
main=(!)<$>readLn<*>readLn
--
f x y=x:y:[x+1..y-1]++[x-1,x-2..y+1]
main=f<$>readLn<*>readLn

```

or, as an IO action taking input and printing the result:

```
main=((\x y->x:y:[x+1..y-1]++[x-1,x-2..y+1])<$>readLn<*>readLn)>>=print
--
x!y=x:y:[x+1..y-1]++[x- 1,x-2..y+1]
main=((!)<$>readLn<*>readLn)>>=print
--
f x y=x:y:[x+1..y-1]++[x-1,x-2..y+1]
main=(f<$>readLn<*>readLn)>>=print

```

The last one is also available on Try It Online! (You can try it online there)
Please remember that TIO requires the input be entered beforehand in the "Input" box.

De-golfed:

```
enumerate' x y = x : y : [x + 1 .. x - 1] ++ [x - 1 , x - 2 .. y + 1]
main = do x <- readLn
          y <- readLn
          print (enumerate' x y)

```

Note: `:` is an operator to prefix an element to a list.

Note: `a!b` will not work if `-XBangBatterns` is enabled.
Use `a#b` instead.

Note: `-XNegativeLiterals` will break this. Insert a space between `x-` and `1`.
This will parse as `x + (negate 1)` instead of `x $ (-1)`.
> 2 votes

# Answer
# C# (Visual C# Interactive Compiler), 86 bytes

```
x=>y=>{var l=new List<int>{x,y};for(int s=x>y?-1:1;x!=y&(x+=s)!=y;)l.Add(x);return l;}

```

Try it online!

-1 thanks @auhmaan!
> 2 votes

# Answer
## JavaScript, 75 bytes

```
(a,b,n=-~(a>b?a-b:b-a)-2)=>[a,b,...[...Array(n<2?0:n)].map(_=>a<b?++a:--a)]

```

Try it online!
> 2 votes

# Answer
# Husk, 5 bytes

```
+¹ht…

```

Try it online!

Thanks to Dominic Van Essen for the fix.
> 2 votes

# Answer
# C# .NET Core, ~~56~~ 441 bytes

Here is my corrected solution without predefined input variables and without string joining.

```
(a,b)=>n(a,b).c(k(a-b)>1?b>a?r(a+1,b-a-1):r(b+1,a-b-1).i():n());

```

Try it online!

```
n(a,b)               => returns new array with a and b in it
  c(                 => concat the following content
    k(a-b)>1         => when absolute value of a-b greater then one
      b>a            => when b bigger a
        r(a,b-a)     => range from a to b-a
        r(b,a-b).i() => else range from b to a-b reversed
      n()            => else empty array

```

I've created and used the following declarations. When I include those and the minimum code required to compile in the byte count I get 640 bytes.

```
public static class Extensions{
  public static IEnumerable<T> c<T>(this IEnumerable<T> a, IEnumerable<T> b) => a.Concat(b);
  public static IEnumerable<T> i<T>(this IEnumerable<T> a) => a.Reverse();
}

public static Func<int, int> k = Math.Abs;
public static Func<int, int, IEnumerable<int>> r = Enumerable.Range;
public static int[] n(params int[] a) => a;

```

---

```
using System.Linq;using System.Collections.Generic;using System;public static class E{public static IEnumerable<T> c<T>(this IEnumerable<T> a,IEnumerable<T> b)=>a.Concat(b);public static IEnumerable<T> i<T>(this IEnumerable<T> a)=>a.Reverse();}public class P{public static Func<int,int> k=Math.Abs;public static Func<int,int,IEnumerable<int>> r=Enumerable.Range;public static int[] n(params int[] a)=>a;public static void Main(string[] args){Console.WriteLine($"[ {string.Join(", ", f(int.Parse(args[0]), int.Parse(args[1])))} ]");}public static Func<int,int,IEnumerable<int>> f=(a,b)=>n(a,b).c(k(a-b)>1?b>a?r(a,b-a):r(b,a-b).i():n());}

```
> 1 votes

# Answer
# Tcl, 85 bytes

```
proc R a\ b {puts $a\n$b
if $a>$b {lassign $a\ $b b a}
while {[incr a]<$b} {puts $a}}

```

Try it online!
> 1 votes

# Answer
# JavaScript (ES6), 97 bytes

```
a=>b=>[a,b,...((c,d)=>c==d?[]:(s=(m=Math).min(a,b),Array(m.abs(a-b)-1).fill().map(n=>++s)))(a,b)]

```

Can probably be improved!!
> 1 votes

# Answer
# Python 3, 57 bytes

```
def m(a,b):s=(1,-1)[a>b];return[a,b]+list(range(a+s,b,s))

```

Try it online!
> 1 votes

# Answer
**JAVA 147 bytes**

```
f(int a, int b){System.out.print(a+""+b);if(a<b){for(int i=a+1; i<b;i++){System.out.print(i);}}else{for(int i=a-1;i>b;i--){System.out.print(i);}}}

```
> 1 votes

# Answer
# Racket, 68 bytes

```
(define(f a b)(let([s(if(> a b)-1 1)])(list* a b(range(+ a s)b s))))

```

Try it online!

The same as TheGreatGeek's `Clojure` solution
> 1 votes

# Answer
# perl -M5.010 -alE, 58 bytes

```
@_=($F[0]..$F[1],reverse$F[1]..$F[0]);say"$_ @_[1..$#_-1]"

```

This reads two integers (on a single line, separated by whitespace) from `STDIN` and writes the result to `STDOUT`.
> 1 votes

# Answer
# Bash, 62 bytes

```
a=($(seq $1 $2|tr $'\n' ' '))
echo $@ ${a[@]:1:((${#a[@]}-2))}

```

## explanation

`seq` does we want but produces lines, `tr` turns the lines into space-delimited output, the outer parens make that into an array. `$@` is the original input, and the rest of it slices the 0-indexed array from 1 and takes the next "array len - 2" chars.

Try it online!

(NOTE: not all test cases work on TIO for reasons i don't understand, but they do work on my local machine)
> 1 votes

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

```
a=>b=>new[]{a,b}.Concat(b>a?Enumerable.Range(a+1,b+~a):Enumerable.Range(b+1,a!=b?a+~b:0).Reverse())

```

Try it online!

First (and probably last) time golfing in C#.
> 1 votes

# Answer
# F# (Mono), 68 bytes

```
let f x y=
 let s=if x<y then 1 else-1
 Seq.append[x;y][x+s..s..y-s]

```

Try it online!
> 1 votes

# Answer
# Vyxal 1.0.1, 9 bytes

```
=[‿|₌‿⁂JU

```

Don't even think about trying it Online.

## Explained

The output for this challenge is the two input numbers paired together joined with the range between those two numbers. However, there can't be any duplicates in the joined list, so it needs to be uniquified by order of appearance. But we also need to make sure that the two numbers aren't the same: otherwise, a singleton will be returned.
> 1 votes

# Answer
# F#, 67 bytes

```
let f x y=if(y-x<0)then[x;y]@List.rev[y+1..x-1]else[x;y]@[x+1..y-1]

```

Try it online!

Appends a list containing x and y and a list iterating from x+1 to y-1 (if positive) or a list in reverse iteration order from y+1 to x-1 (if negative)
> 1 votes

# Answer
# Perl 5 `-pl`, 46 bytes

```
/ /;$_.=join$",'',$`+1..$'-1,reverse$'+1..$`-1

```

Try it online!
> 1 votes

# Answer
# Arturo, ~~30~~ ~~28~~ 27 bytes

```
$[x,y][p:@[x,y]p++--x..y p]

```

Try it

```
$[x,y][               ; a function taking arguments x and y
    p: @[x,y]         ; assign the list [x,y] to p
    p ++              ; append something to p
    --x..y p          ; the range x to y without p
]                     ; end function, implicit return

```
> 1 votes

# Answer
# Zsh\*, 33 bytes

```
A=({$1..$2});<<<$@\ ;<<<${A:1:-1}

```

Try it online!

(\*) Using `set -o err_return`
> 1 votes

# Answer
# Scala, ~~87~~ 75 bytes

Golfed version. Try it online!

```
(a,b)=>a::b::(if(a>b)(a to b by-1).drop(1)else(a to b by 1).drop(1)).toList

```

Ungolfed version.

```
object Main {
  def main(args: Array[String]): Unit = {
    val f = (a: Int, b: Int) => {
      a :: b :: (if (a > b) (a to b by -1).drop(1) else (a to b by 1).drop(1)).toList
    }
    println(f(0, 5)) // List(0, 5, 1, 2, 3, 4)
    println(f(-3, 8)) // List(-3, 8, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7)
    println(f(4, 4)) // List(4, 4)
    println(f(4, 5)) // List(4, 5)
    println(f(8, 2)) // List(8, 2, 7, 6, 5, 4, 3)
    println(f(-2, -7)) // List(-2, -7, -3, -4, -5, -6)
  }
}

```
> 1 votes

# Answer
# Thunno 2, 5 bytes

```
ẸIḣṫḥ

```

Attempt This Online!

#### Explanation

```
ẸIḣṫḥ  # Implicit input   ->  [8, 2]
Ẹ      # Dump onto stack  ->  8, 2
 I     # Inclusive range  ->  [8,7,6,5,4,3,2]
  ḣ    # Remove head      ->  [7,6,5,4,3,2]
   ṫ   # Remove tail      ->  [7,6,5,4,3]
    ḥ  # Concatenate      ->  [8,2,7,6,5,4,3]
       # Implicit output

```
> 1 votes

# Answer
# Vyxal, 4 bytes

```
ṡÞẇJ

```

Try it Online! (inputs are swapped)

```
ṡ    # Inclusive range
 Þẇ  # Push [first, last] and rest
   J # Concatenate

```
> 1 votes

# Answer
**JavaScript (ES6), 76 bytes**

`(a,b,c=[a,b])=>{c[c.length]=a<b?++a:--a;return a==b?(c.pop()+1&&c):f(a,b,c)}`

invocation should not pass the third argument: `f(-9,9)`

Try it online!

im still thinking...
> 0 votes

# Answer
# Ly, 22 bytes

```
nnsaRl=[pr0]pu' oru' o

```

Try it online!

The tricky bits here are that the range function in `Ly` only works if the start/end are sorted. So the code has to conditionally flip the sequence of numbers before printing them.

```
nna                    - read in the start/end, stash the 2nd number
   aR                  - sort and generate the inclusive range
     l=                - does the 2nd number match the max of the range?
       [p 0]p          - "then" clause
         r             - reverse the stack
             u' o      - output the starting number and a space
                 r     - reverse the stack
                  u' o - output the ending number
                       - the sequence left on the stack prints automatically

```
> 0 votes

---
Tags: code-golf
---


title: The Missing Number Revised

text:
# Question
Title: The Missing Number Revised
**Background:**

I originally posted this question last night, and received backlash on its vagueness. I have since consulted many personnel concerning not only the wording of the problem, but also its complexity (which is not O(1)). This programming problem is an evil spin on an Amazon interview question.

**Question:**

Given a String of randomly concatenated integers \[0, 250), 0 to 250 exclusive, there is ONE number missing in the sequence. Your job is to write a program that will calculate this missing number. There are no other missing numbers in the sequence besides the one, and that is what makes this problem so difficult, and possibly computationally hard.

Doing this problem by hand on smaller Strings, such as examples 1 and 2 below are obviously very easy. Conversely, computing a missing number on incredibly large datasets involving three-digit or four-digit numbers would be incredibly difficult. The idea behind this problem is to construct a program that will do this process FOR you.

**Important Information:**

One thing that appeared as rather confusing when I posted this problem last night was: what exactly a missing number is defined as. A missing number is the number INSIDE of the range specified above; NOT necessarily the digit. In example 3, you will see that the missing number is 9, even though it appears in the sequence. There are 3 places the DIGIT 9 will appear in a series of \[0, 30): “9”, “19”, and “29”. Your objective is to differentiate between these, and discover that 9 is the missing NUMBER (inside of example 3). In other words, the tricky part lies in finding out which sequences of digits are complete and which belong to other numbers.

**Input:**

The input is a String S, containing integers from 0 to 249 inclusive, or 0 to 250 exclusive (in other words, \[0, 250)). These integers, as stated above, are scrambled up to create a random sequence. There are NO delimiters (“42, 31, 23, 44”), or padding 0’s (003076244029002); the problems are exactly as described in the examples. **It is guaranteed that there is only 1 solution in the actual problems. Multiple solutions are not permitted for these.**

**Winning Criteria:**

Whoever has the fastest, and lowest memory usage will be the winner. In the miraculous event that a time ties, lower memory will be used for the time breaker. Please list Big O if you can!

**Examples:**

*Examples 1 and 2 have a range of \[0, 10)*

*Examples 3 and 4 have a range of \[0, 30)*

(Examples 1-4 are just for demonstration. Your program needn't to handle them.)

*Examples 5 has a range of \[0, 250)*

```
1. 420137659
- Missing number => 8

2. 843216075
- Missing number => 9

3. 2112282526022911192312416102017731561427221884513
- Missing number => 9

4. 229272120623131992528240518810426223161211471711
- Missing number => 15

5. 11395591741893085201244471432361149120556162127165124233106210135320813701207315110246262072142253419410247129611737243218190203156364518617019864222241772384813041175126193134141008211877147192451101968789181153241861671712710899168232150138131195104411520078178584419739178522066640145139388863199146248518022492149187962968112157173132551631441367921221229161208324623423922615218321511111211121975723721911614865611197515810239015418422813742128176166949324015823124214033541416719143625021276351260183210916421672722015510117218224913320919223553222021036912321791591225112512304920418584216981883128105227213107223142169741601798025
- Missing number => 71

Test Data:

Problem 1: 6966410819610521530291368349682309217598570592011872022482018312220241246911298913317419721920718217313718080857232177134232481551020010112519172652031631113791105122116319458153244261582135510090235116139611641267691141679612215222660112127421321901862041827745106522437208362062271684640438174315738135641171699510421015199128239881442242382361212317163149232839233823418915447142162771412092492141987521710917122354156131466216515061812273140130240170972181176179166531781851152178225242192445147229991613515911122223419187862169312013124150672371432051192510724356172282471951381601241518410318414211212870941111833193145123245188102

Problem 2: 14883423514241100511108716621733193121019716422221117630156992324819917158961372915140456921857371883175910701891021877194529067191198226669314940125152431532281961078111412624224113912011621641182322612016512820395482371382385363922471472312072131791925510478122073722091352412491272395020016194195116236186596116374117841971602259812110612913254255615723013185162206245183244806417777130181492211412431591541398312414414582421741482461036761192272120204114346205712198918190242184229286518011471231585109384415021021415522313136146178233133168222201785172212108182276835832151134861116216716910511560240392170208215112173234136317520219

Problem 3: 1342319526198176611201701741948297621621214122224383105148103846820718319098731271611601912137231471099223812820157162671720663139410066179891663131117186249133125172622813593129302325881203242806043154161082051916986441859042111711241041590221248711516546521992257224020174102234138991752117924457143653945184113781031116471120421331506424717816813220023315511422019520918114070163152106248236222396919620277541101222101232171732231122301511263822375920856142187182152451585137352921848164219492411071228936130762461191564196185114910118922611881888513917712153146227193235347537229322521516718014542248813617191531972142714505519240144

Problem 4: 2492402092341949619347401841041875198202182031161577311941257285491521667219229672211881621592451432318618560812361201172382071222352271769922013259915817462189101108056130187233141312197127179205981692121101632221732337196969131822110021512524417548627103506114978204123128181211814236346515430399015513513311152157420112189119277138882021676618323919018013646200114160165350631262167910238144334214230146151171192261653158161213431911401452461159313720613195248191505228186244583455139542924222112226148941682087115610915344641782142472102436810828123731134321131241772242411722251997612923295223701069721187182171471055710784170217851

```

# Answer
> 10 votes
# Clingo, ≈ 0.03 seconds

This is too fast to be accurately measured—you’ll need to allow larger input cases rather than artificially stopping at 250.

```
% cat(I) means digits I and I+1 are part of the same number.
{cat(I)} :- digit(I, D), digit(I+1, E).

% prefix(I, X) means some digits ending at I are part of the same
% number prefix X.
prefix(I, D) :- digit(I, D), not cat(I-1), D < n.
prefix(I, 10*X+D) :- prefix(I-1, X), digit(I, D), cat(I-1), X > 0, 10*X+D < n.

% Every digit is part of some prefix.
:- digit(I, D), {prefix(I, X)} = 0.

% If also not cat(I), then this counts as an appearance of the number
% X.
appears(I, X) :- prefix(I, X), not cat(I).

% No number appears more than once.
:- X=0..n-1, {appears(I, X)} > 1.

% missing(X) means X does not appear.
missing(X) :- X=0..n-1, {appears(I, X)} = 0.

% Exactly one number is missing.
:- {missing(X)} != 1.

#show missing/1.

```

### Example input

Input is a list of (*k*, *k*th digit) pairs. Here is problem 1:

```
#const n = 250.
digit(0,6;1,9;2,6;3,6;4,4;5,1;6,0;7,8;8,1;9,9;10,6;11,1;12,0;13,5;14,2;15,1;16,5;17,3;18,0;19,2;20,9;21,1;22,3;23,6;24,8;25,3;26,4;27,9;28,6;29,8;30,2;31,3;32,0;33,9;34,2;35,1;36,7;37,5;38,9;39,8;40,5;41,7;42,0;43,5;44,9;45,2;46,0;47,1;48,1;49,8;50,7;51,2;52,0;53,2;54,2;55,4;56,8;57,2;58,0;59,1;60,8;61,3;62,1;63,2;64,2;65,2;66,0;67,2;68,4;69,1;70,2;71,4;72,6;73,9;74,1;75,1;76,2;77,9;78,8;79,9;80,1;81,3;82,3;83,1;84,7;85,4;86,1;87,9;88,7;89,2;90,1;91,9;92,2;93,0;94,7;95,1;96,8;97,2;98,1;99,7;100,3;101,1;102,3;103,7;104,1;105,8;106,0;107,8;108,0;109,8;110,5;111,7;112,2;113,3;114,2;115,1;116,7;117,7;118,1;119,3;120,4;121,2;122,3;123,2;124,4;125,8;126,1;127,5;128,5;129,1;130,0;131,2;132,0;133,0;134,1;135,0;136,1;137,1;138,2;139,5;140,1;141,9;142,1;143,7;144,2;145,6;146,5;147,2;148,0;149,3;150,1;151,6;152,3;153,1;154,1;155,1;156,3;157,7;158,9;159,1;160,1;161,0;162,5;163,1;164,2;165,2;166,1;167,1;168,6;169,3;170,1;171,9;172,4;173,5;174,8;175,1;176,5;177,3;178,2;179,4;180,4;181,2;182,6;183,1;184,5;185,8;186,2;187,1;188,3;189,5;190,5;191,1;192,0;193,0;194,9;195,0;196,2;197,3;198,5;199,1;200,1;201,6;202,1;203,3;204,9;205,6;206,1;207,1;208,6;209,4;210,1;211,2;212,6;213,7;214,6;215,9;216,1;217,1;218,4;219,1;220,6;221,7;222,9;223,6;224,1;225,2;226,2;227,1;228,5;229,2;230,2;231,2;232,6;233,6;234,0;235,1;236,1;237,2;238,1;239,2;240,7;241,4;242,2;243,1;244,3;245,2;246,1;247,9;248,0;249,1;250,8;251,6;252,2;253,0;254,4;255,1;256,8;257,2;258,7;259,7;260,4;261,5;262,1;263,0;264,6;265,5;266,2;267,2;268,4;269,3;270,7;271,2;272,0;273,8;274,3;275,6;276,2;277,0;278,6;279,2;280,2;281,7;282,1;283,6;284,8;285,4;286,6;287,4;288,0;289,4;290,3;291,8;292,1;293,7;294,4;295,3;296,1;297,5;298,7;299,3;300,8;301,1;302,3;303,5;304,6;305,4;306,1;307,1;308,7;309,1;310,6;311,9;312,9;313,5;314,1;315,0;316,4;317,2;318,1;319,0;320,1;321,5;322,1;323,9;324,9;325,1;326,2;327,8;328,2;329,3;330,9;331,8;332,8;333,1;334,4;335,4;336,2;337,2;338,4;339,2;340,3;341,8;342,2;343,3;344,6;345,1;346,2;347,1;348,2;349,3;350,1;351,7;352,1;353,6;354,3;355,1;356,4;357,9;358,2;359,3;360,2;361,8;362,3;363,9;364,2;365,3;366,3;367,8;368,2;369,3;370,4;371,1;372,8;373,9;374,1;375,5;376,4;377,4;378,7;379,1;380,4;381,2;382,1;383,6;384,2;385,7;386,7;387,1;388,4;389,1;390,2;391,0;392,9;393,2;394,4;395,9;396,2;397,1;398,4;399,1;400,9;401,8;402,7;403,5;404,2;405,1;406,7;407,1;408,0;409,9;410,1;411,7;412,1;413,2;414,2;415,3;416,5;417,4;418,1;419,5;420,6;421,1;422,3;423,1;424,4;425,6;426,6;427,2;428,1;429,6;430,5;431,1;432,5;433,0;434,6;435,1;436,8;437,1;438,2;439,2;440,7;441,3;442,1;443,4;444,0;445,1;446,3;447,0;448,2;449,4;450,0;451,1;452,7;453,0;454,9;455,7;456,2;457,1;458,8;459,1;460,1;461,7;462,6;463,1;464,7;465,9;466,1;467,6;468,6;469,5;470,3;471,1;472,7;473,8;474,1;475,8;476,5;477,1;478,1;479,5;480,2;481,1;482,7;483,8;484,2;485,2;486,5;487,2;488,4;489,2;490,1;491,9;492,2;493,4;494,4;495,5;496,1;497,4;498,7;499,2;500,2;501,9;502,9;503,9;504,1;505,6;506,1;507,3;508,5;509,1;510,5;511,9;512,1;513,1;514,1;515,2;516,2;517,2;518,2;519,3;520,4;521,1;522,9;523,1;524,8;525,7;526,8;527,6;528,2;529,1;530,6;531,9;532,3;533,1;534,2;535,0;536,1;537,3;538,1;539,2;540,4;541,1;542,5;543,0;544,6;545,7;546,2;547,3;548,7;549,1;550,4;551,3;552,2;553,0;554,5;555,1;556,1;557,9;558,2;559,5;560,1;561,0;562,7;563,2;564,4;565,3;566,5;567,6;568,1;569,7;570,2;571,2;572,8;573,2;574,4;575,7;576,1;577,9;578,5;579,1;580,3;581,8;582,1;583,6;584,0;585,1;586,2;587,4;588,1;589,5;590,1;591,8;592,4;593,1;594,0;595,3;596,1;597,8;598,4;599,1;600,4;601,2;602,1;603,1;604,2;605,1;606,2;607,8;608,7;609,0;610,9;611,4;612,1;613,1;614,1;615,1;616,8;617,3;618,3;619,1;620,9;621,3;622,1;623,4;624,5;625,1;626,2;627,3;628,2;629,4;630,5;631,1;632,8;633,8;634,1;635,0;636,2).

```

### Example output

```
$ clingo missing.lp problem1.lp
clingo version 5.2.2
Reading from missing.lp ...
Solving...
Answer: 1
missing(148)
SATISFIABLE

Models       : 1+
Calls        : 1
Time         : 0.032s (Solving: 0.00s 1st Model: 0.00s Unsat: 0.00s)
CPU Time     : 0.032s

```

# Answer
> 9 votes
# C++, 5000 random test cases in 6.1 seconds

This is practically fast, but there may exist some testcases that make it slow. Complexity unknown.

If there are multiple solutions, it will print them all. Example.

**Explanation:**

1. Count the occurrences of digits.
2. List all possible answers.
3. Check if a candidate is a valid answer:

3-1. Try to split the string(s) by numbers which only occur once and mark it as identified, except the candidate.
For example, `2112282526022911192312416102017731561427221884513` has only one `14`, so it can be split into `211228252602291119231241610201773156` and `27221884513`.

3-2. If any split string has length 1, mark it as identified.
If any contradiction is made (identified more than once), the candidate is not valid.
If we cannot find the candidate in the string, the candidate is valid.

3-3. If any split is made, repeat step 3-1. Otherwise, do a brute force search to check if the candidate is valid.

```
#include <cmath>
#include <bitset>
#include <string>
#include <vector>
#include <cstring>
#include <iostream>
#include <algorithm>

const int VAL_MAX = 250;
const int LOG_MAX = log10(VAL_MAX - 1) + 1;
using bools = std::bitset<VAL_MAX>;

std::pair<size_t, size_t> count(const std::string& str, const std::string& target)
{
    size_t ans = 0, offset = 0, pos = std::string::npos;
    for (; (offset = str.find(target, offset)) != std::string::npos; ans++, pos = offset++);
    return std::make_pair(ans, pos);
}

bool dfs(size_t a, size_t b, const std::vector<std::string>& str, bools& cnt, int t)
{ // input: string id, string position, strings, identified, candidate
    if (b == str[a].size()) a++, b = 0;
    if (a == str.size()) return true;   // if no contradiction on all strings, the candidate is valid

    int p = 0;
    for (int i = 0; i < LOG_MAX; i++) { // assume str[a][b...b+i] is a number
        if (str[a].size() == b) break;
        p = p * 10 + (str[a][b++] ^ '0');
        if (p < VAL_MAX && !cnt[p] && p != t) { //if no contradiction
            cnt[p] = true;
            if (dfs(a, b, str, cnt, t)) return true; // recursively check
            cnt[p] = false;
        }
    }
    return false;
}

struct ocr {
    int l, r, G;
    bool operator<(const ocr& i) const { return l > i.l; }
};

int cal(std::vector<std::string> str, bools cnt, int t)
{ // input: a list of strings, whether a number have identified, candidate
  // try to find numbers that only occur once in those strings
    int N = str.size();
    std::vector<ocr> pos;

    for (int i = 0; i < VAL_MAX; i++) {
        if (cnt[i]) continue;             // try every number which haven't identified
        int flag = 0;
        std::string target = std::to_string(i);
        ocr now;
        for (int j = 0; j < N; j++) {     // count occurences
            auto c = count(str[j], target);
            if ((flag += c.first) > 1) break;
            if (c.first) now = {c.second, c.second + target.size(), j};
        }
        if (!flag && t == i) return true; // if cannot find the candidate, then it is valid
        if (i != t && flag == 1) pos.push_back(now), cnt[i] = true;
        // if only occur once, then its position is fixed, mark as identified
    }
    if (!pos.size()) { // if no number is identified, do a brute force search
        std::sort(str.begin(), str.end(), [](const std::string& a, const std::string& b){return a.size() < b.size();});
        return dfs(0, 0, str, cnt, t);
    }

    std::sort(pos.begin(), pos.end());
    std::vector<std::string> lst;
    for (auto& i : pos) {      // split strings by identified numbers
        if ((size_t)i.r > str[i.G].size()) return false;
        std::string tmp = str[i.G].substr(i.r);
        if (tmp.size() == 1) { // if split string has length 1, it is identified
            if (cnt[tmp[0] ^ '0']) return false; // contradiction if it is identified before
            cnt[tmp[0] ^ '0'] = true;
        }
        else if (tmp.size()) lst.push_back(std::move(tmp));
        str[i.G].resize(i.l);
    }
    for (auto& i : str) { // push the remaining strings; same as above
        if (i.size() == 1) {
            if (cnt[i[0] ^ '0']) return false;
            cnt[i[0] ^ '0'] = true;
        }
        else if (i.size()) lst.push_back(std::move(i));
    }
    return cal(lst, cnt, t); // continue the split step with new set of strings
}

int main()
{
    std::string str;
    std::vector<ocr> pos;
    std::vector<int> prob;
    std::cin >> str;

    int p[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    for (int i = 0; i < VAL_MAX; i++)
        for (char j : std::to_string(i)) p[j ^ '0']++;
    for (char i : str) p[i ^ '0']--; // count digit occurrences
    {
        std::string tmp;
        for (int i = 0; i < 10; i++)
            while (p[i]--) tmp.push_back(i ^ '0');
        do {           // list all possible candidates (at most 4)
            int c = std::stoi(tmp);
            if (c < VAL_MAX && tmp[0] != '0') prob.push_back(c);
        } while (std::next_permutation(tmp.begin(), tmp.end()));
    }
    if (prob.size() == 1) { std::cout << prob[0] << '\n'; return 0; }
                       // if only one candidate, output it
    for (int i : prob) // ... or check if each candidate is valid
        if (cal({str}, bools(), i)) std::cout << i << '\n';
}

```

Try it online!

# Answer
> 6 votes
# Clean, ~0.3s

Fixed a huge bug in the algorithm, need to re-optimize it now.

```
module main
import StdEnv
import StdLib
import System.CommandLine

maxNum = 250
sample = "11395591741893085201244471432361149120556162127165124233106210135320813701207315110246262072142253419410247129611737243218190203156364518617019864222241772384813041175126193134141008211877147192451101968789181153241861671712710899168232150138131195104411520078178584419739178522066640145139388863199146248518022492149187962968112157173132551631441367921221229161208324623423922615218321511111211121975723721911614865611197515810239015418422813742128176166949324015823124214033541416719143625021276351260183210916421672722015510117218224913320919223553222021036912321791591225112512304920418584216981883128105227213107223142169741601798025"
case1 = "6966410819610521530291368349682309217598570592011872022482018312220241246911298913317419721920718217313718080857232177134232481551020010112519172652031631113791105122116319458153244261582135510090235116139611641267691141679612215222660112127421321901862041827745106522437208362062271684640438174315738135641171699510421015199128239881442242382361212317163149232839233823418915447142162771412092492141987521710917122354156131466216515061812273140130240170972181176179166531781851152178225242192445147229991613515911122223419187862169312013124150672371432051192510724356172282471951381601241518410318414211212870941111833193145123245188102"
case2 = "14883423514241100511108716621733193121019716422221117630156992324819917158961372915140456921857371883175910701891021877194529067191198226669314940125152431532281961078111412624224113912011621641182322612016512820395482371382385363922471472312072131791925510478122073722091352412491272395020016194195116236186596116374117841971602259812110612913254255615723013185162206245183244806417777130181492211412431591541398312414414582421741482461036761192272120204114346205712198918190242184229286518011471231585109384415021021415522313136146178233133168222201785172212108182276835832151134861116216716910511560240392170208215112173234136317520219"
case3 = "1342319526198176611201701741948297621621214122224383105148103846820718319098731271611601912137231471099223812820157162671720663139410066179891663131117186249133125172622813593129302325881203242806043154161082051916986441859042111711241041590221248711516546521992257224020174102234138991752117924457143653945184113781031116471120421331506424717816813220023315511422019520918114070163152106248236222396919620277541101222101232171732231122301511263822375920856142187182152451585137352921848164219492411071228936130762461191564196185114910118922611881888513917712153146227193235347537229322521516718014542248813617191531972142714505519240144"
case4 = "2492402092341949619347401841041875198202182031161577311941257285491521667219229672211881621592451432318618560812361201172382071222352271769922013259915817462189101108056130187233141312197127179205981692121101632221732337196969131822110021512524417548627103506114978204123128181211814236346515430399015513513311152157420112189119277138882021676618323919018013646200114160165350631262167910238144334214230146151171192261653158161213431911401452461159313720613195248191505228186244583455139542924222112226148941682087115610915344641782142472102436810828123731134321131241772242411722251997612923295223701069721187182171471055710784170217851"

failing = "0102030405060708090100101102103104105106107108109110120130140150160170180190200201202203204205206207208209210220230240249248247246245244243242241239238237236235234233232229228227226225224223222221219218217216215214213212211199198197196195194193192191189188187186185184183182181179178177176175174173172171169168167166165164163162161159158157156155154153152151149148147146145144143142141139138137136135134133132131129128127126125124123122121119118117116115114113112111999897969594939291898887868584838281797877767574737271696867666564636261595857565554535251494847464544434241393837363534333231292827262524232221191817161514131211987654321"

dupes = "19050151158951391658227781234527110196235731198137214733126868520474181772192213718517314542182652441211742304719519143231236593134207203121171237201705111617211824810013324511511436253946122155201534113626129692410611318356178791080921122151321949681166200188841675156120546124912883216212189712281541382202411041372421642917614416870223753814121124318415710310515010682172099012716167102179894920613516297239186222232225635312262134019719915382229399107111802082341491811011604815220291125247641482401691871755205639495788414314011714616366130175601931092467744819271230159131158714761192105218019822421812423322919341426216523821428232"

:: Position :== [Int]
:: Positions :== [Position]
:: Digit :== (Char, Int)
:: Digits :== [Digit]
:: Number :== ([Char], Positions)
:: Numbers :== [Number]
:: Complete :== (Numbers, [Digits])

numbers :: [[Char]]
numbers = [fromString (toString n) \\ n <- [0..(maxNum-1)]]

candidates :: [Char] -> [[Char]]
candidates chars
    = moreCandidates chars []
where
    moreCandidates :: [Char] [[Char]] -> [[Char]]
    moreCandidates [] nums
        = removeDup (filter (\num = isMember num numbers) nums)
    moreCandidates chars []
        = flatten [moreCandidates (removeAt i chars) [[c]] \\ c <- chars & i <- [0..]]
    moreCandidates chars nums
        = flatten [flatten [moreCandidates (removeAt i chars) [ [c : num] \\ num <- nums ]] \\  c <- chars & i <- [0..]]

singletonSieve :: Complete -> Complete
singletonSieve (list, sequence)
    | (list_, sequence_) == (list, sequence)
        = reverseSieve (list, sequence)
    = (list_, sequence_)
where
    singles :: Numbers
    singles
        = filter (\(_, i) = length i == 1) list
    list_ :: Numbers
    list_
        = [(a, filter (\n = not (isAnyMember n (flatten [flatten b_ \\ (a_, b_) <- singles | a_ <> a]))) b) \\ (a, b) <- list]
    sequence_ :: [Digits]
    sequence_
        = foldr splitSequence sequence (flatten (snd (unzip singles)))

reverseSieve :: Complete -> Complete
reverseSieve (list, sequence)
    # sequence
        = foldr splitSequence sequence (flatten (snd (unzip singles)))
    # list
        = [(a, filter (\n = not (isAnyMember n (flatten [flatten b_ \\ (a_, b_) <- singles | a_ <> a]))) b) \\ (a, b) <- list]
    # list
        = [(a, filter (\n = or [any (isPrefixOf n) (tails subSeq) \\ subSeq <- map (snd o unzip) sequence]) b) \\ (a, b) <- list]
    = (list, sequence)
where
    singles :: Numbers
    singles
        = [(a, i) \\ (a, b) <- list, i <- [[subSeq \\ subSeq <- map (snd o unzip) sequence | isMember subSeq b]] | length i == 1]

splitSequence :: Position [Digits] -> [Digits]
splitSequence split sequence
    = flatten [if(isEmpty b) [a] [a, drop (length split) b] \\ (a, b) <- [span (\(_, i) = not (isMember i split)) subSeq \\ subSeq <- sequence] | [] < max a b]

indexSubSeq :: [Char] Digits -> Positions
indexSubSeq _ []
    = []
indexSubSeq a b
    # remainder
        = indexSubSeq a (tl b)
    | startsWith a b
        = [[i \\ (_, i) <- take (length a) b] : remainder]
    = remainder
where
    startsWith :: [Char] Digits -> Bool
    startsWith _ []
        = False
    startsWith [] _
        = False
    startsWith [a] [(b,_):_]
        = a == b
    startsWith [a:a_] [(b,_):b_]
        | a == b
            = startsWith a_ b_
        = False

missingNumber :: String -> [[Char]]
missingNumber string
    # string
        = [(c, i) \\ c <-: string & i <- [0..]]
    # locations
        = [(number, indexSubSeq number string) \\ number <- numbers]
    # digits
        = [length (indexSubSeq [number] [(c, i) \\ c <- (flatten numbers) & i <- [0..]]) \\ number <-: "0123456789"]
    # missing
        = (flatten o flatten) [repeatn (y - length b) a \\ y <- digits & (a, b) <- locations]
    # (answers, _)
        = hd [e \\ e <- iterate singletonSieve (locations, [string]) | length (filter (\(a, b) = (length b == 0) && (isMember a (candidates missing))) (fst e)) > 0]
    # answers
        = filter (\(_, i) = length i == 0) answers
    = filter ((flip isMember)(candidates missing)) ((fst o unzip) answers)

Start world
    # (args, world)
        = getCommandLine world
    | length args < 2
        = abort "too few arguments\n"
    = flatlines [foldr (\num -> \str = if(isEmpty str) num (num ++ [',' : str]) ) [] (missingNumber arg) \\ arg <- tl args]

```

Compile with `clm -h 1024M -s 16M -nci -dynamics -fusion -t -b -IL Dynamics -IL Platform main`

This works by taking every number the string has to contain, and counting the number of places the required digit sequence is present in the string. It then repeatedly does these steps:

* If number has no possible positions, that's the answer
* Remove every number with one possible position (call these `singles`)
* Remove every position from all remaining numbers which overlaps with any positions from the previously removed numbers (the `singles`)

# Answer
> 0 votes
# Rust

Port of @Colera Su's C++ answer in Rust.

\\$ \color{red} {\text{But I made some mistakes, the result of the rust code is not correct.}} \\$

\\$ \color{red} {\text{variable \`prob\` seems to be consistent, the logic that produces \`prob\` seems to be consistent. }} \\$

Any help would be appreciated.

Try it online!

```
use std::collections::HashMap;
use std::cmp::Ordering;

// const VAL_MAX: usize = 250;
// const LOG_MAX: f64 = (VAL_MAX as f64 - 1.0).log10() + 1.0;
const VAL_MAX: usize = 250;
const LOG_MAX: usize = 3;

struct Ocr {
    l: usize,
    r: usize,
    g: usize,
}

impl PartialEq for Ocr {
    fn eq(&self, other: &Self) -> bool {
        self.l == other.l
    }
}

impl Eq for Ocr {}

impl PartialOrd for Ocr {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Ocr {
    fn cmp(&self, other: &Self) -> Ordering {
        other.l.cmp(&self.l)
    }
}

fn count(s: &str, target: &str) -> (usize, usize) {
    let mut count = 0;
    let mut last_index = 0;
    let mut offset = 0;

    while let Some(index) = s[offset..].find(target) {
        count += 1;
        offset += index + target.len();
        last_index = offset;
    }

    (count, last_index)
}

fn dfs(a: usize, mut b: usize, strs: &Vec<String>, cnt: &mut HashMap<usize, bool>, t: usize) -> bool {
    if b == strs[a].len() {
        b = 0;
        if a + 1 == strs.len() {
            return true;
        }
    }

    let mut p = 0;
    for _ in 0..LOG_MAX as usize {
        if strs[a].len() == b {
            break;
        }
        p = p * 10 + (strs[a].as_bytes()[b] as usize - b'0' as usize);
        b += 1;
        if p < VAL_MAX && !*cnt.entry(p).or_insert(false) && p != t {
            cnt.insert(p, true);
            if dfs(a, b, strs, cnt, t) {
                return true;
            }
            cnt.insert(p, false);
        }
    }
    false
}

fn cal(str: Vec<String>, mut cnt: HashMap<usize, bool>, t: usize) -> bool {
    let mut pos = Vec::new();

    for i in 0..VAL_MAX {
        if cnt.get(&i).unwrap_or(&false).clone() {
            continue;
        }
        let target = i.to_string();
        let mut flag = 0;
        let mut now = Ocr { l: 0, r: 0, g: 0 };
        for (j, str) in str.iter().enumerate() {
            let c = count(str, &target);
            flag += c.0;
            if flag > 1 {
                break;
            }
            if c.0 > 0 {
                now = Ocr { l: c.1, r: c.1 + target.len(), g: j };
            }
        }
        if flag == 0 && t == i {
            return true;
        }
        if i != t && flag == 1 {
            pos.push(now);
            cnt.insert(i, true);
        }
    }

    if pos.is_empty() {
        let mut str = str.clone();
        str.sort_by(|a, b| a.len().cmp(&b.len()));
        return dfs(0, 0, &str, &mut cnt, t);
    }

    pos.sort();
    let mut lst = Vec::new();
    let mut str = str.clone();
    for i in pos {
        if i.r > str[i.g].len() {
            return false;
        }
        let tmp = str[i.g][i.r..].to_string();
        if tmp.len() == 1 {
            let value = tmp.as_bytes()[0] as usize - b'0' as usize;
            if *cnt.get(&value).unwrap_or(&false) {
                return false;
            }
            cnt.insert(value, true);
        } else if !tmp.is_empty() {
            lst.push(tmp);
        }
        str[i.g].truncate(i.l);
    }
    for i in str {
        if i.len() == 1 {
            let value = i.as_bytes()[0] as usize - b'0' as usize;
            if *cnt.get(&value).unwrap_or(&false) {
                return false;
            }
            cnt.insert(value, true);
        } else if !i.is_empty() {
            lst.push(i);
        }
    }
    cal(lst, cnt, t)
}

fn main() {
    let mut str = String::new();
    std::io::stdin().read_line(&mut str).unwrap();
    let str = str.trim().to_string();

    let mut p = vec![0; 10];
    for i in 0..VAL_MAX {
        for j in i.to_string().chars() {
            p[j as usize - '0' as usize] += 1;
        }
    }
    for i in str.chars() {
        p[i as usize - '0' as usize] -= 1;
    }

    let mut tmp = String::new();
    for i in 0..10 {
        for _ in 0..p[i] {
            tmp.push((i as u8 + b'0') as char);
        }
    }
    let mut prob = Vec::new();
    loop {
        let c = tmp.parse::<usize>().unwrap();
        if c < VAL_MAX && tmp.chars().next().unwrap() != '0' {
            prob.push(c);
        }
        let mut tmp_bytes = tmp.into_bytes();
        if !tmp_bytes.next_permutation() {
            break;
        }
        tmp = String::from_utf8(tmp_bytes).unwrap();
    }

    println!("{:?}",prob);

    if prob.len() == 1 {
        println!("\n the result is: {:?}", prob[0]);
        return;
    }
    for i in prob {
        if cal(vec![str.clone()], HashMap::new(), i) {
            println!("\n the result is: {:?}", i);
        }
    }
}

pub trait NextPermutation {
    fn next_permutation(&mut self) -> bool;
}

impl<T> NextPermutation for [T]
where
    T: Ord,
{
    fn next_permutation(&mut self) -> bool {
        if self.len() < 2 {
            return false;
        }

        let mut i = self.len() - 1;
        while i > 0 && self[i - 1] >= self[i] {
            i -= 1;
        }

        if i == 0 {
            return false;
        }

        let mut j = self.len() - 1;
        while j >= i && self[j] <= self[i - 1] {
            j -= 1;
        }

        self.swap(j, i - 1);
        self[i..].reverse();

        true
    }
}

```

---
Tags: string, number, sequence, parsing, fastest-code
---


title: Bigram frequencies in text

text:
# Question
Title: Bigram frequencies in text
# Introduction

This challenge is about producing a code to count the frequency of bigrams in a text. A bigram is two consecutive letters in a text. For instance 'aabbcd' contains the bigrams aa, ab, bb, bc, cd once each. Counting bigram frequencies is super useful in cryptography. In a brute force algorithm, this code may be called many times and as a result, must be optimised to run quickly.

# Challenge

* Challenge is in Python 3 and NumPy can be used.
* The input will be a string of text (no spaces or punctuation). The output will be a NumPy array that is 26x26 or a list of lists that would be equivalent to the NumPy array. The first letter of the bigram is the row index and the second letter is the column index. The values in the array represent the frequency of that particular bigram.
* The fastest code wins. I will measure the time it takes for the code to run 10,000 times on my computer (2015 Aspire F15 Intel i3 2.0GHz 4GB RAM).

# Input

This is the input that I will test the code on

```
'WERENOSTRANGERSTOLOVEYOUKNOWTHERULESANDSODOIAFULLCOMMITMENTSWHATIMTHINKINGOFYOUWOULDNTGETTHISFROMANYOTHERGUYIJUSTWANNATELLYOUHOWIMFEELINGGOTTAMAKEYOUUNDERSTANDNEVERGONNAGIVEYOUUPNEVERGONNALETYOUDOWNNEVERGONNARUNAROUNDANDDESERTYOUNEVERGONNAMAKEYOUCRYNEVERGONNASAYGOODBYENEVERGONNATELLALIEANDHURTYOUWEVEKNOWNEACHOTHERFORSOLONGYOURHEARTSBEENACHINGBUTYOURETOOSHYTOSAYITINSIDEWEBOTHKNOWWHATSBEENGOINGONWEKNOWTHEGAMEANDWEREGONNAPLAYITANDIFYOUASKMEHOWIMFEELINGDONTTELLMEYOURETOOBLINDTOSEENEVERGONNAGIVEYOUUPNEVERGONNALETYOUDOWNNEVERGONNARUNAROUNDANDDESERTYOUNEVERGONNAMAKEYOUCRYNEVERGONNASAYGOODBYENEVERGONNATELLALIEANDHURTYOUNEVERGONNAGIVEYOUUPNEVERGONNALETYOUDOWNNEVERGONNARUNAROUNDANDDESERTYOUNEVERGONNAMAKEYOUCRYNEVERGONNASAYGOODBYENEVERGONNATELLALIEANDHURTYOUNEVERGONNAGIVENEVERGONNAGIVEGIVEYOUUPWEVEKNOWNEACHOTHERFORSOLONGYOURHEARTSBEENACHINGBUTYOURETOOSHYTOSAYITINSIDEWEBOTHKNOWWHATSBEENGOINGONWEKNOWTHEGAMEANDWEREGONNAPLAYITIJUSTWANNATELLYOUHOWIMFEELINGGOTTAMAKEYOUUNDERSTANDNEVERGONNAGIVEYOUUPNEVERGONNALETYOUDOWNNEVERGONNARUNAROUNDANDDESERTYOUNEVERGONNAMAKEYOUCRYNEVERGONNASAYGOODBYENEVERGONNATELLALIEANDHURTYOUNEVERGONNAGIVEYOUUPNEVERGONNALETYOUDOWNNEVERGONNARUNAROUNDANDDESERTYOUNEVERGONNAMAKEYOUCRYNEVERGONNASAYGOODBYENEVERGONNATELLALIEANDHURTYOUNEVERGONNAGIVEYOUUPNEVERGONNALETYOUDOWNNEVERGONNARUNAROUNDANDDESERTYOUNEVERGONNAMAKEYOUCRYNEVERGONNASAYGOODBYE'

```

# Output:

This is the expected output

```
[[ 0.  0.  4.  0.  0.  1.  8.  0.  0.  0.  8. 11. 10. 21.  0.  2.  0. 14.
   7. 10.  0.  0.  0.  0. 10.  0.]
 [ 0.  0.  0.  0.  4.  0.  0.  0.  0.  0.  0.  1.  0.  0.  2.  0.  0.  0.
   0.  0.  2.  0.  0.  0.  6.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  4.  0.  0.  0.  0.  0.  0.  1.  0.  0.  6.
   0.  0.  0.  0.  0.  0.  0.  0.]
 [ 6.  6.  0.  6. 10.  0.  0.  5.  1.  0.  0.  0.  0.  3.  8.  0.  0.  0.
   1.  1.  0.  0.  2.  0.  0.  0.]
 [11.  2.  0.  0.  8.  0.  5.  1.  0.  0.  4. 11.  0. 13.  0.  0.  0. 53.
   7. 10.  0. 39.  2.  0. 17.  0.]
 [ 0.  0.  0.  0.  3.  0.  0.  0.  0.  0.  0.  0.  0.  0.  2.  0.  0.  1.
   0.  0.  1.  0.  0.  0.  2.  0.]
 [ 2.  2.  0.  1.  2.  0.  2.  0.  9.  0.  0.  0.  0.  0. 52.  0.  0.  0.
   0.  0.  1.  0.  0.  0.  2.  0.]
 [ 3.  0.  0.  0.  8.  0.  0.  0.  4.  0.  2.  0.  0.  0.  5.  0.  0.  0.
   0.  0.  5.  0.  0.  0.  2.  0.]
 [ 1.  0.  0.  2.  5.  1.  0.  0.  0.  2.  0.  0.  4. 12.  0.  0.  0.  0.
   1.  5.  0.  9.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.
   0.  0.  2.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  8.  0.  0.  0.  1.  0.  0.  0.  1.  7.  0.  0.  0.  0.
   0.  0.  0.  0.  0.  0.  0.  0.]
 [ 7.  0.  1.  1.  7.  0.  0.  0.  9.  0.  0.  9.  1.  0.  3.  0.  0.  0.
   0.  0.  0.  0.  0.  0.  2.  0.]
 [ 9.  0.  0.  0.  5.  3.  0.  0.  1.  0.  0.  0.  1.  0.  0.  0.  0.  0.
   0.  1.  0.  0.  0.  0.  0.  0.]
 [49.  0.  0. 26. 39.  0. 13.  0.  0.  0.  1.  0.  0. 47.  8.  0.  0.  0.
   2.  3.  0.  0.  2.  0.  1.  0.]
 [ 0.  1.  0.  7.  0.  1.  0.  0.  3.  0.  0.  3.  2. 44.  9.  0.  0.  2.
   6.  7. 49.  1. 16.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  2.  0.  6.  0.  0.  0.  0.
   0.  0.  0.  0.  1.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.
   0.  0.  0.  0.  0.  0.  0.  0.]
 [ 1.  0.  0.  0.  6.  2. 38.  2.  0.  0.  0.  0.  0.  0.  7.  0.  0.  0.
   5. 13.  7.  0.  0.  0.  6.  0.]
 [ 9.  4.  0.  0.  7.  1.  0.  2.  2.  0.  1.  0.  0.  0.  3.  0.  0.  0.
   0.  6.  0.  0.  1.  0.  0.  0.]
 [ 5.  0.  0.  0.  8.  0.  1. 10.  4.  0.  0.  0.  1.  0.  7.  0.  0.  1.
   5.  4.  0.  0.  2.  0. 19.  0.]
 [ 1.  0.  6.  6.  0.  0.  0.  2.  0.  0.  1.  3.  0. 24.  0.  7.  0. 10.
   2.  2.  9.  0.  2.  0.  1.  0.]
 [ 0.  0.  0.  0. 49.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.
   0.  0.  0.  0.  0.  0.  0.  0.]
 [ 2.  0.  0.  0.  9.  0.  0.  3.  3.  0.  0.  0.  0.  8.  1.  0.  0.  0.
   0.  3.  0.  0.  2.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.
   0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  6.  0.  6.  0.  5.  0.  0.  0.  0.  6. 43.  0.  0.  0.
   0.  2.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.
   0.  0.  0.  0.  0.  0.  0.  0.]]

```

# Answer
# Python 3 \+ numpy (0.359 seconds)

```
def f(IN):
    a = np.array([IN.encode()],"S").view(np.uint8)-ord('A')
    c = np.bincount(np.ravel_multi_index((a[:-1],a[1:]),(26,26)),None,26*26)
    return c.reshape(26,26)

```

Try it online!

**UPDATE** better array construction (first line in function) thanks @tsh! **(0.332 seconds)**

```
a = np.frombuffer(IN.encode(),"u1")-ord('A')

```

**/UPDATE**
> 5 votes

# Answer
# Python (133 chars) (16.1 seconds)

```
import numpy as np
i=input()
o=np.zeros((26,26))
for b in[(ord(i[j])-65,ord(i[j+1])-65)for j in range(len(i)-1)]:o[b]+=1
print(o)

```

This code runs in O(n) time, where n is the length of the string.
> 3 votes

# Answer
# Rust, 304.1µs

### `src/main.rs`

```
// extern crate ndarray;
use ndarray::Array2;
use std::collections::HashMap;
use std::time::Instant;

fn main() {
    let start = Instant::now();
    let result = convert_string("WERENOSTRANGERSTOLOVEYOUKNOWTHERULESANDSODOIAFULLCOMMITMENTSWHATIMTHINKINGOFYOUWOULDNTGETTHISFROMANYOTHERGUYIJUSTWANNATELLYOUHOWIMFEELINGGOTTAMAKEYOUUNDERSTANDNEVERGONNAGIVEYOUUPNEVERGONNALETYOUDOWNNEVERGONNARUNAROUNDANDDESERTYOUNEVERGONNAMAKEYOUCRYNEVERGONNASAYGOODBYENEVERGONNATELLALIEANDHURTYOUWEVEKNOWNEACHOTHERFORSOLONGYOURHEARTSBEENACHINGBUTYOURETOOSHYTOSAYITINSIDEWEBOTHKNOWWHATSBEENGOINGONWEKNOWTHEGAMEANDWEREGONNAPLAYITANDIFYOUASKMEHOWIMFEELINGDONTTELLMEYOURETOOBLINDTOSEENEVERGONNAGIVEYOUUPNEVERGONNALETYOUDOWNNEVERGONNARUNAROUNDANDDESERTYOUNEVERGONNAMAKEYOUCRYNEVERGONNASAYGOODBYENEVERGONNATELLALIEANDHURTYOUNEVERGONNAGIVEYOUUPNEVERGONNALETYOUDOWNNEVERGONNARUNAROUNDANDDESERTYOUNEVERGONNAMAKEYOUCRYNEVERGONNASAYGOODBYENEVERGONNATELLALIEANDHURTYOUNEVERGONNAGIVENEVERGONNAGIVEGIVEYOUUPWEVEKNOWNEACHOTHERFORSOLONGYOURHEARTSBEENACHINGBUTYOURETOOSHYTOSAYITINSIDEWEBOTHKNOWWHATSBEENGOINGONWEKNOWTHEGAMEANDWEREGONNAPLAYITIJUSTWANNATELLYOUHOWIMFEELINGGOTTAMAKEYOUUNDERSTANDNEVERGONNAGIVEYOUUPNEVERGONNALETYOUDOWNNEVERGONNARUNAROUNDANDDESERTYOUNEVERGONNAMAKEYOUCRYNEVERGONNASAYGOODBYENEVERGONNATELLALIEANDHURTYOUNEVERGONNAGIVEYOUUPNEVERGONNALETYOUDOWNNEVERGONNARUNAROUNDANDDESERTYOUNEVERGONNAMAKEYOUCRYNEVERGONNASAYGOODBYENEVERGONNATELLALIEANDHURTYOUNEVERGONNAGIVEYOUUPNEVERGONNALETYOUDOWNNEVERGONNARUNAROUNDANDDESERTYOUNEVERGONNAMAKEYOUCRYNEVERGONNASAYGOODBYE");
    let duration = start.elapsed();
    println!("Time elapsed in convert_string() is: {:?}", duration);

    println!("[");
    for row in result.genrows() {
        print!("[");
        let last_index = row.len() - 1;
        for (index, item) in row.iter().enumerate() {
            if index == last_index {
                print!("{:3}", item);
            } else {
                print!("{:3},", item);
            }
        }
        println!("]");
    }
    println!("]");
}

fn convert_string(input: &str) -> Array2<i32> {
    let mut transition_counts = HashMap::new();
    let mut prev_char = None;
    for c in input.chars() {
        let current_char = c as i32 - 'A' as i32;
        if let Some(prev) = prev_char {
            *transition_counts.entry((prev, current_char)).or_insert(0) += 1;
        }
        prev_char = Some(current_char);
    }
    let mut result = Array2::zeros((26, 26));
    for (&(i, j), &count) in transition_counts.iter() {
        // println!("{:?}",count);
        result[(i as usize, j as usize)] = count;
    }
    result
}

```

### `Cargo.toml`

```
[package]
name = "rust_hello"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]

ndarray = "0.15"

```

### Build and running

```
# win10 environment

$ cargo build --release
$ target\release\rust_hello.exe
Time elapsed in convert_string() is: 304.1µs
[
[  0,  0,  4,  0,  0,  1,  8,  0,  0,  0,  8, 11, 10, 21,  0,  2,  0, 14,  7, 10,  0,  0,  0,  0, 10,  0]
[  0,  0,  0,  0,  4,  0,  0,  0,  0,  0,  0,  1,  0,  0,  2,  0,  0,  0,  0,  0,  2,  0,  0,  0,  6,  0]
[  0,  0,  0,  0,  0,  0,  0,  4,  0,  0,  0,  0,  0,  0,  1,  0,  0,  6,  0,  0,  0,  0,  0,  0,  0,  0]
[  6,  6,  0,  6, 10,  0,  0,  5,  1,  0,  0,  0,  0,  3,  8,  0,  0,  0,  1,  1,  0,  0,  2,  0,  0,  0]
[ 11,  2,  0,  0,  8,  0,  5,  1,  0,  0,  4, 11,  0, 13,  0,  0,  0, 53,  7, 10,  0, 39,  2,  0, 17,  0]
[  0,  0,  0,  0,  3,  0,  0,  0,  0,  0,  0,  0,  0,  0,  2,  0,  0,  1,  0,  0,  1,  0,  0,  0,  2,  0]
[  2,  2,  0,  1,  2,  0,  2,  0,  9,  0,  0,  0,  0,  0, 52,  0,  0,  0,  0,  0,  1,  0,  0,  0,  2,  0]
[  3,  0,  0,  0,  8,  0,  0,  0,  4,  0,  2,  0,  0,  0,  5,  0,  0,  0,  0,  0,  5,  0,  0,  0,  2,  0]
[  1,  0,  0,  2,  5,  1,  0,  0,  0,  2,  0,  0,  4, 12,  0,  0,  0,  0,  1,  5,  0,  9,  0,  0,  0,  0]
[  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  2,  0,  0,  0,  0,  0]
[  0,  0,  0,  0,  8,  0,  0,  0,  1,  0,  0,  0,  1,  7,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0]
[  7,  0,  1,  1,  7,  0,  0,  0,  9,  0,  0,  9,  1,  0,  3,  0,  0,  0,  0,  0,  0,  0,  0,  0,  2,  0]
[  9,  0,  0,  0,  5,  3,  0,  0,  1,  0,  0,  0,  1,  0,  0,  0,  0,  0,  0,  1,  0,  0,  0,  0,  0,  0]
[ 49,  0,  0, 26, 39,  0, 13,  0,  0,  0,  1,  0,  0, 47,  8,  0,  0,  0,  2,  3,  0,  0,  2,  0,  1,  0]
[  0,  1,  0,  7,  0,  1,  0,  0,  3,  0,  0,  3,  2, 44,  9,  0,  0,  2,  6,  7, 49,  1, 16,  0,  0,  0]
[  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  2,  0,  6,  0,  0,  0,  0,  0,  0,  0,  0,  1,  0,  0,  0]
[  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0]
[  1,  0,  0,  0,  6,  2, 38,  2,  0,  0,  0,  0,  0,  0,  7,  0,  0,  0,  5, 13,  7,  0,  0,  0,  6,  0]
[  9,  4,  0,  0,  7,  1,  0,  2,  2,  0,  1,  0,  0,  0,  3,  0,  0,  0,  0,  6,  0,  0,  1,  0,  0,  0]
[  5,  0,  0,  0,  8,  0,  1, 10,  4,  0,  0,  0,  1,  0,  7,  0,  0,  1,  5,  4,  0,  0,  2,  0, 19,  0]
[  1,  0,  6,  6,  0,  0,  0,  2,  0,  0,  1,  3,  0, 24,  0,  7,  0, 10,  2,  2,  9,  0,  2,  0,  1,  0]
[  0,  0,  0,  0, 49,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0]
[  2,  0,  0,  0,  9,  0,  0,  3,  3,  0,  0,  0,  0,  8,  1,  0,  0,  0,  0,  3,  0,  0,  2,  0,  0,  0]
[  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0]
[  0,  0,  0,  0,  6,  0,  6,  0,  5,  0,  0,  0,  0,  6, 43,  0,  0,  0,  0,  2,  0,  0,  0,  0,  0,  0]
[  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0]
]

```
> 0 votes

# Answer
# Wolfram Language (Mathematica), ~180µs on PC, 1000µs on TIO

```
res=Normal@SparseArray[
   Normal@Counts[
     Partition[
      Flatten[Position[ToUpperCase /@ Alphabet[], #] & /@
        Characters@data], 2, 1]]]

```

Try it online!

Tested for now just on Mathematica 12 on Windows 7 Lenovo laptop, 4x1.5Ghz 4Gb
Sure Mathematica 13 on more powerful PC takes tens of µs
> 0 votes

---
Tags: string, fastest-code, python
---


# Question
Title: All ASCII characters with a given bit count
(Title with thanks to @ChasBrown)

Sandbox

**The Background**

This challenge is inspired by a question that I recently posted on Puzzling Stack Exchange. Please feel free to follow the link if you are interested in the original question. If not then I won't bore you with the details here.

**The Facts**

Every printable standard ASCII character has a decimal value between 32 and 126 inclusive. These can be converted to their corresponding binary numbers in the range 100000 to 1111110 inclusive. When you sum the bits of these binary numbers you will always end up with an integer between 1 and 6 inclusive.

**The Challenge**

Given an integer between 1 and 6 inclusive as input, write a program or function which will output in any acceptable format all of the printable standard ASCII characters where the sum of the bits of their binary value is equal to the input integer.

**The Examples/Test Cases**

```
1 -> ' @'
2 -> '!"$(0ABDHP`'
3 -> '#%&)*,1248CEFIJLQRTXabdhp'
4 -> ''+-.3569:<GKMNSUVYZ\cefijlqrtx'
5 -> '/7;=>OW[]^gkmnsuvyz|'
6 -> '?_ow{}~'

```

An ungolfed Python reference implementation is available here (TIO).

**The Rules**

1. Assume the input will always be an integer (or string representation of an integer) between 1 and 6 inclusive.
2. You may write a program to display the results or a function to return them.
3. Output may be in any reasonable format but **must be consistent for all inputs**. If you choose to output a quoted string then the same type of quotes must be used for all inputs.
4. Standard loopholes prohibited as usual.
5. This is code golf so shortest code in each language wins.

# Answer
# x86-16 machine code, IBM PC DOS, ~~29~~ 25 bytes

**Machine code:**

```
00000000: be81 00ad b330 b108 d0c8 12dd e2fa 3adc  .....0........:.
00000010: 7502 cd29 fec0 79ec c3                   u..)..y..

```

**Listing:**

```
BE 0081     MOV  SI, 081H   ; SI = memory address of command line string
AD          LODSW           ; AL = start ASCII value (is 20H from space on cmd line)
                            ; AH = target number of bits (in ASCII)
        CHR_LOOP:
B3 30       MOV  BL, '0'    ; BL = counter of bits, reset to ASCII zero
B1 08       MOV  CL, 8      ; loop through 8 bits of AL
        BIT_LOOP:
D0 C8       ROL  AL, 1      ; rotate LSB of AL into CF
12 DD       ADC  BL, CH     ; add CF to BL (CH is always 0)
E2 FA       LOOP BIT_LOOP   ; loop to next bit
3A DC       CMP  BL, AH     ; is current char the target number of bits?
75 02       JNE  NO_DISP    ; if not, do not display
CD 10       INT  29H        ; display ASCII char in AL (current char in loop)
        NO_DISP:
FE C0       INC  AL         ; increment char to next ASCII value
79 EC       JNS  CHR_LOOP   ; if char <= 127, keep looping
C3          RET             ; return to DOS

```

Standalone PC DOS executable program, input number from command line. Output is displayed to console window.
> 30 votes

# Answer
# CP-1610 assembly (Intellivision), 20 DECLEs1 = 25 bytes

Takes \\$N\\$ in **R0** and a pointer to the output buffer in **R4**. Writes all matching characters in the buffer and marks the end of the results with **NUL**.

```
                ROMW    10              ; use 10-bit ROM width
                ORG     $4800           ; map this program at $4800

                ;; ------------------------------------------------------------- ;;
                ;;  test code                                                    ;;
                ;; ------------------------------------------------------------- ;;
4800            EIS                     ; enable interrupts

4801            MVII    #$103,    R4    ; set the output buffer at $103 (8-bit RAM)
4803            MVII    #2,       R0    ; test with N = 2
4805            CALL    getChars        ; invoke our routine

4808            MVII    #$103,    R4    ; R4 = pointer into the output buffer
480A            MVII    #$215,    R5    ; R5 = backtab pointer

480C  draw      MVI@    R4,       R0    ; read R0 from the buffer
480D            SLL     R0,       2     ; R0 *= 8
480E            SLL     R0
480F            BEQ     done            ; stop if it's zero

4811            ADDI    #7-256,   R0    ; draw it in white
4815            MVO@    R0,       R5

4816            B       draw            ; go on with the next entry

4818  done      DECR    R7              ; loop forever

                ;; ------------------------------------------------------------- ;;
                ;;  routine                                                      ;;
                ;; ------------------------------------------------------------- ;;
      getChars  PROC

4819            MVII    #32,      R1    ; start with R1 = 32

481B  @loop     MOVR    R1,       R3    ; copy R1 to R3
481C            CLRR    R2              ; clear R2
481D            SETC                    ; start with the carry set

481E  @count    ADCR    R2              ; add the carry to R2
481F            SARC    R3              ; shift R3 to the right (the least
                                        ; significant bit is put in the carry)
4820            BNEQ    @count          ; loop if R3 is not zero

4822            CMPR    R2,       R0    ; if R2 is equal to R0 ...
4823            BNEQ    @next

4825            MVO@    R1,       R4    ; ... write R1 to the output buffer

4826  @next     INCR    R1              ; advance to the next character
4827            CMPI    #127,     R1    ; and loop until 127 is reached
4829            BLT     @loop

482B            MVO@    R3,       R4    ; write NUL to mark the end of the output

482C            JR      R5              ; return

                ENDP

```

### Output for N=2

NB: The opening parenthesis looks a lot like an opening square bracket in the Intellivision font. Both characters are distinct, though.

*screenshot from jzIntv*

---

*1. A CP-1610 opcode is encoded with a 10-bit value, known as a 'DECLE'. This routine is 20 DECLEs long, starting at $4819 and ending at $482C (included).*
> 14 votes

# Answer
# Python 2, 62 bytes

```
lambda n:[chr(i)for i in range(32,127)if bin(i).count('1')==n]

```

Try it online!
> 12 votes

# Answer
# Perl 6, ~~41~~ 34 bytes

```
{chrs grep *.base(2)%9==$_,^95+32}

```

Try it online!

Anonymous code block that takes a number and returns a string of valid characters.

### Explanation:

```
{                                }  # Anonymous code block taking a number
      grep                ,^95+32   # Filter from the range 32 to 126
           *.base(2)                # Where the binary of the digit
                    %9                # When parsed as a decimal modulo 9
                      ==$_            # Is equal to the input
 chrs                               # And convert the list of numbers to a string

```

It can be proven that for any number \\$n\\$ in base \\$b\\$, \\$n \equiv \text{digitsum}(n) \pmod{b-1}\\$ (clue: remember that \\$b \pmod{b-1}=1\\$).

We can use this to get the digitsum of our binary number by parsing it as a decimal number and moduloing by 9, which is valid because the range of numbers we are using is guaranteed to have less than 9 bits. This is helped along by Perl 6's automatic casting of the binary string to a decimal number when used in a numeric context.
> 10 votes

# Answer
# 05AB1E, 8 bytes

```
žQʒÇbSOQ

```

Try it online!

**Explanation**

```
žQ        # push the printable ascii characters
  ʒ       # filter, keep elements whose
   Ç      # character code
    b     # converted to binary
     SO   # has a digit sum
       Q  # equal to the input

```
> 9 votes

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

*Using Jo King's modulo trick*

```
n=>(g=x=>x>>7?'':Buffer(x.toString(2)%9-n?0:[x])+g(x+1))(32)

```

Try it online!

---

# JavaScript (Node.js),  ~~70~~  69 bytes

```
n=>(g=x=>x>>7?'':Buffer((h=x=>x&&x%2+h(x>>1))(x)-n?0:[x])+g(x+1))(32)

```

Try it online!

### Commented

```
n => (              // n = input
  g = x =>          // g = recursive function, taking a byte x
    x >> 7 ?        //   if x = 128:
      ''            //     stop recursion and return an empty string
    :               //   else:
      Buffer(       //     create a Buffer:
        (h = x =>   //       h = recursive function taking a byte x
          x &&      //         stop if x = 0
          x % 2 +   //         otherwise, add the least significant bit
          h(x >> 1) //         and do a recursive call with floor(x / 2)
        )(x)        //       initial call to h
        - n ?       //       if the result is not equal to n:
          0         //         create an empty Buffer (coerced to an empty string)
        :           //       else:
          [x]       //         create a Buffer consisting of the character x
      ) +           //     end of Buffer()
      g(x + 1)      //     append the result of a recursive call to g with x + 1
)(32)               // initial call to g with x = 32

```
> 7 votes

# Answer
# Jelly, 8 bytes

```
ØṖOB§=ʋƇ

```

Try it online!

```
ØṖ       printable ascii character list
  OB     to binary
    §    popcount
     =   equal to input?
      ʋƇ filter (implicitly output)

```
> 7 votes

# Answer
# Brachylog, 7 bytes

```
∈Ṭ&ạhḃ+

```

Try it online!

A predicate which functions as a generator, takes input through its output variable, and produces each character through its input variable. Because Brachylog.

```
           The input variable (which is an element of the output)
∈          is an element of
 Ṭ         the string containing every printable ASCII character
  &        and the input
   ạh      converted to a codepoint
     ḃ     converted to a list of binary digits
      +    sums to
           the output variable (which is the input).

```
> 7 votes

# Answer
# Japt, 9 bytes

```
;EÆ¶Xc¤è1

```

Try it or test all inputs

```
;EÆ¶Xc¤è1     :Implicit input of integer U
;E            :Printable ASCII
  Æ           :Filter each X
   ¶          :Test U for equality with
    Xc        :  Character code of X
      ¤       :  To binary string
       è1     :  Count the 1s

```
> 6 votes

# Answer
# Excel (2016 or later), 76 bytes

```
=CONCAT(IF(LEN(SUBSTITUTE(DEC2BIN(ROW(32:126)),0,))=A1,CHAR(ROW(32:126)),""))

```

Takes input from A1, outputs in whatever cell you put this formula. This is an array formula, so you need to press `Ctrl`+`Shift`+`Enter` to input it. The "2016 or later" is because it needs the `CONCAT` function (the deprecated `CONCATENATE` won't take an array as argument).
> 5 votes

# Answer
# , 77 68 bytes

### Approach using for loop

-9 bytes thanks to Giuseppe

```
n=scan();for(i in 32:126)if(sum(intToBits(i)>0)==n)cat(intToUtf8(i))

```

Try it online!

### Previously:

# , 78 69 66 bytes

-12 bytes thanks to Giuseppe

```
a=32:126;cat(intToUtf8(a[colSums(sapply(a,intToBits)>0)==scan()]))

```

Turns the numbers 32 to 126 into a matrix of bits then sums across the rows to find which match the input number.

Try it online!
> 5 votes

# Answer
# C (standard library), 74 67 bytes

```
i;j;k;f(n){for(i=31;i<126;k||puts(&i))for(k=n,j=++i;j;j/=2)k-=j&1;}

```

Using only standard library functions. Thanks go to @gastropner for improvement from 74 to 67 bytes.

Try it online!
> 5 votes

# Answer
# Java 8, ~~131~~ 71 bytes

-60 bytes thanks to everyone in the comments
Returns a `java.util.stream.IntStream` of codepoints

```
n->java.util.stream.IntStream.range(32,127).filter(i->n.bitCount(i)==n)

```

Try it online!
Using HashSet, 135 bytes. Returns a `Set<Object>`:

```
n->new java.util.HashSet(){{for(int i=31;i++<126;add(Long.toBinaryString(i).chars().map(c->c-48).sum()==n?(char)i+"":""),remove(""));}}

```

Try it online!
> 4 votes

# Answer
# Dyalog APL Extended, ~~24~~ 22 bytes

```
⎕ucs a⌿⍨⎕=+⌿2⊤a←32…126

```

Try it online!

-2 bytes thanks to ngn

Alternative 22 bytes in regular Dyalog APL by ngn:

```
⎕ucs 32+⍸⎕=32↓+/↑,⍳7⍴2

```

Try it online!
> 4 votes

# Answer
# , ~~31~~ ~~27~~ 23 bytes

```
((=1#.#:)u:@#])32+i.@95

```

*-2 thanks to south*

Attempt This Online!

# , ~~31~~ 27 bytes

*-4 bytes thanks to Galen*

```
[:u:32+[:I.]=1#.32#:@+i.@95

```

Try it online!

## Original Answer

```
a.#~&(95{.32}.])]=1#.2#:@i.@^8:

```

Try it online!

* `2#:@i.@^8:` produces the binary numbers 0 through 255 (`2 ^ 8` is 256)
* `1#.` sums each one
* `]=` produces a binary mask showing where the sum equals the original input
* `a.#~ mask` uses that binary mask to filter J's full ascii alphabet `a.`
* `&(95{.32}.])` but before doing so take only elements 32...126 from both the alphabet and the mask
> 4 votes

# Answer
# C# (Visual C# Interactive Compiler), 86 bytes

```
n=>Enumerable.Range(32,95).Where(x=>"0123456".Sum(g=>x>>g-48&1)==n).Select(x=>(char)x)

```

Thanks to @ExpiredData for giving me the idea to use `Sum()`! When I get back to my PC, I will replace the string `"0123456"` with unprintables, saving three bytes.

Try it online!
> 4 votes

# Answer
# Java 10, ~~98~~ ~~97~~ ~~94~~ ~~70~~ 67 bytes

```
n->{for(var c='';c-->31;)if(n.bitCount(c)==n)System.out.print(c);}

```

-24 bytes thanks to *NahuelFouilleul*.

Try it online.

**Explanation:**

Contains an unprintable character with unicode value `127`.

```
n->{                         // Method with Integer parameter and no return-type
  for(var c='';c-->31;)     //  Loop character `c` in the range ['~', ' '] / (127,31):
    if(n.bitCount(c)         //   If the amount of 1-bits in the two's complement binary
                             //   representation of the current characters
                    ==n)     //   equals the input:
      System.out.print(c);}  //    Print the current character

```
> 4 votes

# Answer
# Factor, 52 bytes

```
[ 32 126 [a,b] [ bit-count = ] with filter >string ]

```

Try it online!

* `32 126 [a,b]` Create a range of printable ascii values
* `[ bit-count = ] with filter` Select values with the bit count indicated by the input
* `>string` Convert the result from a sequence of code points to a printable string
> 4 votes

# Answer
# Python 2, 69 bytes

```
lambda n:[chr(i)for i in range(32,127)if sum(map(int,bin(i)[2:]))==n]

```

Try it online!
> 3 votes

# Answer
# Gaia, 10 bytes

```
₵R⟪¤cbΣ=⟫⁇

```

Try it online!

```
		| implicit input, n
₵R		| push printable ascii
  ⟪	⟫⁇	| filter the list where:
   ¤cbΣ		| the sum of the code point in binary
       =	| is equal to n

```
> 3 votes

# Answer
# Ruby, 48 bytes

```
->n{(' '..?~).select{|x|x.ord.digits(2).sum==n}}

```

Try it online!
> 3 votes

# Answer
# Perl 5 `-a`,  ~~50~~ 43 bytes

*@NahuelFouilleul saves 7 bytes*

```
map{$_=chr;unpack('B*')%9-"@F"||say}32..126

```

Try it online!
> 3 votes

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

**Solution:**

```
`c$32+&(+/2\32+!95)=

```

Try it online!

**Explanation:**

Evaluated right-to-left:

```
`c$32+&(+/2\32+!95)= / the solution
                   = / equals?
       (          )  / do this together
               !95   / range 0..94
            32+      / add 32, so range 32..126
          2\         / break into base-2
        +/           / sum up
      &              / indices where true
   32+               / add 32
`c$                  / cast to character

```
> 3 votes

# Answer
# 6502 assembly (NES), 22 bytes

Machine code:

```
a0 1f a6 60 c8 98 30 fb ca 0a b0 fc d0 fb e8 d0 f1 8c 07 20 f0 ec

```

Assembly:

```
    ldy #$1f ; Y holds the current character code
NextCharacter:
    ldx $60 ; load parameter into X
    iny
    tya
    bmi (NextCharacter + 1) ; exit at char 128, #$60 is the return opcode

CountBits:
    dex
Continue:
    asl
    bcs CountBits
    bne Continue

CompareBitCount:
    inx ; fixes off-by-one error and sets Z flag if bit count matches
    bne NextCharacter
    sty $2007
    beq NextCharacter ; always branches

```

Full program. Tested with FCEUX 2.2.3, should work on any standard NES emulator.

Inspired by Ryan Russell's answer. Input given at CPU address $60. Outputs to the console's Picture Processing Unit memory.
> 3 votes

# Answer
# VBA, 146 bytes

```
Sub Main()
n=3
For i=32 To 127
b=CStr(Application.WorksheetFunction.Dec2Bin(i))
If Len(b)-Len(Replace(b,"1",""))=n Then MsgBox Chr(i)
Next
End Sub

```

I wonder if somehow it could be done using Excel alone, I am not a excel formula pro....
> 3 votes

# Answer
# Nibbles, 5 bytes

```
|_~`^+`@ 2

```

That's 10 nibbles each encoded as half a byte in the binary form.

Translation:

```
|          filter
 _         printables (since stdin is empty)
 ~         not
  `^       xor
    +      sum
     `@2   to base 2
        $  filter var (implicit)
    @      first input arg (implicit)

```

It uses not of the xor to set itself up for implicit args (instead of == which wouldn't be able to use any)

Usage:

```
nibbles <filename>.nbl <input number>

```

Nibbles isn't on TIO yet...
> 3 votes

# Answer
# Python 3.10, 58 bytes

```
lambda n:(chr(i)for i in range(32,127)if i.bit_count()==n)

```

Attempt This Online!

It's kind of like Lynn's answer.
Just it uses the `.bit_count` introduced in Python3.10, so its shorter

More info about `.bit_count` here: https://docs.python.org/3/library/stdtypes.html
> 3 votes

# Answer
# Kotlin, 60 bytes

```
{n->(32..127).filter{n==it.countOneBits()}.map{it.toChar()}}

```

Note:
For the moment Kotlin's STDOUT in ATO is always empty.
And TIO doesn't support countOneBits().

More information about how to count bytes for a Kotlin answer: https://codegolf.stackexchange.com/a/202985/112099

Attempt This Online!
> 3 votes

# Answer
# MATL, 10 bytes

```
6Y2tB!si=)

```

Try it online!

## Explanation

```
6Y2        % All ASCII Chars
   t       % dup
    B      % convert each to binary
     !     % transpose
      s    % sum
       i=  % equal to the input?
         ) % Keep truthy elements

```
> 3 votes

# Answer
# Wolfram Language (Mathematica), 70 bytes

```
FromCharacterCode/@Select[32~Range~126,s=#;Tr@IntegerDigits[#,2]==s&]&

```

Try it online!
> 2 votes

# Answer
# PowerShell, 83 bytes

```
param($n)[char[]](32..126|?{([convert]::ToString($_,2)|% t*y|group)[1].count-eq$n})

```

Try it online!

Takes input `$n`, constructs a range from `32` to `126` and pulls out those numbers where `|?{}`: the number, `convert`ed `ToString` in base `2`; converted `t`oCharArra`y`; `group`ed into `0`s and `1`s; taking the `[1]` index of that grouping; taking the `.count` thereof, and checking that it's `-eq`ual to our input `$n`umber. Those numbers are then cast as a `char`-array and left on the pipeline. Output is implicit, with newlines between elements.
> 2 votes

# Answer
# Charcoal, 10 bytes

```
Φγ⁼Σ↨℅ι²Ｉθ

```

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

```
 γ          Predefined ASCII characters
Φ           Filtered by
      ι     Current character's
     ℅      ASCII code
    ↨       Converted to base
       ²    Literal 2
   Σ        Summed
  ⁼         Equals
         θ  First input
        Ｉ   Cast to integer
            Implicitly printed

```
> 2 votes

# Answer
# PHP, 72 bytes

```
for($x=31;$x++<126;)echo$argn==count_chars(decbin($x),1)[49]?chr($x):'';

```

Try it online!
> 2 votes

# Answer
# Red, 92 bytes

```
func[n][repeat k 95[if n = length? replace/all enbase/base c: form #"^_"+ k 2"0"""[prin c]]]

```

Try it online!
> 2 votes

# Answer
## C(MSVC) 50 bytes

```
i;f(n){for(i=31;i++<127;n-__popcnt(i)||puts(&i));}

```

## C(gcc), 60 bytes

```
i;f(n){for(i=31;i++<127;n-__builtin_popcount(i)||puts(&i));}

```

Try it online
> 2 votes

# Answer
# Octave with Communications Package, 32 bytes

```
@(n)t(sum(de2bi(t=' ':'~')')==n)

```

Try it online!
> 2 votes

# Answer
# Factor, 94 bytes

```
: f ( n -- n s ) 94 [0,b] [ 32 + 2 >base [ 49 = ] count over = ] filter [ 32 + ] map >string ;

```

Try it online!
> 2 votes

# Answer
# Haskell, 77 bytes

```
import Data.Char
b 0=0
b k=mod k 2+b(div k 2)
f n=[chr k|k<-[32..126],b k==n]

```

Try it online!
> 2 votes

# Answer
# C (GCC) - 134 Bytes

```
#include <stdio.h>
#include <stdlib.h>
int main(int _,char**v){for(char c=32;c<127;c++)__builtin_popcount(c)-atoi(v[1])||putchar(c);}

```

Compile with `gcc chars.c -o chars`, and run the resulting program with the number of bits as the command-line argument.

Compiles with no warnings.

This program utilizes the `__builtin_popcount` builtin that is present in GCC, which resolves to a `POPCNT` instruction on most x86 hardware built in the last dozen or so years.
> 2 votes

# Answer
# Scala, ~~88~~ 87 bytes

```
(y:Int)=>32 to 126 map{x=>BigInt(x).bitCount->x}filter(_._1==y)map(_._2.toChar)mkString

```
> 2 votes

# Answer
# Z80Golf, 25 bytes

```
00000000: cd03 806f 0e20 517d 45cb 3a9b 10fb de30 ...o. Q}E.:....0
00000010: 2002 79ff 0ce2 0600 76                   .y.....v

```

Try it online!

```
  call $8003    ; A = getchar(), e.g. '5'
  ld l, a       ; L = A
  ld c, ' '     ; C = ' '
next:           ; do {
  ld d, c       ;   D = C
  ld a, l       ;   A = L, e.g. '5'
  ld b, l       ;   B = L (way more than enough)
more:           ;   while (--B ≠ 0) {
  srl d         ;       shift D right, bit 0 goes into Carry
  sbc a, e      ;       A -= 0 + Carry
  djnz more     ;   }
done:
  sbc a, '0'    ;   A -= '0' + Carry
  jr nz, omit   ;   if A == 0:
  ld a, c       ;       putchar(C)
  rst $38
omit:
  inc c         ;   C++
  jp po, next   ; } until overflow, i.e. stop when C becomes 0x80 = -128
  halt

```
> 2 votes

# Answer
# Haskell, 61 bytes

```
f n=[toEnum k|k<-[32..126],sum[k`div`2^i`mod`2|i<-[0..6]]==n]

```

Try it online!

The type of `f` is `f :: (Enum t) => Int -> [t]`. That's more general than necessary, and it means you need to e.g. `putStrLn` the result for Haskell to infer that you want a `[Char]` result.

I don't know what the rules say about that, but replacing `toEnum k` with `['\0'..]!!k` is a workaround costing 3 bytes.
> 2 votes

# Answer
# Forth (gforth), 81 bytes

```
: f 127 32 do 0 i begin 2 /mod >r + r> ?dup 0= until over = if i emit then loop ;

```

Try it online!

### Code Explanation

```
: f           \ start a new word definition
  127 32      \ set up loop parameters
  do          \ loop from 32 to 126
    0 i       \ set up values for counting bits
    begin     \ start an indefinite loop
      2 /mod  \ divide by 2 and get quotient and remainder
      >r + r> \ add the remainder to the counter
      ?dup 0= \ check if quotient equals zero
    until     \ end the loop if it is
    over =    \ check if the result equals the input number
    if        \ if it is
      i emit  \ output the char for the current ascii value
    then      \ end the if
  loop        \ end the counted loop
;             \ end word definition

```
> 2 votes

# Answer
# Perl 5 - 42+1

This is a modification of @Xcali solution, saving one character. Perl's unpack has a built-in bit counting mechanism, no need for the mod-9 trick.

```
#!perl -a
map{$_=chr;unpack('%B*')-"@F"||say}32..126

```
> 2 votes

# Answer
# MS Excel, 76 bytes

An anonymous worksheet function that takes input from cell `A1` and outputs to the calling cell.

```
=Let(a,Row(32:126),Concat(If(Len(Substitute(Dec2Bin(a),0,))=A1,Char(a),"")))

```

Try it Online

## Explanation

```
=Let(...)                      ' begin variable definition block
   a,Row(32:126),              ' assign array `[32...126]` to variable `a`
         Dec2Bin(a)            ' convert `a` to binary
       Substitute(~,0,)        ' for each binary element, remove all `0`s, leaving only `1`s
     If(Len(~)=A1,Char(a),"")  ' iff number of `1`s equals input, print that char
   Concat(~)                   ' concat array and output

```
> 2 votes

# Answer
# Stax, 7 bytes

```
æqäí¼.ö

```

Run and debug it
> 2 votes

# Answer
# Fig, \\$10\log\_{256}(96)\approx\\$ 8.231 bytes

```
Fcp'=#xSbC

```

Try it online!

## Explained (old)

```
VR32 127Co0*v=Mv'Sb
VR32 127            # Put the range [32, 127) into the register
              Mv'   # to each item in that range:
                 Sb # get the sum of the on bits in the binary representation of the number
         o0*v=      # multiply the register by whether each item in the bit count list equals the input and remove 0s. This acts as a makeshift filter that can use global input.
        C           # convert the remaining items to their ascii character equivalent

```
> 2 votes

# Answer
# MathGolf, 12 bytes

```
♣⌡╒T≥gæâΣk=$

```

Try it online.

**Explanation:**

```
♣             # Push 128
 ⌡            # Subtract 2: 126
  ╒           # Pop and push a list in the range [1,126]
   T≥         # Remove the first 31 items: range [32,126]
     g        # Filter this list of integers by,
      æ       # using 4 characters as inner code-block:
       â      #  Convert the integer to a binary-list
        Σ     #  Sum the bits together
         k    #  Push the input-integer
          =   #  Check if it's equal to the sum
           $  # Convert the remaining integers to characters with this codepoint
              # (after which the entire stack is output implicitly as result)

```
> 2 votes

# Answer
# Vyxal, 8 bytes

```
kP'Cb∑?=

```

Try it Online!

### Explained

```
kP'Cb∑?=
kP       # printable ACSI characters with no spaces in between them
  '      # lambda filter
   C     # char
    b    # binary
     ∑   # summate
      ?  # input
       = # equal?

```
> 2 votes

# Answer
# Thunno 2, 9 bytes

```
kcæCh2BS=

```

Attempt This Online!

#### Explanation

```
kcæCh2BS=  # Implicit input
kc         # Printable ASCII characters
  æ        # Filtered by:
   Ch      #  Their ordinal
     2B    #  Converted to binary
       S=  #  Has a sum equal to the input
           # Implicit output

```
> 2 votes

# Answer
# C++ (gcc), ~~124~~ 113 bytes

-11 bytes thanks to @ceilingcat

```
#import<string>
auto a(int n){std::string f;for(int i=30,j,k;++i<127;f+=i*!j,j=n)for(k=i;k;k/=2)j-=k&1;return f;}

```

Try it online!

Iterates through the printable character codes, finds those that match the number of 1 bits desired, returns the string containing those characters concatenated.
> 1 votes

# Answer
## JavaScript (Client && NodeJs), 222 bytes

Try it online

```
x=>[...Array(127).keys()].slice(32).reduce((a,d)=>(a.push({y:[...d.toString(2)].map(x=>+x),z:String.fromCharCode(d)}),a),[]).map(i => (i.y.reduce((a,b)=>(a.y+=+b,a),{y:0,z:i.z}))).reduce((a,b)=>(b.y==x?a.push(b.z):0,a),[])

```
> 1 votes

# Answer
# T-SQL, 153 bytes

Query returns 1 row for each character.

```
DECLARE @ INT=6

SELECT char(number)FROM
spt_values,(values(1),(2),(4),(8),(16),(32),(64))x(x)WHERE
type='P'and number/32in(1,2,3)GROUP BY number
HAVING sum(number/x%2)=@

```

**Try it online**

# 186 bytes

Putting all characters in same row:

```
DECLARE @ INT=6

SELECT string_agg(char(h),'')FROM(SELECT
iif(sum(number/x%2)=@,number,-1)h
FROM spt_values,(values(1),(2),(4),(8),(16),(32),(64))x(x)WHERE
type='P'and number/32in(1,2,3)GROUP BY number)c

```

**Try it online**
> 1 votes

# Answer
# Attache, 25 bytes

```
${{x=1~Bin[Ord@_]}\ascii}

```

Try it online!

## Alternatives

**26 bytes:** `${{x=1~(Bin@Ord@_)}\ascii}`

**26 bytes:** `${{x=Sum@Bin@Ord@_}\ascii}`

**28 bytes:** `${Char!{x=Sum@Bin@_}\32:126}`

**28 bytes:** `ascii&${{y=Sum@Bin@Ord@_}\x}`

**34 bytes:** `ascii&{Mask[_2=Sum@Bin=>Ords@_,_]}`

**35 bytes:** `ascii&{Mask[_2=1&`~@Bin=>Ords@_,_]}`

## Explanation

```
${{x=1~Bin[Ord@_]}\ascii}
${                      }   lambda with named parameter `x` (for scoping)
  {              }\ascii    select all ascii characters...
     1~                       where the number of 1s
       Bin[Ord@_]             in the character's binary representation
   x=                         equals the parameter

```
> 1 votes

# Answer
# 6502 Assembly (NES), 29 bytes

Outputs as tiles to the screen.

Machine code: (xx represents branch displacement bytes which I would probably get wrong assembling by hand)

```
A2 1F
E8
30 xx
86 01
A9 00
06 01
F0 xx
69 00
10 xx
69 00
C5 00
D0 xx
8E 07 20
D0 xx
60

```

Assembly:

```
; Output buffer address in $2006 PPU_ADDR. bits in address 0.
    ldx #31 ; initialize first printable character
@loop:
    inx
    bmi @done ; stop at 128 (127 won't match on input 1-6)
    stx 1 ; initialize address 1 with character
    lda #0
@bits:
    asl 1 ; load a bit into carry
    beq @next
    adc #0 ; add the carry to a
    bpl @bits ; branch always
@next:
    adc #0
    cmp 0
    bne @loop
    stx $2007
    bne @loop
@done:
    rts

```
> 1 votes

# Answer
# Clean, 65 bytes

```
import StdEnv
$n=[c\\c<-[32..127]|sum[(c>>p)rem 2\\p<-[0..6]]==n]

```

Try it online!

Defines `$ :: Int -> [Int]` giving a list of codepoints.
> 1 votes

# Answer
# Rust - 112 bytes

```
fn a(i:u32)->String{std::str::from_utf8(&(0..128u8).filter(|x|x.count_ones()==i).collect::<Vec<u8>>()).unwrap()}

```

Going for worst reasonable answer. Rust does not allow simple conversions from ints to chars to strings.
> 1 votes

# Answer
# JavaScript, 92 bytes

```
f=(b,c=32)=>c<127?(c.toString(2).match(/1/g).length-b?String.fromCharCode(c):"")+f(b,c+1):""

```

I like `Number.prototype.toString(n)`.

```
f=(b,c=32)=>                                                                                //function declaration, starting at character code 32.
            c<127?                                                                           //check for out of range
                  (c.toString(2)                                                             //if the number in binary has
                                .match(/1/g).length                                          //number of 1 bits
                                                   -b?                                       //equal to b
                                                      String.fromCharCode(c):"")             //then add the character
                                                                                +f(b,c+1)    //next character

  :"" //base case for out of range(127)

```
> 1 votes

# Answer
# dc, 52 bytes

```
sn31[dP]sP[1+dd[2~rd0<B]dsBx[+z3<S]dsSxln=PC6>M]dsMx

```

Try it online!

`sn` to store our target bit count from top-of-stack into register `n`. `31` starts us off at our first ASCII value (the main macro increments it immediately). `[dP]sP` is a printing macro, we call this when the bit count is equal to the target. Into our main macro, `M`... `1+dd` increments top-of-stack and duplicates it twice. `[2~rd0<B]dsBx` uses integer division by two w/ remainder to break a decimal value down into binary bits on the stack. `[+z3<S]dsSx` sums stack items until we're back to three values on the stack - our summation and two copies of our ASCII value. `ln=P` compares the summation with `n`, our target bit count, and runs the printing macro `P` if they're equal. `C6>M` keeps running `M` through ASCII value 126.

One thing to note that I sometimes forget about when golfing in `dc` is that there's no harm in burying macros `B` and `S` inside of `M` since they're *always* going to run at least once per run of `M`. This saves a byte in each case - `dsBx` instead of `sB` outside of macro `M` and then `lBx` inside.
> 1 votes

# Answer
# Clam, 11 bytes

```
p#:\bcqQ'a-

```

Prints an array of characters

## Explanation

```
            - Implicit Q = first input
p           - Print...
        'a- - ASCII characters (dictionary access)
 #          - Where...
   \        - The sum of...
    b       - The binary bits of...
     cq     - The charcode of the character
  :         - Equals...
       Q    - Q

```
> 1 votes

# Answer
# Julia 1.0, 43 bytes

```
y->filter(x->count_ones(Int(x))==y,' ':'~')

```

Try it online!
> 1 votes

# Answer
# Arturo, 52 bytes

```
$->x[to[:char]select 32..127=>[x=∑digits.base:2&]]

```

Try it!

Outputs a list of characters, which seems to be allowed.
> 1 votes

---
Tags: code-golf
---