자체 검증 코드 작성


28

문자열을 입력으로 사용하고 문자열이 다음 규칙을 따르는 지 여부에 따라 참 또는 거짓 값을 출력하는 코드를 작성하십시오 .

각 문자를 서로 쌓아두면 바이너리로 변환하고 각 열을 합하면 모든 합이 동일해야합니다. 입력 문자열에 인쇄 가능한 ASCII 문자 (코드 포인트 32-126) 만 포함되어 있다고 가정 할 수 있습니다.

예로서:

O5vy_+~이진 표현은 다음과 같으므로 입력 값이 참된 값을 반환해야합니다.

1001111  | O
0110101  | 5
1110110  | v
1111001  | y
1011111  | _
0101011  | +
1111110  | ~
-------
5555555  <- Sum of bits in each column. Should give a truthy value.

PPCG이진 표현은 다음과 같으므로 입력 은 잘못된 값을 반환해야합니다.

1010000  | P
1010000  | P
1000011  | C
1000111  | G
-------
4020122  <- Should give a falsey value

트위스트는 : 코드가 함수 / 프로그램의 입력으로 사용되는 경우 정확한 값을 반환해야합니다. 즉, 코드는 위와 동일한 규칙을 준수해야합니다 (코드에는 ASCII 32-126이 아닌 문자가 포함될 수 있음).

프로그램 / 기능은 인쇄 가능한 ASCII 만 입력으로 처리해야합니다. 코드에 8 비트, 16 비트 인코딩, 유니 코드, 사용자 정의 문자 세트 (또는 다른 것)가 포함 된 경우 이진 표현은 동일한 규칙을 준수해야하지만 코드를 처리 할 필요는 없습니다. 입력으로.

이것은 이므로 표준 규칙이 적용됩니다.


입력 문자열은 얼마나 걸립니까? 합계의 길이가 항상 7 자리라고 가정 할 수 있습니까?
Okx

또한 프로그램에서 ASCII 문자 이외의 문자를 사용하면 어떻게됩니까?
Okx

"그런 다음 이진 표현은 동일한 규칙을 준수해야합니다"라는 문구는 "인쇄 가능한 ASCII 만 입력으로 처리해야합니다"라는 문구를 명시 적으로 배제해야합니다. .
Jonathan Allan

@ Okx 입력 문자열이 1kB 미만이라고 가정 할 수 있습니다. 입력은 7 비트를 사용하여 표시 할 수있는 인쇄 가능한 ASCII 만 가능하므로 예 : 항상 7 개의 정수 (숫자 일 필요는 없음) 합계가 있습니다.
Stewie Griffin

2
@StewieGriffin 매우 명확한 설명이 아닙니다. 비 ASCII 응답이 있고 프로그램을 프로그램에 입력하려고했는데 ASCII 만 지원하기 때문에 작동하지 않으면 어떻게됩니까?
Okx

답변:


10

자바 스크립트 (ES6) 123 122 120 110 바이트

S=>[...S].map(S=>R.map((_GSSSSSSVWWW,V)=>R[V]-=S.charCodeAt()>>V&1),R=[_=3^3,_,_,_,_,_,_])&&!R.some(S=>S^R[_])

아래는 비트 합계가있는 16 진 덤프입니다.

Addr. | Dump                                            | #6 #5 #4 #3 #2 #1 #0
------+-------------------------------------------------+---------------------
00-0F | 53 3D 3E 5B 2E 2E 2E 53 5D 2E 6D 61 70 28 53 3D |  8 11  9 11  9  9  9
10-1F | 3E 52 2E 6D 61 70 28 28 5F 47 53 53 53 53 53 53 | 20 18 19 17 14 20 19
20-2F | 56 57 57 57 2C 56 29 3D 3E 52 5B 56 5D 2D 3D 53 | 30 24 32 25 26 30 29
30-3F | 2E 63 68 61 72 43 6F 64 65 41 74 28 29 3E 3E 56 | 41 37 37 32 34 38 36
40-4F | 26 31 29 2C 52 3D 5B 5F 3D 33 5E 33 2C 5F 2C 5F | 47 47 48 43 44 47 46
50-5F | 2C 5F 2C 5F 2C 5F 2C 5F 5D 29 26 26 21 52 2E 73 | 54 57 55 54 56 56 54
60-6D | 6F 6D 65 28 53 3D 3E 53 5E 52 5B 5F 5D 29       | 64 64 64 64 64 64 64

