[Question]
  [
## The challenge
You're given:
* a non-empty, unsorted list **h** of positive integers (the haystack)
* a positive integer **n** (the needle)
Your task is to return the list of all ***unique*** decimal concatenations of permutations of **h** whose binary representation contains the binary representation of **n**.
## Examples
1. **h = [ 1, 2, 3 ]**  
**n = 65**
[![example](https://i.stack.imgur.com/Xllzk.png)](https://i.stack.imgur.com/Xllzk.png)
There's only one matching concatenation, so the expected output is `[321]`.
2. **h = [ 1, 2, 3 ]**  
**n = 7**
This time, there are three concatenations which contain the binary pattern **111**. The expected output is `[123, 231, 312]`.
3. **h = [ 12, 3 ]**  
**n = 7**
Only two permutations are available and both are matching. The expected output is `[123, 312]`.
4. **h = [ 1, 2, 2 ]**  
**n = 15**
The only matching concatenation is **122** (**1111010** in binary, which contains **1111**), so the expected output is `[122]`. Note that two permutations actually lead to **122** but you are *not* allowed to output `[122, 122]`.
## Clarifications and rules
* You may take the needle as an integer (`65`), a string representing a decimal value (`"65"`) or a string representing a binary value (`"1000001"`).
* You may take the haystack as a native array/object/set of integers (`[11,12,13]`), a native array/object/set of strings representing decimal values (`["11","12","13"]`), or a delimited string of decimal values (`"11 12 13"` or `"11,12,13"`). You may also opt for a variant using arrays of digits (like `[[1,1],[1,2],[1,3]]`).
* The output must follow one of the formats described above for the haystack, but not necessarily the same one.
* You're not supposed to handle haystacks whose highest decimal concatenation is greater than the highest representable unsigned integer in your language.
* Apart from that, your code should theoretically support any input -- assuming it's given enough time and memory.
* This is ~~SPARTA!~~ [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes win!
## Test cases
```
Haystack             | Needle   | Output
---------------------+----------+-----------------------------------
[ 1, 2, 3 ]          | 65       | [ 321 ]
[ 1, 2, 3 ]          | 7        | [ 123, 231, 312 ]
[ 12, 3 ]            | 7        | [ 123, 312 ]
[ 1, 2, 2 ]          | 15       | [ 122 ]
[ 1, 2 ]             | 7        | []
[ 12, 34, 56 ]       | 21       | [ 125634, 341256, 345612, 563412 ]
[ 1, 2, 3, 4, 5 ]    | 511      | [ 53241 ]
[ 1, 3, 5, 7, 9 ]    | 593      | [ 37519, 51793, 75913, 75931 ]
[ 11, 12, 13, 14 ]   | 12141311 | [ 12141311 ]
[ 1, 2, 1, 2, 1, 2 ] | 1015     | [ 221112 ]
```
  
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10~~ 8 bytes
Takes the needle in binary to save 1 byte.
-2 bytes thanks to Emigna
```
œJÙʒbŒIå
```
[Try it online!](https://tio.run/nexus/05ab1e#@390stfhmacmJR2d5Hl46f//0YY6RjrGsVyGhoYA "05AB1E – TIO Nexus")
```
œJÙʒbŒIå   Arguments: a, n
œJÙ        Get all unique permutations of a
   ʒ       Filter: Keep if following code returns true
    b      Convert to binary
     Œ     Get all substrings
      Iå   Check if substrings contain n
           Implicit output of filtered list
```
[Answer]
## Python 2, 90 bytes
-3 bytes thanks to @Gábor Fekete
[Try it online](https://tio.run/nexus/python2#HYoxCsMwDEX3nkJoiVVMIR0L3TOEXKDp4NAYVGLLKOpUenYn6YcHj8fv72NdQppeATo/3L4MURQYOEOZNX0sGEteXUccYTjyxNlxNtc0l7ccTkS/U1RJwDariSwrcCqidq5F9yv07oEterz@eXps9yHVDQ)
Takes as input array of strings, representing ints from hay and string, representing needle in binary
```
from itertools import*
lambda H,N:{i for i in permutations(H)if N in bin(int(''.join(i)))}
```
[Answer]
# Java 10, ~~320~~ ~~312~~ ~~305~~ ~~297~~ 292 bytes
```
import java.util.*;Set s=new HashSet();l->n->{Long q=0;p(l,0);for(var x:s)if(q.toString(q.decode(x+""),2).contains(n))System.out.println(x);}void p(List l,int k){int i=k,x=l.size();for(Collections C=null;i<x;p(l,k+1),C.swap(l,k,i++))C.swap(l,i,k);if(k>x-2)s.add((l+"").replaceAll("\\D",""));}
```
Input as List & binary-String, output as Strings on new-lines.
**Explanation:**
[Try it here.](https://tio.run/##zZNRb9owEMff8ylOPNnDuDhAKxqC1HWaNqmTJvG47sE1hhqMncYOhSE@O3MCZZW2wcMmqB9iX3K5@/3vzhM@543JcLrZXFzAV557sCPwjxIell42hC2MB8S6lenwdaRmmQ1Ok/AbLbzS9F0Swav1u8OoMMIra@itNa6YyTw54PNxd0gioblz8IUrs4qiA2xxc882kB5cauQzfOLuMVgIJ1H0ErJ3p5wnLxC9gc@VGff7ICA9mIA1430G3eibRn91Z80YntJmkiFNmjgZ2RzNeQ6La4fVCD1Rb7fhw3EohR1KtKjXapjEmAprfBDlkMF4sHRezqgtPM2Cu9cGLXCyjqLkMFGH7YnmVg0hQ6U20CTEgClelZtKp2SRaurUD4m2iLdWa1nVwoFITaF1onqLSsS0zjAR1D3zyiKqXsd4bysyxUkQNu0vGjF2lA@HCOlSEc1lprmQN1qj2v39hxoJL4OEDUBWPGglwHnuw1ZxzoJwtK3Mt@/A8aoanbLHMIMUys6VRtm28sOMCsqzTC/RTZ7zZcjrSp2IEYgJtDCmXAiZefTZeDmWeSj7e2V4vtwV/7KDd5H@UOha42@rtk/vdlCvxul/cF2dGOtNQlW1io9isTP08E02sE2gc3mULGZnGXkCJd5Rug47PV5g6xC4ItA9jtdtnRgv8JXNZQGStY/fhZi1WYudpcW/nscxm/90adfRevMT)
```
import java.util.*;           // Required import for Set, HashSet, List, and Collections
Set s=new HashSet();          // Class-level Set
l->n->{                       // Method (1) with List and String parameters and no return-type
  Long q=0;                   //  Number-object is required for two static method-calls below
  p(l,0);                     //  Determine all permutations of given list and put it in the Set
  for(var x:s)                //  Loop over these permutations
    if(q.toString(q.decode(x+""),2)
                              //   If the binary String of the current permutation
        .contains(n))         //   contains the binary String of the input integer
      System.out.println(x);} //    Print this permutation
void p(List l,int k){         // Method (2) with List and integer parameters and no return-type
  int i=k,x=l.size();         //  Two temp integers
  for(Collections C;          //  Collections-object is required for two static method-calls below
      i<x                     //  Loop `i` in the range [`k`, list-size)
      ;                       //    After every iteration:
       p(l,k+1),              //     Do a recursive-call to this method with `k+1`
       Collections.swap(l,k,i++))
                              //     And swap the items at indices `k` and `i` back
    Collections.swap(l,i,k);  //   Swap the items at indices `i` and `k`
  if(k>x-2)                   //  If `k` is now equal to the size of the list - 1
    s.add((l+"").replaceAll("\\D",""));}
                              //   Add this permutation to the Set
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~15~~ ~~14~~ ~~13~~ ~~12~~ 10 bytes
Takes the haystack as an array of integers and the needle as a binary string. Outputs an array of integer strings.
```
á m¬f_°¤øV
```
* Saved a byte thanks to [ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions)
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=4SBtrGZfsKT4Vg==&input=WzEyLCAzNCwgNTZdLCIxMDEwMSIKLVE=)
---
## Explanation
```
á m¬â f_°¤øV
              :Implicit input of array U=haystack and string V=needle
á             :Unique permutations of U
  m           :Map
   ¬          :  Join to a string
    f_        :Filter
      °       :  Postfix increment current element to cast it to an integer
       ¤      :  Convert to base-2 string
        øV    :  Does that contain V?
              :Implicit output of resulting array
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~61~~ 59 bytes
```
->a,n{a.permutation.select{|s|"%b"%s.join=~/#{"%b"%n}/}|[]}
```
[Try it online!](https://tio.run/nexus/ruby#S7P9r2uXqJNXnahXkFqUW1qSWJKZn6dXnJqTmlxSXVNco6SapKRarJeVn5lnW6evXA3m59Xq19ZEx9b@L1BIi4421DHSMY7VMTON5SooLSlWUNfV1VXnQpYyxy5jFKtjaBr7HwA "Ruby – TIO Nexus")
Cool feature of the day: I didn't know I could output the binary representation of a string containing a number.
Example:
```
puts "%b"%"123"
-> 1111011
```
[Answer]
# JavaScript (ES6), 140 bytes
Takes needle as a binary string.
```
(h,n,S=new Set,p=(a,m='')=>a.length?a.map((_,i)=>p(A=[...a],m+A.splice(i,1))):S.add(+m),_=p(h))=>[...S].filter(d=>~d.toString(2).indexOf(n))
```
```
f=
(h,n,S=new Set,p=(a,m='')=>a.length?a.map((_,i)=>p(A=[...a],m+A.splice(i,1))):S.add(+m),_=p(h))=>[...S].filter(d=>~d.toString(2).indexOf(n))
console.log( f([1, 2, 3], (65).toString(2)) )
console.log( f([12, 34, 56], (21).toString(2)) )
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 15 bytes
```
{hpc.ḃs~ḃ~t?∧}ᵘ
```
[Try it online!](https://tio.run/nexus/brachylog2#@1@dUZCs93BHc3EdkKgrsX/Usbz24dYZ//9HRxvqGOkYxeoYmsb@jwIA "Brachylog – TIO Nexus")
### Explanation
```
{            }ᵘ    Find all unique outputs, given [h, n], of:
 hpc.                The Output is the concatenation of a permutation of h
    .ḃs              Take a substring of the binary representation of the Output
       ~ḃ            Convert it back to a decimal number
         ~t?∧        This decimal number must me n
```
[Answer]
## Mathematica, ~~170~~ 156 bytes
```
(t={};l=Length;v=IntegerDigits;j=v[#2, 2];s=FromDigits/@Flatten/@v@Permutations@#1;Table[If[l@SequenceCases[v[s[[i]],2],j]>0,t~AppendTo~s[[i]]],{i,l@s}];t)&
```
  
**input**
> 
> [{12, 34, 56}, 21]
> 
> 
> 
**output** 
> 
> {125634, 341256, 345612, 563412}
> 
> 
> 
[Answer]
## CJam, ~~23~~ ~~22~~ ~~21~~ 19 bytes
```
{e!{si2b1$2b#)},\;}
```
This is a block that takes inputs `n h` on the stack and leaves the output as an array on the stack.
Explanation:
```
                   e# Stack:                      | 65 [1 2 3]
e!                 e# Unique Permutations:        | 65 [[1 2 3] [1 3 2] [2 1 3] [2 3 1] [3 1 2] [3 2 1]]
  {                e# Filter where block is true: | 65 [3 2 1]
   s               e#   Convert to string:        | 65 "321"
    i              e#   Convert to int:           | 65 321
     2b            e#   Convert to binary:        | 65 [1 0 1 0 0 0 0 0 1]
       1$          e#   Copy behind:              | 65 [1 0 1 0 0 0 0 0 1] 65
         2b        e#   Convert to binary:        | 65 [1 0 1 0 0 0 0 0 1] [1 0 0 0 0 0 1]
           #       e#   Find array in another:    | 65 2
            )      e#   Increment:                | 65 3
             },    e# End filter                  | 65 [321]
               \;  e# Delete back:                | [321]
```
[Answer]
# R, 114 bytes
```
pryr::f(plyr::l_ply(combinat::permn(x),function(y)if(grepl(p,R.utils::intToBin(paste(y,collapse=""))))cat(y,"\n")))
```
Uses a bunch of packages. `pryr::f()` automatically creates a function, taking `p`, a string of the binary pattern to look for, and `x`, a vector with the other input as input. `combinat::permn` creates all permutations of `x`. `R.utils::intToBin` is a nice and wordy version to convert a numeric (or character representation of a numeric) to a binary number, already conveniently stored as a character. So applying this over all the permutations and outputting them if the binary string `p` is contained in the binary version of the concatenation. An explicit newline is printed, because otherwise the output would be `12 56 3456 34 1234 56 1234 12 56`.
`plyr`'s `l_ply` is used to surpress outputting a null list, besides the regular output. If output like this is allowed:
```
3 2 1 
[[1]]
NULL
[[2]]
NULL
[[3]]
NULL
[[4]]
NULL
[[5]]
NULL
[[6]]
NULL
```
Then we can save few bytes by using `lapply` instead:
## 108 bytes:
```
pryr::f(lapply(combinat::permn(x),function(y)if(grepl(p,R.utils::intToBin(paste(y,collapse=""))))cat(y,"\n")))
```
~~If output like this is allowed:~~
```
[[1]]
NULL
[[2]]
NULL
[[3]]
NULL
[[4]]
[1] 3 2 1
[[5]]
NULL
[[6]]
NULL
```
Then we can do it even shorter:
## 101 bytes:
```
pryr::f(lapply(combinat::permn(x),function(y)if(grepl(p,R.utils::intToBin(paste0(y,collapse=""))))y))
```
Not allowed.
[Answer]
# [Perl 6](http://perl6.org/), 69 bytes
```
{set @^a.permutations».join.grep(*.fmt('%b').contains($^b.base(2)))}
```
]