在十进制干草堆中找到二进针


41

挑战

您得到:

  • 一个非空的,未排序的正整数列表h(干草堆)
  • 正整数n(针)

您的任务是返回h的排列的所有唯一十进制串联的列表,其二进制表示形式包含n的二进制表示形式。

例子

  1. h = [1,2,3]
    n = 65

    例

    只有一个匹配的串联,因此预期的输出为[321]

  2. h = [1,2,3]
    n = 7

    这次,存在包含二进制模式111的三个串联。预期输出为[123, 231, 312]

  3. h = [12,3]
    n = 7

    只有两个排列可用,并且都匹配。预期输出为[123, 312]

  4. h = [1,2,2]
    n = 15

    唯一匹配的串联是122(二进制1111010,包含1111),因此预期输出是[122]。需要注意的是两个置换实际上导致122,但你是不是允许输出[122, 122]

澄清和规则

  • 您可以将指针作为整数(65),代表十进制值"65"的字符串()或代表二进制值的字符串("1000001")。
  • 您可以将干草堆当作本机数组/对象/整数集([11,12,13]),本机数组/对象/字符串集代表十进制值(["11","12","13"])或带分隔符的十进制值字符串("11 12 13""11,12,13")。您也可以选择使用数字数组(例如[[1,1],[1,2],[1,3]])作为变体。
  • 输出必须遵循上述针对干草堆的格式之一,但不一定要相同。
  • 您不应该处理最高十进制连接数大于语言中可表示的最高无符号整数的干草堆。
  • 除此之外,您的代码理论上应该支持任何输入-假设有足够的时间和内存。
  • 这是SPARTA! ,所以最短答案以字节为单位!

测试用例

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 ]

1
我的解决方案的输出如下所示set([(1, 2, 2)])。是有效的还是应该摆脱 set
死负鼠,

@DeadPossum是的,它是有效的。
Arnauld

干草堆输入可以是单个字符串(“ 123”)吗?在某些语言中,字符串与字符数组相同,因此我认为这很有意义
Luis Mendo

@LuisMendo不能因为["12","3"]["1","23"]是两个不同的干草堆。
Arnauld

@Arnauld啊,我以为他们是数字。谢谢
路易斯·门多

Answers:


17

05AB1E10 8字节

取二进制针以节省1个字节。

-2字节归功于Emigna

œJÙʒbŒIå

在线尝试!

œ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


@Emigna谢谢,这节省了2个字节:)
kalsowerus

11

Python 2,90个字节

-3个字节,感谢@GáborFekete

在线尝试

将字符串作为输入数组,表示干草和字符串中的整数,表示二进制形式的needle

from itertools import*
lambda H,N:{i for i in permutations(H)if N in bin(int(''.join(i)))}

4
写入{...}而不是set(...)保存3个字节。
加博尔·费克特(GáborFekete)

1
@GáborFekete我总是忘记了,{}被设置了:D谢谢
死负鼠

我相信这失败了H=['1'], N='0'
user2357112 '17

哦,等等,要求输入为正。
user2357112 '17

10

爪哇10,320个 312 305 297 292字节

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",""));}

输入为列表和二进制字符串,输出为换行符。

说明:

在这里尝试。

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