데모


10

MATL , 10 9 바이트

BXs&=?I&]

입력은 작은 따옴표로 묶은 문자열입니다 (입력에 단일 qout이 포함 된 경우 복제하여 이스케이프 처리).

출력은 3진실이며 거짓과 같은 것은 없습니다 (빈 출력).

온라인으로 사용해보십시오!

이진 코드는 다음과 같습니다.

B     1 0 0 0 0 1 0
X     1 0 1 1 0 0 0
s     1 1 1 0 0 1 1
&     0 1 0 0 1 1 0
=     0 1 1 1 1 0 1
?     0 1 1 1 1 1 1
I     1 0 0 1 0 0 1
&     0 1 0 0 1 1 0
]     1 0 1 1 1 0 1

Sum   5 5 5 5 5 5 5

설명

B      % Input string (implicit). Convert each char to its ASCII code, and 
       % then to binary. This gives a binary matrix, with each char of the 
       % input corresponding to a row
Xs     % Sum of each column. Gives a row vector
&=     % All pairwise equality comparisons
?      % If all are true
  I    %    Push 3
  &    %    Specify that the next function, namely implicit display, will 
       %    take one input, instead of the whole stack which is the default
]      % End
       % Display (implicit)

8

젤리 , 11 10 바이트

OBUSE&889.

온라인으로 사용해보십시오! 또는 테스트 및 자체 입력을 참조하십시오(코드는 모두 인쇄 가능한 ASCII이며 Jelly의 코드 페이지 에서 동일한 값을 갖습니다 (아래 참조)).

Char -> Hex -> Decimal -> Binary
O       0x4F   79         0b1001111
B       0x42   66         0b1000010
U       0x55   85         0b1010101
S       0x53   83         0b1010011
E       0x45   69         0b1000101
&       0x26   38         0b0100110
8       0x38   56         0b0111000
8       0x38   56         0b0111000
9       0x39   57         0b0111001
.       0x2E   46         0b0101110
                            -------
                            5555555

방법?

OBUSE&889. - Main link: string
O          - cast to ordinals
 B         - convert to binary
  U        - upend (reverses each to prepare for vectorised sum)
   S       - sum (vectorises)
    E      - all equal? (yields 1 if all bit-sums are equal and 0 if not)
      889. - 889.0
     &     - bitwise and (1 & 889.0 is 1; and 0 & 889.0 is 0)

Your code looks much like Dennis's.
Erik the Outgolfer

Yeah, I saw after.
Jonathan Allan

6

Jelly, 11 10 bytes

OBUSE$*8?8

Uses no no-ops or comments.

Try it online!

Binary breakdown

O  1 0 0 1 1 1 1
B  1 0 0 0 0 1 0
U  1 0 1 0 1 0 1
S  1 0 1 0 0 1 1
E  1 0 0 0 1 0 1
$  0 1 0 0 1 0 0
*  0 1 0 1 0 1 0
8  0 1 1 1 0 0 0
?  0 1 1 1 1 1 1
8  0 1 1 1 0 0 0
————————————————
∑  5 5 5 5 5 5 5

How it works

OBUSE$*8?8  Main link. Argument: s (string)

