Половина помилок


19

Завдання

Враховуючи не порожній масив 0та 1, вдвічі зменшити довжину прогонів 0.

Вхідні дані

Масив 0і 1. Прийнятний формат:

  • Справжній масив вашої мови
  • Рядок з розділеним рядком 0і1
  • Суміжний рядок 0і1
  • Будь-який інший розумний формат

Наприклад, прийнятні наступні три входи:

  • [1, 0, 0, 1]
  • "1\n0\n0\n1"(де \nліній подачі ліній U + 000A)
  • "1001"

Можна припустити, що пробіги 0будуть мати рівну довжину .

Вихідні дані

Масив 0та 1у прийнятних форматах вище.

Тестові шафи

input ↦ output
[1,0,0,1,0,0,1] ↦ [1,0,1,0,1]
[1,1,0,0,1,1,0,0,1] ↦ [1,1,0,1,1,0,1]
[1,1,0,0,1,1,1,0,0,1,1] ↦ [1,1,0,1,1,1,0,1,1]
[1,1,1] ↦ [1,1,1]
[0,0,1] ↦ [0,1]
[0,0] ↦ [0]
[1,1,1,0,0,0,0,1,1,1,1,0,0,1,0,0,1,1,0,0,1,1,1,1,0,0,1,0,0] ↦ [1,1,1,0,0,1,1,1,1,0,1,0,1,1,0,1,1,1,1,0,1,0]

Оцінка балів

Це . Найкоротша відповідь у байтах виграє.

Застосовуються стандартні лазівки .


В останньому тесті, чи не мають пробіги нулів рівну довжину?
OldBunny2800

@ OldBunny2800 Уважно прочитайте тестовий випадок; 0-прогони мають довжини 4, 2, 2, 2, 2 і 2.
HyperNeutrino

Чи можемо ми взяти trueі falseзамість 1і 0?
Кіос

@Cyoce, якою мовою?
Лина монашка

@LeakyNun Ruby, який розглядає 0 правдою.
Cyoce

Відповіді:



11

05AB1E , 5 байт

00¤.:

Спробуйте в Інтернеті!

Пояснення

00     # push 00
  ¤    # tail, pushes 0
   .:  # replace

2
Це було легко; чому я не придумав цього?
Leaky Nun

00це дивна поведінка ...
Ерік Атголфер

@EriktheOutgolfer: Послідовні цифри об'єднані, щоб утворити число, тому 11одинадцять, а не 1,1. Побічним ефектом цього є те, що 00стає 00замість 0,0:)
Emigna

@Emigna Я б очікував, що це стане 0або 0 0замість цього, але як би там не було.
Erik the Outgolfer


7

C (gcc) , 35 байт

f(char*s){while(*s)putchar(*s),*s++-48?:s++;}

48 - код асції "0"

краща версія 43 байти, як запропонував Ніл

f(char*s){while(*s)putchar(*s),s+=2-*s%2;}

ще 40 байт цього разу (знову, як запропонували Neil & VisualMelon) :)

f(char*s){for(;*s;s+=50-*s)putchar(*s);}

а потім 35 байт завдяки Khaled.K

f(char*s){*s&&f(s+50-putchar(*s));}

Спробуйте в Інтернеті!


1
Було б s+=2-*s%2працювати?
Ніл

1
Якщо я правильно порахував, я думаю, що це for(;*s;s+=2-*s%2)putchar(*s);економить ще один байт.
Ніл