个人而言,我会把l->n->{...以后void p(...的拉姆达是答案的提示和功能需要设置为拉姆达工作。关于“函数表达式”的共识类似于“您提交的最后一个“表达式”可以是“函数表达式”,如果存储到变量中时它可以满足函数答案的要求” IIRC。但这只是格式问题,也是一个主观的问题。
CAD97

@ CAD97我不知道顺序很重要。上一次我发布了Java 8答案,并使用了两种方法,void因为它比第二个lambda和倍数短.apply。尚未检查此答案(即void p(List l,int k)&2x p(l,0)(l,k)->&2x p.apply(l,0))。嗯..第二个似乎在这种情况下短1个字节。但是您说规则指出您只能使用一种lambda方法吗?仍然有些困惑为什么它必须是最后一个。我个人总是按照以下顺序发布答案:imports; class-fields; main-method/lambda; other methods
凯文·克鲁伊森

再次,这主要是观点,我想让一个更有经验的人在真正说一种或另一种方式之前先加入。但是,我知道这是真的:如果您需要调用方法(例如,递归或作为辅助方法),则它需要有一个名称。至于排序,它并不真正重要,因为它不会改变的字节数。但我要订购imports;helper methods;lambda
CAD97,2017年

@ CAD97啊,当然,它是void p(List l,int k)&2x f(l,0);f=(l,p)->&2x的p.apply(l,0);替代(这意味着当前版本短1字节)。至于顺序,我会一直坚持下去,因为我已经回答了所有问题,从个人角度讲,从解释中的main方法开始,然后是helper方法,对我来说也很有意义有。
凯文·克鲁伊森

不幸的是,您不能只f=(lambda)使用Java,而是java.util.function.BiConsumer<List,Integer>f=(l,p)->{...}
CAD97

9

Japt15 14 13 12 10字节

将干草堆作为整数数组,将针作为二进制字符串。输出整数字符串数组。

á m¬f_°¤øV

试试吧


说明

á 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

关于我会做的事,很好。®¬nÃ在映射上保存一个字节。(我也将移至â程序的中间以摆脱第二个Ã;不保存任何字节,但效率更高一些,看起来更好一些)
ETHproductions

啊哈,谢谢@ETHproductions-我非常专注于查看是否可以通过将每个数字输出为数组来节省任何字节,我错过了对映射的简单更改。â最后,当Arnauld指出我忘记从最终数组中删除重复项时,这是一个快速解决方案,但是,没错,在运行过滤器之前删除重复项会更有效。
毛茸茸的

4

红宝石61 59字节

->a,n{a.permutation.select{|s|"%b"%s.join=~/#{"%b"%n}/}|[]}

在线尝试!

当今最酷的功能:我不知道我可以输出包含数字的字符串的二进制表示形式。

例:

puts "%b"%"123"

-> 1111011

3

JavaScript(ES6),140个字节

将针作为二进制字符串。

(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))


3

Brachylog,15个字节

{hpc.ḃs~ḃ~t?∧}ᵘ

在线尝试!

说明

{            }ᵘ    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

2

数学,170个 156字节

(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)&


输入

[{12,34,56},21]

输出

{125634、341256、345612、563412}


处有一个空格v[#2, 2]
伊西(Yytsi)'17

1

CJam,23 22 21 19字节

{e!{si2b1$2b#)},\;}

这是一个n h在堆栈上获取输入并将输出作为数组保留在堆栈上的块。

说明:

                   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]

1

R,114字节

pryr::f(plyr::l_ply(combinat::permn(x),function(y)if(grepl(p,R.utils::intToBin(paste(y,collapse=""))))cat(y,"\n")))

使用一堆包。pryr::f()自动创建一个函数,该函数使用,p要查找的二进制模式的字符串和x使用其他输入作为输入的向量。combinat::permn创建的所有排列xR.utils::intToBin是一个很好用的版本,用于将数字(或数字的字符表示形式)转换为已经方便地存储为字符的二进制数。因此,如果二进制字符串p包含在串联的二进制版本中,则将其应用于所有排列并输出它们。打印显式换行符,否则输出为12 56 3456 34 1234 56 1234 12 56

plyrl_ply用于surpress输出空列表,除了常规输出。如果允许这样的输出:

3 2 1 
[[1]]
NULL

[[2]]
NULL

[[3]]
NULL

[[4]]
NULL

[[5]]
NULL

[[6]]
NULL

然后,我们可以使用lapply来节省一些字节:

108字节:

pryr::f(lapply(combinat::permn(x),function(y)if(grepl(p,R.utils::intToBin(paste(y,collapse=""))))cat(y,"\n")))

如果允许这样的输出:

[[1]]
NULL

[[2]]
NULL

[[3]]
NULL

[[4]]
[1] 3 2 1

[[5]]
NULL

[[6]]
NULL

然后我们可以做的更短:

101个字节:

pryr::f(lapply(combinat::permn(x),function(y)if(grepl(p,R.utils::intToBin(paste0(y,collapse=""))))y))

不允许。


0

Perl 6、69字节

{set @^a.permutations».join.grep(*.fmt('%b').contains($^b.base(2)))}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.