Talk interpreter

9

2

"Talk" is a baroquified accumulator-based language that is created in response to Dennis's quote on talk.tryitonline.net.

Waiting for someone to create an esolang called talk. 

. The "Talk" language has 4 commands:

  • 00 If the accumulator is 0, set the accumulator to 0.
  • 01 If the accumulator is 0, set the accumulator to 1.
  • 10 If the accumulator is 1, set the accumulator to 0.
  • 11 If the accumulator is 1, set the accumulator to 1.

Input:

  • The input can be taken via any acceptable input method by our standard I/O rules.

  • There are two inputs, the initial accumulator value and the program. You can merge these two inputs into one input or split your input into valid commands (e.g. taking them as a list; e.g. [00, 01, 00]) if you like.

Output:

  • On the end of a command execution, the accumulator is outputted implicitly.

Rules:

  • The input can be a single string or character list.
  • As this is , the shortest answer, in bytes, wins.
  • We take digits or strings/characters.

    Test cases:

0 0001111101 -> 1
0 000100 -> 1
0 11001000 -> 0

Leaderboards

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

# Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

# Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

# Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the leaderboard snippet:

# [><>](http://esolangs.org/wiki/Fish), 121 bytes

var QUESTION_ID=190819;
var OVERRIDE_USER=8478;
var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(d){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(d,e){return"https://api.stackexchange.com/2.2/answers/"+e.join(";")+"/comments?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){answers.push.apply(answers,d.items),answers_hash=[],answer_ids=[],d.items.forEach(function(e){e.comments=[];var f=+e.share_link.match(/\d+/);answer_ids.push(f),answers_hash[f]=e}),d.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){d.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),d.has_more?getComments():more_answers?getAnswers():process()}})}getAnswers();var SCORE_REG=function(){var d=String.raw`h\d`,e=String.raw`\-?\d+\.?\d*`,f=String.raw`[^\n<>]*`,g=String.raw`<s>${f}</s>|<strike>${f}</strike>|<del>${f}</del>`,h=String.raw`[^\n\d<>]*`,j=String.raw`<[^\n<>]+>`;return new RegExp(String.raw`<${d}>`+String.raw`\s*([^\n,]*[^\s,]),.*?`+String.raw`(${e})`+String.raw`(?=`+String.raw`${h}`+String.raw`(?:(?:${g}|${j})${h})*`+String.raw`</${d}>`+String.raw`)`)}(),OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(d){return d.owner.display_name}function process(){var d=[];answers.forEach(function(n){var o=n.body;n.comments.forEach(function(q){OVERRIDE_REG.test(q.body)&&(o="<h1>"+q.body.replace(OVERRIDE_REG,"")+"</h1>")});var p=o.match(SCORE_REG);p&&d.push({user:getAuthorName(n),size:+p[2],language:p[1],link:n.share_link})}),d.sort(function(n,o){var p=n.size,q=o.size;return p-q});var e={},f=1,g=null,h=1;d.forEach(function(n){n.size!=g&&(h=f),g=n.size,++f;var o=jQuery("#answer-template").html();o=o.replace("{{PLACE}}",h+".").replace("{{NAME}}",n.user).replace("{{LANGUAGE}}",n.language).replace("{{SIZE}}",n.size).replace("{{LINK}}",n.link),o=jQuery(o),jQuery("#answers").append(o);var p=n.language;p=jQuery("<i>"+n.language+"</i>").text().toLowerCase(),e[p]=e[p]||{lang:n.language,user:n.user,size:n.size,link:n.link,uniq:p}});var j=[];for(var k in e)e.hasOwnProperty(k)&&j.push(e[k]);j.sort(function(n,o){return n.uniq>o.uniq?1:n.uniq<o.uniq?-1:0});for(var l=0;l<j.length;++l){var m=jQuery("#language-template").html(),k=j[l];m=m.replace("{{LANGUAGE}}",k.lang).replace("{{NAME}}",k.user).replace("{{SIZE}}",k.size).replace("{{LINK}}",k.link),m=jQuery(m),jQuery("#languages").append(m)}}
body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px}
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> 

user85052

Posted 2019-08-25T05:41:43.767

Reputation:

3So there's two inputs, the sequence of commands and the initial accumulator value? – xnor – 2019-08-25T06:15:31.850

3Test cases would be very helpful here. – Unrelated String – 2019-08-25T06:17:48.610

1If the accumulator condition is not met, its state remains unchanged, right? – Joel – 2019-08-25T06:23:31.467

4Some test cases that don't change the accumulator, start with 1 in the accumulator or have no instructions would be good – Jo King – 2019-08-25T08:04:50.523

8

Can Talk really be considered a programming language?

– Luis Mendo – 2019-08-25T10:05:51.960

8@A_ That comment was probably meant as a joke. Back in the day, a language called Lang would have a URL lang.tryitonline.net (now it's tio.run/#lang). So a language called Talk would cause confusion with the URL for the then-recently created chatroom, which is talk.tryitonline.net – Luis Mendo – 2019-08-25T10:26:25.907

7

In the future, please refrain from changing I/O after a number of answers have been posted. I came back today and having mapped inputs allowed makes this an entirely different challenge from what I answered.

– GammaFunction – 2019-08-25T13:20:06.010

1I appreciate it, thank you. – GammaFunction – 2019-08-25T13:50:51.530

1Are we allowed to take the program as individual integers, such as [0, 1, 1, 0]? – TheOnlyMrCat – 2019-08-26T06:36:31.620

@TheOnlyMrCat Yes. – None – 2019-08-26T06:42:41.347

@A_ does the program have to write characters 0/1 (ASCII 48/49) or can it output ASCII 0/1 (NUL or SOH)? – osuka_ – 2019-08-26T17:44:01.250

1@osuka_ Both, as people are already using ASCII 0/1 in this challenge. – None – 2019-08-27T02:09:56.993

This seems kinds similar to boolfuck. – val says Reinstate Monica – 2019-08-27T17:08:41.923

Can the accumulator be 2? – Helena – 2019-08-28T11:26:02.347

@Helena No, the accumulator can only save binary values. – None – 2019-08-28T13:25:34.860

Answers

20

Jelly, 3 bytes

y@/

Input is a single list: the accumulator, followed by the pairs.

Try it online!

How it works

The y atom performs transliteration; [a,b]yc replaces a with b, so it returns b if a=c and c if a≠c.

y@/ folds/reduces the input by y with swapped arguments, performing one transliteration per pair.

Dennis

Posted 2019-08-25T05:41:43.767

Reputation: 196 637

13This is the only Jelly answer that I have seen so far that only uses ASCII characters. – None – 2019-08-26T00:38:19.530

2

There were a few. Look ma, no Unicode!

– Dennis – 2019-08-28T12:47:19.940

21

Python 3, 43 bytes

lambda s:re.sub("00|11","",s)[-1]
import re

Try it online!

The function takes a single string as input, where the first character is the initial state and the rest of the string represents the commands. This solution can be easily ported to other languages that have better support for regular expressions.

The difficult part is to prove the solution yields the correct outcome. To see this, we need a deep analysis of the commands. Firstly, we can see the commands have the following properties:

  • Property (1): commands 00 and 11 retain the accumulator state.
  • Property (2): commands 01 and 10 make the accumulator state the same as the second bit regardless of its original state.

Therefore, the final accumulator state is:

  • Case 1: If no 01 or 10 command exists, the final state is the same as the initial state.
  • Case 2: Otherwise, the last bit of the last 10 or 01 command.

Next we will show the solution yields the correct outcome in both cases. We will prove the statement for the final state 0 and the final state of 1 can be proved analogously. If the final state is 0 the input is in either of the following forms:

  • ^0{2k+1}11(11|00)*

    For Case 1, the input string s must start with 2k+1 0s, followed by 11 and 00 commands. Eliminating 00s and 11s yields a single 0, which is the final state.

  • .+10{2k+1}11(11|00)*

    For Case 2, the input string ends with a 10 command, followed by zero or more 00 and 11 s. This pattern is equivalent to a 1 followed by 2k+1 0s, and then zero or more 11s and 00s. Eliminating 00s and 11s leaves behind the last one of the 2k+1 0s at the end of the string, which represents the final state.

Based on all the above, after eliminating 00s and 11s simultaneously in one single pass (01001 is a counter-example if 00 is eliminated in one pass and then 11 in another pass) from the input s, the last character is the final state. Hence the correctness of the solution is proved.

Joel

Posted 2019-08-25T05:41:43.767

Reputation: 1 691

Welcome to PPCG! Excellent answer, and a nice formal proof to go with it! – GammaFunction – 2019-08-25T10:21:06.797

3Thanks. I feel that people may doubt such a simple solution yields the correct outcome at the first glance. So there is a need to provide a proof for that. – Joel – 2019-08-25T10:24:36.753

9

Perl 6, 17 bytes

{m/.)>[(.)$0]*$/}

Try it online!

Takes advantage of "You can merge these two inputs into one input if you like" by taking input as the accumulator value concatenated with the commands e.g. 1,[00,11] is 10011. If this isn't okay, than it's only 5 extra bytes to take it as f(accumulator, commands). Returns a match object that can be coerced to a string.

Explanation:

{                }  # Anonymous code block
 m/             /   # Find the first match from the input
   .)>              # Capture a number
      [     ]*      # Followed by any number of
       (.)$0        # Pairs of identical characters
              $     # Ending the string