1
Що було б не так s+=50-*s? Не робиться C протягом віків і не хочу бентежити себе, використовуючи невизначене поведінку (що надходить із C #, де її немає)
VisualMelon

1
Дивлячись на putcharдокументи, ви можете це зробити f(char*s){for(;*s;s+=50-putchar(*s));}?
VisualMelon

3
Ви можете зберегти 5 байтів, зробивши це рекурсивноf(char*s){*s&&f(s+50-putchar(*s));}
Khaled.K



6

Java, 50 байт

String f(String s){return s.replaceAll("00","0");}

Спробуйте в Інтернеті


1
Дуже вдалий вибір входу! До речі, якщо ви зацікавлені в переході на Java 8+ рішення можна використовувати лямбда: s->s.replaceAll("00","0").
Якоб

Ще краще скористайтеся replaceзамість того, replaceAllщоб зберегти 3 байти
Бенджамін Уркхарт

@BenjaminUrquhart replaceзамінить лише перше явище
Khaled.K

@ Khaled.K у javascript, так. У Java вона замінює всі події
Бенджамін Уркхарт

5

Haskell , 28 байт

f(h:t)=h:f(drop(1-h)t)
f e=e

Спробуйте в Інтернеті!

Рекурсивно приймає перший елемент, скидаючи другий, якщо перший - нуль, поки список порожній не буде. Якщо перший запис є h, то перший 1-hвипадає з решти.


5

Japt , 7 6 5 байт

d'0²0

Спробуйте в Інтернеті!

Просто замінює кожен пробіг двох нулів на вході на один нуль. Використовується рядок введення (тобто "1001001").


1
Приємно! Вам навіть не потрібно 'я думаю
ETHproductions

О, ви можете зберегти ще один байт, замінивши "00"на '0²:-)
ETHproductions

Ну, це дивно. Дякую, хоча!
Лука


4

Аліса , 13 байт

/oe00/
@iS0e\

Спробуйте в Інтернеті!

Пояснення

/.../
@...\

Це простий шаблон для лінійних програм, які повністю працюють в звичайному режимі. Початковий /відображає IP для переміщення на південний схід, а потім він відскакує по діагоналі вгору та вниз через код, поки дзеркала в кінці. Вони просто зміщують позицію на одну, так що на зворотному шляху IP-адреса проходить решту комірок. Читаючи код цим зигзагоподібним способом, він стає:

ie00e0So@

Це проста підстановка рядків:

i   Read all input.
e   Push an empty string.
00  Append two zeros to create the string "00".
e   Push an empty string.
0   Append a zero to create the string "0".
S   Substitute all occurrences of "00" in the input with "0".
o   Output the result.   
@   Terminate the program.

Існує кілька інших способів просунути два рядки, наприклад, '00'0або e000t, але я не знайшов там нічого, що б'є 5 байтів (і мені доведеться поголити два байти, щоб скоротити програму).


2
Схоже, ти нещодавно закохався в Алісу ...
Лина монашка

6
@LeakyNun Будь ласка, не кажіть моїй дружині ...
Мартін Ендер

@MartinEnder Я скажу це пані Ендер!
Ерік Аутгольфер



3

JavaScript (ES6), 26 21 байт

Приймає введення як рядок і повертає рядок.

s=>s.replace(/00/g,0)

Спробуй це

f=
s=>s.replace(/00/g,0)
i.addEventListener("input",_=>o.innerText=f(i.value))
console.log(f("1001001")) // "10101"
console.log(f("110011001")) // "1101101"
console.log(f("11001110011")) // "110111011"
console.log(f("111")) // "111"
console.log(f("001")) // "01"
console.log(f("00")) // "0"
console.log(f("11100001111001001100111100100")) // "1110011110101101111010"
<input id=i><pre id=o>


3

Луа, 33 байти

print((io.read():gsub("00","0")))

Бере рядок через введення та конденсує подвійні нулі. Легко.


3

Желе , 8 байт

ṣ1j1,1m2

Спробуйте в Інтернеті!

Можливо, інші відповіді мовами без .replace()або подібних можуть використати цю хитрість.

Пояснення

ṣ1j1,1m2 - (duplicates the 1s, then halves all lengths)
ṣ1       - split by the element 1
  j1,1   - join the elements with the two-element list 1,1
      m2 - get every second element

3

Аліса , 12 10 байт

2 байти збережено завдяки Мартіну Ендеру

i.h%.7%$io

Спробуйте в Інтернеті!

Пояснення

Це 1-D код, який працює в кардинальному режимі, тому легко стежити за його потоком:

i                   Read a byte from input (pushes -1 on EOF)
 .h                 Duplicate it and add 1 to the copy
   %                Compute n%(n+1). This will exit with an error on n==-1
                    and return n for any non-negative n.
    .7%             Duplicate the input again and compute its value modulo 7
                    This returns 6 for '0' (unicode value 48) and 0 for '1'
                    (unicode value 49)
       $i           If this last result was not 0, input another number.
                    This ignores every other '0' in the input
                    and moves to the following number (another '0')
         o          Output the last byte read

                    At the end, wrap back to the beginning of the line

Насправді ви можете зберегти ще два байти за допомогоюi.h%...
Мартін Ендер

@MartinEnder ти зла людина, збираючись навчити людей грати брудно ...: D
Лев

2

Python (список вводу / виводу), 36 байт

f=lambda l:l and l[:1]+f(l[2-l[0]:])

Спробуйте в Інтернеті!

Рекурсивно приймає перший елемент, а потім видаляє решту, якщо перший був нульовим.


38 байт:

lambda l:eval(`l`.replace('0, 0','0'))

Спробуйте в режимі он-лайн. Це займає список Python і виводить список Python, здійснюючи заміну на його рядковому поданні. Рядок вводу / виводу дозволить більш пряме і коротше рішення, як-от

lambda s:s.replace('00','0')

для '1001' формату.


The first answer with format specified, nice.
Leaky Nun

1
String I/O is allowed. lambda s:s.replace('00','0') should be fine.
Jonathan Allan


2

Perl 5, 7+1(-p flag)=8 bytes

<>if/0/

Takes input as newline separated numbers. Skips the next line if it sees a zero.



2

MATL, 5 bytes

FFOZt

Try it online!

Explanation

This is similar to Stewie Griffin's Octave answer:

FF     % Push [0 0]
O      % Push 0
Zt     % Implicitly take input. Replace [0 0] by 0. Implicitly display

8 bytes

vy~f2L)(

This avoids the string/array replacement builtin.

Try it online!

Explanation

Consider input [1,0,0,1,0,0,1] as an example:

v      % Concatenate stack (which is empty): pushes []
       % STACK: []
y      % Implicit input. Duplicate from below
       % STACK: [1,0,0,1,0,0,1], [], [1,0,0,1,0,0,1]
~f     % Negate, find: gives indices of zeros
       % STACK: [1,0,0,1,0,0,1], [], [2,3,5,6]
2L     % Push [2,2,1i]. As an index, this is interpreted as 2:2:end
       % STACK: [1,0,0,1,0,0,1], [], [2,3,5,6], [2,2,1i]
)      % Reference indexing. This selects the even-indexed entries
       % STACK: [1,0,0,1,0,0,1], [], [3,6]
