문제

내 (코드 골프) 도전은 다음과 같습니다. 바이트의 두 배열을 가져 와서 두 번째 배열이 첫 번째 배열인지 결정하십시오. 그렇다면 두 번째 배열의 내용이 첫 번째에 나타나는 인덱스를 출력하십시오. 첫 번째 배열에서 두 번째 배열을 찾지 못하면 -1을 출력하십시오.

예제 입력 : {63, 101, 245, 215, 0} {245, 215}

예상 출력 : 2

입력 예제 2 : {24, 55, 74, 3, 1} {24, 56, 74}

예상 출력 2 : -1

편집하다: 누군가는 bool이 중복되었다고 지적 했으므로, 당신의 함수는 모든 기능이 값의 색인을 나타내는 int를 반환하는 것입니다.

도움이 되었습니까?

해결책

제이

요청한 것보다 훨씬 더 많은 기능에 대해 37 자 : 목록을 반환합니다. 모두 일치하는 지수.

I.@(([-:#@[{.>@])"_ 0(<@}."0 _~i.@#))

용법:

   NB. 이 기능의 이름을 알려주십시오
    =: I.@(([-:#@[{.>@])"_ 0(<@}."0 _~i.@#))
   NB. 테스트 #1
   245 215  63 101 245 215 0
2
   NB. 테스트 #2- 결과 없음
   24 56 74  24 55 74 3 1

   NB. 테스트 #3 : 여러 위치에서 일치합니다
   1 1  1 1 1 2 1 1 3
0 1 4
   NB. 테스트 #4 : 정확한 부분 문자열 일치 만
   1 2  0 1 2 3 1 0 2 1 2 0
1 7

NB. list[0 to end], list[1 to end], list[2 to end], ...
<@}."0 _~i.@#

NB. Does the LHS completely match the RHS (truncated to match LHS)?
[-:#@[{.>@]

NB. boolean list of match/no match
([-:#@[{.>@])"_ 0(<@}."0 _~i.@#)

NB. indices of *true* elements
I.@(([-:#@[{.>@])"_ 0(<@}."0 _~i.@#))

다른 팁

일반적인 LISP :

(defun golf-code (master-seq sub-seq)
  (search sub-seq master-seq))

추신, 149 146 170 166 167 159 자 ( "작업"부분에서) :

% define data
/A [63 101 245 215 0] def
/S [245 215] def

% do the work
/d{def}def/i{ifelse}d/l S length 1 sub d/p l d[/C{dup[eq{pop -1}{dup S p
get eq{pop p 0 eq{]length}{/p p 1 sub d C}i}{p l eq{pop}if/p l d C}i}i}d
A aload pop C

% The stack now contains -1 or the position

이것을 찾습니다 마지막 서브 어레이가 두 번 이상 포함되어있는 경우.

수정 기록 :

  • 바꾸다 false ~에 의해 [[ne 그리고 true ~에 의해 [[eq 세 문자를 저장합니다
  • 마지막 요소 인 경우 잘못된 음수를 유발할 수있는 버그를 제거했습니다. S 두 번 나타납니다 A. 불행히도이 버그 픽스에는 24자가 있습니다.
  • 버그 픽스를 조금 저렴하게 만들어 4 개의 숯을 저장했습니다.
  • 대시는 이름의 합법적 인 캐릭터이기 때문에 공간을 다시 삽입해야했습니다. 테스트 케이스 가이 시점에 도달하지 않았기 때문에이 구문 오류가 잡히지 않았습니다.
  • OP가 더 이상 필요하지 않기 때문에 Bools의 반환을 중단했습니다. 8 숯을 저장합니다.

설명 버전 :

불행히도, SO 구문 형광펜은 PostScript를 알지 못하므로 가독성이 여전히 제한되어 있습니다.

/A [63 101 245 215 0] def
/S [245 215 ] def

/Slast S length 1 sub def % save the index of the last element of S,
                          % i.e. length-1
/Spos Slast def % our current position in S; this will vary
[ % put a mark on the bottom of the stack, we need this later.

/check % This function recursively removes values from the stack
       % and compares them to the values in S
{
  dup [ 
  eq
  { % we found the mark on the bottom, i.e. we have no match
    pop -1 % remove the mark and push the results
  }
  { % we're not at the mark yet
    dup % save the top value (part of the bugfix)
    S Spos get
    eq 
    {  % the top element of the stack is equal to S[Spos]
       pop % remove the saved value, we don't need it
       Spos 0
       eq 
       { % we are at the beginning of S, so the whole thing matched.
         ] length % Construct an array from the remaining values
                  % on the stack. This is the part of A before the match,
                  % so its length is equal to the position of the match.
                  % Hence we push the result and we're done.
       }
       { % we're not at the beginning of S yet, so we have to keep comparing
         /Spos Spos 1 sub def % decrease Spos
         check % recurse
       }
       ifelse
    }
    { % the top element of the stack is different from S[Spos]
      Spos Slast eq {pop} if % leave the saved top value on the stack
                             % unless we're at the end of S, because in
                             % this case, we have to compare it to the
                             % last element of S (rest of the bugfix)
      /Spos Slast def % go back to the end of S
      check % recurse
    }
    ifelse
 }
 ifelse
}
def % end of the definition of check

A aload % put the contents of A onto the stack; this will also push A again,
        % so we have to ...
pop % ...remove it again
check % And here we go!

C99

#include <string.h>

void find_stuff(void const * const array1, const size_t array1length, /* Length in bytes, not elements */
                void const * const array2, const size_t array2length, /* Length in bytes, not elements */
                char * bReturnBool,
                int * bReturnIndex)
{
    void * found = memmem(array1, array1length, array2, array2length);
    *bReturnBool = found != NULL;
    *bReturnIndex = *bReturnBool ? found - array1 : -1;
}

속기로 그리고 약간 훨씬 더 지저분한 :

#include <string.h>
#define f(a,b,c,d,e,f) { void * g = memmem(a, b, c, d); f = (e = !!g) ? g - a : -1; }

파이썬 2 & 3, 73 68 58 자

기반 니힐 첼리아'에스 대답 Kaiser.se'에스 대답:

>>> t=lambda l,s:''.join(map(chr,l)).find(''.join(map(chr,s)))
>>> t([63, 101, 245, 215, 0], [245, 215])
2
>>> t([24, 55, 74, 3, 1], [24, 56, 74])
-1

파이썬 3, 41 36 자

부분적으로 감사합니다 Gnibbler:

>>> t=lambda l,s:bytes(l).find(bytes(s))
>>> t([63, 101, 245, 215, 0], [245, 215])
2
>>> t([24, 55, 74, 3, 1], [24, 56, 74])
-1

Haskell, 68 64 자

OP에 의해 지정된 인수 순서 :

import List;t l s=maybe(-1)id$findIndex id$map(isPrefixOf s)$tails l

처럼 일시적인 인수를 전환하고 코드를 네 가지 문자로 줄일 수 있습니다.

import List;t s=maybe(-1)id.findIndex id.map(isPrefixOf s).tails

파이썬에서 :

def test(large, small):
    for i in range(len(large)):
        if large[i:i+len(small)] == small:
            return i
    return -1

그러나 사람들은 간결하지 않기 때문에 우아하지 않습니다.

def f(l,s):
 for i in range(len(l)):
  if l[i:i+len(s)]==s:return i
 return -1

이는 75 자입하여 공백을 세고 있습니다.

Ruby, 배열#팩 사용 (41 Chars Body) :

def bytearray_search(a,b)
  (i=b.pack('C*').index(b.pack('C*')))?i:-1
end

Perl (36 Chars 바디, 매개 변수 처리 제외) :

sub bytearray_search {
  ($a,$b) = @_;
  index(pack('C*',@$a),pack('C*',@$b))
}

나는 속임수를 쓰고 있다고 생각하지만 Perl을 사용하면 OP가 원하는대로 할 수 있습니다.

sub byte_substr {
    use bytes;
    index shift,shift
}

보통 index() Perl에서는 문자 의미론이있는 문자열에서 작동하지만 "Bytes 사용"Pragma는 대신 바이트 세그먼트를 사용합니다. 인력에서 :

"바이트 사용"이 적용되면 인코딩은 일시적으로 무시되고 각 문자열은 일련의 바이트로 취급됩니다.

파이썬의 다른 하나 :

def subarray(large, small):
    strsmall = ' '.join([str(c).zfill(3) for c in small])
    strlarge = ' '.join([str(c).zfill(3) for c in large])
    pos = strlarge.find(strsmall)
    return  ((pos>=0), pos//4)

루비 1.9 (44b)

_=->a,b{[*a.each_cons(b.size)].index(b)||-1}

p _[[63, 101, 245, 215, 0], [245, 215]]
p _[[24, 55, 74, 3, 1], [24, 56, 74]]

고루비 (29b)

_=->a,b{a.e_(b.sz).dx(b)||-1}

파이썬: 84 자

def f(a,b):
 l=[a[i:i+len(b)]for i in range(len(a))]
 return b in l and l.index(b)or-1

프롤로그: 84 문자 (-1을 반환하는 대신 "아니오") :

s(X,[]).
s([H|T],[H|U]):-s(T,U).
f(X,Y,0):-s(X,Y).
f([_|T],Y,N):-f(T,Y,M),N is M+1.

64 자의 Python OneLiner 기능 정의

def f(l,s): return ''.join(map(chr,l)).find(''.join(map(chr,s)))

우리는 명시 적으로 통과되기 때문에 바이트 배열 우리는 그것을 Python의 기본 바이트 어레이로 변환 할 수 있습니다. str 그리고 사용 str.find

Python3 36 바이트

Stephan202를 기반으로합니다

>>> t=lambda l,s:bytes(l).find(bytes(s))
... 
>>> t([63, 101, 245, 215, 0], [245, 215])
2
>>> t([24, 55, 74, 3, 1], [24, 56, 74])
-1

파이썬에서 :

def SearchArray(input, search):
found = -1
for i in range(0, len(input) - len(search)):
    for j in range(0, len(search)):
        if input[i+j] == search[j]:
            found = i
        else:
            found = -1
            break
if  found >= 0:
    return True, found
else:
    return False, -1

테스트합니다

print SearchArray([ 63, 101, 245, 215, 0 ], [ 245, 215 ])
print SearchArray([ 24, 55, 74, 3, 1 ], [ 24, 56, 74 ])

어떤 인쇄 :

(True, 2)
(False, -1)

더 짧은 솔루션이 있지만 실제로 휴대용이 아닌 파이썬 언어 기능을 사용합니다.

C#:

private object[] test(byte[] a1, byte[] a2)
{
    string s1 = System.Text.Encoding.ASCII.GetString(a1);
    string s2 = System.Text.Encoding.ASCII.GetString(a2);
    int pos = s1.IndexOf(s2, StringComparison.Ordinal);
    return new object[] { (pos >= 0), pos };
}

사용 예 :

byte[] a1 = new byte[] { 24, 55, 74, 3, 1 };
byte[] a2 = new byte[] { 24, 56, 74 };
object[] result = test(a1, a2);
Console.WriteLine("{0}, {1}", result[0], result[1]); // prints "False, -1"
public class SubArrayMatch
{
    private bool _IsMatch;
    private int _ReturnIndex = -1;
    private List<byte> _Input;
    private List<byte> _SubArray;
    private bool _Terminate = false;
#region "Public Properties"
    public List<byte> Input {
        set { _Input = value; }
    }

    public List<byte> SubArray {
        set { _SubArray = value; }
    }

    public bool IsMatch {
        get { return _IsMatch; }
    }

    public int ReturnIndex {
        get { return _ReturnIndex; }
    }
#endregion
#region "Constructor"
    public SubArrayMatch(List<byte> parmInput, List<byte> parmSubArray)
    {
        this.Input = parmInput;
        this.SubArray = parmSubArray;
    }
#endregion
#region "Main Method"
    public void MatchSubArry()
    {
        int _MaxIndex;
        int _Index = -1;
        _MaxIndex = _Input.Count - 1;

        _IsMatch = false;

        foreach (byte itm in _Input) {
            _Index += 1;

            if (_Terminate == false) {
                if (SubMatch(_Index, _MaxIndex) == true) {
                    _ReturnIndex = _Index;
                    _IsMatch = true;
                    return;
                }
            }
            else {
                return;
            }
        }
    }

    private bool SubMatch(int BaseIndex, int MaxIndex)
    {
        int _MaxSubIndex;
        byte _cmpByte;
        int _itr = -1;

        _MaxSubIndex = _SubArray.Count - 1;
        _MaxSubIndex += 1;

        if (_MaxSubIndex > MaxIndex) {
            _Terminate = true;
            return false;
        }

        foreach (byte itm in _SubArray) {
            _itr += 1;

            _cmpByte = _Input(BaseIndex + _itr);

            if (!itm == _cmpByte) {
                return false;
            }
        }

        return true;
    }
#endregion

}

Anhar Hussain Miah '편집 : Anhar.miah @: 03/07/2009

PHP

105 년 ...

function a_m($h,$n){$m=strstr(join(",",$h),join(",",$n));return$m?(count($h)-substr_count($m,",")-1):-1;}        

또는 더 명시 적으로

function array_match($haystack,$needle){
  $match = strstr (join(",",$haystack), join(",",$needle));
  return $match?(count($haystack)-substr_count($match,",")-1):-1;
}

gnu c :

int memfind(const char * haystack, size_t haystack_size, const char * needle,
    size_t needle_size)
{
    const char * match = memmem(haystack, hasystack_size, needle, needle_size);
    return match ? match - haystack : -1;
}

라이브러리가없는 ansi c :

int memfind(const char * haystack, size_t haystack_size, const char * needle,
    size_t needle_size)
{
    size_t pos = 0;
    for(; pos < haystack_size; ++pos)
    {
        size_t i = 0;
        while(pos + i < haystack_size && i < needle_size &&
            haystack[pos + i] == needle[i]) ++i;

        if(i == needle_size) return pos;
    }

    return -1;
}

루비. 세계에서 가장 짧은 것은 아니지만 배열의 확장이기 때문에 시원합니다.

class Array
  def contains other=[]
    index = 0
    begin
      matched = 0
      ndx = index
      while other[matched] == self[ndx]
        return index if (matched+1) == other.length
        matched += 1
        ndx += 1
      end
    end until (index+=1) == length
    -1
  end
end

puts [ 63, 101, 245, 215, 0 ].contains [245, 215]
# 2
puts [ 24, 55, 74, 3, 1 ].contains [24, 56, 74 ]
# -1

C#, "A"및 "B"라는 목록 :

Enumerable.Range(-1, a.Count).Where(n => n == -1 
    || a.Skip(n).Take(b.Count).SequenceEqual(b)).Take(2).Last();

첫 번째 인스턴스를 반환하는 것이 신경 쓰지 않으면 다음과 같이 할 수 있습니다.

Enumerable.Range(-1, a.Count).Last(n => n == -1 
    || a.Skip(n).Take(b.Count).SequenceEqual(b));
int m(byte[]a,int i,int y,byte[]b,int j,int z){return i<y?j<z?a[i]==b[j++]?m(a,++i,y,b,j,z):m(a,0,y,b,j,z):-1:j-y;}

자바, 116 자. 약간의 추가 기능이 있습니다. 좋아, 따라서 시작 조건과 배열 길이를 발신자로 푸시하는 것은 kludge입니다. 다음과 같다고 부릅니다.

m(byte[] substring, int substart, int sublength, byte[] bigstring, int bigstart, int biglength)

처럼 프레드릭 문자열 변환 방식을 사용하여 이미 코드를 게시했습니다. C#을 사용하여 수행 할 수있는 또 다른 방법이 있습니다.

Jwoolard 나를 이겼다, btw. 나도 그가 가진 것과 같은 알고리즘을 사용했습니다. 이것은 대학에서 C ++를 사용하여 해결해야 할 문제 중 하나였습니다.

public static bool Contains(byte[] parent, byte[] child, out int index)
{
    index = -1;

    for (int i = 0; i < parent.Length - child.Length; i++)
    {
        for (int j = 0; j < child.Length; j++)
        {
            if (parent[i + j] == child[j])
                index = i;
            else
            {
                index = -1;
                break;
            }
        }
    }

    return (index >= 0);
}

LISP v1

(defun byte-array-subseqp (subarr arr)
  (let ((found (loop 
                  for start from 0 to (- (length arr) (length subarr))
                  when (loop 
                          for item across subarr
                          for index from start below (length arr)
                          for same = (= item (aref arr index))
                          while same
                          finally (return same))
                  do (return start))))
    (values (when found t) ; "real" boolean
            (or found -1))))

LISP v2 (NB, SubSeq는 사본을 만듭니다

(defun byte-array-subseqp (subarr arr)
  (let* ((alength (length arr))
         (slength (length subarr))
         (found (loop 
                   for start from 0 to (- alength slength)
                   when (equalp subarr (subseq arr start (+ start slength)))
                   do (return start))))
    (values (when found t)
            (or found -1))))

씨#:

public static object[] isSubArray(byte[] arr1, byte[] arr2) {
  int o = arr1.TakeWhile((x, i) => !arr1.Skip(i).Take(arr2.Length).SequenceEqual(arr2)).Count();
  return new object[] { o < arr1.Length, (o < arr1.Length) ? o : -1 };
}

루비에서 :

def subset_match(array_one, array_two)
  answer = [false, -1]
  0.upto(array_one.length - 1) do |line|
    right_hand = []
    line.upto(line + array_two.length - 1) do |inner|
      right_hand << array_one[inner]
    end
    if right_hand == array_two then answer = [true, line] end
  end
  return answer
end

예 : IRB (main) : 151 : 0> subset_match ([24, 55, 74, 3, 1], [24, 56, 74] => [false, -1

irb (main) : 152 : 0> subset_match ([63, 101, 245, 215, 0], [245, 215]) => [true, 2

C#, 평등 연산자가있는 모든 유형과 함께 작동합니다.

first
  .Select((index, item) => 
    first
     .Skip(index)
     .Take(second.Count())
     .SequenceEqual(second) 
    ? index : -1)
  .FirstOrDefault(i => i >= 0)
  .Select(i => i => 0 ? 
     new { Found = true, Index = i } 
    : 
     new { Found = false, Index - 1 });
(defun golf-code (master-seq sub-seq)
  (let ((x (search sub-seq master-seq)))
    (values (not (null x)) (or x -1))))

Haskell (114 Chars) :

import Data.List
import Data.Maybe
g a b | elem b $ subsequences a = fromJust $ elemIndex (head b) a | otherwise = -1

루비, 라의 코드를 본 후 부끄러워

def contains(a1, a2)
  0.upto(a1.length-a2.length) { |i| return i if a1[i, a2.length] == a2 }
  -1
end

문자열 비교를 사용하는 C# 버전은 다음과 같습니다. 그것은 올바르게 작동하지만 나에게 약간 해킹됩니다.

int FindSubArray(byte[] super, byte[] sub)
{
    int i = BitConverter.ToString(super).IndexOf(BitConverter.ToString(sub));
    return i < 0 ? i : i / 3;
}

// 106 characters
int F(byte[]x,byte[]y){int i=BitConverter.ToString(x)
.IndexOf(BitConverter.ToString(y));return i<0?i:i/3;}

다음은 각 개별 배열 요소를 실제 비교하는 약간 더 긴 버전입니다.

int FindSubArray(byte[] super, byte[] sub)
{
    int i, j;
    for (i = super.Length - sub.Length; i >= 0; i--)
    {
        for (j = 0; j < sub.Length && super[i + j] == sub[j]; j++);
        if (j >= sub.Length) break;
    }
    return i;
}

// 135 characters
int F(byte[]x,byte[]y){int i,j;for(i=x.Length-y.Length;i>=0;i--){for
(j=0;j<y.Length&&x[i+j]==y[j];j++);if(j>=y.Length)break;}return i;}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top