Basically this works because the 00 and 11 commands do literally nothing, while the 01 and 10 commands just set the accumulator to the second digit of the command. If there are no commands, then it takes the initial value of the accumulator instead.

Jo King

Posted 2019-08-25T05:41:43.767

Reputation: 38 234

6

Python 3, 52 bytes

f=lambda a,s:s and f([s[1],a][s[0]==s[1]],s[2:])or a

Try it online!

Fixed inconsistent return type thanks to Chas Brown

Takes input as two strings; the accumulator and the code.

negative seven

Posted 2019-08-25T05:41:43.767

Reputation: 1 931

Oh no, that was fast. – HighlyRadioactive – 2019-08-25T07:19:31.133

1Nice but it has this potential problem - f(1,'11')==f(1,'01') is False; it sometimes returns an int and sometimes a str. So maybe specify it takes acc input as a string? – Chas Brown – 2019-08-25T07:42:06.993

@ChasBrown Good call, that's much simpler than what I was thinking about. – negative seven – 2019-08-25T07:48:38.243

Nice, but since your function is recursive, it cannot be anonymous. It should be 52 bytes.

– Jitse – 2019-08-26T09:48:53.517

6

Zsh, 33 bytes

The character list is passed as arguments, the initial value of the accumulator is passed as stdin.