(      % Assignment indexing. This deletes the specified entries
       % (assigns them the empty array). Implicitly display
       % STACK: [1,0,1,0,1]

1

Brachylog, 10 bytes

ḅ{cẹ|ḍh}ᵐc

Try it online!

Not sure this is optimal yet…

Explanation

This exploits the bug that c on a list of integers that has leading zeroes will fail.

ḅ               Blocks; group consecutive equal elements together
 {     }ᵐ       Map on each block:
  c               It is possible to concatenate the block into an int (i.e. it contains 1s)
   ẹ              Split it again into a list of 1s
    |             Else
     ḍh           Dichotomize and take the head
         c      Concatenate the blocks into a single list

How is that a bug?
Leaky Nun

@LeakyNun We should be able to concatenate [0,0,4,2] into 42. Leading zeroes make it fail right now because it's here to prevent infinite leading zeroes when the Input is a variable, but here the Input is fully grounded so that limitation shouldn't exist.
Fatalize

Would you write a Prolog answer?
Leaky Nun

1

C#, 191 bytes

string a(string s){var l=(s+'1').ToCharArray();s="";int b=0;for(int i=0;i<l.Length;i++){if(l[i]=='1'){if(b>0){s+=new string('0',b/2);b=0;}s+=l[i];}else b++;}return s.Substring(0,s.Length-1);}

Try it online!

It's neither clean nor short, but it works.

Takes input as a contiguous string of characters, outputs in the same format

Explanation:

string a(string s){                  //Define method a that takes input string s and returns a string
  var l=(s+'1').ToCharArray();       //Add a 1 to the end of s and split into char array l
  s="";                              //Empty s
  int b=0;                           //Initialize int b with value 0
  for(int i=0;i<l.Length;i++){       //Loop through l
    if(l[i]=='1'){                   //If current char is 1
      if(b>0){                       //If b is not 0
        s+=new string('0',b/2);      //Add half the amount of 0s we've counted to s
        b=0;                         //Reset b
      }                              //End if b is not 0
      s+=l[i];                       //Add current char to s
    }                                //End if current char is 1
    else b++;                        //If current char is not 1, increment b
  }                                  //End loop
  return s.Substring(0,s.Length-1);  //Return string minus last char
}                                    //End method

Note

Yes I am aware this could simply be done using s.Replace("00","0"), my aim was to avoid using the obvious solution. After all, the whole point of PPCG is to have fun, right? ;)