O           Ordinal; map all characters in s to their code points.
 B          Binary; convert each code point to base 2.
  U         Upend; reverse each binary array to right-align the digits.
       8?   If 8 is non-zero (it is):
   SE$          Sum the corresponding digits and test the the sums for equality.
            Else (never happens):
      *  8      Raise all binary digits to the eighth power.

Is Jelly TC using only printable ASCII?
Pavel

I don't think so.
Dennis

1
I like that this code starts with OBUSE because it sounds like ABUSE.
Esolanging Fruit

4

Mathematica, 88 bytes

Total@IntegerDigits[ToCharacterCode@#,2,7]~MatchQ~{"?";a_ ..}&

Contains many unprintable characters between the quotes. Has 49 of each bit.

Here's the hexdump:

0000-0010:  54 6f 74 61-6c 40 49 6e-74 65 67 65-72 44 69 67  Total@In tegerDig
0000-0020:  69 74 73 5b-54 6f 43 68-61 72 61 63-74 65 72 43  its[ToCh aracterC
0000-0030:  6f 64 65 40-23 2c 32 2c-37 5d 7e 4d-61 74 63 68  ode@#,2, 7]~Match
0000-0040:  51 7e 7b 22-3f 1f 1f 1f-1f 1f 1f 1f-1f 1f 1f 1f  Q~{"?... ........
0000-0050:  1f 1f 1f 1f-1f 1a 1a 1a-1a 18 18 18-18 18 10 22  ........ ......."
0000-0058:  3b 61 5f 20-2e 2e 7d 26                          ;a_...}&

4

Octave, 53 52 bytes

Making a complete rewrite helped me golf the code 5 bytes, but I had to add more no-ops, making it a net-save of only 1 byte.

@(_)~diff(sum(de2bi(+_)))%RRPPPVVVW?????????________

I can't add a TIO-link, since none of the online interpreters have implemented the communication toolbox necessary for de2bi. Changing it to dec2bin instead would cost 4 bytes (2 for working code, and two no-ops).

I found no way to avoid any of the 27 no-ops. All function names and parentheses are between either below 64, or higher than 96, meaning all "necessary" characters have a 1 in the 6th position (from the right, 2^5). I had a solution with only 23 no-ops, but the code itself was longer. The actual code is 25 bytes, and has the following column sum when counting the bits of the binary equivalent:

15   22    6   15   10    9   13

There are 22 bits in the 6th position from the right (2^5), and only 6 bits in the 4th position from the right (2^3). That means, we have to add at least 16 bytes, to get the 6 up to 22. Now, the comment character % adds a bit to the 6th position, increasing it to 23. All printable ASCII-characters needs at least one of the two top bits to be 1. Therefore, adding 17 bytes will give us at least 27 bits in each of the two "top spots" (2^6 and 2^5). Now, we have 27 bits in the top two spots, and 22 in the rest. In order to get to an equilibrium, we have to add 10 bytes, to get to an even 32 bits in each position.

An explanation of the new code (52 bytes):

@(_)~diff(sum(de2bi(+_)))
@(_)      % An anonymous function that take a variable _ as input
          % We use underscore, instead of a character, since it has the
          % most suitable binary represetation
              de2bi(+_)    % Convert the input string to a binary matrix
          sum(de2bi(+_))   % Take the sum of each column
     diff(sum(de2bi(+_)))  % And calculate the difference between each sum
    ~diff(sum(de2bi(+_)))  % Negate the result, meaning 0 becomes true, 
                           % and everything else becomes false

A vector containing only 1s (true) is evaluated to true in Octave, and a vector containing at least one zero is evaluated to false in Octave.

An explanation of the old code (53 bytes):

@(_)!((_=sum(de2bi(+_)))-_(1))%RRRFVVVVVVVVV_____????

@(_)      % An anonymous function that take a variable _ as input
          % We use underscore, instead of a character, since it has the
          % most suitable binary represetation
    !     % Negate the result, meaning 0 becomes true, and everything else becomes false
        de2bi(+_)         % Convert the input string to a binary matrix
    sum(de2bi(+_))        % Take the sum of each column
 (_=sum(de2bi(+_)))       % Assign the result to a new variable, also called _
                          % It's not a problem that we use the same variable name, due
                          % to the order of evaluation
((_=sum(de2bi(+_)))-_(1)) % Subtract the first element of the new variable _
                          % If all elements of the new variable _ are identical, then this
                          % should give us a vector containing only zeros,
                          % otherwise, at least one element should be non-zero
!((_=sum(de2bi(+_)))-_(1))  % And finally, we negate this.

A vector containing only 1s (true) is evaluated to true in Octave, and a vector containing at least one zero is evaluated to false in Octave.


3

JavaScript (ES6), 139 111 107 bytes

f=
S=>![...""+1E6].some((____________ABQWWWWWWWWW,P)=>P*=R^(R^=R,[...S].map(Q=>R+=Q.charCodeAt()>>P&1),R),R=0)
<textarea oninput=o.textContent=f(this.value) style=width:100% rows=10>S=>![...""+1E6].some((____________ABQWWWWWWWWW,P)=>P*=R^(R^=R,[...S].map(Q=>R+=Q.charCodeAt()>>P&1),R),R=0)</textarea><div id=o>true

Contains 81 63 61 of each bit.


2

Scala, 149 bytes

_.map(C=>("0"*7++(BigInt(C)toString 2))takeRight 7 map(_-48)).transpose.map(_.sum).toSet.size==1//______________________________

Usage:

val f:(String=>Any)=_.map(C=>("0"*7++(BigInt(C)toString 2))takeRight 7 map(_-48)).transpose.map(_.sum).toSet.size==1//______________________________
println(f("string here")

Hexdump:

00000000  5f 2e 6d 61 70 28 43 3d  3e 28 22 30 22 2a 37 2b  |_.map(C=>("0"*7+|
00000010  2b 28 42 69 67 49 6e 74  28 43 29 74 6f 53 74 72  |+(BigInt(C)toStr|
00000020  69 6e 67 20 32 29 29 74  61 6b 65 52 69 67 68 74  |ing 2))takeRight|
00000030  20 37 20 6d 61 70 28 5f  2d 34 38 29 29 2e 74 72  | 7 map(_-48)).tr|
00000040  61 6e 73 70 6f 73 65 2e  6d 61 70 28 5f 2e 73 75  |anspose.map(_.su|
00000050  6d 29 2e 74 6f 53 65 74  2e 73 69 7a 65 3d 3d 31  |m).toSet.size==1|
00000060  2f 2f 5f 5f 5f 5f 5f 5f  5f 5f 5f 5f 5f 5f 5f 5f  |//______________|
00000070  5f 5f 5f 5f 5f 5f 5f 5f  5f 5f 5f 5f 5f 5f 5f 5f  |________________|
00000080  1f 1f 1f 1f 1e 1e 1e 1e  16 16 16 16 16 12 12 10  |................|
00000090  10 10 10 10 10                                    |.....|

Ungolfed:

string =>
  string.map(char =>
    (
      "0" * 7 ++ BigInt(char).toString(2)
    ).takeRight(7).map(n=>n-48)
  ).transpose
  .map(bits=>bits.sum)
  .toSet
  .size == 1
  //______________________________

Explanation:

string =>                      //create an anonymous function with a parameter string
  string.map(char =>           //map each char in the string to
    (
      "0" * 7                  //a string of 7 zeroes
      ++                       //concatenated with
      BigInt(char).toString(2) //the ascii value as a binary string
    ).takeRight(7)             //the last 7 items from this sequence
    .map(n=>n-48)              //where each digit is mapped to its numerical value
  ).transpose                  //transpose, so the colums become rows and vice-versa
  .map(bits=>bits.sum)         //maps the bits in each column to their sum
  .toSet                       //and convert the sequence of sums to a set
  .size == 1                   //which has 1 element of the sums are the same
  //______________________________

1

J, 45 bytes

[:(*/@:={.)[:+/2 #.inv 3 u:]NB.____UUUUUUUUDD

Try it online! Includes test cases for most submissions submitted, along with the source code.


1

Haskell, 118 bytes

_R _S=mod _S 2:_R(div _S 2)
_Z _S|_V:_W<-take 7.foldl1(zipWith(+))$_R.fromEnum<$>_S=all(==_V)_W
--________

Try it online! Usage: _Z "some string" returns either True or False.

There are some unprintable chars in the comment on the last line, so here is a string of the program using escaped chars:

"_R _S=mod _S 2:_R(div _S 2)\n_Z _S|_V:_W<-take 7.foldl1(zipWith(+))$_R.fromEnum<$>_S=all(==_V)_W\n--___\US\US\US\ETB\DC3\DC3\DC3\DC3\DC3\DC3\DC2\DC2_____"

Each bit occurs 68 times.


The shortest code I came up with was 82 bytes:

b n=mod n 2:b(div n 2)
(all=<<(==).head).take 7.foldl1(zipWith(+)).map(b.fromEnum)

However the sums of the bits for this code are [33,28,41,48,20,79,46], so 79 - 20 = 59 no-ops plus 2 bytes for starting a comment would additionally be needed, totalling in 143 bytes.

While rearranging the program I found that using upper case letters as variable names helps to level the sums because they don't have the bit in the 6th position set. Because Haskell does not allow variable names to start with an upper case letter they need to be prepended with _, which also does not set the 6th bit.

In doing so I ended up with the above solution which has 97 bytes before adding the no-ops and the bist sum to [50,47,56,56,48,68,60], so (68 - 47) = 21, so only 21 bytes need to be added in the comment.


1

PHP, 95 93 91 bytes

I am so happy that PHP function names are case insensitive!

FOR(ZZSSSSQ__*;$W=ORD($argn[$T++]);)FOR($V=7;$V--;)$R[$V]+=$W>>$V&1;PRINT MIN($R)==MAX($R);

where the * must be replaced with ASCII 151 (0x97). (PHP would complain about any control character in the code - apart from \r and \n, but I need something with bit 4 set, so I added 128.)

+1 byte for pure printable ASCII: Use _7 instead.

Run with echo '<input>' | php -nR '<code>' or test it online. Output is 1 for truthy, empty for falsy.


0

Python 2, 117 bytes

All "spaces" are tabs to reduce number of 0x20 bits.

def Y(S):
    O=map(sorted,zip(*['{:07b}'.format(ord(W))for   W   in  S]))
    return  O[1:]==O[:-1]#V_____________

Contains 66 of each bit. (There is no '%07b' as explained in this issue.)

Hex dump:

00000000: 64 65 66 09 59 28 53 29 3a 0a 09 4f 3d 6d 61 70  def.Y(S):..O=map
00000010: 28 73 6f 72 74 65 64 2c 7a 69 70 28 2a 5b 27 7b  (sorted,zip(*['{
00000020: 3a 30 37 62 7d 27 2e 66 6f 72 6d 61 74 28 6f 72  :07b}'.format(or
00000030: 64 28 57 29 29 66 6f 72 09 57 09 69 6e 09 53 5d  d(W))for.W.in.S]
00000040: 29 29 0a 09 72 65 74 75 72 6e 09 4f 5b 31 3a 5d  ))..return.O[1:]
00000050: 3d 3d 4f 5b 3a 2d 31 5d 23 56 5f 5f 5f 5f 5f 5f  ==O[:-1]#V______
00000060: 5f 5f 5f 5f 5f 5f 5f 16 16 16 16 16 16 16 16 16  _______.........
00000070: 16 16 14 14 10                                   .....

If you read the description of the bug report... "resolution: not a bug".
mbomb007
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.