read a
for x y;a=$[x^a?a:y]
<<<$a

Try it online!


39 bytes: If the commands must be a single string

Input is accumulator commands as arguments.

for x y (${(s::)2})1=$[x^$1?$1:y]
<<<$1

Try it online!


For fun, here's a 50 byte recursive one-liner (TIO):

<<<${${2+`f $[$1^${2[1]}?$1:${2[2]}] ${2:2}`}:-$1}

GammaFunction

Posted 2019-08-25T05:41:43.767

Reputation: 2 838

5

Brachylog, 11 9 bytes

tġ₂≠ˢtt|h

Try it online!

Since it's been long enough that I've been able to forget the notion of printing the accumulator after each command, I've formulated a significantly less naïve solution with some inspiration from Jo King's Perl answer.

       |     The output is
     tt      the last element of the last element of
t            the last element of the input
 ġ₂          split into length-2 slices
   ≠ˢ        with equal pairs removed.
       |     If there is no such element, the input
        h    's first element is the output.

Old solution:

Brachylog, 18 16 bytes

ġ₂ᵗc{th~h?tt|h}ˡ

Try it online!

-2 bytes from changing the input format.

Unrelated String

Posted 2019-08-25T05:41:43.767

Reputation: 5 300

5

JavaScript (ES6), 27 bytes

Takes input as (a)(code), where code is a is list of 2-bit integers.

a=>c=>c.map(x=>a^=x==a+1)|a

Try it online!


JavaScript (ES6),  47  40 bytes

Takes input as (a)(code), where code is a string.

a=>c=>c.replace(/../g,x=>a^=x%4==a+1)&&a

Try it online!

How?

All possible cases are summarized below. The only two cases where we need to toggle the accumulator are \$(a=0,x=01_2)\$ and \$(a=1,x=10_2)\$.

  a | x (bin) | int(x) % 4 | a + 1 | equal?
----+---------+------------+-------+--------
  0 |   "00"  |  0 % 4 = 0 |   1   |   N
  1 |   "00"  |  0 % 4 = 0 |   2   |   N
  0 |   "01"  |  1 % 4 = 1 |   1   |   Y
  1 |   "01"  |  1 % 4 = 1 |   2   |   N
  0 |   "10"  | 10 % 4 = 2 |   1   |   N
  1 |   "10"  | 10 % 4 = 2 |   2   |   Y
  0 |   "11"  | 11 % 4 = 3 |   1   |   N
  1 |   "11"  | 11 % 4 = 3 |   2   |   N