@Mr.Xcoder That's not true. This is about as golfed as you can get without using the language's built-in Replace I'm using C# so I'm under no delusions about getting the shortest possible code, especially with languages like Jelly around, so might as well have a little fun in the process.
Skidsdev

of course fun is important as well. I apologise for the comment above and I must admit I liked your answer myself (the technique you used).
Mr. Xcoder

@Mr.Xcoder no hard feelings, ultimately we're all here to have fun and flex our otherwise useless ability to compress code as much as possible ;)
Skidsdev

You can do a lot shorter than this without replace! string a(string s){var r="";for(int i=0;i<s.Length;i+=50-s[i])r+=s[i];return r;} (looks like this is basically the C answer)
VisualMelon

1

Pyth, 8 bytes

:z"00"\0

Try-it link.

Explanation:

:z"00"\0 Takes unquoted contiguous 1-line input.
 z       Initialized to unevaluated first input line (Q won't be any shorter)
  "00"   Matching regex pattern /00/g
      \0 Substitution string "0"
:        Regex find-and-replace

1

Awk - 18 bytes

First try doing anything with Awk so it might be possible to golf it more.

{gsub(00,0);print}

Usage: echo "1001001" | awk '{gsub(00,0);print}'


1

Batch, 24 bytes

@set/ps=
@echo %s:00=0%

Takes input on STDIN. Somewhat competitive for once.


1

Common Lisp, SBCL, 48 32 bytes

-16 bytes thanks to Julian Wolf

(format t"~{~[0~*~;1~]~}"(read))

input:

(1 0 0 0 0 1 1 1 0 0)

output:

1001110

Explanation

We read input list. List is used in format function. We loop through it outputting 1 if element is 1 and outputting 0 and skipping next element of list for 0.


Using ~[ rather than ~:[ lets you index with 0 and 1 directly, which should save you a bunch of bytes
Julian Wolf

@JulianWolf Thank you!

1

Mathematica, 24 bytes

StringReplace["00"->"0"]

A function that expects a string of "0"s and "1"s and returns a similar string. Self-explanatory syntax. Mathematica has lots of transformation builtins; the key is to use one that transforms every relevant subexpression (unlike /.) but only passes through the expression once (unlike //.).


1

Jelly, 10 bytes

Œg¹m2$S?€F

Try it online!

Explanation

Œg¹m2$S?€F
Œg          - Group runs of equal elements
        €   - To each run...
      S?    - If sum is truthy,
  ¹         -   return the run as it is
   m2$      - Else return every second element of the run.
Використовуючи наш веб-сайт, ви визнаєте, що прочитали та зрозуміли наші Політику щодо файлів cookie та Політику конфіденційності.
Licensed under cc by-sa 3.0 with attribution required.