Arnauld

Posted 2019-08-25T05:41:43.767

Reputation: 111 334

4

sed -E, 26 19 bytes

A whopping -7 bytes from @Cowsquack by realizing removing all pairs works as well.

s/(.)\1//g
s/.*\B//

Takes input concatenated together on stdin. Inspired by Jo King's Perl answer. Strip trailing pairs Remove all pairs, then get last digit.

Try it online! Try it online!

GammaFunction

Posted 2019-08-25T05:41:43.767

Reputation: 2 838

1

The last line can be simply s/.*\B//, but anyways changing the approach slightly gives an even shorter 19 bytes Try it online!

– user41805 – 2019-08-25T10:54:32.203

1Huh, I didn't think that s/(.)\1//g would work, since it could remove the end of one pair and the start of the next, but it still works out. Excellent! – GammaFunction – 2019-08-25T12:35:05.610

@GammaFunction s/(.)\1//g is equivalent to s/00|11//g as shown in my solution. – Joel – 2019-08-25T15:26:05.077

4

Retina 0.8.2, 18 11 bytes

(.)\1

!`.$

Try it online! Link includes test cases. Takes input concatenated. Saved 6 bytes thanks to @CowsQuack for pointing out that removing all doubled characters and then taking the last remaining character works, although in fact the port of @JoKing's original answer could have been golfed by 3 bytes even without that trick.

Neil

Posted 2019-08-25T05:41:43.767

Reputation: 95 035

12 bytes Try it online!

– user41805 – 2019-08-25T10:52:33.733

@Cowsquack D'oh, once you think about separating the stages, that's a 2-byte saving already, then another byte saved because you can use !`.$, and then another 4 bytes because you don't have to limit to trailing pairs... – Neil – 2019-08-25T15:12:05.553

4

Python 3, 38 bytes

lambda l:[y for*x,y in l if[y]!=x][-1]

Try it online!

Based on Joel's solution. Takes input as a list of the initial accumulator value (length-one string) followed by the commands (length-two strings). Finds the last command with two unequal values, and outputs its second character.

To make this fall through to the initial accumulator value when there are no such commands, we make it so that the single-char initial value string passes the test. We do so by checking if a singleton list with the last character is unequal to a list of all preceding characters, which is passed by any length-one string or length-two string with two different characters.

xnor

Posted 2019-08-25T05:41:43.767

Reputation: 115 687

3

Perl 5 -p, 37 33 bytes

$\=<>;s/(.)(.)/$\=$2if$\==$1/ge}{

Try it online!

Input is two lines: first line is the command sequence, second is the accumulator.

Xcali

Posted 2019-08-25T05:41:43.767

Reputation: 7 671

3

Jelly, 8 6 bytes

EÐḟṪṪo

Try it online!

-2 bytes thanks to Nick Kennedy informing me of a rules change. (His proposed golf, EÐḟFȯṪ, seems somewhat more clever but has the same length as my previous solution minus s2.) The input format now takes the commands as a list of two-character strings, but the testing footer translates from the old format for convenience.

Translated from my newer Brachylog solution.

Old version:

Jelly, 13 bytes

ḢẎ⁼⁹a⁸o
s2ç@ƒ

Try it online!

I'm not 100% sure this is correct, but it succeeds on all three test cases. Takes the commands as the left argument and the initial accumulator as the right argument.

Unrelated String

Posted 2019-08-25T05:41:43.767

Reputation: 5 300

1The input is allowed to be split into a list, so you could have EÐḟFȯṪ with the input as e.g. [[0,0],[0,1],[1,1],[1,1],[0,1]]. – Nick Kennedy – 2019-08-25T19:30:22.147

Wow, the changes to the spec really were quite large... – Unrelated String – 2019-08-25T19:42:01.160

3

Python 2, 56 bytes

f=lambda a,c:f([a,1,0,a][int(c[:2],2)],c[2:])if c else a

Try it online!

Chas Brown

Posted 2019-08-25T05:41:43.767

Reputation: 8 959

3

Haskell, 29 bytes

Defines an unnamed function on the first line with type (Foldable t, Eq b) => b -> t [b] -> b. For the purposes of this code golf, we can instantiate it as Char -> [String] -> Char where the first argument is the accumulator and the second is a list of string with each string being a single command.

foldl(#)
a#[x,y]|a==x=y|1>0=a

Try it online!

ankh-morpork

Posted 2019-08-25T05:41:43.767

Reputation: 1 350

1

Same bytecount if you define it using prefix notation. I can't believe I wrote almost the exact same answer at the same time, even including the type signature explanation…

– cole – 2019-08-25T21:48:48.670

2

Python, 111 bytes

def f(a,b):
    c=a
    for i in range(0,len(b)-1,2):
        c=(not b[i])*(c or b[i] or b[i+1]) or c*b[i]*b[i+1]
    return c

Ungolfed. EDIT: AHHH Someone beat me to it!

HighlyRadioactive

Posted 2019-08-25T05:41:43.767

Reputation: 1 585

2

Haskell, 36 bytes

f(x:y:s)=f s.last.(:[y|x/=y])
f _=id

Try it online!

Takes input as f(string)(char) where the character is the accumulator and the string is the list of commands.

Jo King

Posted 2019-08-25T05:41:43.767

Reputation: 38 234

2

05AB1E, 3 bytes

ø`:

Try it online!

Zip, dump on the stack, replace.

Grimmy

Posted 2019-08-25T05:41:43.767

Reputation: 12 521

2

Stax, 3 bytes

F|t

Run and debug it

For each instruction, perform character translation.

recursive

Posted 2019-08-25T05:41:43.767

Reputation: 8 616

1

Keg, -ir, 16 bytes

"(!;½|':"=['_"|_

Try it online!

Explained:

  1. Takes the implicit input and right shifts the accumulators value to the bottom

  2. Repeat the following (length of stack - 1 divided by 2) times

2.1. Shift the accumulator back to the top

2.2. Compare for equality with the first part of the command

2.2.1. If true, replace the accumulator, otherwise pop the replacement

Input is taken as the initial acc value concatenated with the source. E.g.

010011000
  • First char is acc value
  • Rest is program

Lyxal

Posted 2019-08-25T05:41:43.767

Reputation: 5 253

1

Bash, 58 40 bytes

Add one byte for a full program: change f to $0.

(($1=$2-a?a:$3,1))&&f $1 ${@:4}||echo $1

58 bytes Try it online!

The ternary will return false when $1 is set to 0, but the ,1 at the end ensures the whole ((expression)) will return true, except a syntax error.

When all the arguments are consumed, a syntax error happens and the recursion ends.


GammaFunction

Posted 2019-08-25T05:41:43.767

Reputation: 2 838

1

Charcoal, 16 bytes

F⪪η²F⁼θ§ι⁰≔§ι¹θθ

Try it online! Link is to verbose version of code. Takes separate arguments. Explanation:

F⪪η²

Split the instructions into pairs of digits and loop over them.

F⁼θ§ι⁰

If the accumulator is equal to the first digit...

≔§ι¹θ

... then assign the second digit to it.

θ

Print the accumulator at the end of the loop.

Neil

Posted 2019-08-25T05:41:43.767

Reputation: 95 035

1

MATL, 13 12 bytes

!dh2Ol4$Ys0)

Takes the input as a 2-column matrix where each row is a command, and a number

Try it online! Or verify all test cases

Luis Mendo

Posted 2019-08-25T05:41:43.767

Reputation: 87 464

1

Jelly, 7 bytes

fؽḂ⁹;Ṫ

A dyadic Link accepting the program as a list of integers on the left and the initial accumulator on the right which yields an integer.

Try it online! Or see a test-suite

Jonathan Allan

Posted 2019-08-25T05:41:43.767

Reputation: 67 804

I am removing input-mapping because @GammaFunction recommended me to do this. – None – 2019-08-25T13:30:09.510

@A_ ah OK cant delete on mobile so will have to address this later – Jonathan Allan – 2019-08-25T13:35:56.190

@A_ fixed up to work with 0,1,2,3 the unmapped version of the instructions as digits is that OK? – Jonathan Allan – 2019-08-25T16:01:22.267

1Yes, that's OK. – None – 2019-08-25T21:51:07.990

1

C (gcc), 45 41 bytes

f(a,i)char*i;{a=*i?f(a^*i?a:i[1],i+2):a;}

Try it online!

4 bytes shaved off thanks to @ErikF!

G. Sliepen

Posted 2019-08-25T05:41:43.767

Reputation: 580

1

You can save 4 bytes by using the usual trick of storing the return value in the first parameter: Try it online!

– ErikF – 2019-08-26T02:58:38.327

1

PHP, 38 bytes

<?=strtr($argn,['00'=>'',11=>''])[-1];

Try it online!

Basically port of Jo King's idea.

Night2

Posted 2019-08-25T05:41:43.767

Reputation: 5 484

1

Runic Enchantments, 28 bytes

/~@/i~/i<
/=?/~iR:l}i{l1-=?!

Try it online!

Takes input as a series of space separated bytes (Runic does not understand lists). The first byte is the initial state and every other byte is the program. No validation is performed (i.e. it assumes only valid programs are given as input and it doesn't care what value is used to represent 0 and 1).

Draco18s no longer trusts SE

Posted 2019-08-25T05:41:43.767

Reputation: 3 053

1

x86 Assembly, 33 Bytes

Takes the initial accumulator state in CL (integer 0 or 1) and the address of the commands as a zero-terminated ASCII String in ESI. Leaves the final accumulator state in CL.

Point the call instruction at offset 0x1B (label interpret in the Explanation).

3C 30 74 03 B0 01 C3 30 C0 C3 E8 F1 FF FF FF 38
C8 AC 75 07 E8 E7 FF FF FF 88 C1 AC 84 C0 75 EA
C3

Explanation (Using Intel Syntax):

; function to convert ASCII '1'/'0' into 0 or 1 int values (from AL to AL)
ctob:
        CMP AL, 0x30 ; '0'
        JE .zero
        MOV AL, 1
        RET
        .zero:
        XOR AL, AL
        RET

; interpreting function
        interp_lp:
                CALL ctob     ; convert to number
                CMP AL, CL    ; compare to current accumulator
                LODSB         ; read the next character of the string
                              ; this doesn't affect any flags and we need to do
                              ; it in both cases anyway
                JNE interpret ; if AL != CL (from above, not the new value of AL), skip forward
                CALL ctob     ; convert AL to number
                MOV CL, AL    ; store AL in CL
interpret:      LODSB         ; read the next character of the string
                TEST AL, AL   ; check if it is a zero byte
                JNZ interp_lp ; if not, jump back into the loop
        RET

Fayti1703

Posted 2019-08-25T05:41:43.767

Reputation: 71

0

C (clang), 68 62 bytes

t(s,e,a)char*s,*e;{for(;s<e;++s)a=*s++-48^a?a:*s-48;puts(&a);}

Try it online!

Takes a pointer to the start of the source string, a pointer to the end of the source string (start + strlen(start)), and the initial accumulator value.

Old version (prints ASCII 48/49 for 0/1):

t(s,e,a)char*s,*e;{for(;s<e;++s)a=*s++-48^a?a:*s-48;putchar(a+48);}

osuka_

Posted 2019-08-25T05:41:43.767

Reputation: 391

0

Crystal, 46 bytes

With commands in an Array(Tuple(Int32,Int32)), such as [{0,0}, {0,1}, {0,0}].

def f(s,i);i.map{|c,v|s+=~(s^c)&(s^v)%2};s;end

Try it online!

It's pretty simple to understand in a more readable form:

def f(state, instructions)
  instructions.map do |check, value|
    state += ~(state ^ check) & (state ^ value) % 2
  end
  state
end

The function loops through each command, automatically unpacking the tuple values into c and v. It then sets the state by the formula

state = state + NOT(state XOR check) AND (state XOR value) mod 2

which I arrived at mostly by trial and error. Once all commands have been processed, it returns the state value.

Kinxer

Posted 2019-08-25T05:41:43.767

Reputation: 31

0

Java (JDK), 38 bytes

a->p->p.reduce(a,(s,c)->c<1|c>2?s:c%2)

Try it online!

The inputs are an int and an IntStream of 0, 1, 2 or 3, which correspond to 00, 01, 10, 11 from binary.

Olivier Grégoire

Posted 2019-08-25T05:41:43.767

Reputation: 10 647

0

Ruby, 33 bytes

->a,s{s[/(00|11)*$/]="";s[-1]||a}

Try it online!

G B

Posted 2019-08-25T05:41:43.767

Reputation: 11 099